void CameraInfluence::calculatePointCamera(Ogre::Vector3 target_position, Ogre::Quaternion target_rotation) {
	camera->setPosition(new_target_position);

	LibGens::Vector3 camera_position_v = camera_object->getPosition();
	Ogre::Vector3 camera_position(camera_position_v.x, camera_position_v.y, camera_position_v.z);
	camera->lookAt(camera_position);

	camera->roll(Ogre::Degree(e_zrot->value));
	camera->moveRelative(Ogre::Vector3(0.0, 0.0, e_distance->value));

	// Store Results
	result_position = camera->getPosition();
	result_rotation = camera->getOrientation();
	fovy = Ogre::Degree(e_fovy->value);
}
Ejemplo n.º 2
0
    virtual void calc()
    {
        if( fn_bind() )          // avoid GPF!
        {
            if( fn_calc() )      // check or recalc input
            {

                glm::mat4 camera_world_position(1.f);                 // camera world position
                glm::mat4 camera_view(1.f);                           // camera view transformation

                // load camera world position from gdom "wpos"
                set_glm_mat4_from_m4(camera_world_position, mp_wpos); // init glm-variable from gx-gdom-field

                // GetViewMatrix() const
                float* cwp = glm::value_ptr(camera_world_position);   // used as float[16]
                glm::vec3 camera_position(cwp[12], cwp[13], cwp[14]); // cwp translation;
                glm::vec3 z(cwp[ 2], cwp[ 6], cwp[10]);               // cwp z-vector;
                glm::vec3 look_at_point = camera_position + z;
                glm::vec3 up_vector      (cwp[ 1], cwp[ 5], cwp[ 9]); // cwp y-vector;

                camera_view = glm::lookAt(camera_position, look_at_point, up_vector);

                // save camera_view to gdom "view"
                set_m4_from_glm_mat4(mp_view, camera_view);

                // reset state to GOOD
                return gx::fn::calc_success();
            }
            else
            {
                return gx::fn::fn_calc_failed();
            }
        }
        else
        {
            return gx::fn::fn_bind_failed();
        }
    }
