void ParticleFactory::CreateExplosionParticleGeometry(Ogre::String object_name, int num_particles){

		/* Retrieve scene manager and root scene node */
        //Ogre::SceneManager* scene_manager = ogre_root_->getSceneManager("MySceneManager");
        Ogre::SceneNode* root_scene_node = scene_manager->getRootSceneNode();

        /* Create the 3D object */
        Ogre::ManualObject* object = NULL;
        object = scene_manager->createManualObject(object_name);
        object->setDynamic(false);

        /* Create point list for the object */
		object->begin("", Ogre::RenderOperation::OT_POINT_LIST);

		/* Initialize random numbers */
		std::srand(std::time(0));

		/* Create a set of points which will be the particles */
		/* This is similar to drawing a sphere: we will sample points on a sphere, but will allow them to also
		   deviate a bit from the sphere along the normal (change of radius) */
		float trad = 0.04; // Defines the starting point of the particles
        float maxspray = 0.01; // This is how much we allow the points to deviate from the sphere
		float u, v, w, theta, phi, spray; // Work variables
		for (int i = 0; i < num_particles; i++){
			
			// Randomly select three numbers to define a point in spherical coordinates
			u = ((double) rand() / (RAND_MAX));
            v = ((double) rand() / (RAND_MAX));
            w = ((double) rand() / (RAND_MAX));

			// Use u to define the angle theta along one direction of a sphere
            theta = u * 2.0 * 3.1416;
			// Use v to define the angle phi along the other direction of the sphere
			phi = acos(2.0*v - 1.0);
			// Use we to define how much we can deviate from the surface of the sphere (change of radius)
            spray = maxspray*pow((float) w, (float) (1.0/3.0)); // Cubic root of w

			// Define the normal and point based on theta, phi and the spray
            Ogre::Vector3 normal = Ogre::Vector3(spray*cos(theta)*sin(phi), spray*sin(theta)*sin(phi), spray*cos(phi));
			object->position(normal.x*trad, normal.y*trad, normal.z*trad);
			object->normal(normal);
			object->colour(Ogre::ColourValue(i/(float) num_particles, 0.0, 1.0 - (i/(float) num_particles))); // We can use the color for debug, if needed
		}
		
		/* We finished the object */
        object->end();
		
        /* Convert triangle list to a mesh */
        object->convertToMesh(object_name);

}
Exemplo n.º 2
0
Ogre::String GameBuildingSystem::BuildBuildings( Ogre::SceneManager *sceneMan, GameRoadGraphAreaTreeNode *roadRoot )
{
  Ogre::ManualObject *manObject = NULL;
  Ogre::String manObjectName    = "Buildings";
  manObject = sceneMan->createManualObject( manObjectName );
  manObject->setDynamic( false );
  
  BuildToArea( roadRoot, manObject );

  manObject->setCastShadows( true );

  sceneMan->getRootSceneNode()->createChildSceneNode()->attachObject( manObject );
  return manObjectName;
}
Exemplo n.º 3
0
void
	Player::createHitBox(std::string name)
{
	Ogre::ManualObject* myManualObject =  mSceneManager->createManualObject(name); 
	myManualObject->setDynamic(true);
	Ogre::SceneNode* myManualObjectNode = mSceneManager->getRootSceneNode()->createChildSceneNode(name + "_node"); 

	Ogre::MaterialPtr myManualObjectMaterial = Ogre::MaterialManager::getSingleton().create(name + "Material","General"); 
	myManualObjectMaterial->setReceiveShadows(false); 
	myManualObjectMaterial->getTechnique(0)->setLightingEnabled(true);
	myManualObjectMaterial->getTechnique(0)->getPass(0)->setDiffuse(1,0,0,0); 
	myManualObjectMaterial->getTechnique(0)->getPass(0)->setAmbient(1,0,0); 
	myManualObjectMaterial->getTechnique(0)->getPass(0)->setSelfIllumination(1,0,0);

	myManualObjectNode->attachObject(myManualObject);
}
Ogre::ManualObject * CCone::CreateCone(Ogre::Real Intensity)
{
	Ogre::ManualObject *Cone = NULL;
	Ogre::SceneManager *SceneManager = Ogre::Root::getSingleton().getSceneManager("DynamicEffects");
	Cone = SceneManager->createManualObject("Cone");
	Cone->setDynamic(false);
    Cone->begin("BaseWhiteNoLighting", Ogre::RenderOperation::OT_TRIANGLE_LIST);

	Ogre::Real deltaAngle = (Ogre::Math::TWO_PI / m_BaseSegments);
	Ogre::Real deltaHeight = m_Height/(Ogre::Real)m_HeightSegments;
	
	Ogre::Vector3 Normal = Ogre::Vector3(m_Radius, m_Height, 0.f).normalisedCopy();
	Ogre::Quaternion Quaternion;
	
	int Offset = 0;

	for (int HeightSegmentIndex = 0; HeightSegmentIndex <= m_HeightSegments; HeightSegmentIndex++)
	{
		Ogre::Real Radius = m_Radius * (1 - HeightSegmentIndex / (Ogre::Real)m_HeightSegments);
		
		for (int BaseSegmentIndex = 0; BaseSegmentIndex <= m_BaseSegments; BaseSegmentIndex++)
		{
			Ogre::Real x = Radius* cosf(BaseSegmentIndex * deltaAngle);
			Ogre::Real z = Radius * sinf(BaseSegmentIndex * deltaAngle);
			Cone->position(x, HeightSegmentIndex * deltaHeight, z);
			
			Cone->colour(Intensity, Intensity, 0.0, 1.0);
			Quaternion.FromAngleAxis(Ogre::Radian(-BaseSegmentIndex*deltaAngle), Ogre::Vector3::NEGATIVE_UNIT_Y);
			Cone->normal(Quaternion * Normal);
			Cone->textureCoord(BaseSegmentIndex / (Ogre::Real)m_BaseSegments, HeightSegmentIndex / (Ogre::Real)m_HeightSegments);

			if (HeightSegmentIndex != m_HeightSegments && BaseSegmentIndex != m_BaseSegments)
			{
				Cone->index(Offset + m_BaseSegments + 2);
				Cone->index(Offset);
				Cone->index(Offset + m_BaseSegments + 1);
				Cone->index(Offset + m_BaseSegments + 2);
				Cone->index(Offset + 1);
				Cone->index(Offset);
			}

			Offset++;
		}
	}

	int centerIndex = Offset;
	
	Cone->position(0,0,0);
	Cone->normal(Ogre::Vector3::NEGATIVE_UNIT_Y);
	Cone->textureCoord(0.0,1);
	Offset++;
	
	for (int BaseSegmentIndex=0; BaseSegmentIndex <= m_BaseSegments; BaseSegmentIndex++)
	{
		Ogre::Real x = m_Radius * cosf(BaseSegmentIndex*deltaAngle);
		Ogre::Real z = m_Radius * sinf(BaseSegmentIndex*deltaAngle);

		Cone->position(x, 0.0f, z);
		Cone->colour(Intensity, Intensity, 0.0, 0.0);
		Cone->normal(Ogre::Vector3::NEGATIVE_UNIT_Y);
		Cone->textureCoord(BaseSegmentIndex/(Ogre::Real)m_BaseSegments,0.0);
		if (BaseSegmentIndex != m_BaseSegments)
		{
			Cone->index(centerIndex);
			Cone->index(Offset);
			Cone->index(Offset+1);
		}
		Offset++;
	}

	Cone->end();

	return Cone;
}
int DecalManager::addTerrainDecal(Ogre::Vector3 position, Ogre::Vector2 size, Ogre::Vector2 numSeg, Ogre::Real rotation, Ogre::String materialname, Ogre::String normalname)
{
#if 0
	Ogre::ManualObject *mo = gEnv->ogreSceneManager->createManualObject();
	String oname = mo->getName();
	SceneNode *mo_node = terrain_decals_snode->createChildSceneNode();

	mo->begin(materialname, Ogre::RenderOperation::OT_TRIANGLE_LIST);
	AxisAlignedBox *aab=new AxisAlignedBox();
	float uTile = 1, vTile = 1;

	Vector3 normal = Vector3(0,1,0); // UP
	
	int offset = 0;
	float ground_dist = 0.001f;

	Ogre::Vector3 vX = normal.perpendicular();
	Ogre::Vector3 vY = normal.crossProduct(vX);
	Ogre::Vector3 delta1 = size.x / numSeg.x * vX;
	Ogre::Vector3 delta2 = size.y / numSeg.y * vY;
	// build one corner of the square
	Ogre::Vector3 orig = -0.5*size.x*vX - 0.5*size.y*vY;

	for (int i1 = 0; i1<=numSeg.x; i1++)
		for (int i2 = 0; i2<=numSeg.y; i2++)
		{
			Vector3 pos = orig+i1*delta1+i2*delta2 + position;
			pos.y = hfinder->getHeightAt(pos.x, pos.z) + ground_dist;
			mo->position(pos);
			aab->merge(pos);
			mo->textureCoord(i1/(Ogre::Real)numSeg.x*uTile, i2/(Ogre::Real)numSeg.y*vTile);
			mo->normal(normal);
		}

	bool reverse = false;
	if (delta1.crossProduct(delta2).dotProduct(normal)>0)
		reverse= true;
	for (int n1 = 0; n1<numSeg.x; n1++)
	{
		for (int n2 = 0; n2<numSeg.y; n2++)
		{
			if (reverse)
			{
				mo->index(offset+0);
				mo->index(offset+(numSeg.y+1));
				mo->index(offset+1);
				mo->index(offset+1);
				mo->index(offset+(numSeg.y+1));
				mo->index(offset+(numSeg.y+1)+1);
			}
			else
			{
				mo->index(offset+0);
				mo->index(offset+1);
				mo->index(offset+(numSeg.y+1));
				mo->index(offset+1);
				mo->index(offset+(numSeg.y+1)+1);
				mo->index(offset+(numSeg.y+1));
			}
			offset++;
		}
		offset++;
	}
	offset+=numSeg.y+1;

	mo->end();
	mo->setBoundingBox(*aab);
	// some optimizations
	mo->setCastShadows(false);
	mo->setDynamic(false);
	delete(aab);

	MeshPtr mesh = mo->convertToMesh(oname+"_mesh");

	// build edgelist
	mesh->buildEdgeList();

	// remove the manualobject again, since we dont need it anymore
	gEnv->ogreSceneManager->destroyManualObject(mo);

	unsigned short src, dest;
	if (!mesh->suggestTangentVectorBuildParams(VES_TANGENT, src, dest))
	{
		mesh->buildTangentVectors(VES_TANGENT, src, dest);
	}
	
	Entity *ent = gEnv->ogreSceneManager->createEntity(oname+"_ent", oname+"_mesh");
	mo_node->attachObject(ent);

	mo_node->setVisible(true);
	//mo_node->showBoundingBox(true);
	mo_node->setPosition(Vector3::ZERO); //(position.x, 0, position.z));


	// RTSS
	//Ogre::RTShader::ShaderGenerator::getSingleton().createShaderBasedTechnique(materialname, Ogre::MaterialManager::DEFAULT_SCHEME_NAME, Ogre::RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME);
	//Ogre::RTShader::ShaderGenerator::getSingleton().invalidateMaterial(RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME, materialname);
	RTSSgenerateShadersForMaterial(materialname, normalname);

#endif
	return 0;
}
int DecalManager::addTerrainSplineDecal(Ogre::SimpleSpline *spline, float width, Ogre::Vector2 numSeg, Ogre::Vector2 uvSeg, Ogre::String materialname, float ground_offset, Ogre::String export_fn, bool debug)
{
#if 0
	Ogre::ManualObject *mo = gEnv->ogreSceneManager->createManualObject();
	String oname = mo->getName();
	SceneNode *mo_node = terrain_decals_snode->createChildSceneNode();

	mo->begin(materialname, Ogre::RenderOperation::OT_TRIANGLE_LIST);
	AxisAlignedBox *aab=new AxisAlignedBox();

	int offset = 0;

	// how width is the road?
	float delta_width = width / numSeg.x;

	float steps_len = 1.0f / numSeg.x;

	for (int l = 0; l<=numSeg.x; l++)
	{
		// get current position on that spline
		Vector3 pos_cur  = spline->interpolate(steps_len * (float)l);
		Vector3 pos_next = spline->interpolate(steps_len * (float)(l + 1));
        Ogre::Vector3 direction = (pos_next - pos_cur);
		if (l == numSeg.x)
		{
			// last segment uses previous position
			pos_next = spline->interpolate(steps_len * (float)(l - 1));
			direction = (pos_cur - pos_next);
		}


		for (int w = 0; w<=numSeg.y; w++)
		{
			// build vector for the width
			Vector3 wn = direction.normalisedCopy().crossProduct(Vector3::UNIT_Y);
			
			// calculate the offset, spline in the middle
			Vector3 offset = (-0.5 * wn * width) + (w/numSeg.y) * wn * width;

			// push everything together
			Ogre::Vector3 pos = pos_cur + offset;
			// get ground height there
			pos.y = hfinder->getHeightAt(pos.x, pos.z) + ground_offset;

			// add the position to the mesh
			mo->position(pos);
			aab->merge(pos);
			mo->textureCoord(l/(Ogre::Real)numSeg.x*uvSeg.x, w/(Ogre::Real)numSeg.y*uvSeg.y);
			mo->normal(Vector3::UNIT_Y);
		}
	}

	bool reverse = false;
	for (int n1 = 0; n1<numSeg.x; n1++)
	{
		for (int n2 = 0; n2<numSeg.y; n2++)
		{
			if (reverse)
			{
				mo->index(offset+0);
				mo->index(offset+(numSeg.y+1));
				mo->index(offset+1);
				mo->index(offset+1);
				mo->index(offset+(numSeg.y+1));
				mo->index(offset+(numSeg.y+1)+1);
			}
			else
			{
				mo->index(offset+0);
				mo->index(offset+1);
				mo->index(offset+(numSeg.y+1));
				mo->index(offset+1);
				mo->index(offset+(numSeg.y+1)+1);
				mo->index(offset+(numSeg.y+1));
			}
			offset++;
		}
		offset++;
	}
	offset+=numSeg.y+1;

	mo->end();
	mo->setBoundingBox(*aab);
	// some optimizations
	mo->setCastShadows(false);
	mo->setDynamic(false);
	delete(aab);

	MeshPtr mesh = mo->convertToMesh(oname+"_mesh");

	// build edgelist
	mesh->buildEdgeList();

	// remove the manualobject again, since we dont need it anymore
	gEnv->ogreSceneManager->destroyManualObject(mo);

	unsigned short src, dest;
	if (!mesh->suggestTangentVectorBuildParams(VES_TANGENT, src, dest))
	{
		mesh->buildTangentVectors(VES_TANGENT, src, dest);
	}
	
	Entity *ent = gEnv->ogreSceneManager->createEntity(oname+"_ent", oname+"_mesh");
	mo_node->attachObject(ent);

	mo_node->setVisible(true);
	//mo_node->showBoundingBox(true);
	mo_node->setPosition(Vector3::ZERO); //(position.x, 0, position.z));


	if (!export_fn.empty())
	{
		MeshSerializer *ms = new MeshSerializer();
		ms->exportMesh(mesh.get(), export_fn);
		LOG("spline mesh exported as " + export_fn);
		delete(ms);
	}

	// TBD: RTSS
	//Ogre::RTShader::ShaderGenerator::getSingleton().createShaderBasedTechnique(materialname, Ogre::MaterialManager::DEFAULT_SCHEME_NAME, Ogre::RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME);
	//Ogre::RTShader::ShaderGenerator::getSingleton().invalidateMaterial(RTShader::ShaderGenerator::DEFAULT_SCHEME_NAME, materialname);
	RTSSgenerateShadersForMaterial(materialname, "");

#endif
	return 0;
}
void ParticleFactory::CreateThrusterParticleGeometry(Ogre::String object_name, int num_particles, float loop_radius, float circle_radius){

	//try {
		/* Retrieve scene manager and root scene node */
       // Ogre::SceneManager* scene_manager = ogre_root_->getSceneManager("MySceneManager");
        Ogre::SceneNode* root_scene_node = scene_manager->getRootSceneNode();

        /* Create the 3D object */
        Ogre::ManualObject* object = NULL;
        object = scene_manager->createManualObject(object_name);
        object->setDynamic(false);
/*
        /* Create point list for the object */
		object->begin("", Ogre::RenderOperation::OT_POINT_LIST);

		/* Initialize random numbers */
		std::srand(std::time(0));

		/* Create a set of points which will be the particles */
		/* This is similar to drawing a torus: we will sample points on the surface of the torus */

		
		float maxspray = 1.5; // This is how much we allow the points to wander around
		float u, v, w, theta, phi, spray; // Work variables
		for (int i = 0; i < num_particles; i++){
			
			// Randomly select two numbers to define a point on the torus
			u = ((double) rand() / (RAND_MAX));
            v = ((double) rand() / (RAND_MAX));
            
			// Use u and v to define the point on the torus
            theta = u * Ogre::Math::TWO_PI;
			phi = v * Ogre::Math::TWO_PI;
			Ogre::Vector3 center = Ogre::Vector3(loop_radius*cos(theta), loop_radius*sin(theta), 0.0);
            Ogre::Vector3 normal = Ogre::Vector3(cos(theta)*cos(phi), sin(theta)*cos(phi), sin(phi));
			object->position(center + normal*circle_radius); // Position of the point
			object->colour(Ogre::ColourValue(((float) i)/((float) num_particles), 0.0, 1.0 - (((float) i)/((float) num_particles))));
			object->textureCoord(Ogre::Vector2(0.0, 0.0));

			// Now sample a point on a sphere to define a direction for points to wander around
			u = ((double) rand() / (RAND_MAX));
            v = ((double) rand() / (RAND_MAX));
			w = ((double) rand() / (RAND_MAX));
			
			theta = u * Ogre::Math::TWO_PI;
			phi = acos(2.0*v * -1.0);
			spray = maxspray*pow((float) w, (float) (1.0/4.0)); // Cubic root
			Ogre::Vector3 wander = Ogre::Vector3(spray*cos(theta)*cos(phi), spray*cos(theta)*sin(phi), sin(phi)*-2);

			object->normal(wander);
		}

		object->position(Ogre::Vector3(0.0f, 0.0f, -30.0f));
		object->colour(Ogre::ColourValue(0.0f, 0.0f, 0.0f));
		object->textureCoord(Ogre::Vector2(0.0f, 0.0f));
		object->normal(Ogre::Vector3(0.0f, 0.0f, -30.0f));

        object->end();
		
		
		
        /* Convert triangle list to a mesh */
        object->convertToMesh(object_name);
  /*  }
    catch (Ogre::Exception &e){
        throw(OgreAppException(std::string("Ogre::Exception: ") + std::string(e.what())));
    }
    catch(std::exception &e){
        throw(OgreAppException(std::string("std::Exception: ") + std::string(e.what())));
    }*/
}
void  ParticleFactory::CreateSplineControlPoints(Ogre::String control_points_name, int num_control_points, Ogre::String material_name){

		// Control points for the spline
		Ogre::Vector3 *control_point;

		/* Allocate memory for control points */
		control_point = new Ogre::Vector3[num_control_points];

		/* Create control points of a piecewise spline */
		/* We store the control points in groups of 4 */
		/* Each group represents the control points (p0, p1, p2, p3) of a cubic Bezier curve */
		/* To ensure C1 continuity, we constrain the first and second point of each curve according to the previous curve */
        
		// Initialize the first two control points to fixed values */
		control_point[0] = Ogre::Vector3(-20.0, 0.0, 0.0);
		control_point[1] = Ogre::Vector3(20.0, 0.0, 0.0);

		// Create remaining points
		for (int i = 2; i < num_control_points; i++){
			// Check if we have the first or second point of a curve
			// Then we need to constrain the points
			if (i % 4 == 0){
				// Constrain the first point of the curve
				// p3 = q0, where the previous curve is (p0, p1, p2, p3) and the current curve is (q0, q1, q2, q3)
				// p3 is at position -1 from the current point q0
				control_point[i] = control_point[i - 1];
			} else if (i % 4 == 1){
				// Constrain the second point of the curve
				// q1 = 2*p3 – p2
				// p3 is at position -1 and we add another -1 since we are at i%4 == 1 (not i%4 == 0)
				// p2 is at position -2 and we add another -1 since we are at i%4 == 1 (not i%4 == 0)
				control_point[i] = 2.0*control_point[i -2] - control_point[i - 3];
			} else {
				// Other points: we can freely assign random values to them
				// Get 3 random numbers
				float u, v, w;
				//u = ((double) rand() / (RAND_MAX));
				//v = ((double) rand() / (RAND_MAX));
				//w = ((double) rand() / (RAND_MAX));
				// Define control points based on u, v, and w and scale by the control point index
				//control_point[i] = Ogre::Vector3(u*3.0*(i/4 + 1), v*3.0*(i/4+1), w*3.0*(i/4+1));
				//control_point[i] = Ogre::Vector3(u*3.0*(i/4 + 1), v*3.0*(i/4+1), 0.0); // Easier to visualize with the control points on the screen

				//x = cx + r * cos(a)
				//y = cy + r * sin(a)
			
				u = 20 * cos(Ogre::Math::RangeRandom(-25,25));
				v = 20 * sin(Ogre::Math::RangeRandom(-50,50));
				w = (Ogre::Math::RangeRandom(-15,15));
				control_point[i] = Ogre::Vector3(u, w, v);

			}
		}

		/* Add control points to the material's shader */
		/* Translate the array of Ogre::Vector3 to an accepted format */
		float *shader_data;
		shader_data = new float[num_control_points*4];
		for (int i = 0; i < num_control_points; i++){
			shader_data[i*4] = control_point[i].x;
			shader_data[i*4 + 1] = control_point[i].y;
			shader_data[i*4 + 2] = control_point[i].z;
			shader_data[i*4 + 3] = 0.0;
		}

		/* Add array as a parameter to the shader of the specified material */
		Ogre::MaterialPtr mat = static_cast<Ogre::MaterialPtr>(Ogre::MaterialManager::getSingleton().getByName(material_name));
		mat->getBestTechnique()->getPass(0)->getVertexProgramParameters()->setNamedConstant("control_point", shader_data, num_control_points, 4);

		/* Also create a mesh out of the control points, so that we can render them, if needed */
		
        Ogre::ManualObject* object = NULL;
        object = scene_manager->createManualObject(control_points_name);
        object->setDynamic(false);
		object->begin("", Ogre::RenderOperation::OT_POINT_LIST);
		for (int i = 0; i < num_control_points; i++){
			object->position(control_point[i]);
			// Color allows us to keep track of control point ordering
			object->colour(1.0 - ((float) i)/((float)num_control_points), 0.0, ((float) i)/((float)num_control_points));
		}
		object->end();
        object->convertToMesh(control_points_name);

		/* Free memory we used to store control points temporarily */
		delete [] control_point;
		
}
void  ParticleFactory::CreateSplineParticleGeometry(Ogre::String object_name, int num_particles, float loop_radius, float circle_radius){

		/* Retrieve scene manager and root scene node */
        Ogre::SceneNode* root_scene_node = scene_manager->getRootSceneNode();

        /* Create the 3D object */
        Ogre::ManualObject* object = NULL;
        object = scene_manager->createManualObject(object_name);
        object->setDynamic(false);
        
		/* Create point list for the object */
		object->begin("", Ogre::RenderOperation::OT_POINT_LIST);

		/* Initialize random numbers */
		std::srand(std::time(0));

		/* Create a set of points which will be the particles */
		/* This is similar to drawing a torus: we will sample points on a torus, but will allow the points to also
		   deviate a bit from the torus along the direction of a random vector */
        float maxspray = 0.5; // This is how much we allow the points to deviate along a normalized vector
		float u, v, w, theta, phi, spray; // Work variables
		for (int i = 0; i < num_particles; i++){
			
			// Get two random numbers
			u = ((double) rand() / (RAND_MAX));
            v = ((double) rand() / (RAND_MAX));
            
			// Use u and v to define a point on the torus with angles theta and phi
            theta = u * Ogre::Math::TWO_PI;
			phi = v * Ogre::Math::TWO_PI;

			// Get center of loop and point's normal on the torus
			Ogre::Vector3 center = Ogre::Vector3(loop_radius*cos(theta), loop_radius*sin(theta), 0.0);
            Ogre::Vector3 normal = Ogre::Vector3(cos(theta)*cos(phi), sin(theta)*cos(phi), sin(phi));

			// Next, we want to let the points deviate along the direction of a random vector
			// To obtain a random vector, we sample a point on the sphere
			// The point on the sphere minus the origin (0, 0) is the random vector

			// Randomly select two numbers to define a point in spherical coordinates
			u = ((double) rand() / (RAND_MAX));
            v = ((double) rand() / (RAND_MAX));
			
			// Use u to define the angle theta along one direction of a sphere
			theta = u * Ogre::Math::TWO_PI;
			// Use v to define the angle phi along the other direction of the sphere
			phi = acos(2.0*v - 1.0);
			// Get the point on the sphere (equivalent to a normalized direction vector since the origin is zero)
			Ogre::Vector3 direct = Ogre::Vector3(cos(theta)*sin(phi), sin(theta)*sin(phi), -cos(phi));
			// We need z = -cos(phi) to make sure that the z coordinate runs from -1 to 1 as phi runs from 0 to pi

			// Now, multiply a random amount of deviation by this vector, which is the deviation we will add to the point on the torus
			w = ((double) rand() / (RAND_MAX));
			spray = maxspray*pow((float) w, (float) (1.0/3.0)); // cbrt(w);
			Ogre::Vector3 wander = Ogre::Vector3(spray*direct.x, spray*direct.y, direct.z);
				
			// Add computed quantities to the object
			object->position(center + normal*circle_radius);
			object->normal(wander);
			object->colour(Ogre::ColourValue(((float) i)/((float) num_particles), 0.0, 0.0)); // Store particle id in the red channel as a float
			object->textureCoord(Ogre::Vector2(0.0, 0.0));
		}
		
		/* We finished the object */
        object->end();
		
        /* Convert triangle list to a mesh */
        object->convertToMesh(object_name);
   
}
void CSceletalAnimationView::EngineSetup(void)
{
	Ogre::Root *Root = ((CSceletalAnimationApp*)AfxGetApp())->m_Engine->GetRoot();
	Ogre::SceneManager *SceneManager = NULL;
	SceneManager = Root->createSceneManager(Ogre::ST_GENERIC, "Animation");
 
    //
    // Create a render window
    // This window should be the current ChildView window using the externalWindowHandle
    // value pair option.
    //

    Ogre::NameValuePairList parms;
    parms["externalWindowHandle"] = Ogre::StringConverter::toString((long)m_hWnd);
    parms["vsync"] = "true";

	CRect   rect;
    GetClientRect(&rect);
	Ogre::RenderTarget *RenderWindow = Root->getRenderTarget("Mouse Input");

	if (RenderWindow == NULL)
	{
	try
	{
		m_RenderWindow = Root->createRenderWindow("Mouse Input", rect.Width(), rect.Height(), false, &parms);
	}
    catch(...)
	{
		MessageBox("Cannot initialize\nCheck that graphic-card driver is up-to-date", "Initialize Render System", MB_OK | MB_ICONSTOP);
		exit(EXIT_SUCCESS);
	}
	}
// Load resources
	Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();

    // Create the camera
    m_Camera = SceneManager->createCamera("Camera");
    m_Camera->setNearClipDistance(0.5);
	m_Camera->setFarClipDistance(5000); 
	m_Camera->setCastShadows(false);
	m_Camera->setUseRenderingDistance(true);
	m_Camera->setPosition(Ogre::Vector3(5.0, 5.0, 10.0));
	Ogre::SceneNode *CameraNode = NULL;
	CameraNode = SceneManager->getRootSceneNode()->createChildSceneNode("CameraNode");

	Ogre::Viewport* Viewport = NULL;
	
	if (0 == m_RenderWindow->getNumViewports())
	{
		Viewport = m_RenderWindow->addViewport(m_Camera);
		Viewport->setBackgroundColour(Ogre::ColourValue(0.8f, 0.8f, 0.8f));
	}

    // Alter the camera aspect ratio to match the viewport
    m_Camera->setAspectRatio(Ogre::Real(rect.Width()) / Ogre::Real(rect.Height()));
	m_Camera->lookAt(Ogre::Vector3(0.5, 0.5, 0.5));
	m_Camera->setPolygonMode(Ogre::PolygonMode::PM_WIREFRAME);

	Ogre::ManualObject* ManualObject = NULL;
	ManualObject = SceneManager->createManualObject("Animation");
	ManualObject->setDynamic(false);
    ManualObject->begin("BaseWhiteNoLighting", Ogre::RenderOperation::OT_TRIANGLE_LIST);
	//face 1
	ManualObject->position(0, 0, 0);//0
	ManualObject->position(1, 0, 0);//1
	ManualObject->position(1, 1, 0);//2
	ManualObject->triangle(0, 1, 2);//3
	
	ManualObject->position(0, 0, 0);//4
	ManualObject->position(1, 1, 0);//5
	ManualObject->position(0, 1, 0);//6
	ManualObject->triangle(3, 4, 5);//7
	//face 2
	ManualObject->position(0, 0, 1);//8
	ManualObject->position(1, 0, 1);//9
	ManualObject->position(1, 1, 1);//10
	ManualObject->triangle(6, 7, 8);//11

	ManualObject->position(0, 0, 1);//12
	ManualObject->position(1, 1, 1);//13
	ManualObject->position(0, 1, 1);//14
	ManualObject->triangle(9, 10, 11);//15
	//face 3
	ManualObject->position(0, 0, 0);//16
	ManualObject->position(1, 0, 0);//17
	ManualObject->position(1, 0, 1);//18
	ManualObject->triangle(12, 13, 14);//19

	ManualObject->position(0, 0, 0);
	ManualObject->position(1, 0, 1);
	ManualObject->position(0, 1, 1);
	ManualObject->triangle(15, 16, 17);
	//face 4
	ManualObject->position(1, 0, 0);
	ManualObject->position(1, 1, 0);
	ManualObject->position(1, 1, 1);
	ManualObject->triangle(18, 19, 20);

	ManualObject->position(1, 0, 0);
	ManualObject->position(1, 1, 1);
	ManualObject->position(1, 0, 1);
	ManualObject->triangle(21, 22, 23);
	//face 5
	ManualObject->position(0, 1, 0);
	ManualObject->position(1, 1, 0);
	ManualObject->position(0, 1, 1);
	ManualObject->triangle(24, 25, 26);

	ManualObject->position(1, 1, 0);
	ManualObject->position(1, 1, 1);
	ManualObject->position(0, 1, 1);
	ManualObject->triangle(27, 28, 29);
	
	//face 6
	ManualObject->position(0, 0, 0);
	ManualObject->position(0, 1, 1);
	ManualObject->position(0, 0, 1);
	ManualObject->triangle(30, 31, 32);

	ManualObject->position(0, 0, 0);
	ManualObject->position(0, 1, 0);
	ManualObject->position(0, 1, 1);
	ManualObject->triangle(33, 34, 35);

	ManualObject->end();
	Ogre::MeshPtr MeshPtr = ManualObject->convertToMesh("Animation");
	Ogre::SubMesh* sub = MeshPtr->getSubMesh(0);
	
	Ogre::SkeletonPtr Skeleton = Ogre::SkeletonManager::getSingleton().create("Skeleton", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
	MeshPtr.getPointer()->_notifySkeleton(Skeleton);
	Ogre::Bone *Root1 = NULL;
	Ogre::Bone *Child1 = NULL;
	Ogre::Bone *Child2 = NULL;

	Root1 = Skeleton.getPointer()->createBone("Root");
	Root1->setPosition(Ogre::Vector3(0.0, 0.0, 0.0));
	Root1->setOrientation(Ogre::Quaternion::IDENTITY);
	
	Child1 = Root1->createChild(1);
	Child1->setPosition(Ogre::Vector3(4.0, 0.0, 0.0));
	Child1->setOrientation(Ogre::Quaternion::IDENTITY);
	Child2 = Root1->createChild(2);
	Child2->setPosition(Ogre::Vector3(5.0, 0.0, 0.0));
	Child2->setOrientation(Ogre::Quaternion::IDENTITY);

	Ogre::VertexBoneAssignment Assignment;

	Assignment.boneIndex = 0;
	Assignment.vertexIndex = 0;
	Assignment.weight = 1.0;
	Skeleton->setBindingPose();

	sub->addBoneAssignment(Assignment);

	Assignment.vertexIndex = 1;
	sub->addBoneAssignment(Assignment);

	Assignment.vertexIndex = 2;
	sub->addBoneAssignment(Assignment);

	Ogre::Animation *Animation = MeshPtr->createAnimation("HandAnimation", 100.0);
	Ogre::NodeAnimationTrack *Track = Animation->createNodeTrack(0, Root1);
	Ogre::TransformKeyFrame *KeyFrame = NULL;

	for (float FrameTime = 0.0; FrameTime < 100.0; FrameTime += 0.1)
	{
		KeyFrame = Track->createNodeKeyFrame(FrameTime);
		KeyFrame->setTranslate(Ogre::Vector3(10.0, 0.0, 0.0));
	}

	Root1->setManuallyControlled(true);
	Child1->setManuallyControlled(true);
	Child2->setManuallyControlled(true);
	MeshPtr->load();

	MeshPtr.getPointer()->_notifySkeleton(Skeleton);
		
//	Ogre::SkeletonSerializer skeletonSerializer;
//	skeletonSerializer.exportSkeleton(Skeleton.get(), "C:\\Users\\Ilya\\Documents\\Visual Studio 2010\\Projects\\Recipes\\media\\models\\testskeleton.skeleton");
//	Ogre::MeshSerializer ser;
//    ser.exportMesh(MeshPtr.get(), "C:\\Users\\Ilya\\Documents\\Visual Studio 2010\\Projects\\Recipes\\media\\models\\testskeleton.mesh");

	Ogre::Entity *Entity = SceneManager->createEntity("Animation", "Animation"/*"testskeleton.mesh"*/);
	Ogre::SceneNode *SceneNode = SceneManager->getRootSceneNode()->createChildSceneNode();
	SceneNode->attachObject(Entity);
	Entity->setDisplaySkeleton(true);

	m_AnimationState = Entity->getAnimationState("HandAnimation");
	m_AnimationState->setEnabled(true);
	m_AnimationState->setLoop(true);
	
	m_Camera->setPolygonMode(Ogre::PolygonMode::PM_WIREFRAME);
	 
	Root->renderOneFrame();
}
void CTransparentMaterialView::EngineSetup(void)
{
	Ogre::Root *Root = ((CTransparentMaterialApp*)AfxGetApp())->m_Engine->GetRoot();

	Ogre::SceneManager *SceneManager = NULL;

	SceneManager = Root->createSceneManager(Ogre::ST_GENERIC, "MFCOgre");

    //
    // Create a render window
    // This window should be the current ChildView window using the externalWindowHandle
    // value pair option.
    //

    Ogre::NameValuePairList parms;
    parms["externalWindowHandle"] = Ogre::StringConverter::toString((long)m_hWnd);
    parms["vsync"] = "true";

	CRect   rect;
    GetClientRect(&rect);

	Ogre::RenderTarget *RenderWindow = Root->getRenderTarget("Ogre in MFC");

	if (RenderWindow == NULL)
	{
	try
	{
		m_RenderWindow = Root->createRenderWindow("Ogre in MFC", rect.Width(), rect.Height(), false, &parms);
	}
    catch(...)
	{
		MessageBox("Cannot initialize\nCheck that graphic-card driver is up-to-date", "Initialize Render System", MB_OK | MB_ICONSTOP);
		exit(EXIT_SUCCESS);
	}
	}
// Load resources
	Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();

    // Create the camera
    m_Camera = SceneManager->createCamera("Camera");
    m_Camera->setNearClipDistance(0.5);
	m_Camera->setFarClipDistance(5000); 
	m_Camera->setCastShadows(false);
	m_Camera->setUseRenderingDistance(true);
	m_Camera->setPosition(Ogre::Vector3(320.0, 240.0, 500.0));
	Ogre::SceneNode *CameraNode = NULL;
	CameraNode = SceneManager->getRootSceneNode()->createChildSceneNode("CameraNode");

	Ogre::Viewport* Viewport = NULL;
	
	if (0 == m_RenderWindow->getNumViewports())
	{
		Viewport = m_RenderWindow->addViewport(m_Camera);
		Viewport->setBackgroundColour(Ogre::ColourValue(0.8f, 1.0f, 0.8f));
	}

    // Alter the camera aspect ratio to match the viewport
    m_Camera->setAspectRatio(Ogre::Real(rect.Width()) / Ogre::Real(rect.Height()));

	Ogre::ManualObject *Screen = SceneManager->createManualObject("Screen");
	Screen->setDynamic(true);
	Screen->begin("window", Ogre::RenderOperation::OT_TRIANGLE_LIST);

	Screen->position(-100,-100,50);
	Screen->textureCoord(0,0);

	Screen->position(300,-100,50);
	Screen->textureCoord(1,0);

	Screen->position(300,300,50);
	Screen->textureCoord(1,1);

	Screen->triangle(0, 1, 2);
		
	Screen->position(-100,-100,50);
	Screen->textureCoord(0,0);

	Screen->position(300,300,50);
	Screen->textureCoord(1,1);

	Screen->position(-100,300,50);
	Screen->textureCoord(0,1);

	Screen->triangle(3, 4, 5);
	 
	Screen->end();
	
	Ogre::Entity *RobotEntity = SceneManager->createEntity("Robot", "robot.mesh");
	Ogre::SceneNode *RobotNode = SceneManager->getRootSceneNode()->createChildSceneNode();
	RobotNode->attachObject(RobotEntity);

	Ogre::SceneNode *WindowNode = SceneManager->getRootSceneNode()->createChildSceneNode();
	WindowNode->attachObject(Screen);
}
Exemplo n.º 12
0
void OgreApplication::CreateWall(Ogre::String material_name){
	    
	try {

		/* Create two rectangles */

        /* Retrieve scene manager and root scene node */
        Ogre::SceneManager* scene_manager = ogre_root_->getSceneManager("MySceneManager");
        Ogre::SceneNode* root_scene_node = scene_manager->getRootSceneNode();

        /* Create the 3D object */
        Ogre::ManualObject* object = NULL;
        Ogre::String object_name = "Wall";
        object = scene_manager->createManualObject(object_name);
        object->setDynamic(false);

        /* Create triangle list for the object */
        object->begin(material_name, Ogre::RenderOperation::OT_TRIANGLE_LIST);

		/* Add vertices */
		/* One side of the "wall" */
		object->position(-1.0,-1.0,0.0);
		object->normal(0.0, 0.0, -1.0);
		object->tangent(-1.0, 0.0, 0.0);
		object->textureCoord(1.0, 0.0);

        object->position(-1.0,1.0,0.0);
		object->normal(0.0, 0.0, -1.0);
		object->tangent(-1.0, 0.0, 0.0);
		object->textureCoord(1.0, 1.0);

        object->position(1.0,1.0,0.0);
		object->normal(0.0, 0.0, -1.0);
		object->tangent(-1.0, 0.0, 0.0);
		object->textureCoord(0.0, 1.0);

        object->position(1.0,-1.0,0.0);
		object->normal(0.0, 0.0, -1.0);
		object->tangent(-1.0, 0.0, 0.0);
		object->textureCoord(0.0, 0.0);

		/* The other side of the "wall" */
        object->position(-1.0,-1.0,0.0);
		object->normal(0.0, 0.0, 1.0);
		object->tangent(1.0, 0.0, 0.0);
		object->textureCoord(0.0, 0.0);

        object->position(-1.0,1.0,0.0);
		object->normal(0.0, 0.0, 1.0);
		object->tangent(1.0, 0.0, 0.0);
		object->textureCoord(0.0, 1.0);

        object->position(1.0,1.0,0.0);
		object->normal(0.0, 0.0, 1.0);
		object->tangent(1.0, 0.0, 0.0);
		object->textureCoord(1.0, 1.0);

        object->position(1.0,-1.0,0.0);
		object->normal(0.0, 0.0, 1.0);
		object->tangent(1.0, 0.0, 0.0);
		object->textureCoord(1.0, 0.0);
        
		/* Add triangles */
		/* One side */
		object->triangle(0, 1, 2);
        object->triangle(0, 2, 3);
		/* The other side */
        object->triangle(4, 7, 6);
        object->triangle(4, 6, 5);
        
		/* We finished the object */
        object->end();
		
        /* Convert triangle list to a mesh */
        Ogre::String mesh_name = "Wall";
        object->convertToMesh(mesh_name);

        /* Create one instance of the sphere (one entity) */
		/* The same object can have multiple instances or entities */
        Ogre::Entity* entity = scene_manager->createEntity(mesh_name);

		/* Apply a material to the entity to give it color */
		/* We already did that above, so we comment it out here */
		/* entity->setMaterialName(material_name); */
		/* But, this call is useful if we have multiple entities with different materials */

		/* Create a scene node for the entity */
		/* The scene node keeps track of the entity's position */
        Ogre::SceneNode* scene_node = root_scene_node->createChildSceneNode(mesh_name);
        scene_node->attachObject(entity);

        /* Position and rotate the entity with the scene node */
		//scene_node->rotate(Ogre::Vector3(0, 1, 0), Ogre::Degree(60));
		//scene_node->rotate(Ogre::Vector3(1, 0, 0), Ogre::Degree(30));
		//scene_node->rotate(Ogre::Vector3(1, 0, 0), Ogre::Degree(-90));
        //scene_node->translate(0.0, 0.0, 0.0);
		scene_node->scale(0.5, 0.5, 0.5);
    }
    catch (Ogre::Exception &e){
        throw(OgreAppException(std::string("Ogre::Exception: ") + std::string(e.what())));
    }
    catch(std::exception &e){
        throw(OgreAppException(std::string("std::Exception: ") + std::string(e.what())));
    }
}
Exemplo n.º 13
0
void CubeWorld::createChunkWater (const int StartX, const int StartY, const int StartZ)
{
	block_t LastBlock = 0;

	int iVertex = 0;
	block_t Block;
	block_t Block1;

	/* Only create visible faces of chunk */
	block_t DefaultBlock = 1;
	int SX = 0;
	int SY = 0;
	int SZ = 0;
	int MaxSize = WORLD_SIZE;

	float BlockLight;
	float BlockLight1;
	float BlockLight2;

	float V1, V2;

	Ogre::ManualObject* MeshChunk = new Ogre::ManualObject("MeshWaterChunk" + Ogre::StringConverter::toString(m_ChunkID));
	MeshChunk->setDynamic(true);
	MeshChunk->begin("WaterTest");

	for (int z = StartZ; z < CHUNK_SIZE + StartZ; ++z)
	{
		for (int y = StartY; y < CHUNK_SIZE + StartY; ++y)
		{
			for (int x = StartX; x < CHUNK_SIZE + StartX; ++x)
			{
				Block = GetBlock(x,y,z);
				if (Block != 5) continue;   //Only create water meshes


				BlockLight  = GetBlockLight(x, y, z) / 255.0f;
				BlockLight1 = BlockLight * 0.9f;
				BlockLight2 = BlockLight * 0.8f;


				V1 = 1.0f/5.0f * (float)(Block - 1);
				V2 = V1 + 1.0f/5.0f;

				//x-1
				Block1 = DefaultBlock;
				if (x > SX) Block1 = GetBlock(x-1,y,z);

				if (Block1 != 5)
				{
                                        //create face of block
					MeshChunk->position(x, y,   z+1); MeshChunk->normal(-1,0,0);	MeshChunk->textureCoord(0, V2); MeshChunk->colour(BlockLight, BlockLight, BlockLight);
					MeshChunk->position(x, y+1, z+1); MeshChunk->normal(-1,0,0);	MeshChunk->textureCoord(1, V2); MeshChunk->colour(BlockLight, BlockLight, BlockLight);
					MeshChunk->position(x, y+1, z);	  MeshChunk->normal(-1,0,0);	MeshChunk->textureCoord(1, V1); MeshChunk->colour(BlockLight, BlockLight, BlockLight);
					MeshChunk->position(x, y,   z);	  MeshChunk->normal(-1,0,0);	MeshChunk->textureCoord(0, V1); MeshChunk->colour(BlockLight, BlockLight, BlockLight);

					MeshChunk->triangle(iVertex, iVertex+1, iVertex+2);
					MeshChunk->triangle(iVertex+2, iVertex+3, iVertex);

					iVertex += 4;
                                }

				//x+1
				Block1 = DefaultBlock;
				if (x < SX + MaxSize - 1)
					Block1 = GetBlock(x+1,y,z);

				if (Block1 != 5)
				    {
					    MeshChunk->position(x+1, y,   z);	MeshChunk->normal(1,0,0); MeshChunk->textureCoord(0, V2); MeshChunk->colour(BlockLight, BlockLight, BlockLight);
					    MeshChunk->position(x+1, y+1, z);	MeshChunk->normal(1,0,0); MeshChunk->textureCoord(1, V2); MeshChunk->colour(BlockLight, BlockLight, BlockLight);
					    MeshChunk->position(x+1, y+1, z+1);	MeshChunk->normal(1,0,0); MeshChunk->textureCoord(1, V1); MeshChunk->colour(BlockLight, BlockLight, BlockLight);
					    MeshChunk->position(x+1, y,   z+1);	MeshChunk->normal(1,0,0); MeshChunk->textureCoord(0, V1); MeshChunk->colour(BlockLight, BlockLight, BlockLight);

					    MeshChunk->triangle(iVertex, iVertex+1, iVertex+2);
					    MeshChunk->triangle(iVertex+2, iVertex+3, iVertex);

					    iVertex += 4;
				    }

				//y-1
				Block1 = DefaultBlock;
				if (y > SY)
					Block1 = GetBlock(x,y-1,z);

				if (Block1 != 5)
				    {
					    MeshChunk->position(x,   y, z);		MeshChunk->normal(0,-1,0); MeshChunk->textureCoord(0, V2); MeshChunk->colour(BlockLight2, BlockLight2, BlockLight2);
					    MeshChunk->position(x+1, y, z);		MeshChunk->normal(0,-1,0); MeshChunk->textureCoord(1, V2); MeshChunk->colour(BlockLight2, BlockLight2, BlockLight2);
					    MeshChunk->position(x+1, y, z+1);	MeshChunk->normal(0,-1,0); MeshChunk->textureCoord(1, V1); MeshChunk->colour(BlockLight2, BlockLight2, BlockLight2);
					    MeshChunk->position(x,   y, z+1);	MeshChunk->normal(0,-1,0); MeshChunk->textureCoord(0, V1); MeshChunk->colour(BlockLight2, BlockLight2, BlockLight2);

					    MeshChunk->triangle(iVertex, iVertex+1, iVertex+2);
					    MeshChunk->triangle(iVertex+2, iVertex+3, iVertex);

					    iVertex += 4;
				    }


				//y+1
				Block1 = DefaultBlock;
				if (y < SY + MaxSize - 1)
					Block1 = GetBlock(x,y+1,z);

				if (Block1 != 5)
				    {
					    MeshChunk->position(x,   y+1, z+1);		MeshChunk->normal(0,1,0); MeshChunk->textureCoord(0, V2); MeshChunk->colour(BlockLight2, BlockLight2, BlockLight2);
					    MeshChunk->position(x+1, y+1, z+1);		MeshChunk->normal(0,1,0); MeshChunk->textureCoord(1, V2); MeshChunk->colour(BlockLight2, BlockLight2, BlockLight2);
					    MeshChunk->position(x+1, y+1, z);		MeshChunk->normal(0,1,0); MeshChunk->textureCoord(1, V1); MeshChunk->colour(BlockLight2, BlockLight2, BlockLight2);
					    MeshChunk->position(x,   y+1, z);		MeshChunk->normal(0,1,0); MeshChunk->textureCoord(0, V1); MeshChunk->colour(BlockLight2, BlockLight2, BlockLight2);

					    MeshChunk->triangle(iVertex, iVertex+1, iVertex+2);
					    MeshChunk->triangle(iVertex+2, iVertex+3, iVertex);

					    iVertex += 4;
				    }

				//z-1
				Block1 = DefaultBlock;
				if (z > SZ)
					Block1 = GetBlock(x,y,z-1);

				if (Block1 != 5)
				    {
					    MeshChunk->position(x,   y+1, z);		MeshChunk->normal(0,0,-1); MeshChunk->textureCoord(0, V2); MeshChunk->colour(BlockLight1, BlockLight1, BlockLight1);
					    MeshChunk->position(x+1, y+1, z);		MeshChunk->normal(0,0,-1); MeshChunk->textureCoord(1, V2); MeshChunk->colour(BlockLight1, BlockLight1, BlockLight1);
					    MeshChunk->position(x+1, y,   z);		MeshChunk->normal(0,0,-1); MeshChunk->textureCoord(1, V1); MeshChunk->colour(BlockLight1, BlockLight1, BlockLight1);
					    MeshChunk->position(x,   y,   z);		MeshChunk->normal(0,0,-1); MeshChunk->textureCoord(0, V1); MeshChunk->colour(BlockLight1, BlockLight1, BlockLight1);

					    MeshChunk->triangle(iVertex, iVertex+1, iVertex+2);
					    MeshChunk->triangle(iVertex+2, iVertex+3, iVertex);

					    iVertex += 4;
				    }


				//z+1
				Block1 = DefaultBlock;
				if (z < SZ + MaxSize - 1)
					Block1 = GetBlock(x,y,z+1);

				if (Block1 != 5)
				    {
					    MeshChunk->position(x,   y,   z+1);		MeshChunk->normal(0,0,1); MeshChunk->textureCoord(0, V2); MeshChunk->colour(BlockLight1, BlockLight1, BlockLight1);
					    MeshChunk->position(x+1, y,   z+1);		MeshChunk->normal(0,0,1); MeshChunk->textureCoord(1, V2); MeshChunk->colour(BlockLight1, BlockLight1, BlockLight1);
					    MeshChunk->position(x+1, y+1, z+1);		MeshChunk->normal(0,0,1); MeshChunk->textureCoord(1, V1); MeshChunk->colour(BlockLight1, BlockLight1, BlockLight1);
					    MeshChunk->position(x,   y+1, z+1);		MeshChunk->normal(0,0,1); MeshChunk->textureCoord(0, V1); MeshChunk->colour(BlockLight1, BlockLight1, BlockLight1);

					    MeshChunk->triangle(iVertex, iVertex+1, iVertex+2);
					    MeshChunk->triangle(iVertex+2, iVertex+3, iVertex);

					    iVertex += 4;
				    }
			}
		}
	}
	MeshChunk->end();
	mSceneMgr->getRootSceneNode()->createChildSceneNode()->attachObject(MeshChunk);
	++m_ChunkID;

}
Exemplo n.º 14
0
// Given a scene node for a terrain, find the manual object on that scene node and
// update the manual object with the heightmap passed. If  there is no manual object on
// the scene node, remove all it's attachments and add the manual object.
// The heightmap is passed in a 1D array ordered by width rows (for(width) {for(length) {hm[w,l]}})
// This must be called between frames since it touches the scene graph
// BETWEEN FRAME OPERATION
void Region::UpdateTerrain(const int hmWidth, const int hmLength, const float* hm) {
	Ogre::SceneNode* node = this->TerrainSceneNode;
	LG::Log("Region::UpdateTerrain: updating terrain for region %s", this->Name.c_str());

	if (node == NULL) {
		LG::Log("Region::UpdateTerrain: terrain scene node doesn't exist. Not updating terrain.");
		return;
	}

	// Find the movable object attached to the scene node. If not found remove all.
	if (node->numAttachedObjects() > 0) {
		Ogre::MovableObject* attached = node->getAttachedObject(0);
		if (attached->getMovableType() != "ManualObject") {
            // don't know why this would ever happen but clean out the odd stuff
            LG::Log("Found extra stuff on terrain scene node");
			node->detachAllObjects();
		}
	}
	// if there is not a manual object on the node, create a new one
	if (node->numAttachedObjects() == 0) {
		LG::Log("Region::UpdateTerrain: creating terrain ManualObject for region %s", this->Name.c_str());
        // if no attached objects, we add our dynamic ManualObject
		Ogre::ManualObject* mob = LG::RendererOgre::Instance()->m_sceneMgr->createManualObject("ManualObject/" + node->getName());
		mob->addQueryFlags(Ogre::SceneManager::WORLD_GEOMETRY_TYPE_MASK);
		mob->setDynamic(true);
		mob->setCastShadows(true);
		mob->setVisible(true);
		node->attachObject(mob);
		// m_visCalc->RecalculateVisibility();
	}

	Ogre::ManualObject* mo = (Ogre::ManualObject*)node->getAttachedObject(0);

	// stuff our heightmap information into the dynamic manual object
	mo->estimateVertexCount(hmWidth * hmLength);
	mo->estimateIndexCount(hmWidth * hmLength * 6);

	if (mo->getNumSections() == 0) {
		// if first time
		mo->begin(LG::GetParameter("Renderer.Ogre.DefaultTerrainMaterial"));
	}
	else {
		mo->beginUpdate(0);					// we've been here before
	}

	int loc = 0;
	for (int xx = 0; xx < hmWidth; xx++) {
		for (int yy = 0; yy < hmLength; yy++) {
			mo->position((Ogre::Real)xx, (Ogre::Real)yy, hm[loc++]);
			mo->textureCoord((float)xx / (float)hmWidth, (float)yy / (float)hmLength);
			mo->normal(0.0, 1.0, 0.0);	// always up (for the moment)
		}
	}

	for (int px = 0; px < hmLength-1; px++) {
		for (int py = 0; py < hmWidth-1; py++) {
			mo->quad(px      + py       * hmWidth,
					 px      + (py + 1) * hmWidth,
					(px + 1) + (py + 1) * hmWidth,
					(px + 1) + py       * hmWidth
					 );
		}
	}

	mo->end();

	return;
}
Exemplo n.º 15
0
void Client::initScene() {
	Ogre::Vector3 lightPosition = Ogre::Vector3(0,10,50);
	
	// Set the scene's ambient light
	mSceneMgr->setAmbientLight(Ogre::ColourValue(.1f, .1f, .1f));
	Ogre::Light* pointLight = mSceneMgr->createLight("pointLight");
	pointLight->setType(Ogre::Light::LT_POINT);
	pointLight->setPosition(lightPosition);
	// create a marker where the light is
	Ogre::Entity* ogreHead2 = mSceneMgr->createEntity( "Head2", "ogrehead.mesh" );
	Ogre::SceneNode* headNode2 = mSceneMgr->getRootSceneNode()->createChildSceneNode( "HeadNode2", lightPosition );
	headNode2->attachObject( ogreHead2 );
	headNode2->scale( .5, .5, .5 );
	
	// make a quad
	Ogre::ManualObject* lManualObject = NULL;
	Ogre::String lNameOfTheMesh = "TestQuad";
	{
		// params
		Ogre::String lManualObjectName = "TestQuad";
		bool lDoIWantToUpdateItLater = false;
		// code
		lManualObject = mSceneMgr->createManualObject(lManualObjectName);
		lManualObject->setDynamic(lDoIWantToUpdateItLater);
		lManualObject->begin("BaseWhiteNoLighting", Ogre::RenderOperation::OT_TRIANGLE_LIST);
		{	// Specify Vertices
			float xmin = 0.0f, xmax = 100.0f, zmin = -100.0f, zmax = 0.0f, ymin = -50.0f, ymax = 0.0f;
			
			lManualObject->position(xmin, ymin, zmin);// a vertex
			lManualObject->colour(Ogre::ColourValue::Red);
			lManualObject->textureCoord(0.0,0.0);
			
			lManualObject->position(xmax, ymin, zmin);// a vertex
			lManualObject->colour(Ogre::ColourValue::Green);
			lManualObject->textureCoord(1.0,0.0);
			
			lManualObject->position(xmin, ymin, zmax);// a vertex
			lManualObject->colour(Ogre::ColourValue::Blue);
			lManualObject->textureCoord(0.0,1.0);
			
			lManualObject->position(xmax, ymin, zmax);// a vertex
			lManualObject->colour(Ogre::ColourValue::Blue);
			lManualObject->textureCoord(1.0,1.0);
		}
		{	// specify geometry
			lManualObject->triangle(0,2,1);
			lManualObject->triangle(3,1,2);
		}
		lManualObject->end();
		lManualObject->convertToMesh(lNameOfTheMesh);
	}
	Ogre::Entity* lEntity = mSceneMgr->createEntity(lNameOfTheMesh);
	Ogre::SceneNode* lNode = mSceneMgr->getRootSceneNode()->createChildSceneNode();
	lNode->attachObject(lEntity);
	Ogre::Entity* ogreHead = mSceneMgr->createEntity("Head", "ogrehead.mesh");
	// Create a SceneNode and attach the Entity to it
	Ogre::SceneNode* headNode = mSceneMgr->getRootSceneNode()->createChildSceneNode("HeadNode",Ogre::Vector3(0,-20,0));
	headNode->attachObject(ogreHead);
	ogreHead->setMaterialName("Hatching");
	
	lEntity->setMaterialName("Hatching");
	// postprocessing effects
	//Ogre::CompositorManager::getSingleton().addCompositor(mViewport,"Sobel" );
	//Ogre::CompositorManager::getSingleton().setCompositorEnabled(mCamera->getViewport(), "Sobel", true);
	//Ogre::CompositorManager::getSingleton().addCompositor(mViewport,"CelShading" );
	//Ogre::CompositorManager::getSingleton().setCompositorEnabled(mCamera->getViewport(), "CelShading", true);
}
void CGeoImageView::EngineSetup(void)
{
	Ogre::Root *Root = ((CGeoImageApp*)AfxGetApp())->m_Engine->GetRoot();

	Ogre::SceneManager *SceneManager = NULL;

	SceneManager = Root->createSceneManager(Ogre::ST_GENERIC, "MFCOgre");

    //
    // Create a render window
    // This window should be the current ChildView window using the externalWindowHandle
    // value pair option.
    //

    Ogre::NameValuePairList parms;
    parms["externalWindowHandle"] = Ogre::StringConverter::toString((long)m_hWnd);
    parms["vsync"] = "true";

	CRect   rect;
    GetClientRect(&rect);

	Ogre::RenderTarget *RenderWindow = Root->getRenderTarget("Ogre in MFC");

	if (RenderWindow == NULL)
	{
	try
	{
		m_RenderWindow = Root->createRenderWindow("Ogre in MFC", rect.Width(), rect.Height(), false, &parms);
	}
    catch(...)
	{
		MessageBox("Cannot initialize\nCheck that graphic-card driver is up-to-date", "Initialize Render System", MB_OK | MB_ICONSTOP);
		exit(EXIT_SUCCESS);
	}
	}
// Load resources
	Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();

    // Create the camera
    m_Camera = SceneManager->createCamera("Camera");
    m_Camera->setNearClipDistance(0.5);
	m_Camera->setFarClipDistance(5000); 
	m_Camera->setCastShadows(false);
	m_Camera->setUseRenderingDistance(true);
//	m_Camera->setPosition(Ogre::Vector3(320.0, 240.0, 500.0));
	Ogre::SceneNode *CameraNode = NULL;
	CameraNode = SceneManager->getRootSceneNode()->createChildSceneNode("CameraNode");

	Ogre::Viewport* Viewport = NULL;
	
	if (0 == m_RenderWindow->getNumViewports())
	{
		Viewport = m_RenderWindow->addViewport(m_Camera);
		Viewport->setBackgroundColour(Ogre::ColourValue(0.8f, 1.0f, 0.8f));
	}

    // Alter the camera aspect ratio to match the viewport
    m_Camera->setAspectRatio(Ogre::Real(rect.Width()) / Ogre::Real(rect.Height()));
		

	TIFF 	*Tif = (TIFF*)0;  /* TIFF-level descriptor */
  	GTIF	*GTif = (GTIF*)0; /* GeoKey-level descriptor */

	CString SourcePath = "C:\\Users\\Ilya\\Documents\\Visual Studio 2010\\Projects\\Recipes\\media\\materials\\textures\\o41078a1.tif";
 int ImageWidth;
 int ImageHeight;

 double LowerLeftX;
 double LowerLeftY;

 double UpperRightX;
 double UpperRightY;

 int Xpos;
 int Ypos;

	Tif = XTIFFOpen((LPCSTR)SourcePath, "r");
	GTif = GTIFNew(Tif);
 
	GTIFDefn Definition;
	GTIFGetDefn(GTif, &Definition);
 
	GTIFPrint(GTif, 0, 0);

	TIFFGetField( Tif, TIFFTAG_IMAGEWIDTH, &ImageWidth);
 	TIFFGetField( Tif, TIFFTAG_IMAGELENGTH, &ImageHeight);

int res = 0;

 double LowerRightX = ImageWidth;
 double LowerRightY = ImageHeight;

 res = GTIFImageToPCS(GTif, &LowerRightX, &LowerRightY);
  //Lower Left
 LowerLeftX = 0.0;
 LowerLeftY = ImageHeight;

 res = GTIFImageToPCS(GTif, &LowerLeftX, &LowerLeftY);

 //Upper Right
 UpperRightX = ImageWidth;
 UpperRightY = 0.0;

 res = GTIFImageToPCS(GTif, &UpperRightX, &UpperRightY);

 double UpperLeftX = 0.0;
 double UpperLeftY = 0.0;

 res = GTIFImageToPCS(GTif, &UpperLeftX, &UpperLeftY);

  	Ogre::ManualObject *Terrain = SceneManager->createManualObject("Terrain");
	Terrain->setDynamic(false);
	Terrain->begin("Terrain", Ogre::RenderOperation::OT_TRIANGLE_FAN);

#define MIN(x,y)     (((x) < (y)) ? (x) : (y))
#define MAX(x,y)     (((x) > (y)) ? (x) : (y))

#define SW     0
#define NW     1
#define NE     2
#define SE     3

FILE *File = NULL;
char            Dummy[160];
char inText[24];
 char *Dest;
	int             base[2048];         /* array of base elevations */
char            mapLabel[145];
int             DEMlevel, elevationPattern, groundSystem, groundZone;
double          projectParams[15];
int             planeUnitOfMeasure, elevUnitOfMeasure, polygonSizes;
double          groundCoords[4][2], elevBounds[2], localRotation;
int             accuracyCode;
double          spatialResolution[3];
int             profileDimension[2];
int             firstRow, lastRow;
int             wcount = 0;

double          verticalScale = 1.0;      /* to stretch or shrink elevations */
double          deltaY;
char *junk;

double eastMost;
double westMost;
double southMost;
double northMost;

int  eastMostSample;
int  westMostSample;
int southMostSample;
int northMostSample;

int        rowCount, columnCount, r, c;
int	rowStr = 1;
int rowEnd;
int colStr = 1;
int colEnd;
int colInt = 1;
int rowInt = 1;
int outType = 0;
 int k,l ;
 double comp = 0.0;

     int 	   mod ;
    int             tempInt, lastProfile = 0;

    float           noValue = 0.0f;
    int             profileID[2], profileSize[2];
    double          planCoords[2], localElevation, elevExtremea[2];


 File = fopen("C:\\Users\\Ilya\\Documents\\Visual Studio 2010\\Projects\\Recipes\\media\\geotiff\\karthaus_pa.dem", "r");

 fscanf(File, "%144c%6d%6d%6d%6d",
	     mapLabel,              /* 1 */
	     &DEMlevel,             /* 2 */
	     &elevationPattern,     /* 3 */
             &groundSystem,         /* 4 */
             &groundZone );         /* 5 */


    for (k=0; k<15 ; k++) 
	{
     fscanf(File,"%24c", inText);    /* 6 */
      Dest = strchr(inText,'D');  *Dest = 'E';
      projectParams[k]  = strtod(inText,&junk);
    }

    fscanf(File,"%6d%6d%6d",
             &planeUnitOfMeasure,   /* 7 */
             &elevUnitOfMeasure,    /* 8 */
             &polygonSizes);        /* 9 */

    for (k=0; k < 4 ; k++)
       for (l=0; l < 2 ; l++)
	   { 
        fscanf(File,"%24c", inText);    /* 6 */
        Dest = strchr(inText,'D');  *Dest = 'E';
        groundCoords[k][l]  = strtod(inText,&junk);
	   }

    fscanf(File,"%24c", inText);
    Dest = strchr(inText,'D');  *Dest = 'E';
    elevBounds[0] = strtod(inText,&junk);       /* 10 */
    fscanf(File,"%24c", inText);
    
	Dest = strchr(inText,'D');  *Dest = 'E';
    elevBounds[1] = strtod(inText,&junk);      /* 11 */
    fscanf(File,"%24c", inText);
    Dest = strchr(inText,'D');  *Dest = 'E';
    localRotation  = strtod(inText,&junk);      /* 12 */

   fscanf(File,"%1d%12le%12le%12le%6d%6d",
             &accuracyCode,             /* 13 */
	     &spatialResolution[0],     /* 14 */
             &spatialResolution[1],     /* 14 */
             &spatialResolution[2],     /* 14 */
             &profileDimension[0],      /* 15 */
             &profileDimension[1]);     /* 15 */

   fscanf(File, "%160c", Dummy);

    if (spatialResolution[0] == 3.0) 
	{
	 comp   = spatialResolution[0] - 1.0 ;
	 deltaY = spatialResolution[1] / 3600.  ;
    }
    else
	{
	 comp   = 0.;
	 deltaY = spatialResolution[1] ;
    }

    eastMost  = MAX(groundCoords[NE][0], groundCoords[SE][0]);
    westMost  = MIN(groundCoords[NW][0], groundCoords[SW][0]);
    northMost = MAX(groundCoords[NE][1], groundCoords[NW][1]);
    southMost = MIN(groundCoords[SW][1], groundCoords[SE][1]);
    eastMostSample =  ((int) (eastMost / spatialResolution[0]))
		     * (int) spatialResolution[0];
    westMostSample =  ((int) ((westMost + comp) / spatialResolution[0]))
		     * (int) spatialResolution[0] ;
    northMostSample = ((int) (northMost / spatialResolution[1]))
		     * (int) spatialResolution[1] ;
    southMostSample = ((int) ((southMost + comp) / spatialResolution[1]))
		     * (int) spatialResolution[1] ;
    
	columnCount = (eastMostSample  - westMostSample)
		  / (int) spatialResolution[0] + 1;
    rowCount    = (northMostSample - southMostSample)
		  / (int) spatialResolution[1] + 1;

    if (columnCount != profileDimension[1])
	  columnCount =MIN( profileDimension[1], columnCount);

for (c = 1; c <= columnCount; c++) 
 {
  fscanf(File, "%d%d%d%d",
		 &profileID[0],        /* 1 */
		 &profileID[1],        /* 1 */
		 &profileSize[0],      /* 2 */
		 &profileSize[1]);     /* 2 */

       fscanf(File,"%24c", inText);
       Dest = strchr(inText,'D');  *Dest = 'E';
       planCoords[0]   = strtod(inText,&junk);     /* 3 */
	  fscanf(File,"%24c", inText);
       Dest = strchr(inText,'D');  *Dest = 'E';
       planCoords[1]   = strtod(inText,&junk);     /* 3 */
	   fscanf(File,"%24c", inText);
       Dest = strchr(inText,'D');  *Dest = 'E';
       localElevation  = strtod(inText,&junk);     /* 4 */
	 fscanf(File,"%24c", inText);
       Dest = strchr(inText,'D');  *Dest = 'E';
       elevExtremea[0] = strtod(inText,&junk);     /* 5 */
	   fscanf(File,"%24c", inText);
       Dest = strchr(inText,'D');  *Dest = 'E';
       elevExtremea[1] = strtod(inText,&junk);     /* 5 */

       lastProfile =  profileID[1];

       firstRow = abs(((int) (planCoords[1] - southMostSample))
		 / (int) spatialResolution[1]);
       lastRow = firstRow + profileSize[0] - 1;

       for ( r = 0 ; r < firstRow  ; r++ ) 
		   base[r] = 0;

/*     read in all the data for this column */
       for (r = firstRow; r <= lastRow; r++ )
       {
	  fscanf(File, "%6d",	&tempInt);
	   base[r] = tempInt;
       }

    double          tempFloat;

   for (r = firstRow; r <= lastRow; r += rowInt) 
   {
    tempFloat = (float) base[r]  * verticalScale;
 	Terrain->position(planCoords[0], tempFloat, planCoords[1]);

	Ogre::Real u = 0.0;
	Ogre::Real v = 0.0;

	if (planCoords[0] > LowerLeftX && planCoords[0] < UpperRightX)
	{
		u = (planCoords[0] - LowerLeftX) / (UpperRightX - LowerLeftX);
	}

	if (planCoords[1] > LowerLeftY && planCoords[1] < UpperRightY)
	{
		v = (planCoords[1] - LowerLeftY) / (UpperRightY - LowerLeftY);
	}

	Terrain->textureCoord(u, v); 
	planCoords[1] += deltaY;
   }
 }

 Terrain->end();
 fclose(File);

	Ogre::SceneNode* node = SceneManager->getRootSceneNode()->createChildSceneNode();
	node->setPosition(0, 0, 0);
	node->attachObject(Terrain);

	Ogre::AxisAlignedBox Box = Terrain->getBoundingBox();
	Ogre::Vector3 Center = Box.getCenter();

	Ogre::Vector3 Target = Center;
	Ogre::Vector3 Position = Center;

	Position[1] += 5000.0;
	m_Camera->setPosition(Position);
	m_Camera->lookAt(Target);
}