Esempio n. 1
0
void LodManager::loadLod(Ogre::MeshPtr mesh, const LodDefinition& def)
{
    if (def.getUseAutomaticLod()) {
        loadAutomaticLod(mesh);
    } else if (def.getLodDistanceCount() == 0) {
        mesh->removeLodLevels();
        return;
    } else {
        Ogre::LodStrategy* strategy;
        if (def.getStrategy() == LodDefinition::LS_DISTANCE) {
            strategy = &Ogre::DistanceLodStrategy::getSingleton();
        } else {
            strategy = &Ogre::PixelCountLodStrategy::getSingleton();
        }
        mesh->setLodStrategy(strategy);

        if (def.getType() == LodDefinition::LT_AUTOMATIC_VERTEX_REDUCTION) {
            // Automatic vertex reduction
            LodConfig lodConfig;
            lodConfig.mesh = mesh;
            const LodDefinition::LodDistanceMap& data = def.getManualLodData();
            if (def.getStrategy() == LodDefinition::LS_DISTANCE) {
                // TODO: Use C++11 lambda, instead of template.
                loadAutomaticLodImpl(data.begin(), data.end(), lodConfig);
            } else {
                loadAutomaticLodImpl(data.rbegin(), data.rend(), lodConfig);
            }
            // Uncomment the ProgressiveMesh of your choice.
            // NOTE: OgreProgressiveMeshExt doesn't support collapse cost based reduction.
            // OgreProgressiveMeshExt pm;
            // ProgressiveMeshGenerator pm;
            QueuedProgressiveMeshGenerator pm;
            pm.build(lodConfig);
        } else {
            // User created Lod

            mesh->removeLodLevels();

            const LodDefinition::LodDistanceMap& data = def.getManualLodData();
            if (def.getStrategy() == LodDefinition::LS_DISTANCE) {
                // TODO: Use C++11 lambda, instead of template.
                loadUserLodImpl(data.begin(), data.end(), mesh.get());
            } else {
                loadUserLodImpl(data.rbegin(), data.rend(), mesh.get());
            }
        }
    }
}
    //-----------------------------------------------------------------------
    CollisionModelPtr CollisionModelManager::getCollisionModel(const Ogre::MeshPtr& mesh)
    {
        // Find in the cache
        CacheItemMap::iterator it = mCacheItemMap.find(mesh.get());

        if (it == mCacheItemMap.end())
        {
            // Free out-of-date collision models first
            _checkMemoryUsage();

            // Create new collision model
            CollisionModelPtr collisionModel(new CollisionModel);
            collisionModel->addMesh(mesh);
            collisionModel->build(false);

            // Add to cache
            _add(mesh, collisionModel);

            return collisionModel;
        }
        else
        {
            CacheItem* item = &it->second;

            // Update LRU queue
            _moveToFront(item);

            return item->collisionModel;
        }
    }