Ejemplo n.º 3
0
	virtual void updateTexturesAndMeshes(IGameDef *gamedef)
	{
#ifndef SERVER
		infostream<<"ItemDefManager::updateTexturesAndMeshes(): Updating "
				<<"textures and meshes in item definitions"<<std::endl;

		ITextureSource *tsrc = gamedef->getTextureSource();
		INodeDefManager *nodedef = gamedef->getNodeDefManager();
		IrrlichtDevice *device = tsrc->getDevice();
		video::IVideoDriver *driver = device->getVideoDriver();

		for(std::map<std::string, ItemDefinition*>::iterator
				i = m_item_definitions.begin();
				i != m_item_definitions.end(); i++)
		{
			ItemDefinition *def = i->second;

			bool need_node_mesh = false;

			// Create an inventory texture
			def->inventory_texture = NULL;
			if(def->inventory_image != "")
			{
				def->inventory_texture = tsrc->getTextureRaw(def->inventory_image);
			}
			else if(def->type == ITEM_NODE)
			{
				need_node_mesh = true;
			}

			// Create a wield mesh
			if(def->wield_mesh != NULL)
			{
				def->wield_mesh->drop();
				def->wield_mesh = NULL;
			}
			if(def->type == ITEM_NODE && def->wield_image == "")
			{
				need_node_mesh = true;
			}
			else if(def->wield_image != "" || def->inventory_image != "")
			{
				// Extrude the wield image into a mesh

				std::string imagename;
				if(def->wield_image != "")
					imagename = def->wield_image;
				else
					imagename = def->inventory_image;

				def->wield_mesh = createExtrudedMesh(
						tsrc->getTextureRaw(imagename),
						driver,
						def->wield_scale * v3f(40.0, 40.0, 4.0));
				if(def->wield_mesh == NULL)
				{
					infostream<<"ItemDefManager: WARNING: "
						<<"updateTexturesAndMeshes(): "
						<<"Unable to create extruded mesh for item "
						<<def->name<<std::endl;
				}
			}

			if(need_node_mesh)
			{
				/*
					Get node properties
				*/
				content_t id = nodedef->getId(def->name);
				const ContentFeatures &f = nodedef->get(id);

				u8 param1 = 0;
				if(f.param_type == CPT_LIGHT)
					param1 = 0xee;

				/*
				 	Make a mesh from the node
				*/
				MeshMakeData mesh_make_data(gamedef);
				MapNode mesh_make_node(id, param1, 0);
				mesh_make_data.fillSingleNode(&mesh_make_node);
				MapBlockMesh mapblock_mesh(&mesh_make_data);

				scene::IMesh *node_mesh = mapblock_mesh.getMesh();
				assert(node_mesh);
				setMeshColor(node_mesh, video::SColor(255, 255, 255, 255));

				/*
					Scale and translate the mesh so it's a unit cube
					centered on the origin
				*/
				scaleMesh(node_mesh, v3f(1.0/BS, 1.0/BS, 1.0/BS));
				translateMesh(node_mesh, v3f(-1.0, -1.0, -1.0));

				/*
					Draw node mesh into a render target texture
				*/
				if(def->inventory_texture == NULL)
				{
					core::dimension2d<u32> dim(64,64);
					std::string rtt_texture_name = "INVENTORY_"
						+ def->name + "_RTT";
					v3f camera_position(0, 1.0, -1.5);
					camera_position.rotateXZBy(45);
					v3f camera_lookat(0, 0, 0);
					core::CMatrix4<f32> camera_projection_matrix;
					// Set orthogonal projection
					camera_projection_matrix.buildProjectionMatrixOrthoLH(
							1.65, 1.65, 0, 100);

					video::SColorf ambient_light(0.2,0.2,0.2);
					v3f light_position(10, 100, -50);
					video::SColorf light_color(0.5,0.5,0.5);
					f32 light_radius = 1000;

					def->inventory_texture = generateTextureFromMesh(
						node_mesh, device, dim, rtt_texture_name,
						camera_position,
						camera_lookat,
						camera_projection_matrix,
						ambient_light,
						light_position,
						light_color,
						light_radius);

					// render-to-target didn't work
					if(def->inventory_texture == NULL)
					{
						def->inventory_texture =
							tsrc->getTextureRaw(f.tname_tiles[0]);
					}
				}

				/*
					Use the node mesh as the wield mesh
				*/
				if(def->wield_mesh == NULL)
				{
					// Scale to proper wield mesh proportions
					scaleMesh(node_mesh, v3f(30.0, 30.0, 30.0)
							* def->wield_scale);
					def->wield_mesh = node_mesh;
					def->wield_mesh->grab();
				}

				// falling outside of here deletes node_mesh
			}
		}
#endif
	}
	MultiViewportExample(void)
	 : make_shape(1.0, 0.1, 8, 4, 48)
	 , shape_instr(make_shape.Instructions())
	 , shape_indices(make_shape.Indices())
	 , camera_position_3(prog, "CameraPosition[3]")
	 , camera_matrix_0(prog, "CameraMatrix[0]")
	 , camera_matrix_1(prog, "CameraMatrix[1]")
	 , camera_matrix_2(prog, "CameraMatrix[2]")
	 , camera_matrix_3(prog, "CameraMatrix[3]")
	 , model_matrix(prog, "ModelMatrix")
	{
		VertexShader vs;
		// Set the vertex shader source
		vs.Source(
			"#version 330\n"
			"uniform mat4 ModelMatrix;"
			"uniform vec3 LightPos;"

			"in vec4 Position;"
			"in vec3 Normal;"

			"out vec3 vertNormal;"
			"out vec3 vertTexCoord;"
			"out vec3 vertLightDir;"
			"out vec3 vertLightRefl;"

			"void main(void)"
			"{"
			"	vertNormal = mat3(ModelMatrix)*Normal;"
			"	vertTexCoord = Normal;"
			"	gl_Position = ModelMatrix * Position;"
			"	vertLightDir = LightPos-gl_Position.xyz;"
			"	vertLightRefl = reflect(-vertLightDir, vertNormal);"
			"}"
		);
		vs.Compile();

		GeometryShader gs;
		// Set the geometry shader source
		gs.Source(
			"#version 330\n"
			"#extension GL_ARB_viewport_array : enable\n"
			"layout(triangles) in;"
			"layout(triangle_strip, max_vertices = 12) out;"

			"uniform mat4 CameraMatrix[4];"
			"uniform vec3 CameraPosition[4];"

			"in vec3 vertNormal[];"
			"in vec3 vertTexCoord[];"
			"in vec3 vertLightDir[];"
			"in vec3 vertLightRefl[];"

			"out vec3 geomNormal;"
			"out vec3 geomTexCoord;"
			"out vec3 geomLightDir;"
			"out vec3 geomLightRefl;"
			"out vec3 geomViewDir;"
			"out vec3 geomViewRefl;"

			"void main(void)"
			"{"
			"	for(int vp=0; vp!=4; ++vp)"
			"	{"
			"		gl_ViewportIndex = vp;"
			"		for(int v=0; v!=3; ++v)"
			"		{"
			"			geomNormal = vertNormal[v];"
			"			geomTexCoord = vertTexCoord[v];"
			"			geomLightDir = vertLightDir[v];"
			"			geomLightRefl = vertLightRefl[v];"
			"			geomViewDir = "
			"				CameraPosition[vp] - "
			"				gl_in[v].gl_Position.xyz;"
			"			geomViewRefl = reflect("
			"				-geomViewDir,"
			"				geomNormal"
			"			);"
			"			gl_Position = "
			"				CameraMatrix[vp] *"
			"				gl_in[v].gl_Position;"
			"			EmitVertex();"
			"		}"
			"		EndPrimitive();"
			"	}"
			"}"
		);
		gs.Compile();

		FragmentShader fs;
		// set the fragment shader source
		fs.Source(
			"#version 330\n"
			"uniform samplerCube TexUnit;"
			"in vec3 geomNormal;"
			"in vec3 geomTexCoord;"
			"in vec3 geomLightDir;"
			"in vec3 geomLightRefl;"
			"in vec3 geomViewDir;"
			"in vec3 geomViewRefl;"
			"out vec4 fragColor;"
			"void main(void)"
			"{"
			"	float l = length(geomLightDir);"
			"	float d = dot("
			"		normalize(geomNormal), "
			"		normalize(geomLightDir)"
			"	) / l;"
			"	float s = dot("
			"		normalize(geomLightRefl),"
			"		normalize(geomViewDir)"
			"	);"
			"	vec3 lt = vec3(1.0, 1.0, 1.0);"
			"	vec3 tex = texture(TexUnit, geomTexCoord).rgb;"
			"	fragColor = vec4("
			"		tex * 0.4 + "
			"		(lt + tex) * 1.5 * max(d, 0.0) + "
			"		lt * pow(max(s, 0.0), 64), "
			"		1.0"
			"	);"
			"}"
		);
		// compile it
		fs.Compile();

		// attach the shaders to the program
		prog.AttachShader(vs);
		prog.AttachShader(gs);
		prog.AttachShader(fs);
		// link and use it
		prog.Link();
		prog.Use();

		// bind the VAO for the shape
		shape.Bind();

		verts.Bind(Buffer::Target::Array);
		{
			std::vector<GLfloat> data;
			GLuint n_per_vertex = make_shape.Positions(data);
			Buffer::Data(Buffer::Target::Array, data);
			VertexAttribArray attr(prog, "Position");
			attr.Setup<GLfloat>(n_per_vertex);
			attr.Enable();
		}

		normals.Bind(Buffer::Target::Array);
		{
			std::vector<GLfloat> data;
			GLuint n_per_vertex = make_shape.Normals(data);
			Buffer::Data(Buffer::Target::Array, data);
			VertexAttribArray attr(prog, "Normal");
			attr.Setup<GLfloat>(n_per_vertex);
			attr.Enable();
		}

		// setup the texture
		{
			GLuint tex_side = 512;
			auto image = images::NewtonFractal(
				tex_side, tex_side,
				Vec3f(0.8f, 0.8f, 1.0f),
				Vec3f(0.1f, 0.0f, 0.2f),
				Vec2f(-0.707f, -0.707f),
				Vec2f( 0.707f,  0.707f),
				images::NewtonFractal::X4Minus1(),
				[](double x) -> double
				{
					return pow(SineWave(pow(x,0.5)), 4.0);
				}
			);
			auto bound_tex = Bind(tex, Texture::Target::CubeMap);
			bound_tex.MinFilter(TextureMinFilter::Linear);
			bound_tex.MagFilter(TextureMagFilter::Linear);
			bound_tex.WrapS(TextureWrap::ClampToEdge);
			bound_tex.WrapT(TextureWrap::ClampToEdge);
			bound_tex.WrapR(TextureWrap::ClampToEdge);

			for(int i=0; i!=6; ++i)
				Texture::Image2D(Texture::CubeMapFace(i), image);
		}
		//
		UniformSampler(prog, "TexUnit").Set(0);
		Uniform<Vec3f>(prog, "LightPos").Set(Vec3f(3.0f, 5.0f, 4.0f));
		//
		gl.ClearColor(0.1f, 0.05f, 0.2f, 0.0f);
		gl.ClearDepth(1.0f);
		gl.Enable(Capability::DepthTest);

		gl.Enable(Capability::CullFace);
		gl.FrontFace(make_shape.FaceWinding());
		gl.CullFace(Face::Back);

		Uniform<Vec3f> camera_position(prog, "CameraPosition");
		camera_position[0].Set(Vec3f(2, 0, 0));
		camera_position[1].Set(Vec3f(0, 2, 0));
		camera_position[2].Set(Vec3f(0, 0, 2));
	}
