62 lines
		
	
	
		
			1.3 KiB
		
	
	
	
		
			C++
		
	
	
	
	
	
			
		
		
	
	
			62 lines
		
	
	
		
			1.3 KiB
		
	
	
	
		
			C++
		
	
	
	
	
	
| #include "material.h"
 | |
| 
 | |
| #include "../lib/glm/glm.hpp"
 | |
| 
 | |
| #include "shader.h"
 | |
| #include "state.h"
 | |
| #include "texture.h"
 | |
| 
 | |
| Material::Material(const std::shared_ptr<Texture>& tex,
 | |
| 		   const std::shared_ptr<Shader>&  shader)
 | |
|     : shader_(shader), texture_(tex)
 | |
| {
 | |
| }
 | |
| 
 | |
| const std::shared_ptr<Shader>& Material::shader() const
 | |
| {
 | |
| 	return shader_ ? shader_ : state::default_shader;
 | |
| }
 | |
| 
 | |
| std::shared_ptr<Shader>& Material::shader()
 | |
| {
 | |
| 	return shader_ ? shader_ : state::default_shader;
 | |
| }
 | |
| 
 | |
| void Material::set_shader(const std::shared_ptr<Shader>& shader)
 | |
| {
 | |
| 	shader_ = shader;
 | |
| }
 | |
| 
 | |
| void Material::prepare()
 | |
| {
 | |
| 	// Activate shader
 | |
| 	std::shared_ptr<Shader> active_shader = shader();
 | |
| 	if (!active_shader)
 | |
| 		return;
 | |
| 
 | |
| 	active_shader->use();
 | |
| 
 | |
| 	// Set uniform variables
 | |
| 	const glm::mat4 mvp =
 | |
| 	    state::projection_matrix * state::view_matrix * state::model_matrix;
 | |
| 	const int mvp_loc = active_shader->uniform_location("mvp");
 | |
| 	Shader::set_mat4(mvp_loc, mvp);
 | |
| 
 | |
| 	// Set texture-related uniforms
 | |
| 	const int use_texture_loc =
 | |
| 	    active_shader->uniform_location("useTexture");
 | |
| 	if (texture_) {
 | |
| 		Shader::set_int(use_texture_loc, 1);
 | |
| 		const int sampler_loc =
 | |
| 		    active_shader->uniform_location("texSampler");
 | |
| 		Shader::set_int(sampler_loc, 0); // Texture unit 0
 | |
| 	} else {
 | |
| 		Shader::set_int(use_texture_loc, 0);
 | |
| 	}
 | |
| 
 | |
| 	// Bind texture if available
 | |
| 	if (texture_) {
 | |
| 		texture_->bind();
 | |
| 	}
 | |
| }
 |