Exemplo n.º 1
0
void MyGame::Update(float elapsedTime)
{
    static float spawnTimer = 0;

    spawnTimer += elapsedTime;

    if(spawnTimer >= 0.15f)
    {
        Cube* c = new Cube(Vector3f(1.f, 1.f, 1.f));
        c->SetTexture(Texture::Get("!debug.png"));
        GetScene().GetRoot()->AddChild(c);
        RigidBody* rb = c->AddToPhysic(1, Vector3f(0, 25, 7.5));
        rb->ApplyForce(Vector3f(0, -10.f, 0));
        spawnTimer = 0;

        m_cubeCount++;
    }

    std::ostringstream fps;
    fps << "FPS: " << GetFps();
    m_txtFps->SetText(fps.str());

    std::ostringstream CubeCount;
    CubeCount << "Cube count: " << m_cubeCount;
    m_txtCubeCount->SetText(CubeCount.str());
}
// returns the "range" of fps, etc. for this index
HRESULT STDMETHODCALLTYPE CPushPinDesktop::GetStreamCaps(int iIndex, AM_MEDIA_TYPE **pmt, BYTE *pSCC)
{
    CAutoLock cAutoLock(m_pFilter->pStateLock());
	HRESULT hr = GetMediaType(iIndex, &m_mt); // ensure setup/re-use m_mt ...
	// some are indeed shared, apparently.
    if(FAILED(hr))
    {
        return hr;
    }

    *pmt = CreateMediaType(&m_mt); // a windows lib method, also does a copy for us
	if (*pmt == NULL) return E_OUTOFMEMORY;

	
    DECLARE_PTR(VIDEO_STREAM_CONFIG_CAPS, pvscc, pSCC);
	
    /*
	  most of these are listed as deprecated by msdn... yet some still used, apparently. odd.
	*/

    pvscc->VideoStandard = AnalogVideo_None;
    pvscc->InputSize.cx = getCaptureDesiredFinalWidth();
	pvscc->InputSize.cy = getCaptureDesiredFinalHeight();

	// most of these values are fakes..
	pvscc->MinCroppingSize.cx = getCaptureDesiredFinalWidth();
    pvscc->MinCroppingSize.cy = getCaptureDesiredFinalHeight();

    pvscc->MaxCroppingSize.cx = getCaptureDesiredFinalWidth();
    pvscc->MaxCroppingSize.cy = getCaptureDesiredFinalHeight();

    pvscc->CropGranularityX = 1;
    pvscc->CropGranularityY = 1;
    pvscc->CropAlignX = 1;
    pvscc->CropAlignY = 1;

    pvscc->MinOutputSize.cx = 1;
    pvscc->MinOutputSize.cy = 1;
    pvscc->MaxOutputSize.cx = getCaptureDesiredFinalWidth();
    pvscc->MaxOutputSize.cy = getCaptureDesiredFinalHeight();
    pvscc->OutputGranularityX = 1;
    pvscc->OutputGranularityY = 1;

    pvscc->StretchTapsX = 1; // We do 1 tap. I guess...
    pvscc->StretchTapsY = 1;
    pvscc->ShrinkTapsX = 1;
    pvscc->ShrinkTapsY = 1;

	pvscc->MinFrameInterval = m_rtFrameLength; // the larger default is actually the MinFrameInterval, not the max
	pvscc->MaxFrameInterval = 500000000; // 0.02 fps :) [though it could go lower, really...]

    pvscc->MinBitsPerSecond = (LONG) 1*1*8*GetFps(); // if in 8 bit mode 1x1. I guess.
    pvscc->MaxBitsPerSecond = (LONG) getCaptureDesiredFinalWidth()*getCaptureDesiredFinalHeight()*32*GetFps() + 44; // + 44 header size? + the palette?

	return hr;
}
Exemplo n.º 3
0
void CVideoSyncD3D::Run(CEvent& stopEvent)
{
  int64_t Now;
  int64_t LastVBlankTime;
  int NrVBlanks;
  double VBlankTime;
  int64_t systemFrequency = CurrentHostFrequency();

  // init the vblanktime
  Now = CurrentHostCounter();
  LastVBlankTime = Now;
  m_lastUpdateTime = Now - systemFrequency;
  while (!stopEvent.Signaled() && !m_displayLost && !m_displayReset)
  {
    // sleep until vblank
    Microsoft::WRL::ComPtr<IDXGIOutput> pOutput;
    DX::DeviceResources::Get()->GetOutput(&pOutput);
    HRESULT hr = pOutput->WaitForVBlank();

    // calculate how many vblanks happened
    Now = CurrentHostCounter();
    VBlankTime = (double)(Now - LastVBlankTime) / (double)systemFrequency;
    NrVBlanks = MathUtils::round_int(VBlankTime * m_fps);

    // update the vblank timestamp, update the clock and send a signal that we got a vblank
    UpdateClock(NrVBlanks, Now, m_refClock);

    // save the timestamp of this vblank so we can calculate how many vblanks happened next time
    LastVBlankTime = Now;

    if ((Now - m_lastUpdateTime) >= systemFrequency)
    {
      float fps = m_fps;
      if (fps != GetFps())
        break;
    }

    // because we had a vblank, sleep until half the refreshrate period because i think WaitForVBlank block any rendering stuf
    // without sleeping we have freeze rendering
    int SleepTime = (int)((LastVBlankTime + (systemFrequency / MathUtils::round_int(m_fps) / 2) - Now) * 1000 / systemFrequency);
    if (SleepTime > 50)
      SleepTime = 50; //failsafe
    if (SleepTime > 0)
      ::Sleep(SleepTime);
  }

  m_lostEvent.Set();
  while (!stopEvent.Signaled() && m_displayLost && !m_displayReset)
  {
    Sleep(10);
  }
}
Exemplo n.º 4
0
void InfoPanel::Paint(Draw& w)
{
	Size sz = GetSize();
	Size wsz = screenRect.GetSize();
	Color frameColor = Color(183, 183, 183);
	Color bgColor = Color(102, 102, 102);
	w.DrawRect(sz, bgColor);
	w.DrawRect(0, 0, 1, sz.cy, frameColor);
	w.DrawRect(0, 0, sz.cx, 1, frameColor);
	w.DrawRect(sz.cx - 1, 0, 1, sz.cy, frameColor);
	String info = Format("FPS: %.2f, Textures: %d (%d), Size: %d, %d", GetFps(), resources.textures.GetCount(), resources.bindedTextures, wsz.cx, wsz.cy);
	w.DrawText(5, sz.cy - 18, info, StdFont(), White);
}
HRESULT CPushPinDesktop::FillBuffer(IMediaSample *pSample)
{
	LocalOutput("video frame requested");

	__int64 startThisRound = StartCounter();
	BYTE *pData;

    CheckPointer(pSample, E_POINTER);
	if(m_bReReadRegistry) {
	  reReadCurrentStartXY(1);
	}

	
	if(!ever_started) {
		// allow it to startup until Run is called...so StreamTime can work see http://stackoverflow.com/questions/2469855/how-to-get-imediacontrol-run-to-start-a-file-playing-with-no-delay/2470548#2470548
		// since StreamTime anticipates that the graph's start time has already been set
		FILTER_STATE myState;
		CSourceStream::m_pFilter->GetState(INFINITE, &myState);
		while(myState != State_Running) {
		  // TODO accomodate for pausing better, we're single run only currently [does VLC do pausing even?]
		  Sleep(1);
		  LocalOutput("sleeping till graph running for audio...");
		  m_pParent->GetState(INFINITE, &myState);	  
		}
		ever_started = true;
	}


    // Access the sample's data buffer
    pSample->GetPointer(&pData);

    // Make sure that we're still using video format
    ASSERT_RETURN(m_mt.formattype == FORMAT_VideoInfo);

    VIDEOINFOHEADER *pVih = (VIDEOINFOHEADER*) m_mt.pbFormat;

	boolean gotNew = false; // dedupe stuff
	while(!gotNew) {

      CopyScreenToDataBlock(hScrDc, pData, (BITMAPINFO *) &(pVih->bmiHeader), pSample);
	
	  if(m_bDeDupe) {
			if(memcmp(pData, pOldData, pSample->GetSize())==0) { // took desktop:  10ms for 640x1152, still 100 fps uh guess...
			  Sleep(m_millisToSleepBeforePollForChanges);
			} else {
			  gotNew = true;
			  memcpy( /* dest */ pOldData, pData, pSample->GetSize()); // took 4ms for 640x1152, but it's worth it LOL.
			  // LODO memcmp and memcpy in the same loop LOL.
			}
	  } else {
		// it's always new for everyone else (the typical case)
	    gotNew = true;
	  }
	}

	// capture some debug stats (how long it took) before we add in our own arbitrary delay to enforce fps...
	long double millisThisRoundTook = GetCounterSinceStartMillis(startThisRound);
	fastestRoundMillis = min(millisThisRoundTook, fastestRoundMillis); // keep stats :)
	sumMillisTook += millisThisRoundTook;

	CRefTime now;
	CRefTime endFrame;
	now = 0;
	CSourceStream::m_pFilter->StreamTime(now);
	if((now > 0) && (now < previousFrameEndTime)) { // now > 0 to accomodate for if there is no reference graph clock at all...also at boot strap time to ignore it XXXX can negatives even ever happen anymore though?
		while(now < previousFrameEndTime) { // guarantees monotonicity too :P
		  LocalOutput("sleeping because %llu < %llu", now, previousFrameEndTime);
		  Sleep(1);
          CSourceStream::m_pFilter->StreamTime(now);
		}
		// avoid a tidge of creep since we sleep until [typically] just past the previous end.
		endFrame = previousFrameEndTime + m_rtFrameLength;
	    previousFrameEndTime = endFrame;
	    
	} else {
		// if there's no reference clock, it will "always" think it missed a frame
	  if(show_performance) {
		  if(now == 0) 
			  LocalOutput("probable none reference clock, streaming fastly");
		  else
	          LocalOutput("it missed a frame--can't keep up %d %llu %llu", countMissed++, now, previousFrameEndTime); // we don't miss time typically I don't think, unless de-dupe is turned on, or aero, or slow computer, buffering problems downstream, etc.
	  }
	  // have to add a bit here, or it will always be "it missed a frame" for the next round...forever!
	  endFrame = now + m_rtFrameLength;
	  // most of this stuff I just made up because it "sounded right"
	  //LocalOutput("checking to see if I can catch up again now: %llu previous end: %llu subtr: %llu %i", now, previousFrameEndTime, previousFrameEndTime - m_rtFrameLength, previousFrameEndTime - m_rtFrameLength);
	  if(now > (previousFrameEndTime - (long long) m_rtFrameLength)) { // do I even need a long long cast?
		// let it pretend and try to catch up, it's not quite a frame behind
        previousFrameEndTime = previousFrameEndTime + m_rtFrameLength;
	  } else {
		endFrame = now + m_rtFrameLength/2; // ?? seems to not hurt, at least...I guess
		previousFrameEndTime = endFrame;
	  }
	    
	}

	// accomodate for 0 to avoid startup negatives, which would kill our math on the next loop...
	previousFrameEndTime = max(0, previousFrameEndTime); 

    pSample->SetTime((REFERENCE_TIME *) &now, (REFERENCE_TIME *) &endFrame);
	//pSample->SetMediaTime((REFERENCE_TIME *)&now, (REFERENCE_TIME *) &endFrame); 
    LocalOutput("timestamping video packet as %lld -> %lld", now, endFrame);

    m_iFrameNumber++;

	// Set TRUE on every sample for uncompressed frames http://msdn.microsoft.com/en-us/library/windows/desktop/dd407021%28v=vs.85%29.aspx
    pSample->SetSyncPoint(TRUE);

	// only set discontinuous for the first...I think...
	pSample->SetDiscontinuity(m_iFrameNumber <= 1);

#ifdef _DEBUG
    // the swprintf costs like 0.04ms (25000 fps LOL)
	double m_fFpsSinceBeginningOfTime = ((double) m_iFrameNumber)/(GetTickCount() - globalStart)*1000;
	swprintf(out, L"done video frame! total frames: %d this one %dx%d -> (%dx%d) took: %.02Lfms, %.02f ave fps (%.02f is the theoretical max fps based on this round, ave. possible fps %.02f, fastest round fps %.02f, negotiated fps %.06f), frame missed %d", 
		m_iFrameNumber, m_iCaptureConfigHeight, m_iCaptureConfigWidth, getNegotiatedFinalWidth(), getNegotiatedFinalHeight(), millisThisRoundTook, m_fFpsSinceBeginningOfTime, 1.0*1000/millisThisRoundTook,   
		/* average */ 1.0*1000*m_iFrameNumber/sumMillisTook, 1.0*1000/fastestRoundMillis, GetFps(), countMissed);
	LocalOutput(out);
	set_config_string_setting(L"frame_stats", out);
#endif
    return S_OK;
}
bool CMaxInterface::ExportAnimationFromMaxscriptCall(const std::string& strFilename, void* _AnimExportParams)
{
	if (!_AnimExportParams)
	{
		theExporter.SetLastError("_AnimExportParams pointer is null.", __FILE__, __LINE__);
		return false;
	}

	AnimExportParams*	param = reinterpret_cast<AnimExportParams*>(_AnimExportParams);


	// build a skeleton candidate
	CSkeletonCandidate skeletonCandidate;

	//Remove user interface
	/*// show export wizard sheet
	CAnimationExportSheet sheet("Cal3D Animation Export", GetMainWnd());
	sheet.SetSkeletonCandidate(&skeletonCandidate);
	sheet.SetAnimationTime(GetStartFrame(), GetEndFrame(), GetCurrentFrame(), GetFps());
	sheet.SetWizardMode();
	if(sheet.DoModal() != ID_WIZFINISH) return true;
	*/

	//Following block replaces the user interface interactions
	{
		// create the skeleton candidate from the skeleton file
		if(! skeletonCandidate.CreateFromSkeletonFile(param->m_skeletonfilepath))
		{
			AfxMessageBox(theExporter.GetLastError().c_str(), MB_OK | MB_ICONEXCLAMATION);
			return false;
		}	

		//Set all bones in our array of nodes selected
		std::vector<CBoneCandidate *>& vectorBoneCandidate = skeletonCandidate.GetVectorBoneCandidate();

		int NumElemInTabMaxscript = param->m_tabbones.Count();

		// Select bone candidates that are in our array
		int idx = 0;
		const int numelems = vectorBoneCandidate.size();
		for (idx = 0;idx<numelems;idx++)
		{
			CBoneCandidate * bonecandidate = vectorBoneCandidate[idx];
			if (! bonecandidate)return false;

			//Deselect it
			bonecandidate->SetSelected(false);
			
			int j;
			for (j=0;j<NumElemInTabMaxscript;j++)
			{
				std::string bcname		= bonecandidate->GetNode()->GetName();
				std::string	bonename	= param->m_tabbones[j]->GetName();

				if (bcname == bonename)
				{
					//This bone candidate is in the array passed by maxscript, so select it.
					bonecandidate->SetSelected(true);
					break;
				}
			}
		}
	}

  CalCoreAnimationPtr coreAnimation = theExporter.ExtractAnimation(
      skeletonCandidate,
      param->m_startframe,
      param->m_endframe,
      param->m_frameoffset,
      GetFps(),
      param->m_framerate);
  if (!coreAnimation)
  {
    return false;
  }

  // save core animation to the file
	if(!CalSaver::saveCoreAnimation(strFilename, coreAnimation.get()))
	{
		theExporter.SetLastError(CalError::getLastErrorText(), __FILE__, __LINE__);
		return false;
	}

	return true;
}
HRESULT CPushPinDesktop::FillBuffer(IMediaSample *pSample)
{
	__int64 startThisRound = StartCounter();
	BYTE *pData;

    CheckPointer(pSample, E_POINTER);
	if(m_bReReadRegistry) {
	  reReadCurrentPosition(1);
	}

    // Access the sample's data buffer
    pSample->GetPointer(&pData);

    // Make sure that we're still using video format
    ASSERT(m_mt.formattype == FORMAT_VideoInfo);

    VIDEOINFOHEADER *pVih = (VIDEOINFOHEADER*) m_mt.pbFormat;

	// for some reason the timings are messed up initially, as there's no start time at all for the first frame (?) we don't start in State_Running ?
	// race condition?
	// so don't do some calculations unless we're in State_Running
	FILTER_STATE myState;
	CSourceStream::m_pFilter->GetState(INFINITE, &myState);
	bool fullyStarted = myState == State_Running;
	
	boolean gotNew = false;
	while(!gotNew) {

      CopyScreenToDataBlock(hScrDc, pData, (BITMAPINFO *) &(pVih->bmiHeader), pSample);
	
	  if(m_bDeDupe) {
			if(memcmp(pData, pOldData, pSample->GetSize())==0) { // took desktop:  10ms for 640x1152, still 100 fps uh guess...
			  Sleep(m_millisToSleepBeforePollForChanges);
			} else {
			  gotNew = true;
			  memcpy( /* dest */ pOldData, pData, pSample->GetSize()); // took 4ms for 640x1152, but it's worth it LOL.
			  // LODO memcmp and memcpy in the same loop LOL.
			}
	  } else {
		// it's always new for everyone else!
	    gotNew = true;
	  }
	}
	// capture how long it took before we add in our own arbitrary delay to enforce fps...
	long double millisThisRoundTook = GetCounterSinceStartMillis(startThisRound);
	fastestRoundMillis = min(millisThisRoundTook, fastestRoundMillis); // keep stats :)
	sumMillisTook += millisThisRoundTook;

	CRefTime now;
	CRefTime endFrame;
    CSourceStream::m_pFilter->StreamTime(now);

    // wait until we "should" send this frame out...
	if((now > 0) && (now < previousFrameEndTime)) { // now > 0 to accomodate for if there is no reference graph clock at all...also boot strap time ignore it :P
		while(now < previousFrameEndTime) { // guarantees monotonicity too :P
		  Sleep(1);
          CSourceStream::m_pFilter->StreamTime(now);
		}
		// avoid a tidge of creep since we sleep until [typically] just past the previous end.
		endFrame = previousFrameEndTime + m_rtFrameLength;
	    previousFrameEndTime = endFrame;
	    
	} else {
	  if(show_performance)
	    LocalOutput("it missed a frame--can't keep up %d", countMissed++); // we don't miss time typically I don't think, unless de-dupe is turned on, or aero, or slow computer, buffering problems downstream, etc.
	  // have to add a bit here, or it will always be "it missed some time" for the next round...forever!
	  endFrame = now + m_rtFrameLength;
	  // most of this stuff I just made up because it "sounded right"
	  //LocalOutput("checking to see if I can catch up again now: %llu previous end: %llu subtr: %llu %i", now, previousFrameEndTime, previousFrameEndTime - m_rtFrameLength, previousFrameEndTime - m_rtFrameLength);
	  if(now > (previousFrameEndTime - (long long) m_rtFrameLength)) { // do I need a long long cast?
		// let it pretend and try to catch up, it's not quite a frame behind
        previousFrameEndTime = previousFrameEndTime + m_rtFrameLength;
	  } else {
		endFrame = now + m_rtFrameLength/2; // ?? seems to work...I guess...
		previousFrameEndTime = endFrame;
	  }
	    
	}
	previousFrameEndTime = max(0, previousFrameEndTime);// avoid startup negatives, which would kill our math on the next loop...
    
	// LocalOutput("marking frame with timestamps: %llu %llu", now, endFrame);
    pSample->SetTime((REFERENCE_TIME *) &now, (REFERENCE_TIME *) &endFrame);
	//pSample->SetMediaTime((REFERENCE_TIME *)&now, (REFERENCE_TIME *) &endFrame); //useless seemingly

	if(fullyStarted) {
      m_iFrameNumber++;
	}

	// Set TRUE on every sample for uncompressed frames http://msdn.microsoft.com/en-us/library/windows/desktop/dd407021%28v=vs.85%29.aspx
    pSample->SetSyncPoint(TRUE);

	// only set discontinuous for the first...I think...
	pSample->SetDiscontinuity(m_iFrameNumber <= 1);

    // the swprintf costs like 0.04ms (25000 fps LOL)
	m_fFpsSinceBeginningOfTime = ((double) m_iFrameNumber)/(GetTickCount() - globalStart)*1000;
	swprintf(out, L"done frame! total frames: %d this one %dx%d -> (%dx%d) took: %.02Lfms, %.02f ave fps (%.02f is the theoretical max fps based on this round, ave. possible fps %.02f, fastest round fps %.02f, negotiated fps %.06f), frame missed %d", 
		m_iFrameNumber, m_iCaptureConfigHeight, m_iCaptureConfigWidth, getNegotiatedFinalWidth(), getNegotiatedFinalHeight(), millisThisRoundTook, m_fFpsSinceBeginningOfTime, 1.0*1000/millisThisRoundTook,   
		/* average */ 1.0*1000*m_iFrameNumber/sumMillisTook, 1.0*1000/fastestRoundMillis, GetFps(), countMissed);
//#ifdef _DEBUG // probably not worth it but we do hit this a lot...hmm...
	LocalOutput(out);
	set_config_string_setting(L"frame_stats", out);
//#endif
    return S_OK;
}
Exemplo n.º 8
0
void Render ()
{
   LoadFPS (60);
   glClearColor (250/255.0, 245/255.0, 245/255.0, 1);
   srand (time (NULL) );
   //at global scope
   static float currentRayAngle = 0;
   currentRayAngle += 6;
   //calculate points of ray


   b2Vec2 p1 ( b2Vec2 (agent->body->GetPosition ().x,
                       agent->body->GetPosition ().y) ); //center of scene
   b2Vec2 p2 = p1 + rayLength * b2Vec2 (sinf (DEGTORAD * (currentRayAngle  ) ),
                                        cosf ( DEGTORAD * (currentRayAngle ) ) );

   b2Vec2 p3 ( b2Vec2 (agent->body->GetPosition ().x,
                       agent->body->GetPosition ().y) );
   b2Vec2 p4 = p3 + rayLength * b2Vec2 (sinf (DEGTORAD * (currentRayAngle + 90) ),
                                        cosf ( DEGTORAD * (currentRayAngle + 90) ) );

   b2Vec2 p5 ( b2Vec2 (agent->body->GetPosition ().x,
                       agent->body->GetPosition ().y) ); //center of scene
   b2Vec2 p6 = p5 + rayLength * b2Vec2 (sinf (DEGTORAD * (currentRayAngle + 180) ),
                                        cosf ( DEGTORAD * (currentRayAngle + 180) ) );

   b2Vec2 p7 ( b2Vec2 (agent->body->GetPosition ().x,
                       agent->body->GetPosition ().y) );
   b2Vec2 p8 = p7 + rayLength * b2Vec2 (sinf (DEGTORAD * (currentRayAngle + 270 ) ),
                                        cosf ( DEGTORAD * (currentRayAngle + 270 ) ) );
   b2Vec2 p9 =  b2Vec2 (agent->body->GetPosition ().x ,
                        agent->body->GetPosition ().y  - 4 ) ;
   b2Vec2 p10 = b2Vec2 (agent->body->GetPosition ().x ,
                        agent->body->GetPosition ().y - 4 )  + rayLength / 2.0 * b2Vec2 (sinf ( (
                                 agent->angle + 1.57) ),
                              cosf ( ( agent->angle + 1.57  ) ) );

   b2Vec2 p11 =  b2Vec2 (agent->body->GetPosition ().x ,
                         agent->body->GetPosition ().y + 4  ) ;
   b2Vec2 p12 = b2Vec2 (agent->body->GetPosition ().x,
                        agent->body->GetPosition ().y + 4   )  + rayLength / 2.0  * b2Vec2 (sinf ( (
                                 agent->angle + 1.57) ),
                              cosf ( ( agent->angle + 1.57 ) ) );

   b2RayCastInput input;
   input.p1 = p1;
   input.p2 = p2;
   input.maxFraction = rayLength / 50.0;

   b2RayCastInput input2;
   input2.p1 = p3;
   input2.p2 = p4;
   input2.maxFraction = rayLength / 50.0;

   b2RayCastInput input3;
   input3.p1 = p5;
   input3.p2 = p6;
   input3.maxFraction = rayLength / 50.0 ;

   b2RayCastInput input4;
   input4.p1 = p7;
   input4.p2 = p8;
   input4.maxFraction = rayLength / 50.0;

   b2RayCastInput input5;
   input5.p1 = p9;
   input5.p2 = p10;
   input5.maxFraction = rayLength / 50.0;

   b2RayCastInput input6;
   input6.p1 = p11;
   input6.p2 = p12;
   input6.maxFraction = rayLength / 50.0;

   //check every fixture of every body to find closest
   float closestFraction = rayLength / 50.0; //start with end of line as p2
   float closestFraction2 = rayLength / 50.0 ;
   float closestFraction3 =  rayLength / 50.0;
   float closestFraction4 =  rayLength / 50.0;
   float closestFraction5 = rayLength / 50.0;
   float closestFraction6 = rayLength / 50.0;
   static int timer = 0;
   timer++;
   b2Vec2 intersectionNormal (0, 0);

   bool isObstacle[5] = {0} ;
   static int freeAngle[5] = {0};
   freeAngle[1] = agent->angle;
   static int count = 0 ;
   /*
    * Raycasting is done here, there are 6 ray here
   */
   for (b2Body * b = myWorld.GetBodyList (); b; b = b->GetNext () )
   {
      if (100 == (int) b->GetUserData () )
      { break; }
      for (b2Fixture * f = b->GetFixtureList (); f; f = f->GetNext () )
      {
         b2RayCastOutput output;

         if ( f->RayCast ( &output, input, 0 ) )
         {
            if ( output.fraction < closestFraction )
            {
               isObstacle[1] = 1;

               count = 0 ;
               closestFraction = output.fraction;
               intersectionNormal = output.normal;
               b2Vec2 intersectionPoint = p1 + closestFraction * (p2 - p1);
               b2Vec2 diff1  =  agent->body->GetPosition () - intersectionPoint;

               int x = diff1.x / (800 / 80.0) ;
               int y = diff1.y / (600 / 60.0) ;
               carCollisionMap[20 - y][20 - x] = 1;
            }
         }

         b2RayCastOutput output2;
         if (f->RayCast (&output2, input2, 0) )
         {
            if (output2.fraction < closestFraction)
            {
               isObstacle[2] = 1;
               closestFraction2 = output2.fraction;
               b2Vec2 intersectionPoint2 = p3 + closestFraction2 * (p4 - p3);

               b2Vec2 diff2 =  agent->body->GetPosition () - intersectionPoint2;
               int x = diff2.x / (800 / 80.0) ;
               int y = diff2.y / (600 / 60.0) ;
               carCollisionMap[20 - y][20 - x] = 1;
            }

         }
         b2RayCastOutput output3;
         if (f->RayCast (&output3, input3, 0) )
         {
            if (output3.fraction < closestFraction3)
            {
               isObstacle[3] = 1;
               closestFraction3 = output3.fraction;
               b2Vec2 intersectionPoint3 = p5 + closestFraction3 * (p6 - p5);

               b2Vec2 diff2 =  agent->body->GetPosition () - intersectionPoint3;
               int x = diff2.x / (800 / 80.0) ;
               int y = diff2.y / (600 / 60.0) ;
               carCollisionMap[20 - y][20 - x] = 1;
            }
         }

         b2RayCastOutput output4;
         if (f->RayCast (&output4, input4, 0) )
         {
            if (output4.fraction < closestFraction4)
            {
               isObstacle[4] = 1;
               closestFraction4 = output4.fraction;
               b2Vec2 intersectionPoint4 = p7 + closestFraction4 * (p8 - p7);

               b2Vec2 diff2 =  agent->body->GetPosition () - intersectionPoint4;
               int x = diff2.x / (800 / 80.0) ;
               int y = diff2.y / (600 / 60.0) ;
               carCollisionMap[20 - y][20 - x] = 1;
            }
         }

         b2RayCastOutput output5;
         if (f->RayCast (&output5, input5, 0) )
         {
            if (output5.fraction < closestFraction5)
            {
               closestFraction5 = output5.fraction;
               b2Vec2 intersectionPoint5 = p9 + closestFraction5 * (p10 - p9);

               b2Vec2 diff2 =  agent->body->GetPosition () - intersectionPoint5;
               int x = diff2.x / (800 / 80.0) ;
               int y = diff2.y / (600 / 60.0) ;
               carCollisionMap[20 - y][20 - x] = 1;
               agent->frontObstacle = 1;
            }
         }
         b2RayCastOutput output6;
         if (f->RayCast (&output6, input6, 0) )
         {
            if (output6.fraction < closestFraction6)
            {
               closestFraction6 = output6.fraction;
               b2Vec2 intersectionPoint6 = p11 + closestFraction6 * (p12 - p11);

               b2Vec2 diff2 =  agent->body->GetPosition () - intersectionPoint6;
               int x = diff2.x / (800 / 80.0) ;
               int y = diff2.y / (600 / 60.0) ;
               carCollisionMap[20 - y][20 - x] = 1;
               agent->frontObstacle = 1;
            }
         }
      }
   }

   static float timetem= glutGet(GLUT_ELAPSED_TIME);
   if(glutGet(GLUT_ELAPSED_TIME)-timetem > 1000)
   for (int i = 1 ; i <= 4; ++i)
   {
      if (isObstacle[i] == false)
      {
         float tempAngle;
         tempAngle = (int) (currentRayAngle + 90 * (i - 1) ) % 360;

         if (tempAngle >= converToDegree (agent->angle) && tempAngle <= (int) (converToDegree (agent->angle) + 180) % 360)
         {
            if (agent->nearestAngle[RIGHT_SIDE] > tempAngle - converToDegree (agent->angle) )
            {
               agent->nearestAngle[RIGHT_SIDE] = tempAngle - converToDegree (agent->angle) ;

            }
            else
            { isObstacle[i] = true; }
         }
         else
         {
            if (agent->nearestAngle[LEFT_SIDE] > (360 - tempAngle) - converToDegree (agent->angle) )
            { agent->nearestAngle[LEFT_SIDE] = fabs ( (360 - tempAngle) - converToDegree (agent->angle) ); }
            else
            { isObstacle[i] = true; }
         }

      }
      timetem= glutGet(GLUT_ELAPSED_TIME);
   }


// if no obstacle is infront of behicle and destination is set, then head for the destination
// this is done by changing vehicle angle to face the destination



   b2Vec2 intersectionPoint  = p1  + closestFraction  * (p2 - p1);
   b2Vec2 intersectionPoint2 = p3  + closestFraction2 * (p4 - p3);
   b2Vec2 intersectionPoint3 = p5  + closestFraction3 * (p6 - p5);
   b2Vec2 intersectionPoint4 = p7  + closestFraction4 * (p8 - p7);
   b2Vec2 intersectionPoint5 = p9  + closestFraction4 * (p10 - p9);
   b2Vec2 intersectionPoint6 = p11 + closestFraction4 * (p12 - p11);
   float dist = (agent->body->GetPosition().x - intersectionPoint5.x) * (agent->body->GetPosition().x - intersectionPoint5.x)
               + (agent->body->GetPosition().y - intersectionPoint5.y) * (agent->body->GetPosition().x - intersectionPoint5.y);
   //draw a line
   glColor3f (255, 0, 0); //white
   glBegin (GL_LINES);
   glVertex2f ( p1.x, p1.y );
   glVertex2f ( intersectionPoint.x, intersectionPoint.y );
   glEnd ();

   SetRenderColor (0, 0, 0, 255);
   if (isObstacle[1] == false)
   { SetRenderColor (255, 0, 255, 255); }
   //draw a point at the intersection point
   glPointSize (10);

   glBegin (GL_POINTS);
   glVertex2f ( intersectionPoint.x, intersectionPoint.y );
   glEnd ();

   SetRenderColor (255, 34, 25, 255);
   glBegin (GL_POINTS);
   glVertex2f ( destination.x, destination.y );
   glEnd ();

   glBegin (GL_LINES);
   glVertex2f ( p3.x, p3.y );
   glVertex2f ( intersectionPoint2.x, intersectionPoint2.y );
   glEnd ();

   glBegin (GL_LINES);
   glVertex2f ( p5.x, p5.y );
   glVertex2f ( intersectionPoint3.x, intersectionPoint3.y );
   glEnd ();

   glBegin (GL_LINES);
   glVertex2f ( p7.x, p7.y );
   glVertex2f ( intersectionPoint4.x, intersectionPoint4.y );
   glEnd ();

   glBegin (GL_LINES);
   glVertex2f ( p9.x, p9.y );
   glVertex2f ( intersectionPoint5.x, intersectionPoint5.y );
   glEnd ();
   glBegin (GL_POINTS);
   glVertex2f ( intersectionPoint5.x, intersectionPoint5.y );
   glEnd ();
   glBegin (GL_LINES);
   glVertex2f ( p11.x, p11.y );
   glVertex2f ( intersectionPoint6.x, intersectionPoint6.y );
   glEnd ();

   glBegin (GL_POINTS);
   glVertex2f ( intersectionPoint6.x, intersectionPoint6.y );
   glEnd ();
   SetRenderColor (0, 0, 0, 255);
   if (isObstacle[2] == false)
   { SetRenderColor (255, 0, 255, 255); }
   glPointSize (10);
   glBegin (GL_POINTS);
   glVertex2f ( intersectionPoint2.x, intersectionPoint2.y );
   glEnd ();


   SetRenderColor (0, 0, 0, 255);
   if (isObstacle[3] == false)
   { SetRenderColor (255, 0, 255, 255); }
   glBegin (GL_POINTS);
   glVertex2f ( intersectionPoint3.x, intersectionPoint3.y );
   glEnd ();


   SetRenderColor (0, 0, 0, 255);
   if (isObstacle[4] == false)
   { SetRenderColor (255, 0, 255, 255); }

   glBegin (GL_POINTS);
   glVertex2f ( intersectionPoint4.x, intersectionPoint4.y );
   glEnd ();

//   glBegin (GL_LINES);
//   glVertex2f ( agent->body->GetPosition ().x, agent->body->GetPosition ().y );
//   glVertex2f ( agent->body->GetPosition ().x + sin (agent->angle + 1.57) * 100,
//                agent->body->GetPosition ().y + cos (agent->angle + 1.57) * 100);
//   glEnd ();

   static float posx = 0;
   posx = posx + .1;
// we are drawing collision array here
   for (int i = 0; i < 40; ++i)
      for (int j = 0; j < 40; ++j)
      {
         if (carCollisionMap[i][j] == 1)
         {
            glPointSize (5);
            glBegin (GL_POINTS);
            glVertex2f (agent->body->GetPosition ().x -  (20 - j) * 10 ,
                        agent->body->GetPosition ().y -  (20 - i) * 10 );

            glEnd ();
         }
      }

   turnToDestination();
   turnToNearestAngle ();
   agent->isCollision = 0;

//  checking collision here, not so important now
   for (int i = 1; i < 15; ++i)
   {
      float x = 20  + (i * 2) * sinf (agent->angle + 1.57) ;
      float y = 20  +  (i * 2) * cosf (agent->angle + 1.57);
      if (x < 40 && y < 40)
         if (carCollisionMap[ (int) y][ (int) x] == 1)
         {
//               printf ("obstacle found\n");
            agent->isCollision = 1;
            static float timerT = glutGet (GLUT_ELAPSED_TIME);
            bool safe = 1;
            safe = rand () % 2;
            if (!agent->frontObstacle)
               if (agent->nearestAngle[LEFT_SIDE] != 1000 || agent->nearestAngle[RIGHT_SIDE] != 1000)
               {
//                  if (glutGet (GLUT_ELAPSED_TIME) - timerT > 500)
                  {
                     if (agent->nearestAngle[LEFT_SIDE] < agent->nearestAngle[RIGHT_SIDE])
                     {
                        printf ("Left side wins %f\n", agent->nearestAngle[LEFT_SIDE]);
                        agent->angle = agent->angle - .2;
                        agent->foundNearestAngle = true;
//                  agent->nearestAngle[RIGHT_SIDE] = 1000;
                     }
                     else
                     {
                        printf ("Right side wins %f\n", agent->nearestAngle[RIGHT_SIDE]);
                        agent->foundNearestAngle = true;
//                  agent->nearestAngle[LEFT_SIDE] = 1000;
                        agent->angle = agent->angle + .2;
                     }
                 timerT = glutGet (GLUT_ELAPSED_TIME);
                  }
               }
//            if (glutGet (GLUT_ELAPSED_TIME) - timerT > 1000)
//            {
//
//               if (safe == 1)
//                  for (int j = 0; j < 10; ++j)
//                  {
//                     float x = 20 + ( (j ) * sinf (agent->angle + 1.57 + .3) ) ;
//                     float y = 20 + ( (j ) * cosf (agent->angle + 1.57 + .3) ) ;
//
//                     if (carCollisionMap[ (int) y][ (int) x] == 1)
//                     {
//                        safe = 0;
//                        break;
//                     }
//                  }
//               if (safe == 1)
//               { agent->angle = agent->angle + .3; }
//               {
//                  memset (carCollisionMap, 0, sizeof (carCollisionMap) );
//               }
//               if (safe == 0)
//               {
//                  safe = 1;
//                  for (int j = 0; j < 10; ++j)
//                  {
//                     float x = 20 + ( (j ) * sinf (agent->angle + 1.57 - .3) ) ;
//                     float y = 20 + ( (j ) * cosf (agent->angle + 1.57 - .3) ) ;
//                     if (carCollisionMap[ (int) y][ (int) x] == 1)
//                     {
//                        safe = 0;
//                        break;
//                     }
//                  }
//                  if (safe == 1)
//                  {
//                     agent->angle = agent->angle - .3;
//                     memset (carCollisionMap, 0, sizeof (carCollisionMap) );
//                  }
//               }
//               timerT = glutGet (GLUT_ELAPSED_TIME);
//            }

         }
   }

   agent->moveForward ();
   SetRenderColor (0, 0, 0, 255);

   RenderBitmapText (60, 550, GLUT_BITMAP_9_BY_15, "ctrl + left click to add obstacle, alt + left click to add a destination");

   sprintf (fps, "%f", GetFps () );
   SetRenderColor (255, 0, 255, 255);
   RenderBitmapText (10, 590, GLUT_BITMAP_9_BY_15, fps);

   myWorld.DrawDebugData ();

}
Exemplo n.º 9
0
int SGP_MaxInterface::GetFrameCount()
{
	return (GetEndTick()-GetStartTick())/GetFps() + 1;
}