Ejemplo n.º 5
0
bool generate_image(std::string part_of_name, video::IImage *& baseimg,
		IrrlichtDevice *device, SourceImageCache *sourcecache)
{
	video::IVideoDriver* driver = device->getVideoDriver();
	assert(driver);

	// Stuff starting with [ are special commands
	if(part_of_name.size() == 0 || part_of_name[0] != '[')
	{
		video::IImage *image = sourcecache->getOrLoad(part_of_name, device);

		if(image == NULL)
		{
			if(part_of_name != ""){
				errorstream<<"generate_image(): Could not load image \""
						<<part_of_name<<"\""<<" while building texture"<<std::endl;
				errorstream<<"generate_image(): Creating a dummy"
						<<" image for \""<<part_of_name<<"\""<<std::endl;
			}

			// Just create a dummy image
			//core::dimension2d<u32> dim(2,2);
			core::dimension2d<u32> dim(1,1);
			image = driver->createImage(video::ECF_A8R8G8B8, dim);
			assert(image);
			/*image->setPixel(0,0, video::SColor(255,255,0,0));
			image->setPixel(1,0, video::SColor(255,0,255,0));
			image->setPixel(0,1, video::SColor(255,0,0,255));
			image->setPixel(1,1, video::SColor(255,255,0,255));*/
			image->setPixel(0,0, video::SColor(255,myrand()%256,
					myrand()%256,myrand()%256));
			/*image->setPixel(1,0, video::SColor(255,myrand()%256,
					myrand()%256,myrand()%256));
			image->setPixel(0,1, video::SColor(255,myrand()%256,
					myrand()%256,myrand()%256));
			image->setPixel(1,1, video::SColor(255,myrand()%256,
					myrand()%256,myrand()%256));*/
		}

		// If base image is NULL, load as base.
		if(baseimg == NULL)
		{
			//infostream<<"Setting "<<part_of_name<<" as base"<<std::endl;
			/*
				Copy it this way to get an alpha channel.
				Otherwise images with alpha cannot be blitted on 
				images that don't have alpha in the original file.
			*/
			core::dimension2d<u32> dim = image->getDimension();
			baseimg = driver->createImage(video::ECF_A8R8G8B8, dim);
			image->copyTo(baseimg);
			image->drop();
		}
		// Else blit on base.
		else
		{
			//infostream<<"Blitting "<<part_of_name<<" on base"<<std::endl;
			// Size of the copied area
			core::dimension2d<u32> dim = image->getDimension();
			//core::dimension2d<u32> dim(16,16);
			// Position to copy the blitted to in the base image
			core::position2d<s32> pos_to(0,0);
			// Position to copy the blitted from in the blitted image
			core::position2d<s32> pos_from(0,0);
			// Blit
			image->copyToWithAlpha(baseimg, pos_to,
					core::rect<s32>(pos_from, dim),
					video::SColor(255,255,255,255),
					NULL);
			// Drop image
			image->drop();
		}
	}
	else
	{
		// A special texture modification

		/*infostream<<"generate_image(): generating special "
				<<"modification \""<<part_of_name<<"\""
				<<std::endl;*/
		
		/*
			This is the simplest of all; it just adds stuff to the
			name so that a separate texture is created.

			It is used to make textures for stuff that doesn't want
			to implement getting the texture from a bigger texture
			atlas.
		*/
		if(part_of_name == "[forcesingle")
		{
			// If base image is NULL, create a random color
			if(baseimg == NULL)
			{
				core::dimension2d<u32> dim(1,1);
				baseimg = driver->createImage(video::ECF_A8R8G8B8, dim);
				assert(baseimg);
				baseimg->setPixel(0,0, video::SColor(255,myrand()%256,
						myrand()%256,myrand()%256));
			}
		}
		/*
			[crackN
			Adds a cracking texture
		*/
		else if(part_of_name.substr(0,6) == "[crack")
		{
			if(baseimg == NULL)
			{
				errorstream<<"generate_image(): baseimg==NULL "
						<<"for part_of_name=\""<<part_of_name
						<<"\", cancelling."<<std::endl;
				return false;
			}
			
			// Crack image number and overlay option
			s32 progression = 0;
			bool use_overlay = false;
			if(part_of_name.substr(6,1) == "o")
			{
				progression = stoi(part_of_name.substr(7));
				use_overlay = true;
			}
			else
			{
				progression = stoi(part_of_name.substr(6));
				use_overlay = false;
			}

			// Size of the base image
			core::dimension2d<u32> dim_base = baseimg->getDimension();
			
			/*
				Load crack image.

				It is an image with a number of cracking stages
				horizontally tiled.
			*/
			video::IImage *img_crack = sourcecache->getOrLoad("crack.png", device);
		
			if(img_crack && progression >= 0)
			{
				// Dimension of original image
				core::dimension2d<u32> dim_crack
						= img_crack->getDimension();
				// Count of crack stages
				s32 crack_count = dim_crack.Height / dim_crack.Width;
				// Limit progression
				if(progression > crack_count-1)
					progression = crack_count-1;
				// Dimension of a single crack stage
				core::dimension2d<u32> dim_crack_cropped(
					dim_crack.Width,
					dim_crack.Width
				);
				// Create cropped and scaled crack images
				video::IImage *img_crack_cropped = driver->createImage(
						video::ECF_A8R8G8B8, dim_crack_cropped);
				video::IImage *img_crack_scaled = driver->createImage(
						video::ECF_A8R8G8B8, dim_base);

				if(img_crack_cropped && img_crack_scaled)
				{
					// Crop crack image
					v2s32 pos_crack(0, progression*dim_crack.Width);
					img_crack->copyTo(img_crack_cropped,
							v2s32(0,0),
							core::rect<s32>(pos_crack, dim_crack_cropped));
					// Scale crack image by copying
					img_crack_cropped->copyToScaling(img_crack_scaled);
					// Copy or overlay crack image
					if(use_overlay)
					{
						overlay(baseimg, img_crack_scaled);
					}
					else
					{
						img_crack_scaled->copyToWithAlpha(
								baseimg,
								v2s32(0,0),
								core::rect<s32>(v2s32(0,0), dim_base),
								video::SColor(255,255,255,255));
					}
				}

				if(img_crack_scaled)
					img_crack_scaled->drop();

				if(img_crack_cropped)
					img_crack_cropped->drop();
				
				img_crack->drop();
			}
		}
		/*
			[combine:WxH:X,Y=filename:X,Y=filename2
			Creates a bigger texture from an amount of smaller ones
		*/
		else if(part_of_name.substr(0,8) == "[combine")
		{
			Strfnd sf(part_of_name);
			sf.next(":");
			u32 w0 = stoi(sf.next("x"));
			u32 h0 = stoi(sf.next(":"));
			infostream<<"combined w="<<w0<<" h="<<h0<<std::endl;
			core::dimension2d<u32> dim(w0,h0);
			baseimg = driver->createImage(video::ECF_A8R8G8B8, dim);
			while(sf.atend() == false)
			{
				u32 x = stoi(sf.next(","));
				u32 y = stoi(sf.next("="));
				std::string filename = sf.next(":");
				infostream<<"Adding \""<<filename
						<<"\" to combined ("<<x<<","<<y<<")"
						<<std::endl;
				video::IImage *img = sourcecache->getOrLoad(filename, device);
				if(img)
				{
					core::dimension2d<u32> dim = img->getDimension();
					infostream<<"Size "<<dim.Width
							<<"x"<<dim.Height<<std::endl;
					core::position2d<s32> pos_base(x, y);
					video::IImage *img2 =
							driver->createImage(video::ECF_A8R8G8B8, dim);
					img->copyTo(img2);
					img->drop();
					img2->copyToWithAlpha(baseimg, pos_base,
							core::rect<s32>(v2s32(0,0), dim),
							video::SColor(255,255,255,255),
							NULL);
					img2->drop();
				}
				else
				{
					infostream<<"img==NULL"<<std::endl;
				}
			}
		}
		/*
			"[brighten"
		*/
		else if(part_of_name.substr(0,9) == "[brighten")
		{
			if(baseimg == NULL)
			{
				errorstream<<"generate_image(): baseimg==NULL "
						<<"for part_of_name=\""<<part_of_name
						<<"\", cancelling."<<std::endl;
				return false;
			}

			brighten(baseimg);
		}
		/*
			"[noalpha"
			Make image completely opaque.
			Used for the leaves texture when in old leaves mode, so
			that the transparent parts don't look completely black 
			when simple alpha channel is used for rendering.
		*/
		else if(part_of_name.substr(0,8) == "[noalpha")
		{
			if(baseimg == NULL)
			{
				errorstream<<"generate_image(): baseimg==NULL "
						<<"for part_of_name=\""<<part_of_name
						<<"\", cancelling."<<std::endl;
				return false;
			}

			core::dimension2d<u32> dim = baseimg->getDimension();
			
			// Set alpha to full
			for(u32 y=0; y<dim.Height; y++)
			for(u32 x=0; x<dim.Width; x++)
			{
				video::SColor c = baseimg->getPixel(x,y);
				c.setAlpha(255);
				baseimg->setPixel(x,y,c);
			}
		}
		/*
			"[makealpha:R,G,B"
			Convert one color to transparent.
		*/
		else if(part_of_name.substr(0,11) == "[makealpha:")
		{
			if(baseimg == NULL)
			{
				errorstream<<"generate_image(): baseimg==NULL "
						<<"for part_of_name=\""<<part_of_name
						<<"\", cancelling."<<std::endl;
				return false;
			}

			Strfnd sf(part_of_name.substr(11));
			u32 r1 = stoi(sf.next(","));
			u32 g1 = stoi(sf.next(","));
			u32 b1 = stoi(sf.next(""));
			std::string filename = sf.next("");

			core::dimension2d<u32> dim = baseimg->getDimension();
			
			/*video::IImage *oldbaseimg = baseimg;
			baseimg = driver->createImage(video::ECF_A8R8G8B8, dim);
			oldbaseimg->copyTo(baseimg);
			oldbaseimg->drop();*/

			// Set alpha to full
			for(u32 y=0; y<dim.Height; y++)
			for(u32 x=0; x<dim.Width; x++)
			{
				video::SColor c = baseimg->getPixel(x,y);
				u32 r = c.getRed();
				u32 g = c.getGreen();
				u32 b = c.getBlue();
				if(!(r == r1 && g == g1 && b == b1))
					continue;
				c.setAlpha(0);
				baseimg->setPixel(x,y,c);
			}
		}
		/*
			[inventorycube{topimage{leftimage{rightimage
			In every subimage, replace ^ with &.
			Create an "inventory cube".
			NOTE: This should be used only on its own.
			Example (a grass block (not actually used in game):
			"[inventorycube{grass.png{mud.png&grass_side.png{mud.png&grass_side.png"
		*/
		else if(part_of_name.substr(0,14) == "[inventorycube")
		{
			if(baseimg != NULL)
			{
				errorstream<<"generate_image(): baseimg!=NULL "
						<<"for part_of_name=\""<<part_of_name
						<<"\", cancelling."<<std::endl;
				return false;
			}

			str_replace_char(part_of_name, '&', '^');
			Strfnd sf(part_of_name);
			sf.next("{");
			std::string imagename_top = sf.next("{");
			std::string imagename_left = sf.next("{");
			std::string imagename_right = sf.next("{");

			// Generate images for the faces of the cube
			video::IImage *img_top = generate_image_from_scratch(
					imagename_top, device, sourcecache);
			video::IImage *img_left = generate_image_from_scratch(
					imagename_left, device, sourcecache);
			video::IImage *img_right = generate_image_from_scratch(
					imagename_right, device, sourcecache);
			assert(img_top && img_left && img_right);

			// Create textures from images
			video::ITexture *texture_top = driver->addTexture(
					(imagename_top + "__temp__").c_str(), img_top);
			video::ITexture *texture_left = driver->addTexture(
					(imagename_left + "__temp__").c_str(), img_left);
			video::ITexture *texture_right = driver->addTexture(
					(imagename_right + "__temp__").c_str(), img_right);
			assert(texture_top && texture_left && texture_right);

			// Drop images
			img_top->drop();
			img_left->drop();
			img_right->drop();
			
			/*
				Draw a cube mesh into a render target texture
			*/
			scene::IMesh* cube = createCubeMesh(v3f(1, 1, 1));
			setMeshColor(cube, video::SColor(255, 255, 255, 255));
			cube->getMeshBuffer(0)->getMaterial().setTexture(0, texture_top);
			cube->getMeshBuffer(1)->getMaterial().setTexture(0, texture_top);
			cube->getMeshBuffer(2)->getMaterial().setTexture(0, texture_right);
			cube->getMeshBuffer(3)->getMaterial().setTexture(0, texture_right);
			cube->getMeshBuffer(4)->getMaterial().setTexture(0, texture_left);
			cube->getMeshBuffer(5)->getMaterial().setTexture(0, texture_left);

			core::dimension2d<u32> dim(64,64);
			std::string rtt_texture_name = part_of_name + "_RTT";

			v3f camera_position(0, 1.0, -1.5);
			camera_position.rotateXZBy(45);
			v3f camera_lookat(0, 0, 0);
			core::CMatrix4<f32> camera_projection_matrix;
			// Set orthogonal projection
			camera_projection_matrix.buildProjectionMatrixOrthoLH(
					1.65, 1.65, 0, 100);

			video::SColorf ambient_light(0.2,0.2,0.2);
			v3f light_position(10, 100, -50);
			video::SColorf light_color(0.5,0.5,0.5);
			f32 light_radius = 1000;

			video::ITexture *rtt = generateTextureFromMesh(
					cube, device, dim, rtt_texture_name,
					camera_position,
					camera_lookat,
					camera_projection_matrix,
					ambient_light,
					light_position,
					light_color,
					light_radius);
			
			// Drop mesh
			cube->drop();

			// Free textures of images
			driver->removeTexture(texture_top);
			driver->removeTexture(texture_left);
			driver->removeTexture(texture_right);
			
			if(rtt == NULL)
			{
				baseimg = generate_image_from_scratch(
						imagename_top, device, sourcecache);
				return true;
			}

			// Create image of render target
			video::IImage *image = driver->createImage(rtt, v2s32(0,0), dim);
			assert(image);

			baseimg = driver->createImage(video::ECF_A8R8G8B8, dim);

			if(image)
			{
				image->copyTo(baseimg);
				image->drop();
			}
		}
		else
		{
			errorstream<<"generate_image(): Invalid "
					" modification: \""<<part_of_name<<"\""<<std::endl;
		}
	}

	return true;
}
Ejemplo n.º 6
0
int main(int argc, char **args)
{
  const char *ctm_filepath = (argc > 1) ? args[1] : "teapot.ctm";

	trackback_state_initialize(camera_rotation);
	trackback_state_initialize(light_rotation);
	current_trackball_state = &camera_rotation;

  if (!glfwInit()) {
    std::cerr << "Failed to initialize GLFW" << std::endl;
    exit(EXIT_FAILURE);
  }

  int depth_bits = 16;
  if (!glfwOpenWindow(640, 480, 0, 0, 0, 0, depth_bits, 0, GLFW_WINDOW)) {
    std::cerr << "Failed to open GLFW window" << std::endl;
    glfwTerminate();
    exit(EXIT_FAILURE);
  }
  glfwGetWindowSize(&screen_width, &screen_height);
  glfwSetWindowSizeCallback(resize);
  glfwSetKeyCallback(keyboard);
  glfwSetMouseButtonCallback(mouse);
  glfwSetMousePosCallback(motion);
  glfwSetWindowTitle("Spinning Teapot");
  glfwEnable(GLFW_STICKY_KEYS);
  glfwSwapInterval(1);

	// Shaders
	shader_program_t phong_shader;
	build_shader_program(phong_shader, "phong.vs", "phong.fs");
	shader_program_t rect_shader;
	build_shader_program(rect_shader, "rect.vs", "rect.fs");
	shader_program_t render_buffer_shader;
	build_shader_program(render_buffer_shader, "render_buffer.vs", "render_buffer.fs");
	shader_program_t bump_shader;
	build_shader_program(bump_shader, "bump.vs", "bump.fs");

	//--- Mesh Objects
	mesh_t mesh_floor;
	load_mesh_cube(mesh_floor);
  mesh_object_t floor;
  if (! build_mesh_object(mesh_floor, floor) ) {
    glfwTerminate();
    exit(EXIT_FAILURE);	
	}

	mesh_t mesh_plane;
	load_mesh_plane(mesh_plane);
  mesh_object_t plane;
  if (! build_mesh_object(mesh_plane, plane) ) {
    glfwTerminate();
    exit(EXIT_FAILURE);	
	}

	mesh_t mesh_teapot;
	if (! load_mesh_from_file(ctm_filepath, mesh_teapot) ) {
	  glfwTerminate();
    exit(EXIT_FAILURE);		
	}
	compute_tangent_vectors(mesh_teapot);
  mesh_object_t teapot;
  if (! build_mesh_object(mesh_teapot, teapot) ) {
	  glfwTerminate();
    exit(EXIT_FAILURE);
	}

  //--- Texture
	const char *texture_filepath = "checker.tga";
	texture_t tex;
	tex.unit_id = 1;
	if (! build_texutre_from_file(texture_filepath, tex)) {
		std::cout << "Failed to load texture: " << texture_filepath << std::endl;
	  glfwTerminate();
	  exit(EXIT_FAILURE);		
	}

	//--- FBO
	texture_t depth_tex_buffer;
	int depth_tex_width = 2 * screen_width;
	int depth_tex_height = 2 * screen_height;
	depth_tex_buffer.unit_id = 2;
	GLuint fb_handle;
	create_framebuffer_and_depth_texture(depth_tex_width, depth_tex_height, depth_tex_buffer, &fb_handle);

	// Scene settings
  glm::vec3 camera_position(0.0f, 0.0f, 5.0f);
  glm::vec3 camera_center(0.0f, 0.0f, 0.0f);
  glm::vec3 camera_up(0.0f, 1.0f, 0.0f);
  glm::mat4 view_matrix = glm::lookAt(camera_position, camera_center, camera_up); // from world to camera

	glm::mat4 light_pov_matrix;	
	glm::mat4 bias(
		0.5f, 0.0f, 0.0f, 0.0f,
		0.0f, 0.5f, 0.0f, 0.0f,
		0.0f, 0.0f, 0.5f, 0.0f,
		0.5f, 0.5f, 0.5f, 1.0f
		);

	teapot.material.diffuse = glm::vec3(0.0f, 1.0f, 1.0f);
	teapot.material.specular = glm::vec3(0.8f);
	teapot.material.shininess = 128.0f;	
	teapot.textures.push_back(tex);	
	teapot.textures.push_back(depth_tex_buffer);
	
	floor.material.diffuse = glm::vec3(1.0f, 1.0f, 1.0f);
	floor.material.specular = glm::vec3(0.8f);
	floor.material.shininess = 2.0f;
	floor.textures.push_back(depth_tex_buffer);
	
	plane.textures.push_back(depth_tex_buffer);

	glEnable(GL_TEXTURE_2D);
	glEnable(GL_DEPTH_TEST);
	glEnable(GL_CULL_FACE);

  do {
		//--- Transform
		glm::vec3 light_position = glm::mat3_cast(light_rotation.orientation) * glm::vec3(0.0f, 5.0f, 0.0f);
		glm::vec3 light_center(0.0f, 0.0f, 0.0f);
		glm::vec3 light_up(0.0f, 0.0f, 1.0f);
		glm::mat4 light_view_matrix = glm::lookAt(light_position, light_center, light_up);
		
		teapot.matrix = glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, 0.5f, 0.0f));
		floor.matrix = glm::scale(glm::mat4(1.0f), glm::vec3(2.0f, 0.05f, 2.0f));
		plane.matrix = glm::scale(glm::mat4(1.0f), glm::vec3(screen_width, screen_height, 1.0f));
		
		//--- Render
		glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fb_handle);
		{
	    __projection_matrix = glm::perspective(30.0f, (float) screen_width / (float) screen_height, 0.5f, 30.0f);
			__view_matrix = light_view_matrix;
			light_pov_matrix = bias * __projection_matrix * light_view_matrix;
			
			glClear(GL_DEPTH_BUFFER_BIT);
			glClearDepth(1.0f);
			glViewport(0, 0, depth_tex_width, depth_tex_height);
			teapot.shader_program = &render_buffer_shader;
			teapot.shader_program->bind();
			render_object(teapot);
			teapot.shader_program->release();
			floor.shader_program = &render_buffer_shader;
			floor.shader_program->bind();
    	render_object(floor);
			floor.shader_program->release();		
		}
		glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);		
	
