Example #1
0
//-------------------------------------------------------------------------------------
bool BaseApplication::setup(void)
{
    Ogre::LogManager * lm = new Ogre::LogManager();
    lm->createLog("Ogre.log", true, false, false);
    mRoot = new Ogre::Root(mPluginsCfg);

    setupResources();

    bool carryOn = configure();
    if (!carryOn) return false;

    chooseSceneManager();
    createCamera();
    createViewports();

    // Set default mipmap level (NB some APIs ignore this)
    Ogre::TextureManager::getSingleton().setDefaultNumMipmaps(5);

    // Create any resource listeners (for loading screens)
    createResourceListener();
    // Load resources
    loadResources();

    // Create the scene
    createScene();

    createFrameListener();

    return true;
};
//---------------------------------------------------------------------
int MilkshapePlugin::Execute (msModel* pModel)
{
    // Do nothing if no model selected
    if (!pModel)
        return -1;

	Ogre::LogManager logMgr;
	logMgr.createLog("msOgreExporter.log", true);
	logMgr.logMessage("OGRE Milkshape Exporter Log");
	logMgr.logMessage("---------------------------");
	Ogre::ResourceGroupManager resGrpMgr;

	//
    // check, if we have something to export
    //
    if (msModel_GetMeshCount (pModel) == 0)
    {
        ::MessageBox (NULL, "The model is empty!  Nothing exported!", "OGRE Export", MB_OK | MB_ICONWARNING);
        return 0;
    }

    if (!showOptions()) return 0;

    if (exportMesh)
    {
        doExportMesh(pModel);
    }

    return 0;

}
Example #3
0
	/********************************************************************************************************
	*                           Method to write data to OGRE format                                         *
	********************************************************************************************************/
	MStatus OgreExporter::writeOgreData()
	{
		// Create singletons
		Ogre::LogManager logMgr;
		Ogre::ResourceGroupManager rgm;
		Ogre::MeshManager meshMgr;
		Ogre::SkeletonManager skelMgr;
		Ogre::MaterialManager matMgr;
		Ogre::DefaultHardwareBufferManager hardwareBufMgr;

		// Create a log
		logMgr.createLog("ogreMayaExporter.log", true);

		// Write mesh binary
		if (m_params.exportMesh)
		{
			std::cout << "Writing mesh binary...\n";
			std::cout.flush();
			stat = m_pMesh->writeOgreBinary(m_params);
			if (stat != MS::kSuccess)
			{
				std::cout << "Error writing mesh binary file\n";
				std::cout.flush();
			}
		}

		// Write skeleton binary
		if (m_params.exportSkeleton)
		{
			if (m_pMesh->getSkeleton())
			{
				std::cout << "Writing skeleton binary...\n";
				std::cout.flush();
				stat = m_pMesh->getSkeleton()->writeOgreBinary(m_params);
				if (stat != MS::kSuccess)
				{
					std::cout << "Error writing mesh binary file\n";
					std::cout.flush();
				}
			}
		}
		
		// Write materials data
		if (m_params.exportMaterial)
		{
			std::cout << "Writing materials data...\n";
			std::cout.flush();
			stat  = m_pMaterialSet->writeOgreScript(m_params);
			if (stat != MS::kSuccess)
			{
				std::cout << "Error writing materials file\n";
				std::cout.flush();
			}
		}

		return MS::kSuccess;
	}
Example #4
0
    void Entresol::SetupLogging(const String& LogFileName)
    {
        /// @todo Allow the FrameScheduler Log target to be inspected and changed here
        Ogre::LogManager* OgreLogs = Ogre::LogManager::getSingletonPtr();
        if( NULL == OgreLogs )
            { OgreLogs = new Ogre::LogManager(); }

        if(!LogFileName.empty())
        {
            OgreLogs->createLog(String("Graphics")+LogFileName,true,true);
        }
        else
        {
            OgreLogs->createLog("GraphicsMezzanine.log",true,true);
        }
        this->Aggregator = new Threading::LogAggregator();
        Aggregator->SetAggregationTarget(&WorkScheduler);
        this->WorkScheduler.AddWorkUnitMain(Aggregator, "LogAggregator");
    }
/** Setup a minimal ogre renderer
  *
  * \param custom_log Should we create a custom log
  * \param base_dir   The path to the config and data files 
  *                   (plugins.cfg and ogre.cfg
  *
  * \warning Incorrect base_dir could lead to a 'memory access violation' when
  *          launched.
  *
  * \note The \c custom_log parameter is used to avoid an Ogre3D assertion
  *       that occurs when creating our custom log. 
  *
  */
