Ejemplo n.º 1
0
//-------------------------------------------------------------------------------------
void App::go(void)
{
#ifdef _DEBUG
    mResourcesCfg = "resources_d.cfg";
    mPluginsCfg = "plugins_d.cfg";
#else
    mResourcesCfg = "resources.cfg";
    mPluginsCfg = "plugins.cfg";
#endif

    if (!setup())
        return;
	
	Ogre::Timer timer;
	//mRoot->startRendering();
	float lastTime = timer.getMicroseconds()/1000000.0f;
	float curTime = timer.getMicroseconds()/1000000.0f;
	while(update(curTime - lastTime))
	{
		lastTime = curTime;
		curTime = timer.getMicroseconds()/1000000.0f;
		//timer.reset();
	}

    // clean up
    destroyScene();
}
Ejemplo n.º 2
0
//---------------------------------------------------------------------
unsigned long renderThreadApp(Ogre::ThreadHandle* threadHandle) {
	LeDernierMorkid::LeDernierMorkidThreadData* threadData     = reinterpret_cast<LeDernierMorkid::LeDernierMorkidThreadData*>(threadHandle->getUserParam());
	GraphicsSystem*                             graphicsSystem = threadData->graphicsSystem;
	Ogre::Barrier*                              barrier        = threadData->barrier;

	graphicsSystem->initialize("Le Dernier Morkid");
	graphicsSystem->getInputHandler()->setGrabMousePointer(true);
	graphicsSystem->getInputHandler()->setMouseVisible(false);
	barrier->sync();

	if (graphicsSystem->getQuit()) {
		graphicsSystem->deinitialize();
		return 0; // User cancelled config
	}

	graphicsSystem->createScene();
	barrier->sync();

	Ogre::RenderWindow* renderWindow = graphicsSystem->getRenderWindow();

	Ogre::Timer   timer;
	unsigned long startTime     = timer.getMicroseconds();
	double        timeSinceLast = 1.0 / 60.0;

	while (!graphicsSystem->getQuit()) {
		graphicsSystem->beginFrameParallel();
		graphicsSystem->update(timeSinceLast);
		graphicsSystem->finishFrameParallel();

		if (!renderWindow->isVisible()) {
			// Don't burn CPU cycles unnecessary when we're minimized.
			Ogre::Threads::Sleep(500);
		}

		unsigned long endTime = timer.getMicroseconds();
		timeSinceLast         = (endTime - startTime) / 1000000.0;
		timeSinceLast         = std::min(1.0, timeSinceLast); // Prevent from going haywire.
		startTime             = endTime;
	}

	barrier->sync();

	graphicsSystem->destroyScene();
	barrier->sync();

	graphicsSystem->deinitialize();
	barrier->sync();

	return 0;
}
Ejemplo n.º 3
0
void Application::initializeCEGUI()
{
    Ogre::Timer timer;
    timer.reset();

    CEGUI::OgreRenderer::bootstrapSystem(*mOgreWindow);

    mUIRoot = static_cast<CEGUI::GUISheet*>(CEGUI::WindowManager::getSingleton().createWindow("DefaultWindow", "Root"));
    mUIRoot->setPosition(CEGUI::UVector2(CEGUI::UDim(0, 0), CEGUI::UDim(0, 0)));
    mUIRoot->setSize(CEGUI::UVector2(CEGUI::UDim(1, 0), CEGUI::UDim(1, 0)));
    mUIRoot->setVisible(true);

    CEGUI::System::getSingleton().setGUISheet(mUIRoot);

    CEGUI::SchemeManager::getSingleton().create("OISBDemo.scheme");
	CEGUI::System::getSingleton().setDefaultMouseCursor("OgreTrayImages", "MouseArrow");
    CEGUI::MouseCursor::getSingleton().hide();

    //mUIRoot->addChildWindow(CEGUI::WindowManager::getSingleton().loadWindowLayout("Introduction.layout"));
    mUIRoot->addChildWindow(CEGUI::WindowManager::getSingleton().loadWindowLayout("HUD.layout"));
    mUIHUDThrottle = static_cast<CEGUI::ProgressBar*>(CEGUI::WindowManager::getSingleton().getWindow("HUD/Throttle"));
    mUIHUDVelocity = CEGUI::WindowManager::getSingleton().getWindow("HUD/Velocity");
    mUIHUDAltitude = CEGUI::WindowManager::getSingleton().getWindow("HUD/Altitude");

    std::stringstream sstr;
    sstr << timer.getMicroseconds();

    CEGUI::Logger::getSingleton().logEvent("Time to start CEGUI: " + sstr.str());
}
Ejemplo n.º 4
0
void Application::go()
{
	Ogre::Timer loopTimer;

	bool continueRunning = true;
	while ( continueRunning )
	{
		Ogre::WindowEventUtilities::messagePump();
		
		SimpleInputManager::capture();

		// Update logic stuff
		float elapsedSeconds = loopTimer.getMicroseconds() * 1.0 / 1000000;
		updateLogic( elapsedSeconds );

		// Update graphics stuff
		updateAnimations( elapsedSeconds );
		
		bool windowClosed = m_window->isClosed();
		continueRunning &= ! windowClosed;

		updateStats();

		loopTimer.reset();
		bool renderFrameSuccess = m_root->renderOneFrame();
		continueRunning &= renderFrameSuccess;

		continueRunning &= ! m_exitRequested;		
	}
}
//  Run
//-------------------------------------------------------------------------------------
void BaseApp::Run( bool showDialog )
{
	mShowDialog = showDialog;
	if (!setup())
		return;

	if (!pSet->limit_fps)
		mRoot->startRendering();  // default
	else
	{	Ogre::Timer tim;
		while (1)
		{
			Ogre::WindowEventUtilities::messagePump();
			if (tim.getMicroseconds() > 1000000.0 / pSet->limit_fps_val)
			{
				tim.reset();
				if (!mRoot->renderOneFrame())
					break;
			}else
			if (pSet->limit_sleep >= 0)
				boost::this_thread::sleep(boost::posix_time::milliseconds(pSet->limit_sleep));
	}	}

	destroyScene();
}
Ejemplo n.º 6
0
void App::UpdThr()
{
	Ogre::Timer gtim;
	//#ifdef _WIN32
	//DWORD af = 2;
	//gtim.setOption("QueryAffinityMask", &af);
	//#endif
	gtim.reset();

	while (!mShutDown)
	{
		///  step Game  **

		double dt = double(gtim.getMicroseconds()) * 0.000001;
		gtim.reset();
		
		if (pSet->multi_thr == 1 && !bLoading)
		{
			bSimulating = true;
			bool ret = pGame->OneLoop(dt);
			if (!ret)
				mShutDown = true;

			DoNetworking();
			bSimulating = false;
		}
		boost::this_thread::sleep(boost::posix_time::milliseconds(pSet->thread_sleep));
	}
}
Ejemplo n.º 7
0
void Application::update()
{
	Ogre::Timer loopTimer;

	bool continueRunning = true;
	
	while (continueRunning)
	{
		Ogre::WindowEventUtilities::messagePump();

		SimpleInputManager::capture();
		
		float elapsedSeconds = loopTimer.getMicroseconds() * 1.0 / 1000000;

		m_NXOgreTimeController->advance(elapsedSeconds);
	
		loopTimer.reset();

		updateOverlayInfo();

		bool renderFrameSuccess = m_root->renderOneFrame();
		
		if (!renderFrameSuccess || m_exitRequested)
		{
			continueRunning = false;
		}
	}
}
Ejemplo n.º 8
0
        unsigned long yield( double frameTime, unsigned long startTime )
        {
            unsigned long endTime = mExternalTimer->getMicroseconds();

            while( frameTime * 1000000.0 > (endTime - startTime) )
            {
                endTime = mExternalTimer->getMicroseconds();

#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
                SwitchToThread();
#elif OGRE_PLATFORM == OGRE_PLATFORM_LINUX || OGRE_PLATFORM == OGRE_PLATFORM_ANDROID
                sched_yield();
#endif
            }

            return endTime;
        }