#ifdef DEPTH_BUFFER_DEBUG
		{
			__projection_matrix = glm::ortho(0.0f, (float)screen_width, 0.0f, (float)screen_height, 0.5f, 1.0f);
			__view_matrix = glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, 0.0f, -1.0f));
			
			glDisable(GL_DEPTH_TEST);
			glClear(GL_COLOR_BUFFER_BIT);		
    	glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
    	glViewport(0, 0, screen_width, screen_height);	
			plane.shader_program = &rect_shader;
			plane.shader_program->bind();	
			plane.shader_program->set_uniform_value("texture2", depth_tex_buffer.unit_id); 
	  	render_object(plane);
			plane.shader_program->release();
			glEnable(GL_DEPTH_TEST);
		}
#endif

#ifndef DEPTH_BUFFER_DEBUG
		{			
			glCullFace(GL_BACK);
			glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
			glClearDepth(1.0f);
			glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
			glViewport(0, 0, screen_width, screen_height);

	    __projection_matrix = glm::perspective(camera_fovy, (float) screen_width / (float) screen_height, 1.0f, 30.0f);
			__view_matrix = view_matrix * glm::mat4_cast(camera_rotation.orientation);

#ifdef USE_BUMP_MAPPING
			teapot.shader_program = &bump_shader;
			teapot.shader_program->bind();		
			teapot.shader_program->set_uniform_value("light_world_position", light_position);
			teapot.shader_program->set_uniform_value("surface_color", glm::vec3(0.7f, 0.6f, 0.18f));
			teapot.shader_program->set_uniform_value("bump_density", 16.0f);
			teapot.shader_program->set_uniform_value("bump_size", 0.15f);
			teapot.shader_program->set_uniform_value("specular_factor", 0.5f);
			render_object(teapot);
			teapot.shader_program->release();
#else
			teapot.shader_program = &phong_shader;
			teapot.shader_program->bind();		
			teapot.shader_program->set_uniform_value("light_world_position", light_position);
			teapot.shader_program->set_uniform_value("light_pov_matrix", light_pov_matrix);
			teapot.shader_program->set_uniform_value("texture1", tex.unit_id); 
			teapot.shader_program->set_uniform_value("texture2", depth_tex_buffer.unit_id); 
			render_object(teapot);
			teapot.shader_program->release();
#endif

			floor.shader_program = &phong_shader;
			floor.shader_program->bind();	
			floor.shader_program->set_uniform_value("light_world_position", light_position);
			floor.shader_program->set_uniform_value("light_pov_matrix", light_pov_matrix);
			floor.shader_program->set_uniform_value("texture2", depth_tex_buffer.unit_id); 
	    render_object(floor);
			floor.shader_program->release();	
		}