void 
OgreMinimalSetup::setupOgre(const Ogre::String& base_dir, bool custom_log)
{
  Ogre::Root *root; // The Ogre root singleton

  mListener = new SilentLogListener();

  string dir= base_dir + "config/";
  if (!dirExists(dir)){
    throw "config directory '" + dir + "' does not exist.";
  }

  try{
    if (custom_log == true)
      {
	Ogre::LogManager* logger = new Ogre::LogManager();
	assert(logger && "Failed to create an Ogre Logger");
	logger->createLog("log.log", true, false, true);
	Ogre::LogManager::getSingleton().getDefaultLog()
	  ->addListener(mListener);
      }

  }
  catch(Ogre::Exception e){
    cout << "setupOgre failed to initialize LogManager: "<< e.what() << endl;
    exit(1);
  }

  try
    {
      root = new Ogre::Root(dir + "plugins-unittests.cfg", 
			    dir + "ogre.cfg", dir + "ogre.log");
    }
  catch(Ogre::Exception e){
    cout << "setupOgre failed to initialize Ogre::Root : "<< e.what() << endl;
    exit(1);
  }

  assert(root && "Cannot initialize Ogre::Root");
  assert(Ogre::Root::getSingletonPtr() && "Cannot initialize Ogre::Root");

  // Select rendersystem
  Ogre::RenderSystemList list=Ogre::Root::getSingleton().getAvailableRenderers();
  this->debugRenderList( list );
  Ogre::Root::getSingleton().setRenderSystem(list[0]);
  Ogre::Root::getSingleton().initialise(false, "RainbruRPG blah");
  Ogre::Root::getSingleton().addResourceLocation(base_dir + "data/", "FileSystem");
  Ogre::Root::getSingleton().addResourceLocation(base_dir + "data/gui/fonts", "FileSystem");
  mRenderWindow = Ogre::Root::getSingleton().getRenderSystem()
    ->_createRenderWindow(RW_NAME, 20, 20, false);
  Ogre::TextureManager::getSingleton().setDefaultNumMipmaps(5);
 
}
bool OgreApplication::initStart(void)
{

    mPluginsCfg = "../configs/plugins.cfg";
    mResourcesCfg = "../configs/resources.cfg";

    Ogre::LogManager * lm = new Ogre::LogManager();
    lm->createLog("OgreLogfile.log", true, false, false);

    // construct Ogre::Root
    mRoot = new Ogre::Root(mPluginsCfg, "", "");

    Ogre::ConfigFile cf;
    cf.load(mResourcesCfg);

    // Go through all sections & settings in the file
    Ogre::ConfigFile::SectionIterator seci = cf.getSectionIterator();

    Ogre::String secName, typeName, archName;
    while (seci.hasMoreElements())
    {
        secName = seci.peekNextKey();
        Ogre::ConfigFile::SettingsMultiMap *settings = seci.getNext();
        Ogre::ConfigFile::SettingsMultiMap::iterator i;
        for (i = settings->begin(); i != settings->end(); ++i)
        {
            typeName = i->first;
            archName = i->second;
            Ogre::ResourceGroupManager::getSingleton().addResourceLocation(
                archName, typeName, secName);
        }
    }

    Ogre::ResourceGroupManager::getSingleton().addResourceLocation("../assets/", "FileSystem");

    Ogre::ResourceGroupManager::getSingleton().addResourceLocation("../assets/particles", "FileSystem");

    // Do not add this to the application
    Ogre::RenderSystem *rs = mRoot->getRenderSystemByName("OpenGL Rendering Subsystem");
    mRoot->setRenderSystem(rs);
    rs->setConfigOption("Full Screen", "No");
    rs->setConfigOption("Video Mode", "800 x 600 @ 32-bit colour");
    rs->setStencilCheckEnabled(true);

    mRoot->initialise(false);

    running = true;
    return true;
}
Example #7
0
void Client::StartupOgre() {
	Ogre::LogManager* logMgr = OGRE_NEW Ogre::LogManager;
	logMgr->createLog("DefaultLog", true, false, false);

	mOgreRoot = new Ogre::Root("../data/config/plugins.cfg");

	// setup resources
	// Load resource paths from config file
	Ogre::ConfigFile cf;
	cf.load("../data/config/resources.cfg");

	// Go through all sections & settings in the file
	Ogre::ConfigFile::SectionIterator seci = cf.getSectionIterator();
	Ogre::String secName, typeName, archName;
	while(seci.hasMoreElements()) {
		secName = seci.peekNextKey();
		Ogre::ConfigFile::SettingsMultiMap *settings = seci.getNext();
		Ogre::ConfigFile::SettingsMultiMap::iterator i;
		for(i = settings->begin(); i != settings->end(); ++i) {
			typeName = i->first;
			archName = i->second;
			Ogre::ResourceGroupManager::getSingleton().addResourceLocation(
				archName, typeName, secName);
		}
	}

	// configure
	// Show the configuration dialog and initialise the system
	if(!(mOgreRoot->restoreConfig() || mOgreRoot->showConfigDialog())) {
		exit(0);
	}
	mWindow = mOgreRoot->initialise(true, "Client Window");


	// Set default mipmap level (NB some APIs ignore this)
	Ogre::TextureManager::getSingleton().setDefaultNumMipmaps(5);
	// initialise all resource groups
	// Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();

	Ogre::ResourceGroupManager::getSingleton().initialiseResourceGroup("Basics");
	Ogre::ResourceGroupManager::getSingleton().initialiseResourceGroup("GUI");

	InitializeWindow();
	// ogre loaded
}
Example #8
0
bool initOgreRoot(){
	try{
		// Create logs that funnel to android logs
		Ogre::LogManager *lm = OGRE_NEW Ogre::LogManager();
		Ogre::Log *l = lm->createLog("AndroidLog", true, true, true);
		g_ll = OGRE_NEW AndroidLogListener();
		l->addListener(g_ll);
		
		// Create a root object
		g_root = OGRE_NEW Ogre::Root("", "", "");
		
		// Register the ES2 plugin
		g_gles2Plugin = OGRE_NEW Ogre::GLES2Plugin();
		Ogre::Root::getSingleton().installPlugin(g_gles2Plugin);
		
		// Register particle plugin
		g_pfxPlugin = OGRE_NEW Ogre::ParticleFXPlugin();
		Ogre::Root::getSingleton().installPlugin(g_pfxPlugin);
		
		// Grab the available render systems
		const Ogre::RenderSystemList &renderSystemList = g_root->getAvailableRenderers();
		if(renderSystemList.empty())
		{
			return false;
		}
		
		// Set the render system and init
		Ogre::RenderSystem *system = renderSystemList.front();
		g_root->setRenderSystem(system);
		g_root->initialise(false);
		
		g_lastTime = g_timer.getMilliseconds();
		
		return true;
	}catch(Ogre::Exception &e){
	}
	return false;
}
Example #9
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();
}
Example #10
0
// This function will set up everything required by Ogre
// and it will ask the user for display settings
// At the end of this function Ogre is ready to render.
// This function is mostly taken from tutorials and sample programs.
int CUIMain::SetupOgre(void)
{
	//=================
	//Ogre defaultly logs to console
	// To prevent this the LogManager has to be created
	// before the Root object.
	//=================
	Ogre::LogManager* logMgr = OGRE_NEW Ogre::LogManager;
	logMgr->createLog("Ogre.log", true, false, false);

	//=================
	//Create the Ogre root object
	// It's possible to specify as parameters the paths to the:
	// plugin file (what render systems it has to load), config file (screen resolution etc) and log file
	//=================
	if( !mRoot ) mRoot = OGRE_NEW Ogre::Root();

	//=================
	// Tell Ogre where all the needed resources are (rendersystems and so on)
	//=================
	Ogre::ConfigFile cf;
	cf.load("resources.cfg");
	
	Ogre::String secName, typeName, archName;
	Ogre::ConfigFile::SectionIterator seci = cf.getSectionIterator();
	while (seci.hasMoreElements()){
		secName = seci.peekNextKey();
		Ogre::ConfigFile::SettingsMultiMap *settings = seci.getNext();
		Ogre::ConfigFile::SettingsMultiMap::iterator i;
		
		for (i = settings->begin(); i != settings->end(); ++i)
		{
			typeName = i->first;
			archName = i->second;
			Ogre::ResourceGroupManager::getSingleton().addResourceLocation(archName, typeName, secName);
		}
	}

	//=================
	// Set up the render system.
	// Ogre will ask the user for display settings
	//=================
	if( !mRoot->showConfigDialog() )
		return 0; //The user probably clicked cancel

	mWindow = mRoot->initialise(true, "NNYv3");

	//=================
	// Load all the resources. For now, just load all resources at once. The following is from a tutorial:
	// In a very large game or application, we may have hundreds or even thousands of resources
	// that our game uses - everything from meshes to textures to scripts. At any given time though,
	// we probably will only be using a small subset of these resources. To keep down memory requirements,
	// we can load only the resources that our application is using. We do this by dividing the resources
	// into sections and only initializing them as we go. 
	//=================
	Ogre::TextureManager::getSingleton().setDefaultNumMipmaps(5);
	Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();

	//=================
	// Preparing the scene
	//=================
	mSceneMgr = mRoot->createSceneManager(Ogre::ST_EXTERIOR_CLOSE); //ST_EXTERIOR_CLOSE allows rendering terrain

	mCamera.Initialize(mSceneMgr);

	Ogre::Viewport* vp = mWindow->addViewport(mCamera.GetCamera());
	vp->setBackgroundColour(Ogre::ColourValue(0.9,0.9,0.9));
	//Fog will not work with sky ;)
	//mSceneMgr->setFog(Ogre::FOG_LINEAR, Ogre::ColourValue(0.9,0.9,0.9), 0.0, 50, 500);

	mCamera.GetCamera()->setAspectRatio(Ogre::Real(vp->getActualWidth()) / Ogre::Real(vp->getActualHeight()));
	
	//Set a moving cloud texture as background
	mSceneMgr->setSkyDome(true, "CloudySky", 5, 8);

	//Get a RaySceneQuery object. A SceneQuery object is a class that can query all
	//objects in a region or scene. RaySceneQuery has it as a base class. RaySceneQuery
	//can get all objects that intersect a ray.
	mQueryMouseMovement = mSceneMgr->createRayQuery(Ogre::Ray(), QUERY_MASK_MOUSE_MOVEMENT);
	mQueryMouseSelection = mSceneMgr->createRayQuery(Ogre::Ray(), QUERY_MASK_MOUSE_SELECTING);

	LoadWorld();

	//=================
	// Set up the CEGUI system
	//=================
	mGUIHandler = new CGUIHandler(mWindow, mSceneMgr);

	//=================
	// Create the input handler
	//=================
	mInputHandler = new CInputHandler(mWorld, mCamera, mWindow, mSceneMgr);
	mRoot->addFrameListener(mInputHandler);
	mRoot->addFrameListener(this);

	//=================
	// Create the console overlay
	//=================
	mConsoleOverlay = new ConsoleOverlay();

	return 1;
}
Example #11
0
int main(int argc, char **argv)
#endif
{
    int ret = 0;
    Ogre::Log * log = NULL;
    Ogre::Root * root = NULL;
    GameManager* game = NULL;
    Ogre::LogManager * logMgr = NULL;
    bool configCreated = false;
    std::string ogreLogPath, ogreCfgPath;
    
    srand(time(NULL));
    
    using namespace boost::filesystem;
    // Creates the Lost Marbles directory to write to
    path lostMarblesDir(utils::getLostMarblesWriteDir());
    
    try {
        if(! exists(lostMarblesDir))
            create_directories(lostMarblesDir);
    } catch(const filesystem_error& ex) {
        #if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
        MessageBoxA(NULL, ex.what(), "An exception has occurred!", MB_OK | MB_ICONERROR | MB_TASKMODAL);
        #else
        std::cerr << "An exception has occured: " << ex.what() << std::endl;
        #endif
        ret = 1;
        goto gracefulexit;
    }
    

    ogreLogPath = (lostMarblesDir / "Ogre.log").string();
    logMgr = new Ogre::LogManager();
    log = logMgr->createLog(ogreLogPath, true, true, false);
    
    ogreCfgPath = (lostMarblesDir / "Ogre.cfg").string();
    root = new Ogre::Root("Plugins.cfg",ogreCfgPath);

    log->logMessage("Main Lost Marbles write directory " + lostMarblesDir.string());
    log->logMessage("Log Path: " + ogreLogPath);
    log->logMessage("Config Path: " + ogreCfgPath);

    if(!root->restoreConfig()) {
        configCreated = root->showConfigDialog();
        root->saveConfig();
    } else
        configCreated = true;

    if(configCreated) {
        game = new GameManager();

        try {
            // initialize the game and switch to the first state
            game->start(LogoState::getInstance());
        } catch (Ogre::Exception& e) {
            #if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
            MessageBoxA(NULL, e.getFullDescription().c_str(), "An exception has occurred!", MB_OK | MB_ICONERROR | MB_TASKMODAL);
            #else
            std::cerr << "An exception has occured: " << e.getFullDescription() << std::endl;
            #endif
            ret = 1;
            goto gracefulexit;
        } 
    }

gracefulexit:
    if(game) delete game;
    if(root) delete root;
    if(logMgr) delete logMgr;
    return ret;
}
Example #12
0
 void
 setupLog() {
     static Ogre::LogManager logManager;
     logManager.createLog("default", true, false, false);
 }