Ejemplo n.º 9
0
void Application::run()
{
    initialize();
    setupScene();

    Ogre::Timer timer;
    timer.reset();

    mRunning = true;
    while (mRunning)
    {
        const Ogre::Real delta=
            timer.getMicroseconds() * static_cast<Ogre::Real>(0.000001f);
        timer.reset();

        runOneFrame(delta);
    }

    finalize();
}
Ejemplo n.º 10
0
void Client::Play() {
    OgreEasy::SimpleOgreInit lOgreInit;
    if(!lOgreInit.initOgre()) {
        std::cout<<"Could not init ogre"<<std::endl;
        return;
    }
    Ogre::Root* lRoot = lOgreInit.mRoot.get();
    Ogre::RenderWindow* lWindow = lOgreInit.mWindow;
    World* w = new World();
    w->SetDebugMode(false);
    GameObject camObject = w->AddObject("camera");
    camObject.AddCameraComponent("camera");
    camObject.SetPosition(Ogre::Vector3(0,0,0));
    camObject.LookAt(Ogre::Vector3(0,0,0));

    GameObject& light2 = w->AddObject("point_light");
    light2.AddLightComponent(Ogre::Light::LT_DIRECTIONAL);
    light2.SetPosition(Ogre::Vector3(0,0,40));
    light2.LookAt(Ogre::Vector3(0,100,0));

    GameObject& c = w->AddPhysicsObject("esine", "cube/Cube.mesh");
    c.SetPosition(Ogre::Vector3(0,0,0));
    c.AddBoxCollider(1,1,1);
    PhysicsComponent phys = c.GetPhysicsComponent();
    phys.SetMass(1.0);
    c.SetMaterial("tex");

    GameObject& c2 = w->AddPhysicsObject("esine2", "cube/Cube.mesh");
    c2.SetPosition(Ogre::Vector3(1,2,1));
    c2.AddBoxCollider(1,1,1);
    PhysicsComponent phys2 = c2.GetPhysicsComponent();
    phys2.SetMass(1.0);
    c2.SetMaterial("tex");

    GameObject& taso = w->AddPhysicsObject("taso", "cube/other/Cube.mesh");
    taso.SetPosition(Ogre::Vector3(0, -10, 0));
    taso.AddBoxCollider(10,0.1,10);
    taso.SetMaterial("plane");
    PhysicsComponent phys3 = taso.GetPhysicsComponent();
    phys3.SetMass(0.0);

    GameObject& anim = w->AddObject("anim"  , "second_anim/Cube.mesh");
    anim.SetPosition(Ogre::Vector3(0, -5, 0));
    anim.SetMaterial("tex");

    lRoot->clearEventTimes();
    float f=0.0;
    unsigned long t=0;
    double d;
    Ogre::Timer* a = new Ogre::Timer();
    while(!lWindow->isClosed()) {
        t=a->getMicroseconds();

        camObject.SetPosition(Ogre::Vector3(cos(f)*15.0, -5, sin(f)*15.0));
        camObject.LookAt(Ogre::Vector3(-0,-10,-0), Ogre::Vector3::UNIT_Y);
        w->Update(d);

        f+=d*.5;
        d = (double)(a->getMicroseconds()-t)/1000000;
    }
    delete w;
}
Ejemplo n.º 11
0
 bool mouseReleased(const OIS::MouseEvent& evt, OIS::MouseButtonID id)
 {
  if (evt.state.buttonDown(OIS::MB_Left) == false)
   SdkSample::mouseReleased(evt, id);
  
  Ogre::Ray ray = mTrayMgr->getCursorRay(mCamera);

  beastie::ray_query result;
  
  Ogre::Timer timer;
  unsigned long rayTime = 0;
  
  timer.reset();
  bool ret = mTree->intersect(ray, 10000, result);
  rayTime = timer.getMicroseconds();
  
  mResultObject->beginUpdate(0);
  
  if (ret)
  {
   // Hit something.

   mResultObject->position(result.hitTriangle.a + (result.hitTriangle.n * 3.f));
   mResultObject->position(result.hitTriangle.b + (result.hitTriangle.n * 3.f));
   mResultObject->position(result.hitTriangle.c + (result.hitTriangle.n * 3.f));
   
   mHitPosLabelX->setCaption(Ogre::StringConverter::toString(result.globalPosition.x));
   mHitPosLabelY->setCaption(Ogre::StringConverter::toString(result.globalPosition.y));
   mHitPosLabelZ->setCaption(Ogre::StringConverter::toString(result.globalPosition.z));

  }
  else
  {
   // Didn't hit anything.
   
   // Try raycasting the ground plane.
   Ogre::Vector3 globalPosition;
  
   if (beastie::intersections::line( beastie::line(ray, 100000) , mPlane, globalPosition ))
   {
    mHitPosLabelX->setCaption(Ogre::StringConverter::toString(globalPosition.x));
    mHitPosLabelY->setCaption(Ogre::StringConverter::toString(globalPosition.y));
    mHitPosLabelZ->setCaption(Ogre::StringConverter::toString(globalPosition.z));

    float const radius = 50;
 
    // accuracy is the count of points (and lines).
    // Higher values make the circle smoother, but may slowdown the performance.
    // The performance also is related to the count of circles.
    float const accuracy = 15;
 
    for(float theta = 0; theta <= 2 * Math::PI; theta += Ogre::Math::PI / accuracy) {
      mResultObject->position(globalPosition.x + (radius * cos(theta)), 0, globalPosition.z + (radius * sin(theta)));
      mResultObject->position(globalPosition);
    }


   }
   else
   {
    
    // Really didn't click on anything at all.
    
    mHitPosLabelX->setCaption("-");
    mHitPosLabelY->setCaption("-");
    mHitPosLabelZ->setCaption("-");
    mResultObject->position(0,0,0);
    mResultObject->position(0,0,0);
    mResultObject->position(0,0,0);
    
   }
   
   
  }
  
  mResultObject->end();

  return true;
 }