#endif

    glfwSwapBuffers();

  }
  while (glfwGetKey(GLFW_KEY_ESC) != GLFW_PRESS && glfwGetWindowParam(GLFW_OPENED));

  glfwTerminate();

  return 0;
}
Ejemplo n.º 7
0
    ClientCached* createClientCachedDirect(const std::string &name,
                                           IGameDef *gamedef) const
    {
        infostream<<"Lazily creating item texture and mesh for \""
                  <<name<<"\""<<std::endl;

        // This is not thread-safe
        assert(get_current_thread_id() == m_main_thread);

        // Skip if already in cache
        ClientCached *cc = NULL;
        m_clientcached.get(name, &cc);
        if(cc)
            return cc;

        ITextureSource *tsrc = gamedef->getTextureSource();
        INodeDefManager *nodedef = gamedef->getNodeDefManager();
        IrrlichtDevice *device = tsrc->getDevice();
        video::IVideoDriver *driver = device->getVideoDriver();
        const ItemDefinition *def = &get(name);

        // Create new ClientCached
        cc = new ClientCached();

        bool need_node_mesh = false;

        // Create an inventory texture
        cc->inventory_texture = NULL;
        if(def->inventory_image != "")
        {
            cc->inventory_texture = tsrc->getTextureRaw(def->inventory_image);
        }
        else if(def->type == ITEM_NODE)
        {
            need_node_mesh = true;
        }

        // Create a wield mesh
        assert(cc->wield_mesh == NULL);
        if(def->type == ITEM_NODE && def->wield_image == "")
        {
            need_node_mesh = true;
        }
        else if(def->wield_image != "" || def->inventory_image != "")
        {
            // Extrude the wield image into a mesh

            std::string imagename;
            if(def->wield_image != "")
                imagename = def->wield_image;
            else
                imagename = def->inventory_image;

            cc->wield_mesh = createExtrudedMesh(
                                 tsrc->getTextureRaw(imagename),
                                 driver,
                                 def->wield_scale * v3f(40.0, 40.0, 4.0));
            if(cc->wield_mesh == NULL)
            {
                infostream<<"ItemDefManager: WARNING: "
                          <<"updateTexturesAndMeshes(): "
                          <<"Unable to create extruded mesh for item "
                          <<def->name<<std::endl;
            }
        }

        if(need_node_mesh)
        {
            /*
            	Get node properties
            */
            content_t id = nodedef->getId(def->name);
            const ContentFeatures &f = nodedef->get(id);

            u8 param1 = 0;
            if(f.param_type == CPT_LIGHT)
                param1 = 0xee;

            /*
            	Make a mesh from the node
            */
            MeshMakeData mesh_make_data(gamedef);
            MapNode mesh_make_node(id, param1, 0);
            mesh_make_data.fillSingleNode(&mesh_make_node);
            MapBlockMesh mapblock_mesh(&mesh_make_data);

            scene::IMesh *node_mesh = mapblock_mesh.getMesh();
            assert(node_mesh);
            video::SColor c(255, 255, 255, 255);
            if(g_settings->getS32("enable_shaders") != 0)
                c = MapBlock_LightColor(255, 0xffff, decode_light(f.light_source));
            setMeshColor(node_mesh, c);

            /*
            	Scale and translate the mesh so it's a unit cube
            	centered on the origin
            */
            scaleMesh(node_mesh, v3f(1.0/BS, 1.0/BS, 1.0/BS));
            translateMesh(node_mesh, v3f(-1.0, -1.0, -1.0));

            /*
            	Draw node mesh into a render target texture
            */
            if(cc->inventory_texture == NULL)
            {
                core::dimension2d<u32> dim(64,64);
                std::string rtt_texture_name = "INVENTORY_"
                                               + def->name + "_RTT";
                v3f camera_position(0, 1.0, -1.5);
                camera_position.rotateXZBy(45);
                v3f camera_lookat(0, 0, 0);
                core::CMatrix4<f32> camera_projection_matrix;
                // Set orthogonal projection
                camera_projection_matrix.buildProjectionMatrixOrthoLH(
                    1.65, 1.65, 0, 100);

                video::SColorf ambient_light(0.2,0.2,0.2);
                v3f light_position(10, 100, -50);
                video::SColorf light_color(0.5,0.5,0.5);
                f32 light_radius = 1000;

                cc->inventory_texture = generateTextureFromMesh(
                                            node_mesh, device, dim, rtt_texture_name,
                                            camera_position,
                                            camera_lookat,
                                            camera_projection_matrix,
                                            ambient_light,
                                            light_position,
                                            light_color,
                                            light_radius);

                // render-to-target didn't work
                if(cc->inventory_texture == NULL)
                {
                    cc->inventory_texture =
                        tsrc->getTextureRaw(f.tiledef[0].name);
                }
            }
            else
            {
                if (m_driver == 0)
                    m_driver = driver;

                m_extruded_textures.push_back(cc->inventory_texture);
            }

            /*
            	Use the node mesh as the wield mesh
            */

            // Scale to proper wield mesh proportions
            scaleMesh(node_mesh, v3f(30.0, 30.0, 30.0)
                      * def->wield_scale);

            cc->wield_mesh = node_mesh;
            cc->wield_mesh->grab();

            //no way reference count can be smaller than 2 in this place!
            assert(cc->wield_mesh->getReferenceCount() >= 2);
        }

        // Put in cache
        m_clientcached.set(name, cc);

        return cc;
    }