Esempio n. 3
0
Ogre::Mesh* EC_Mesh::PrepareMesh(const std::string& mesh_name, bool clone)
{
    if (!ViewEnabled())
        return 0;
    if (renderer_.expired())
        return 0;
    RendererPtr renderer = renderer_.lock();   
        
    Ogre::MeshManager& mesh_mgr = Ogre::MeshManager::getSingleton();
    Ogre::MeshPtr mesh = mesh_mgr.getByName(SanitateAssetIdForOgre(mesh_name));
    
    // For local meshes, mesh will not get automatically loaded until used in an entity. Load now if necessary
    if (mesh.isNull())
    {
        try
        {
            mesh_mgr.load(mesh_name, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
            mesh = mesh_mgr.getByName(mesh_name);
        }
        catch (Ogre::Exception& e)
        {
            LogError("Could not load mesh " + mesh_name + ": " + std::string(e.what()));
            return 0;
        }
    }
    
    // If mesh is still null, must abort
    if (mesh.isNull())
    {
        LogError("Mesh " + mesh_name + " does not exist");
        return 0;
    }
    
    if (clone)
    {
        try
        {
            mesh = mesh->clone(renderer->GetUniqueObjectName("EC_Mesh_clone"));
            mesh->setAutoBuildEdgeLists(false);
            cloned_mesh_name_ = mesh->getName();
        }
        catch (Ogre::Exception& e)
        {
            LogError("Could not clone mesh " + mesh_name + ":" + std::string(e.what()));
            return 0;
        }
    }
    
    if (mesh->hasSkeleton())
    {
        Ogre::SkeletonPtr skeleton = Ogre::SkeletonManager::getSingleton().getByName(mesh->getSkeletonName());
        if (skeleton.isNull() || skeleton->getNumBones() == 0)
        {
            LogDebug("Mesh " + mesh_name + " has a skeleton with 0 bones. Disabling the skeleton.");
            mesh->setSkeletonName("");
        }
    }
    
    return mesh.get();
}
    //-----------------------------------------------------------------------
    void CollisionModelManager::_add(const Ogre::MeshPtr& mesh, const CollisionModelPtr& collisionModel)
    {
        std::pair<CacheItemMap::iterator, bool> inserted =
            mCacheItemMap.insert(CacheItemMap::value_type(mesh.get(), CacheItem(mesh, collisionModel)));
        assert(inserted.second);

        _linkToFront(&inserted.first->second);
        mMemoryUsage += collisionModel->getMemoryUsage();
    }
OgrePolyvoxInterface::OgrePolyvoxInterface() {
	scene = (Ogre::SceneManager*)GraphicsManager::instance()->getInterface()->getScene();

	int width, height;
	LOG("Creating heightmap");
	float* heightmap = CreateHeightmapFromFile("..\\heightmap.png", width, height, 1.f);
	LOG("Creating volume");
	volume = new PolyVox::Volume<PolyVox::MaterialDensityPair44>(PolyVox::Region(Vector3DInt32(0,0,0), Vector3DInt32(width-1, 63, height-1)));

	LOG("Writing heightmap to volume");
	createHeightmapInVolume(volume, heightmap, width, height);
	mesh = new PolyVox::SurfaceMesh<PositionMaterialNormal>();
	SurfaceExtractor<MaterialDensityPair44> surfaceExtractor(volume, volume->getEnclosingRegion(), mesh);
	surfaceExtractor.execute();


	const std::vector<boost::uint32_t>& indices = mesh->getIndices();
	const std::vector<PositionMaterialNormal>& vertices = mesh->getVertices();

	node = scene->getRootSceneNode()->createChildSceneNode();

	obj = scene->createManualObject();

	int vertex_count = mesh->getNoOfVertices();
	int index_count = mesh->getNoOfIndices();
	obj->estimateVertexCount(vertex_count);
	obj->estimateIndexCount(index_count);
	LOG("Building manual object");
	obj->begin("BaseWhite", Ogre::RenderOperation::OT_TRIANGLE_LIST);
	
	LOG("Building vertex data");
	for(std::vector<PositionMaterialNormal>::const_iterator pmn = vertices.begin(); pmn != vertices.end(); pmn++) {
		PolyVox::Vector3DFloat position = (*pmn).getPosition();
		PolyVox::Vector3DFloat normal = (*pmn).getNormal();
		obj->position(position.getX(), position.getY(), position.getZ());
		obj->normal(normal.getX(), normal.getY(), normal.getZ());
	}

	LOG("Building indices");
	for(int i=0; i<mesh->getNoOfIndices(); i+=3) {
		obj->triangle(indices[i], indices[i+1], indices[i+2]);
	}

	obj->end();
	char mesh_name[32];
	sprintf(mesh_name, "%i%i", rand()%1000, rand()%1000, rand()%1000, rand()%1000);
	LOG("Converting to mesh");
	Ogre::MeshPtr ptr = obj->convertToMesh(mesh_name);
	Ogre::Mesh* ogremesh = ptr.get();
	Ogre::Entity* entity = scene->createEntity("TilemapEntity", mesh_name);

	node->attachObject(entity);

	LOG("Done!");
}
Esempio n. 6
0
int main(int argc, char** argv)
{	
	static Ogre::String s_strDefault = "";
	Ogre::Root* lpRoot = new Ogre::Root(s_strDefault, s_strDefault, s_strDefault);

	CFBXLoader loader;
	if (argc > 1)
	{
		Ogre::DefaultHardwareBufferManager* lpBufferManager = new Ogre::DefaultHardwareBufferManager(); // needed because we don't have a rendersystem
		Ogre::MeshPtr lpMesh = Ogre::MeshManager::getSingleton().createManual("conversion", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
		loader.convertFbxToMesh(argv[1], lpMesh.get());
		Ogre::MeshSerializer nSerializer;
		nSerializer.exportMesh(lpMesh.get(), "test.mesh", Ogre::MESH_VERSION_1_8);

		delete lpBufferManager;
	}

	delete lpRoot;
	return 0;
}
Esempio n. 7
0
/* Creates a list of triangles and allocating all the vertexs from a mesh
 * Requires:
 * 	@cont		The Vertex container where it will been put the vertexs
 * 	@mesh		The mesh to extract the triangles
 * 	@triangles	The list to be filled with the triangles
 * Returns:
 * 	true		on success
 * 	false		otherwise
 */
bool Util::getTrianglesFromMesh(PolyStructsContainer<sm::Vertex *> &cont,
		PolyStructsContainer<Triangle *> &triangles,
		Ogre::MeshPtr mesh)
{
	ASSERT(!mesh.isNull());

	if(!cont.isEmpty()){
		debug("Warning: Not an empty container\n");
	}

	if(!triangles.isEmpty()){
		debug("Warning, triangles is not empty\n");
		ASSERT(false);
	}

	size_t vertex_count,index_count;
	Ogre::Vector3* vertices = 0;
	long unsigned* indices = 0;

	getMeshInformation(mesh.get(),vertex_count,vertices,index_count,indices);

	// TODO: hacer esta funcion mas rapida, estamos buscando para cada vector
	// el vertice asociado. Es lento

	// here we will map Ogre::Vector3[i] -> Vertex*
	std::vector<sm::Vertex *> vertexMap;
	vertexMap.resize(vertex_count);

	// fills the map of vertexs
	sm::Vertex *v = 0;
	for(size_t i = 0; i < vertex_count; ++i){
		v = findVertex(cont.getObjs(), vertices[i]);
		if(!v){
			// create a new vertex and put it in the container
			v = new sm::Vertex(vertices[i].x, vertices[i].z);
			cont.addObj(v);
		}

		// associate the vec to the vertex
		vertexMap[i] = v;
	}

	// now we have to create the triangles
	for(size_t i = 0; i < index_count; i += 3){
		triangles.addObj(new Triangle(vertexMap[indices[i]],
				vertexMap[indices[i+1]],
				vertexMap[indices[i+2]]));
	}

	delete []vertices;
	delete []indices;

	return true;
}
Esempio n. 8
0
bool AssetsManager::exportMesh(Ogre::MeshPtr mesh, const std::string& filePath)
{
	if (filePath != "") {
		Ogre::MeshSerializer serializer;
		try {
			serializer.exportMesh(mesh.get(), filePath);
			S_LOG_INFO("Exported mesh " << filePath);
		} catch (const Ogre::Exception& ex) {
			S_LOG_FAILURE("Error when exporting mesh " << mesh->getName() << "to path " << filePath <<"." << ex);
			return false;
		}
		return true;
	}
	return false;
}
btTriangleMesh* TriangleMeshFactory::addTriangleMesh(const std::string& _name, Ogre::MeshPtr _fromMesh)
{
	Ogre::MeshPtr mesh = Ogre::MeshManager::getSingleton().load(_name, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);

	//Create complex shape
	unsigned int vertexCount, indexCount;
	Ogre::Vector3* vertices;
	unsigned long* indices;
		
	OgreUtils::getMeshInformation(mesh.get(), vertexCount, vertices, indexCount, indices, Ogre::Vector3::ZERO, Ogre::Quaternion::IDENTITY, Ogre::Vector3(1.f, 1.f, 1.f)/* TODO _scale */);

	btTriangleMesh* triangleMesh = new btTriangleMesh();
	for(unsigned int i = 0; i < indexCount; i += 3)
	{
		triangleMesh->addTriangle(convert(vertices[indices[i+0]]), convert(vertices[indices[i+1]]), convert(vertices[indices[i+2]]));
	}

	mTriangleMeshes[_name] = triangleMesh;

	return triangleMesh;
}
Esempio n. 10
0
DecorativeObject::DecorativeObject(Ogre::SceneManager *mgr, Ogre::String _entName, Ogre::String _meshName, Ogre::String _nodeName, Ogre::SceneNode* parentNode,
                                   Physics* _physics,
                                   btVector3 origin, btVector3 scale,
                                   btVector3 velocity, btScalar _mass, btScalar _rest,
                                   btVector3 _localInertia, btQuaternion *rotation)
  : GameObject(mgr, _entName, _nodeName, parentNode, _physics, origin, scale, velocity, _mass, _rest, _localInertia, rotation)
{

  entity = mgr->createEntity(_entName, _meshName);
  entity->setCastShadows(true);
  node->attachObject(entity);

  Ogre::MeshPtr meshptr = Ogre::Singleton<Ogre::MeshManager>::getSingletonPtr()->load(_meshName, Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);
  MeshStrider *strider = new MeshStrider(meshptr.get());
  collisionShape = new btBvhTriangleMeshShape(strider,true,true);

  addToSimulator(Collisions::CollisionTypes::COL_COLLECTIBLE,
                 0);

  setAmbient(0.5,0.0,0.0);
  setSpecular(0.1,0,0,0.4);
  if (rotation) rotate(*rotation);
}
Esempio n. 11
0
bool AssetsManager::exportMesh(Ogre::MeshPtr mesh, const std::string& filePath)
{
	if (filePath != "") {
		Ogre::MeshSerializer serializer;
		try {
			std::string dirname(filePath);
			size_t end = dirname.find_last_of("/\\");
			if (end != std::string::npos) {
				dirname = dirname.substr(0, end);
			}
			oslink::directory osdir(dirname);
			if (!osdir.isExisting()) {
				oslink::directory::mkdir(dirname.c_str());
			}
			serializer.exportMesh(mesh.get(), filePath);
			S_LOG_INFO("Exported mesh " << filePath);
		} catch (const Ogre::Exception& ex) {
			S_LOG_FAILURE("Error when exporting mesh " << mesh->getName() << "to path " << filePath <<"." << ex);
			return false;
		}
		return true;
	}
	return false;
}
Esempio n. 12
0
void OgreExporter_c::ExportLevel(const WadLevel_c &level, const WadFile_c &file)
{	
	this->ExportLevelMaterials(level, file);

	Ogre::DefaultHardwareBufferManager hardwareBufferManager;
	Ogre::ManualObject manualMesh(level.GetName());	

	const LineDef_s *lineDefs = level.GetLineDefs();
	const size_t numLineDefs = level.GetNumLineDefs();

	const SideDef_s *sideDefs = level.GetSideDefs();
	const Sector_s *sectors = level.GetSectors();

	const Vertex_s *vertices = level.GetVertices();
	for(size_t i = 0;i < numLineDefs; ++i)
	{
		if(lineDefs[i].iLeftSideDef >= 0)
		{
			const SideDef_s &leftSide = sideDefs[lineDefs[i].iLeftSideDef];
			const Sector_s &leftSideSector = sectors[leftSide.iSector];

			const SideDef_s &rightSide = sideDefs[lineDefs[i].iRightSideDef];
			const Sector_s &rightSideSector = sectors[rightSide.iSector];


			if(leftSide.uMiddleTexture.uName != '-')
			{
				this->ExportWallMesh(manualMesh, leftSideSector.iFloorHeight, leftSideSector.iCeilHeight, leftSide.uMiddleTexture, leftSide.iOffsetX, leftSide.iOffsety, vertices, lineDefs[i], file);				
			}

			if(leftSide.uLowerTexture.uName != '-')
			{
				this->ExportWallMesh(manualMesh, leftSideSector.iFloorHeight, leftSideSector.iFloorHeight, leftSide.uLowerTexture, leftSide.iOffsetX, leftSide.iOffsety, vertices, lineDefs[i], file);				
			}

			if(leftSide.uUpperTexture.uName != '-')
			{
				this->ExportWallMesh(manualMesh, rightSideSector.iCeilHeight, leftSideSector.iCeilHeight, leftSide.uUpperTexture, leftSide.iOffsetX, leftSide.iOffsety, vertices, lineDefs[i], file);				
			}
		}
		
		if(lineDefs[i].iRightSideDef >= 0)
		{			
			const SideDef_s &rightSide = sideDefs[lineDefs[i].iRightSideDef];
			const Sector_s &rightSideSector = sectors[rightSide.iSector];

			if(rightSide.uLowerTexture.uName != '-')
			{
				const SideDef_s &leftSide = sideDefs[lineDefs[i].iLeftSideDef];
				const Sector_s &leftSideSector = sectors[leftSide.iSector];

				this->ExportWallMesh(manualMesh, rightSideSector.iFloorHeight, leftSideSector.iFloorHeight, rightSide.uLowerTexture, rightSide.iOffsetX, rightSide.iOffsety, vertices, lineDefs[i], file);				
			}	

			if(rightSide.uMiddleTexture.uName != '-')
			{
				this->ExportWallMesh(manualMesh, rightSideSector.iFloorHeight, rightSideSector.iCeilHeight, rightSide.uMiddleTexture, rightSide.iOffsetX, rightSide.iOffsety, vertices, lineDefs[i], file);				
			}		

			if(rightSide.uUpperTexture.uName != '-')
			{
				const SideDef_s &leftSide = sideDefs[lineDefs[i].iLeftSideDef];
				const Sector_s &leftSideSector = sectors[leftSide.iSector];

				this->ExportWallMesh(manualMesh, leftSideSector.iCeilHeight, rightSideSector.iCeilHeight, rightSide.uUpperTexture, rightSide.iOffsetX, rightSide.iOffsety, vertices, lineDefs[i], file);				
			}	
		}
	}

	namespace fs = boost::filesystem;

	fs::path path(strLevelDirectory);

	std::string levelName = level.GetName();
	levelName += ".mesh";

	path /= levelName;	

	Ogre::LogManager logManager;
	logManager.createLog("ogre.log", true, true, false);

	Ogre::ResourceGroupManager resourceGroupManager;
	Ogre::MeshManager meshManager;
	Ogre::LodStrategyManager logStrategyManager;
	Ogre::MeshPtr mesh = manualMesh.convertToMesh(level.GetName());

	Ogre::MeshSerializer serializer;
	serializer.exportMesh(mesh.get(), path.string());

	mesh.setNull();

	resourceGroupManager.shutdownAll();	

	this->CreateResourcesCfg();
}