Ejemplo n.º 12
0
bool NavMesher::Build()
{
  // ******* Only for OBJ Loading ****
 cleanup();
 const char * filepath = "../../media/models/";
 if (!m_geom || !m_geom->loadMesh(filepath))
 {
  delete m_geom;
  m_geom = 0;
  
  m_ctx->log(RC_LOG_ERROR, "Geom load log %s:");
 }
 assert(m_geom);
 if (!m_geom || !m_geom->getMesh())
 {
  m_ctx->log(RC_LOG_ERROR, "buildNavigation: Input mesh is not specified.");
  return false;
 }
 if(m_geom->getMesh()->getTriCount() <= 0 || m_geom->getMesh()->getVertCount()<=0)
  Ogre::Exception(0,Ogre::String("Bad verts or Triangle count. Verts: "+
  StringConverter::toString( m_geom->getMesh()->getVertCount()) + "/n"
  + "Triangles :" +StringConverter::toString(m_geom->getMesh()->getTriCount())),"NavMesher::Build");
 
 //reset timer
 Ogre::Timer tm;
 tm.reset();
 unsigned long stime = tm.getMicroseconds();
 //clear existing
 Clear();
  // ******* Only for OBJ Loading ****
 const float* bmin = m_geom->getMeshBoundsMin();
 const float* bmax = m_geom->getMeshBoundsMax();
 const float* verts = m_geom->getMesh()->getVerts();
 const int nverts = m_geom->getMesh()->getVertCount();
 const int *tris = m_geom->getMesh()->getTris();
 const int ntris = m_geom->getMesh()->getTriCount();

 if(sizeof(tris) <= 0 || ntris <= 0) {
  return false;
 }
 //
 // Step 1. Initialize build config.
 //
 
 // Init build configuration from GUI
 memset(&m_cfg, 0, sizeof(m_cfg));
 m_cfg.cs = m_cellSize;
 m_cfg.ch = m_cellHeight;
 m_cfg.walkableSlopeAngle = m_agentMaxSlope;
 m_cfg.walkableHeight = (int)ceilf(m_agentHeight / m_cfg.ch);
 m_cfg.walkableClimb = (int)floorf(m_agentMaxClimb / m_cfg.ch);
 m_cfg.walkableRadius = (int)ceilf(m_agentRadius / m_cfg.cs);
 m_cfg.maxEdgeLen = (int)(m_edgeMaxLen / m_cellSize);
 m_cfg.maxSimplificationError = m_edgeMaxError;
 m_cfg.minRegionArea = (int)rcSqr(m_regionMinSize);  // Note: area = size*size
 m_cfg.mergeRegionArea = (int)rcSqr(m_regionMergeSize); // Note: area = size*size
 m_cfg.maxVertsPerPoly = (int)m_vertsPerPoly;
 m_cfg.detailSampleDist = m_detailSampleDist < 0.9f ? 0 : m_cellSize * m_detailSampleDist;
 m_cfg.detailSampleMaxError = m_cellHeight * m_detailSampleMaxError;
 
 // Set the area where the navigation will be build.
 // Here the bounds of the input mesh are used, but the
 // area could be specified by an user defined box, etc.
 rcVcopy(m_cfg.bmin, bmin);
 rcVcopy(m_cfg.bmax, bmax);
 rcCalcGridSize(m_cfg.bmin, m_cfg.bmax, m_cfg.cs, &m_cfg.width, &m_cfg.height);
 // Reset build times gathering.
 m_ctx->resetTimers();
 // Start the build process. 
 m_ctx->startTimer(RC_TIMER_TOTAL);
 
 m_ctx->log(RC_LOG_PROGRESS, "Building navigation:");
 m_ctx->log(RC_LOG_PROGRESS, " - %d x %d cells", m_cfg.width, m_cfg.height);
 m_ctx->log(RC_LOG_PROGRESS, " - %.1fK verts, %.1fK tris", nverts/1000.0f, ntris/1000.0f);
 
 //
 // Step 2. Rasterize input polygon soup.
 //
 
 // Allocate voxel heightfield where we rasterize our input data to.
 m_solid = rcAllocHeightfield();
 if (!m_solid)
 {
  m_ctx->log(RC_LOG_ERROR, "buildNavigation: Out of memory 'solid'.");
  return false;
 }
 if (!rcCreateHeightfield(m_ctx, *m_solid, m_cfg.width, m_cfg.height, m_cfg.bmin, m_cfg.bmax, m_cfg.cs, m_cfg.ch))
 {
  m_ctx->log(RC_LOG_ERROR, "buildNavigation: Could not create solid heightfield.");
  return false;
 }
 
 // Allocate array that can hold triangle area types.
 // If you have multiple meshes you need to process, allocate
 // and array which can hold the max number of triangles you need to process.
 m_triareas = new unsigned char[ntris];
 if (!m_triareas)
 {
  m_ctx->log(RC_LOG_ERROR, "buildNavigation: Out of memory 'm_triareas' (%d).", ntris);
  return false;
 }
 
 // Find triangles which are walkable based on their slope and rasterize them.
 // If your input data is multiple meshes, you can transform them here, calculate
 // the are type for each of the meshes and rasterize them.
 memset(m_triareas, 0, ntris*sizeof(unsigned char));
 rcMarkWalkableTriangles(m_ctx, m_cfg.walkableSlopeAngle, verts, nverts, tris, ntris, m_triareas);
 rcRasterizeTriangles(m_ctx, verts, nverts, tris, m_triareas, ntris, *m_solid, m_cfg.walkableClimb);
 if (!m_keepInterResults)
 {
  delete [] m_triareas;
  m_triareas = 0;
 }
 
 //
 // Step 3. Filter walkables surfaces.
 //
 
 // Once all geoemtry is rasterized, we do initial pass of filtering to
 // remove unwanted overhangs caused by the conservative rasterization
 // as well as filter spans where the character cannot possibly stand.
 rcFilterLowHangingWalkableObstacles(m_ctx, m_cfg.walkableClimb, *m_solid);
 rcFilterLedgeSpans(m_ctx, m_cfg.walkableHeight, m_cfg.walkableClimb, *m_solid);
 rcFilterWalkableLowHeightSpans(m_ctx, m_cfg.walkableHeight, *m_solid);

 //
 // Step 4. Partition walkable surface to simple regions.
 //
 // Compact the heightfield so that it is faster to handle from now on.
 // This will result more cache coherent data as well as the neighbours
 // between walkable cells will be calculated.
 m_chf = rcAllocCompactHeightfield();
 if (!m_chf)
 {
  m_ctx->log(RC_LOG_ERROR, "buildNavigation: Out of memory 'chf'.");
  return false;
 }
 if (!rcBuildCompactHeightfield(m_ctx, m_cfg.walkableHeight, m_cfg.walkableClimb, *m_solid, *m_chf))
 {
  m_ctx->log(RC_LOG_ERROR, "buildNavigation: Could not build compact data.");
  return false;
 }
 
 if (!m_keepInterResults)
 {
  rcFreeHeightField(m_solid);
  m_solid = 0;
 }
  
 // Erode the walkable area by agent radius.
 if (!rcErodeWalkableArea(m_ctx, m_cfg.walkableRadius, *m_chf))
 {
  m_ctx->log(RC_LOG_ERROR, "buildNavigation: Could not erode.");
  return false;
 }
 // (Optional) Mark areas.
 const ConvexVolume* vols = m_geom->getConvexVolumes();
 for (int i  = 0; i < m_geom->getConvexVolumeCount(); ++i)
  rcMarkConvexPolyArea(m_ctx, vols[i].verts, vols[i].nverts, vols[i].hmin, vols[i].hmax, (unsigned char)vols[i].area, *m_chf);
 
 if (m_monotonePartitioning)
 {
  // Partition the walkable surface into simple regions without holes.
  // Monotone partitioning does not need distancefield.
  if (!rcBuildRegionsMonotone(m_ctx, *m_chf, 0, m_cfg.minRegionArea, m_cfg.mergeRegionArea))
  {
   m_ctx->log(RC_LOG_ERROR, "buildNavigation: Could not build regions.");
   return false;
  }
 }
 else
 {
  // Prepare for region partitioning, by calculating distance field along the walkable surface.
  if (!rcBuildDistanceField(m_ctx, *m_chf))
  {
   m_ctx->log(RC_LOG_ERROR, "buildNavigation: Could not build distance field.");
   return false;
  }
  // Partition the walkable surface into simple regions without holes.
  if (!rcBuildRegions(m_ctx, *m_chf, 0, m_cfg.minRegionArea, m_cfg.mergeRegionArea))
  {
   m_ctx->log(RC_LOG_ERROR, "buildNavigation: Could not build regions.");
   return false;
  }
 }
 //
 // Step 5. Trace and simplify region contours.
 //
 
 // Create contours.
 m_cset = rcAllocContourSet();
 if (!m_cset)
 {
  m_ctx->log(RC_LOG_ERROR, "buildNavigation: Out of memory 'cset'.");
  return false;
 }
 if (!rcBuildContours(m_ctx, *m_chf, m_cfg.maxSimplificationError, m_cfg.maxEdgeLen, *m_cset))
 {
  m_ctx->log(RC_LOG_ERROR, "buildNavigation: Could not create contours.");
  return false;
 }
 
 //
 // Step 6. Build polygons mesh from contours.
 //
 
 // Build polygon navmesh from the contours.
 m_pmesh = rcAllocPolyMesh();
 if (!m_pmesh)
 {
  m_ctx->log(RC_LOG_ERROR, "buildNavigation: Out of memory 'pmesh'.");
  return false;
 }
 if (!rcBuildPolyMesh(m_ctx, *m_cset, m_cfg.maxVertsPerPoly, *m_pmesh))
 {
  m_ctx->log(RC_LOG_ERROR, "buildNavigation: Could not triangulate contours.");
  return false;
 }
 
 //
 // Step 7. Create detail mesh which allows to access approximate height on each polygon.
 //
 
 m_dmesh = rcAllocPolyMeshDetail();
 if (!m_dmesh)
 {
  m_ctx->log(RC_LOG_ERROR, "buildNavigation: Out of memory 'pmdtl'.");
  return false;
 }
 if (!rcBuildPolyMeshDetail(m_ctx, *m_pmesh, *m_chf, m_cfg.detailSampleDist, m_cfg.detailSampleMaxError, *m_dmesh))
 {
  m_ctx->log(RC_LOG_ERROR, "buildNavigation: Could not build detail mesh.");
  return false;
 }
 if (!m_keepInterResults)
 {
  rcFreeCompactHeightfield(m_chf);
  m_chf = 0;
  rcFreeContourSet(m_cset);
  m_cset = 0;
 }

 // At this point the navigation mesh data is ready, you can access it from m_pmesh.
 // See rcDebugDrawPolyMesh or dtCreateNavMeshData as examples how to access the data.
 
 //
 // (Optional) Step 8. Create Detour data from Recast poly mesh.
 //
 
 // The GUI may allow more max points per polygon than Detour can handle.
 // Only build the detour navmesh if we do not exceed the limit.
 unsigned char* navData = 0;
 int navDataSize = 0;
 // Update poly flags from areas.

 for (int i = 0; i < m_pmesh->npolys; ++i)
 {
  if (m_pmesh->areas[i] == RC_WALKABLE_AREA)
   m_pmesh->areas[i] = SAMPLE_POLYAREA_GROUND;
   
  if (m_pmesh->areas[i] == SAMPLE_POLYAREA_GROUND ||
   m_pmesh->areas[i] == SAMPLE_POLYAREA_GRASS ||
   m_pmesh->areas[i] == SAMPLE_POLYAREA_ROAD)
  {
   m_pmesh->flags[i] = SAMPLE_POLYFLAGS_WALK;
  }
  else if (m_pmesh->areas[i] == SAMPLE_POLYAREA_WATER)
  {
   m_pmesh->flags[i] = SAMPLE_POLYFLAGS_SWIM;
  }
  else if (m_pmesh->areas[i] == SAMPLE_POLYAREA_DOOR)
  {
   m_pmesh->flags[i] = SAMPLE_POLYFLAGS_WALK | SAMPLE_POLYFLAGS_DOOR;
  }
 }

 memset(&m_params, 0, sizeof(m_params));
 m_params.verts = m_pmesh->verts;
 m_params.vertCount = m_pmesh->nverts;
 m_params.polys = m_pmesh->polys;
 m_params.polyAreas = m_pmesh->areas;
 m_params.polyFlags = m_pmesh->flags;
 m_params.polyCount = m_pmesh->npolys;
 m_params.nvp = m_pmesh->nvp;
 m_params.detailMeshes = m_dmesh->meshes;
 m_params.detailVerts = m_dmesh->verts;
 m_params.detailVertsCount = m_dmesh->nverts;
 m_params.detailTris = m_dmesh->tris;
 m_params.detailTriCount = m_dmesh->ntris;
 m_params.walkableHeight = m_agentHeight;
 m_params.walkableRadius = m_agentRadius;
 m_params.walkableClimb = m_agentMaxClimb;
 rcVcopy(m_params.bmin, m_pmesh->bmin);
 rcVcopy(m_params.bmax, m_pmesh->bmax);
 m_params.cs = m_cfg.cs;
 m_params.ch = m_cfg.ch;
 m_params.buildBvTree = true;
 if (!dtCreateNavMeshData(&m_params, &navData, &navDataSize)) {
   m_ctx->log(RC_LOG_ERROR, "Could not build Detour navmesh.");
  return false;
 }
 
 m_navMesh = dtAllocNavMesh();
 if (!m_navMesh) {
  delete [] navData;
   m_ctx->log(RC_LOG_ERROR, "Could not create Detour navmesh");
  return false;
 }
 m_navQuery = dtAllocNavMeshQuery(); 
 dtStatus status = m_navQuery->init(m_navMesh, 2048);
   if (dtStatusFailed(status)) {
           m_ctx->log(RC_LOG_ERROR, "Could not init Detour navmesh query");
           return false;
   }
 if (!m_navMesh->init(navData, navDataSize, true)) {
  delete [] navData;
   m_ctx->log(RC_LOG_ERROR, "Could not init Detour navmesh");
  return false;
 }
 //take time
 stime = tm.getMicroseconds() - stime;
 DrawDebug();
 return true;
}
Ejemplo n.º 13
0
int main(int argc, const char *argv[])
{
	//GameState *graphicsGameState = 0;
	//GraphicsSystem *graphicsSystem = 0;
	//GameState *logicGameState = 0;
	OGraphics::LogicSystem *logicSystem = 0;
#if USE_F3D 1
	OGraphics::Forward3DGameState *graphicsGameState = new OGraphics::Forward3DGameState(
		"Forward3D & Clustered are techniques capable of rendering many lights. It is required in order\n"
		"to render non-shadow casting non-directional lights with the PBS implementation.\n"
		"Deferred shading has a lot of problems (transparency, antialiasing, multiple BDRF). Besides,\n"
		"it uses a lot of bandwidth. Forward+/Forward2.5 is great, but requires DX11 HW (needs UAV) and\n"
		"a Z-Prepass. This Z-prepass is often a turn off for many (even though in some cases it may\n"
		"improve performance, i.e. if you’re heavily pixel shader or ROP [Raster OPeration] bound).\n"
		"It’s not superior on all accounts, but it can work on DX10 hardware and doesn’t require a\n"
		"Z-prepass. The result is a nice generic algorithm that can run on a lot of hardware and can\n"
		"handle a lot of lights. Whether it performs better or worse than Deferred or Forward+ depends\n"
		"on the scene.\n"
		"\n\n"
		"Like its alternatives Defered & Forward+, it works best with many small lights, or few big\n"
		"lights.\n"
		"Forward3D & Clustered have many parameters, and this demo shows different presets that often\n"
		"trade quality for speed; but sometimes some presets work better on some scenarios than others.\n"
		"This demo stresses the implementation, showing you both its strengths and limitations\n"
		"   1. Increase the number of lights to show the artifacts.\n"
		"   2. Decrease the lights' radius to alleviate the artifacts.\n"
		"   3. Switch profiles to see the differences. Often profile 0 & 5 work best.\n"
		"   4. Repeat steps 1 through 3 using a High threshold.\n"
		"   5. It may be better to have fewer but bigger lights in outdoor scenes\n"
		"   6. Lights are 'lodded' based on distance to camera as a side effect of how the algorithm works\n"
		"It is quite unrealistic that all lights to have the same parameters. Heterogenous\n"
		"light parameters will give you better results.\n"
		"Also avoid keeping too many lights tight in the same place. If we increase the distance\n"
		"between each light in this sample, the artifacts begin to disappear.\n"
		"Light's size has a direct impact on quality. Theoretically all lights have an unlimited\n"
		"range. However we cut it off after certain threshold for performance reasons. Very low\n"
		"thresholds stress the F3D system, but very high thresholds will cut the light too early.\n"
		"\n"
		"Forward+ and Deferred as alternative implementations are planned in the future.\n"
		"\n"
		"This sample depends on the media files:\n"
		"   * Samples/Media/2.0/scripts/Compositors/ShadowMapDebugging.compositor");

	OGraphics::Forward3DGraphicsSystem *graphicsSystem = new OGraphics::Forward3DGraphicsSystem(graphicsGameState);
#endif
#if USE_TERRIAN 1
	OGraphics::Tutorial_TerrainGameState *graphicsGameState = new OGraphics::Tutorial_TerrainGameState(
		"--- !!! NOTE: THIS SAMPLE IS A WORK IN PROGRESS !!! ---\n"
		"This is an advanced tutorial that shows several things working together:\n"
		"   * Own Hlms implementation to render the terrain\n"
		"   * Vertex buffer-less rendering: The terrain is generated purely using SV_VertexID "
		"tricks and a heightmap texture\n"
		"   * Hlms customizations to PBS to make terrain shadows affect regular objects\n"
		"   * Compute Shaders to generate terrain shadows every frame\n"
		"   * Common terrain functionality such as loading the heightmap, generating normals, LOD.\n"
		"The Terrain system is called 'Terra' and has been isolated under the Terra folder like\n"
		"a component for easier copy-pasting into your own projects.\n\n"
		"Because every project has its own needs regarding terrain rendering, we're not providing\n"
		"Terra as an official Component, but rather as a tutorial; where users can copy paste our\n"
		"implementation and use it as is, or make their own tweaks or enhancements.\n\n"
		"This sample depends on the media files:\n"
		"   * Samples/Media/2.0/scripts/Compositors/Tutorial_Terrain.compositor\n"
		"   * Samples/Media/2.0/materials/Tutorial_Terrain/*.*\n"
		"   * Samples/Media/2.0/materials/Common/GLSL/GaussianBlurBase_cs.glsl\n"
		"   * Samples/Media/2.0/materials/Common/HLSL/GaussianBlurBase_cs.hlsl\n"
		"   * Samples/Media/Hlms/Terra/*.*\n");

	OGraphics::Tutorial_TerrainGraphicsSystem *graphicsSystem =
		new OGraphics::Tutorial_TerrainGraphicsSystem(graphicsGameState);
#endif

	graphicsGameState->_notifyGraphicsSystem(graphicsSystem);

	graphicsSystem->initialize(OGraphics::getWindowTitle());
	if (logicSystem)
		logicSystem->initialize();

	if (graphicsSystem->getQuit())
	{
		if (logicSystem)
			logicSystem->deinitialize();
		graphicsSystem->deinitialize();

		if (graphicsSystem)
			delete graphicsSystem;
		if (graphicsGameState)
			delete graphicsGameState;

		return 0; //User cancelled config
	}

	Ogre::RenderWindow *renderWindow = graphicsSystem->getRenderWindow();

	graphicsSystem->createScene01();
	if (logicSystem)
		logicSystem->createScene01();

	graphicsSystem->createScene02();
	if (logicSystem)
		logicSystem->createScene02();

#if OGRE_USE_SDL2
	//Do this after creating the scene for easier the debugging (the mouse doesn't hide itself)
	OGraphics::SdlInputHandler *inputHandler = graphicsSystem->getInputHandler();
	inputHandler->setGrabMousePointer(true);
	inputHandler->setMouseVisible(false);
#endif

	Ogre::Timer timer;
#if KYLE_TUTORIAL_GAME_LOOP 1
	unsigned long startTime = timer.getMicroseconds();
	double accumulator = OGraphics::FRAMETIME;
	double timeSinceLast = OGraphics::FRAMETIME;

	while (!graphicsSystem->getQuit())
	{
		while (accumulator >= OGraphics::FRAMETIME && logicSystem)
		{
			logicSystem->beginFrameParallel();
			logicSystem->update(static_cast<float>(OGraphics::FRAMETIME));
			logicSystem->finishFrameParallel();

			logicSystem->finishFrame();
			graphicsSystem->finishFrame();

			accumulator -= OGraphics::FRAMETIME;
		}

		graphicsSystem->beginFrameParallel();
		graphicsSystem->update(static_cast<float>(timeSinceLast));
		graphicsSystem->finishFrameParallel();
		if (!logicSystem)
			graphicsSystem->finishFrame();

		if (!renderWindow->isVisible())
		{
			//Don't burn CPU cycles unnecessary when we're minimized.
			Ogre::Threads::Sleep(500);
		}

		unsigned long endTime = timer.getMicroseconds();
		timeSinceLast = (endTime - startTime) / 1000000.0; // Presumably puts it in milliseconds
		timeSinceLast  = std::min(1.0, timeSinceLast); //Prevent from going haywire.
		accumulator += timeSinceLast;
		startTime = endTime;
	}
#else
	double dt = OGraphics::FRAMETIME;
	unsigned long startTime = timer.getMicroseconds();
	unsigned long nowTime = 0;
	while (!graphicsSystem->getQuit())
	{
		graphicsSystem->beginFrameParallel();
		graphicsSystem->update(static_cast<float>(dt));
		graphicsSystem->finishFrameParallel();
		// KYLE :: WHAT THE HELL IS THIS?
		if (!logicSystem)
			graphicsSystem->finishFrame();

		do {
			nowTime = timer.getMicroseconds();
			dt = ((nowTime - startTime) / 1000000.0);
			dt = std::min(1.0, dt);
		} while (dt < OGraphics::FRAMETIME);
		startTime = nowTime;
	}
#endif

	graphicsSystem->destroyScene();
	if (logicSystem)
	{
		logicSystem->destroyScene();
		logicSystem->deinitialize();
	}
	graphicsSystem->deinitialize();

	if (graphicsSystem)
		delete graphicsSystem;
	if (graphicsGameState)
		delete graphicsGameState;

	return 0;
}
Ejemplo n.º 14
0
int mainApp()
#endif
{
    PbsMaterialsGameState pbsMaterialsGameState(
        "Shows how to use the PBS material system. There's nothing really fancy,\n"
        "it's just programmer art. The PBS materials can be setup from script or\n"
        "code. This sample does both. At the time being, not all settings from the\n"
        "PBS implementation can be tweaked with scripts. See PbsDatablock::PbsDatablock\n"
        "constructor documentation. Also see the Hlms section of the porting guide in\n"
        "the Docs/2.0 folder.\n"
        "\n"
        "The sphere palette shows what happens when tweaking the roughness around the\n"
        "X axis; and the fresnel term around the Z axis.\n"
        "The scene is being lit by a white directional light (3-split PSSM) and two spot\n"
        "lights, one of warm colour, one cold. Both are also shadowed."
        "\n"
        "Of all the features supported by the PBS implementation, perhaps the hardest to\n"
        "to understand is the Detail Weight Map. It allows you to 'paint' the detail maps\n"
        "over the mesh, by controlling weight of each of the 4 maps via the RGBA channels\n"
        "of the weight map. 'R' controls the detail map 0, 'G' the detail map 1,\n"
        "'B' the detail map 2, and 'A' the detail map 3.\n"
        "\n"
        "This sample depends on the media files:\n"
        "   * Samples/Media/2.0/scripts/Compositors/PbsMaterials.compositor\n"
        "   * Samples/Media/2.0/materials/PbsMaterials/PbsMaterials.material\n"
        "\n"
        "Known issues:\n"
        " * Non shadow casting point & spot lights require Forward3D to be enabled (on desktop).\n"
        "   This is by design (more implementations will come: Forward+ & Deferred; for now the\n"
        "   only one working is F3D).\n"
        " * Shadow casting point lights don't work or work poorly. (feature not implemented yet)\n"
        " * If PSSM shadow casting enabled, the system requires at least one shadow-casting\n"
        "   directional light (bug)\n"
        " * Mobile version only supports forward lighting.\n"
        "\n"
        "LEGAL: Uses Saint Peter's Basilica (C) by Emil Persson under CC Attrib 3.0 Unported\n"
        "See Samples/Media/materials/textures/Cubemaps/License.txt for more information.");
    PbsMaterialsGraphicsSystem graphicsSystem( &pbsMaterialsGameState );

    pbsMaterialsGameState._notifyGraphicsSystem( &graphicsSystem );

    graphicsSystem.initialize( "PBS Materials Sample" );

    if( graphicsSystem.getQuit() )
    {
        graphicsSystem.deinitialize();
        return 0; //User cancelled config
    }

    Ogre::RenderWindow *renderWindow = graphicsSystem.getRenderWindow();

    graphicsSystem.createScene01();
    graphicsSystem.createScene02();

	graphicsSystem.SetUpCustomContent();			// create my custom contents

    //Do this after creating the scene for easier the debugging (the mouse doesn't hide itself)
    SdlInputHandler *inputHandler = graphicsSystem.getInputHandler();
    inputHandler->setGrabMousePointer( true );
    inputHandler->setMouseVisible( false );

    Ogre::Timer timer;
    unsigned long startTime = timer.getMicroseconds();

    double timeSinceLast = 1.0 / 60.0;

    while( !graphicsSystem.getQuit() )
    {
		graphicsSystem.CustomUpdate();		// update my custom rtts
        graphicsSystem.beginFrameParallel();
        graphicsSystem.update( static_cast<float>( timeSinceLast ) );
        graphicsSystem.finishFrameParallel();
        graphicsSystem.finishFrame();

        if( !renderWindow->isVisible() )
        {
            //Don't burn CPU cycles unnecessary when we're minimized.
            Ogre::Threads::Sleep( 500 );
        }

        unsigned long endTime = timer.getMicroseconds();
        timeSinceLast = (endTime - startTime) / 1000000.0;
        timeSinceLast = std::min( 1.0, timeSinceLast ); //Prevent from going haywire.
        startTime = endTime;
    }

    graphicsSystem.destroyScene();
    graphicsSystem.deinitialize();

    return 0;
}