void NativeEnginePrivate::initOgre()
{
#if !defined(NDEBUG)
    Ogre::String pluginsCfg = "plugins_d.cfg";
#else
    Ogre::String pluginsCfg = "plugins.cfg";
#endif

    Ogre::LogManager * lm = new Ogre::LogManager();
    Ogre::Log *log = lm->createLog("", true, false, false);
    log->addListener(this);

    /* Initialize Ogre */
    ogreRoot = new Ogre::Root(pluginsCfg);

    /* Set OpenGL render system on Ogre */
    Ogre::RenderSystem *renderSystem = ogreRoot->getRenderSystemByName("OpenGL Rendering Subsystem");
    if (!renderSystem)
        throw std::exception("Unable to find OpenGL Render System!");
    renderSystem->setConfigOption("Colour Depth", "32");
    renderSystem->setConfigOption("Fixed Pipeline Enabled", "Yes");
    renderSystem->setConfigOption("VSync", "No");
    ogreRoot->setRenderSystem(renderSystem);

    ogreRoot->initialise(false);

    /* Initialize the render window to use the GLWidget internally */
    Ogre::NameValuePairList params;
    params["externalGLControl"] = "true";
    params["externalGLContext"] = QString::number((uint)wglGetCurrentContext()).toStdString(); // TODO: Platform dependent
    params["externalWindowHandle"] = QString::number((uint)glWidget->winId()).toStdString();
    ogreWindow = ogreRoot->createRenderWindow("", glWidget->width(), glWidget->height(), false, &params);

    /* We don't use mip maps since our camera distance from all objects is fixed */
    Ogre::TextureManager::getSingleton().setDefaultNumMipmaps(0);

    /* here we could load "builtin" resources, but all other resources should be controlled by c# */
    /*Ogre::ResourceGroupManager &resourceManager = Ogre::ResourceGroupManager::getSingleton();
    resourceManager.addResourceLocation("C:/Users/Sebastian/AppData/Local/EvilTemple/data.zip", "Zip", "General", true);
    resourceManager.initialiseAllResourceGroups();*/

    /* Create the actual scene manager */
    ogreRoot->addSceneManagerFactory(new SceneFactory);
    ogreRoot->addMovableObjectFactory(new GroundDiscFactory);
    sceneManager = static_cast<Scene*>(ogreRoot->createSceneManager("Scene"));
    sceneManager->resizeWindow(glWidget->width(), glWidget->height());

    /* Create and initialize the main camera */
    camera = sceneManager->getMainCamera();

    /* Create the viewport */
    viewport = ogreWindow->addViewport(camera);
    viewport->setBackgroundColour(Ogre::ColourValue(0.5, 0.5, 0.5));

    sceneManager->setAmbientLight(Ogre::ColourValue(0, 0, 0));

    /* TEST */
    /*Ogre::Entity* model = sceneManager->createEntity("meshes/pcs/pc_human_male/pc_human_male.mesh");

    Ogre::SceneNode* headNode = sceneManager->getRootSceneNode()->createChildSceneNode();
    headNode->setPosition(0, 0, 0);
    headNode->attachObject(model);

    Ogre::AnimationState *animState = model->getAnimationState("unarmed_unarmed_idle");
    animState->setEnabled(true);
    animState->setLoop(true);
    animState->setWeight(1.0f);

    sceneManager->setAmbientLight(Ogre::ColourValue(0, 0, 0));

    // Create a light
    Ogre::Light* l = sceneManager->createLight("MainLight");
    l->setType(Ogre::Light::LT_DIRECTIONAL);
    l->setDirection(-0.6324093645670703858428703903848,
                    -0.77463436252716949786709498111783,
                    0);*/

    /* /TEST */
}
//does all the initial setup of the window, camera, etc.
void OgreDisplay::initialize()
{
	//This code is used to stop ogre from spamming it's log to the command line.
	//It works by creating a dummy loglistener that doesn't output anything
	Ogre::LogManager* logger = new Ogre::LogManager();
	QuietLog qlog;
	logger->createLog("ogre/ogre.log", true, false, true);
	if (!verbose)
	{
		Ogre::LogManager::getSingleton().getDefaultLog()->addListener(&qlog);	
	}
		
	//use the files given 
	root = new Root("ogre/plugins.cfg", "ogre/ogre.cfg", "ogre/ogre.log");

	//this code chooses the renderer to use. without plugins.cfg, this won't work
	RenderSystemList* renderers = root->getAvailableRenderers();
	assert( !renderers->empty() );
	RenderSystem* renderSystems = renderers->at(0);
	root->setRenderSystem(renderSystems);

	//set up some options for our window
	root->getRenderSystem()->setConfigOption( "Full Screen", "No" );
	root->getRenderSystem()->setConfigOption( "Video Mode", "1920x1000" );
	root->getRenderSystem()->setConfigOption( "VSync", "Yes" );
	root->saveConfig();

	//FIXME: how can I get it to read this from resources.cfg instead of manually specifying it here?
	root->addResourceLocation("./content/", "FileSystem");
	
	//if (root->showConfigDialog())
	//FIXME: make it a command line thing to not show this?
	{
		renderWindow = root->initialise(true);
	}

	//choose scene manager, make camera and do clear colour
	sceneMgr = root->createSceneManager( ST_GENERIC, "PrototypeSceneManager");
	camera = sceneMgr->createCamera("ViewCamera");
	camera->setNearClipDistance(0.1);
	camera->setFarClipDistance(1000.0);
	
	viewport = renderWindow->addViewport(camera);
	viewport->setBackgroundColour(ColourValue(1, 1, 1));
	
	camera->setAspectRatio( Real(viewport->getActualWidth()) / Real(viewport->getActualHeight()) );

	//make a texture manager and resource groups
	TextureManager::getSingleton().setDefaultNumMipmaps(5);
	
	//ResourceGroupManager::getSingleton().createResourceGroup("procgen");
	//root->addResourceLocation("../content", "FileSystem", "procgen", true);
	ResourceGroupManager::getSingleton().initialiseAllResourceGroups();

	//some ambient light
	sceneMgr->setAmbientLight(ColourValue(0.0, 0.0, 0.0));
	//set the shadow type we'll be using - commented out because it was causing a crash
	//sceneMgr->setShadowTechnique(Ogre::SHADOWTYPE_STENCIL_ADDITIVE);

	//put the camera looking at the origins
	camera->setPosition(0,0,0);
	camera->lookAt(Vector3(64,64,64));

	//create a static geometry group for doing the voxels
	sceneMgr->createStaticGeometry("voxel_grid");

	//make a billboard group.
	sceneMgr->createBillboardSet("voxel_grid");
	sceneMgr->getRootSceneNode()->attachObject(sceneMgr->getBillboardSet("voxel_grid"));
	sceneMgr->getBillboardSet("voxel_grid")->setDefaultDimensions(1.0, 1.0);
	//enable this to rendering the voxels as points
	sceneMgr->getBillboardSet("voxel_grid")->setPointRenderingEnabled(true);
	sceneMgr->getBillboardSet("voxel_grid")->setMaterialName("basic/cube_default");

	//do mesh setup stuff
	cubeCount = 0;
	cylinderCount = 0;
	this->createCubeMesh(); //use default arguments to make the default cube
	this->createCylinderMesh(); //use default arguments to make the default cylinder
}
Example #15
0
/** Callback event when clicking the export menu option. Adds an instance of the
    options dialog as a property, then uses the InspectObj XSI command to pop it up
    in a modal dialog. If it wasn't cancelled, performs an export.
*/
XSI::CStatus OnOgreMeshExportMenu( XSI::CRef& in_ref )
{	
	Ogre::LogManager logMgr;
	logMgr.createLog("OgreXSIExporter.log", true);
	CString msg(L"OGRE Exporter Version ");
	msg += OGRE_XSI_EXPORTER_VERSION;
	LogOgreAndXSI(msg);

	Application app;
	CStatus st(CStatus::OK);
	Property prop = app.GetActiveSceneRoot().GetProperties().GetItem(exportPropertyDialogName);
	if (prop.IsValid())
	{
		// Check version number
		CString currVersion(prop.GetParameterValue(L"version"));
		if (!currVersion.IsEqualNoCase(OGRE_XSI_EXPORTER_VERSION))
		{
			DeleteObj(exportPropertyDialogName);
			prop.ResetObject();
		}
	}
	if (!prop.IsValid())
	{
		prop = app.GetActiveSceneRoot().AddProperty(exportPropertyDialogName);
		prop.PutParameterValue(L"version", CString(OGRE_XSI_EXPORTER_VERSION));
	}
	
	try
	{
		// Popup Returns true if the command was cancelled otherwise it returns false. 
		CStatus ret = Popup(exportPropertyDialogName,CValue(),L"OGRE Mesh / Skeleton Export",((LONG)siModal),true);
		if (ret == CStatus::OK)
		{
			Ogre::XsiMeshExporter meshExporter;
			Ogre::XsiSkeletonExporter skelExporter;

			// retrieve the parameters
			Parameter param = prop.GetParameters().GetItem(L"objectName");
			CString objectName = param.GetValue();
			param = prop.GetParameters().GetItem( L"targetMeshFileName" );
			Ogre::String meshFileName = XSItoOgre(XSI::CString(param.GetValue()));
			if (meshFileName.empty())
			{
				OGRE_EXCEPT(Ogre::Exception::ERR_INVALIDPARAMS, 
					"You must supply a mesh file name", 
					"OGRE Exporter");
			}
			// fix any omission of '.mesh'
			if (!Ogre::StringUtil::endsWith(meshFileName, ".mesh"))
			{
				meshFileName += ".mesh";
			}
			param = prop.GetParameters().GetItem( L"mergeSubmeshes" );
			bool mergeSubmeshes = param.GetValue();
			param = prop.GetParameters().GetItem( L"exportChildren" );
			bool exportChildren = param.GetValue();
			param = prop.GetParameters().GetItem( L"calculateEdgeLists" );
			bool edgeLists = param.GetValue();
			param = prop.GetParameters().GetItem( L"calculateTangents" );
			bool tangents = param.GetValue();
			param = prop.GetParameters().GetItem( L"tangentSemantic" );
			CString tangentSemStr = param.GetValue();
			Ogre::VertexElementSemantic tangentSemantic = (tangentSemStr == L"t")?
				Ogre::VES_TANGENT : Ogre::VES_TEXTURE_COORDINATES;
			param = prop.GetParameters().GetItem( L"tangentsSplitMirrored" );
			bool tangentsSplitMirrored = param.GetValue();
			param = prop.GetParameters().GetItem( L"tangentsSplitRotated" );
			bool tangentsSplitRotated = param.GetValue();
			param = prop.GetParameters().GetItem( L"tangentsUseParity" );
			bool tangentsUseParity = param.GetValue();
			param = prop.GetParameters().GetItem( L"numLodLevels" );
			long numlods = (LONG)param.GetValue();
			Ogre::XsiMeshExporter::LodData* lodData = 0;
			if (numlods > 0)
			{
				param = prop.GetParameters().GetItem( L"lodDistanceIncrement" );
				float distanceInc = param.GetValue();

				param = prop.GetParameters().GetItem(L"lodQuota");
				CString quota = param.GetValue();

				param = prop.GetParameters().GetItem(L"lodReduction");
				float reduction = param.GetValue();

				lodData = new Ogre::XsiMeshExporter::LodData;
				float currentInc = distanceInc;
				for (int l = 0; l < numlods; ++l)
				{
					lodData->distances.push_back(currentInc);
					currentInc += distanceInc;
				}
				lodData->quota = (quota == L"p") ?
					Ogre::ProgressiveMesh::VRQ_PROPORTIONAL : Ogre::ProgressiveMesh::VRQ_CONSTANT;
				if (lodData->quota == Ogre::ProgressiveMesh::VRQ_PROPORTIONAL)
					lodData->reductionValue = reduction * 0.01;
				else
					lodData->reductionValue = reduction;

			}

			param = prop.GetParameters().GetItem( L"exportSkeleton" );
			bool exportSkeleton = param.GetValue();
			param = prop.GetParameters().GetItem( L"exportVertexAnimation" );
			bool exportVertexAnimation = param.GetValue();
			param = prop.GetParameters().GetItem( L"exportMaterials" );
			bool exportMaterials = param.GetValue();
			param = prop.GetParameters().GetItem( L"copyTextures" );
			bool copyTextures = param.GetValue();

			// create singletons
			Ogre::ResourceGroupManager rgm;
			Ogre::MeshManager meshMgr;
			Ogre::SkeletonManager skelMgr;
			Ogre::MaterialManager matMgr;
			Ogre::DefaultHardwareBufferManager hardwareBufMgr;

			
			// determine number of exportsteps
			size_t numSteps = 3 + OGRE_XSI_NUM_MESH_STEPS;
			if (numlods > 0)
				numSteps++;
			if (edgeLists)
				numSteps++;
			if (tangents)
				numSteps++;
			if (exportSkeleton)
				numSteps += 3;

			Ogre::ProgressManager progressMgr(numSteps);
			
			// Any material prefix? We need that for mesh linking too
			param = prop.GetParameters().GetItem( L"materialPrefix" );
			Ogre::String materialPrefix = XSItoOgre(XSI::CString(param.GetValue()));

			param = prop.GetParameters().GetItem( L"fps" );
			float fps = param.GetValue();
			if (fps == 0.0f)
			{
				OGRE_EXCEPT(Ogre::Exception::ERR_INVALIDPARAMS, 
					"You must supply a valid value for 'FPS'", 
					"OGRE Export");
			}

			Ogre::AnimationList selAnimList;
			if (exportSkeleton || exportVertexAnimation)
			{

				param = prop.GetParameters().GetItem( L"animationList" );
				GridData gd(param.GetValue());
				for (int a = 0; a < gd.GetRowCount(); ++a)
				{
					if (gd.GetCell(ANIMATION_LIST_EXPORT_COL, a) == true)
					{
						Ogre::AnimationEntry ae;
						ae.animationName = XSItoOgre(XSI::CString(gd.GetCell(ANIMATION_LIST_NAME_COL, a)));
						ae.ikSampleInterval = gd.GetCell(ANIMATION_LIST_IKFREQ_COL, a);
						ae.startFrame = (LONG)gd.GetCell(ANIMATION_LIST_START_COL, a);
						ae.endFrame = (LONG)gd.GetCell(ANIMATION_LIST_END_COL, a);
						selAnimList.push_back(ae);
					}
				}
			}

			if (exportSkeleton)
			{
				param = prop.GetParameters().GetItem( L"targetSkeletonFileName" );
				Ogre::String skeletonFileName = XSItoOgre(XSI::CString(param.GetValue()));
				if (skeletonFileName.empty())
				{
					OGRE_EXCEPT(Ogre::Exception::ERR_INVALIDPARAMS, 
						"You must supply a skeleton file name", 
						"OGRE Exporter");
				}

				// fix any omission of '.skeleton'
				if (!Ogre::StringUtil::endsWith(skeletonFileName, ".skeleton"))
				{
					skeletonFileName += ".skeleton";
				}

				// Truncate the skeleton filename to just the name (no path)
				Ogre::String skelName = skeletonFileName;
				int pos = skeletonFileName.find_last_of("\\");
				if (pos == Ogre::String::npos)
				{
					pos = skeletonFileName.find_last_of("/");
				}
				if (pos != Ogre::String::npos)
				{
					skelName = skelName.substr(pos+1, skelName.size() - pos - 1);
				}


				// Do the mesh
				Ogre::DeformerMap& deformers = 
					meshExporter.buildMeshForExport(mergeSubmeshes, 
						exportChildren, edgeLists, tangents, tangentSemantic, 
						tangentsSplitMirrored, tangentsSplitRotated, tangentsUseParity,
						exportVertexAnimation, selAnimList, fps, materialPrefix,
						lodData, skelName);
				// do the skeleton
				const Ogre::AxisAlignedBox& skelAABB = 
					skelExporter.exportSkeleton(skeletonFileName, deformers, fps, selAnimList);

				// Do final mesh export
				meshExporter.exportMesh(meshFileName, skelAABB);
			}
			else
			{
				Ogre::AxisAlignedBox nullbb;
				// No skeleton
				meshExporter.buildMeshForExport(mergeSubmeshes, 
					exportChildren, edgeLists, tangents, tangentSemantic, 
					tangentsSplitMirrored, tangentsSplitRotated, tangentsUseParity,
					exportVertexAnimation, selAnimList, fps, materialPrefix, lodData);
				meshExporter.exportMesh(meshFileName, nullbb);
			}

			
			delete lodData;

			// Do we want to export materials too?
			if (exportMaterials)
			{
				param = prop.GetParameters().GetItem( L"targetMaterialFileName" );
				Ogre::String materialFileName = XSItoOgre(XSI::CString(param.GetValue()));
				// fix any omission of '.material'
				if (!Ogre::StringUtil::endsWith(materialFileName, ".material"))
				{
					materialFileName += ".material";
				}
				
				Ogre::XsiMaterialExporter matExporter;
				try 
				{
					matExporter.exportMaterials(meshExporter.getMaterials(), 
						meshExporter.getTextureProjectionMap(), 
						materialFileName, copyTextures);
				}
				catch (Ogre::Exception& e)
				{
					// ignore, non-fatal and will be in log
				}
			}

		}

	}
	catch (Ogre::Exception& e)
	{
		// Will already have been logged to the Ogre log manager
		// Tell XSI
		app.LogMessage(OgretoXSI(e.getDescription()), XSI::siFatalMsg);
		app.LogMessage(OgretoXSI(e.getFullDescription()), XSI::siInfoMsg);
	}

	//DeleteObj( L"OgreMeshExportOptions" );
	return st;	
}