Ejemplo n.º 8
0
std::shared_ptr<Texture> RenderPass::
get_buffer(std::string const& name, CameraMode mode, bool draw_fps) {

    // check for existance of desired buffer
    if ((mode == CENTER
            && center_eye_buffers_.find(name) == center_eye_buffers_.end())
     || (mode == LEFT
            && left_eye_buffers_.find(name)  == left_eye_buffers_.end())
     || (mode == RIGHT
            && right_eye_buffers_.find(name) == right_eye_buffers_.end())) {

        WARNING("Failed to get buffer \"%s\" from pass \"%s\": "
                "A buffer with this name does not exist!",
                name.c_str(), get_name().c_str());
        return NULL;
    }

    // return appropriate buffer if it has been rendered already
    if (mode == CENTER && rendererd_center_eye_)
        return center_eye_buffers_[name];

    if (mode == LEFT && rendererd_left_eye_)
        return left_eye_buffers_[name];

    if (mode == RIGHT && rendererd_right_eye_)
        return right_eye_buffers_[name];

    // serialize the scenegraph
    Optimizer optimizer;
    optimizer.check(pipeline_->get_current_graph(), render_mask_);

    // if there are dynamic texture inputs for this render pass, get the
    // according buffers recursively
    for (auto& node: optimizer.get_data().nodes_) {
        auto material(inputs_.find(node.material_));

        if (material != inputs_.end()) {
            for (auto& uniform: material->second) {
                overwrite_uniform_texture(material->first, uniform.first,
                              pipeline_->get_render_pass(uniform.second.first)->
                              get_buffer(uniform.second.second, mode));
            }
        }
    }
    // we'll need these two very often now...
    OptimizedScene const& scene(optimizer.get_data());
    RenderContext const& ctx(pipeline_->get_context());

    // get the fbo which should be rendered to
    FrameBufferObject* fbo(NULL);

    switch (mode) {
        case CENTER:
            fbo = &center_eye_fbo_;
            break;
        case LEFT:
            fbo = &left_eye_fbo_;
            break;
        case RIGHT:
            fbo = &right_eye_fbo_;
            break;
    }

    fbo->bind(ctx);

    fbo->clear_color_buffers(ctx);
    fbo->clear_depth_stencil_buffer(ctx);

    ctx.render_context->set_viewport(scm::gl::viewport(math::vec2(0,0),
                                                    math::vec2(fbo->width(),
                                                               fbo->height())));

    auto camera_it(scene.cameras_.find(camera_));
    auto screen_it(scene.screens_.find(screen_));

    if (camera_it != scene.cameras_.end()
        && screen_it != scene.screens_.end()) {

        auto camera(camera_it->second);
        auto screen(screen_it->second);

        math::mat4 camera_transform(camera.transform_);
        if (mode == LEFT) {
            scm::math::translate(camera_transform,
                                 -camera.stereo_width_*0.5f, 0.f, 0.f);
        } else if (mode == RIGHT) {
            scm::math::translate(camera_transform,
                                 camera.stereo_width_*0.5f, 0.f, 0.f);
        }

        auto projection(math::compute_frustum(camera_transform.column(3),
                                              screen.transform_,
                                              0.1, 100000.f));

        math::mat4 view_transform(screen.transform_);
        view_transform[12] = 0.f;
        view_transform[13] = 0.f;
        view_transform[14] = 0.f;
        view_transform[15] = 1.f;

        math::vec3 camera_position(camera_transform.column(3)[0],
                                   camera_transform.column(3)[1],
                                   camera_transform.column(3)[2]);

        view_transform = scm::math::make_translation(camera_position)
                         * view_transform;

        math::mat4 view_matrix(scm::math::inverse(view_transform));

        // update light data uniform block
        if (scene.lights_.size() > 0) {

            if (!light_information_) {
                light_information_ =
                new scm::gl::uniform_block<LightInformation>(ctx.render_device);
            }

            light_information_->begin_manipulation(ctx.render_context);

            LightInformation light;

            light.light_count = math::vec4i(scene.lights_.size(),
                                            scene.lights_.size(),
                                            scene.lights_.size(),
                                            scene.lights_.size());

            for (unsigned i(0); i < scene.lights_.size(); ++i) {

                math::mat4 transform(scene.lights_[i].transform_);

                // calc light radius and position
                light.position[i] = math::vec4(transform[12], transform[13],
                                               transform[14], transform[15]);
                float radius = scm::math::length(light.position[i] - transform
                                              * math::vec4(0.f, 0.f, 1.f, 1.f));

                light.color_radius[i] = math::vec4(scene.lights_[i].color_.r(),
                                                   scene.lights_[i].color_.g(),
                                                   scene.lights_[i].color_.b(),
                                                   radius);
            }

            **light_information_ = light;

            light_information_->end_manipulation();

            ctx.render_context->bind_uniform_buffer(
                                         light_information_->block_buffer(), 0);
        }

        for (auto& core: scene.nodes_) {

            auto geometry = GeometryBase::instance()->get(core.geometry_);
            auto material = MaterialBase::instance()->get(core.material_);

            if (material && geometry) {
                material->use(ctx);

                if (float_uniforms_.find(core.material_)
                    != float_uniforms_.end())  {

                    for (auto val : float_uniforms_[core.material_])
                        material->get_shader()->set_float(ctx, val.first,
                                                          val.second);
                }

                if (texture_uniforms_.find(core.material_)
                    != texture_uniforms_.end()) {

                    for (auto val : texture_uniforms_[core.material_])
                        material->get_shader()->set_sampler2D(ctx, val.first,
                                                              *val.second);
                }

                material->get_shader()->set_mat4(ctx, "projection_matrix",
                                                 projection);

                material->get_shader()->set_mat4(ctx, "view_matrix",
                                                 view_matrix);

                material->get_shader()->set_mat4(ctx, "model_matrix",
                                                 core.transform_);

                material->get_shader()->set_mat4(ctx, "normal_matrix",
                                          scm::math::transpose(
                                          scm::math::inverse(core.transform_)));

                geometry->draw(ctx);

                material->unuse(ctx);

            } else if (material) {
                WARNING("Cannot render geometry \"%s\": Undefined geometry "
                        "name!", core.geometry_.c_str());

            } else if (geometry) {
                WARNING("Cannot render geometry \"%s\": Undefined material "
                        "name: \"%s\"!", core.geometry_.c_str(),
                        core.material_.c_str());

            } else {
                WARNING("Cannot render geometry \"%s\": Undefined geometry "
                        "and material name: \"%s\"!", core.geometry_.c_str(),
                        core.material_.c_str());
            }
        }

        if (scene.lights_.size() > 0) {
            ctx.render_context->reset_uniform_buffers();
        }
    }

    fbo->unbind(ctx);

    // draw fps on the screen
    if (draw_fps) {
        if (!text_renderer_)
            text_renderer_ = new TextRenderer(pipeline_->get_context());

        if (mode == CENTER) {
            text_renderer_->render_fps(pipeline_->get_context(), center_eye_fbo_,
                                       pipeline_->get_application_fps(),
                                       pipeline_->get_rendering_fps());
        } else if (mode == LEFT) {
            text_renderer_->render_fps(pipeline_->get_context(), left_eye_fbo_,
                                       pipeline_->get_application_fps(),
                                       pipeline_->get_rendering_fps());
        } else {
            text_renderer_->render_fps(pipeline_->get_context(), right_eye_fbo_,
                                       pipeline_->get_application_fps(),
                                       pipeline_->get_rendering_fps());
        }
    }

    // return the buffer and set the already-rendered-flag
    if (mode == CENTER) {
        rendererd_center_eye_ = true;
        return center_eye_buffers_[name];
    } else if (mode == LEFT) {
        rendererd_left_eye_ = true;
        return left_eye_buffers_[name];
    } else {
        rendererd_right_eye_ = true;
        return right_eye_buffers_[name];
    }
}
Ejemplo n.º 9
0
int main(int argc, char **args)
{
  if (!glfwInit()) {
    std::cerr << "Failed to initialize GLFW" << std::endl;
    exit(EXIT_FAILURE);
  }

  int depth_bits = 16;
  if (!glfwOpenWindow(640, 480, 0, 0, 0, 0, depth_bits, 0, GLFW_WINDOW)) {
    std::cerr << "Failed to open GLFW window" << std::endl;
    glfwTerminate();
    exit(EXIT_FAILURE);
  }
  glfwGetWindowSize(&screen_width, &screen_height);
  glfwSetWindowTitle("Teapot");
  glfwEnable(GLFW_STICKY_KEYS);
  glfwSwapInterval(1);

	shader_program_t shader_program;
	shader_program_t::build(shader_program, "diffuse.vs", "diffuse.fs");

	mesh_t teapot;
	if (! mesh_t::read_from_file("teapot.ctm", teapot)) {
		std::cerr << "Failed to read ctm file" << std::endl;
	  glfwTerminate();
    exit(EXIT_FAILURE);		
	}
	teapot.load_to_buffers();
	
	projection_matrix = glm::perspective(camera_fovy, (float) screen_width / (float) screen_height, 1.0f, 30.0f);

  glm::vec3 camera_position(0.0f, 0.0f, 3.0f);
  glm::vec3 camera_center(0.0f, 0.0f, 0.0f);
  glm::vec3 camera_up(0.0f, 1.0f, 0.0f);
  view_matrix = glm::lookAt(camera_position, camera_center, camera_up); // from world to camera

	normal_matrix = glm::mat3(glm::transpose(glm::inverse(view_matrix)));

	light_direction = glm::vec3(0.0, -1.0, 0.0);

	glEnable(GL_TEXTURE_2D);
	glEnable(GL_DEPTH_TEST);
	glEnable(GL_CULL_FACE);

  do {
		
		{			
			glCullFace(GL_BACK);
			glClearColor(0.3f, 0.3f, 0.3f, 1.0f);
			glClearDepth(1.0f);
			glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
			glViewport(0, 0, screen_width, screen_height);

			shader_program.bind();
			shader_program.set_uniform_value("light_direction", light_direction);
			shader_program.set_uniform_value("projection_matrix", projection_matrix);
			shader_program.set_uniform_value("model_view_matrix", view_matrix);
			shader_program.set_uniform_value("normal_matrix", normal_matrix);
			teapot.render(shader_program);
			shader_program.release();
		}

    glfwSwapBuffers();

  }
  while (glfwGetKey(GLFW_KEY_ESC) != GLFW_PRESS && glfwGetWindowParam(GLFW_OPENED));

  glfwTerminate();

  return 0;
}