V2D Lens:: profile(const double alpha) const { const double r = Radius__(alpha); return V2D(r*Sin(alpha),Radius__(0)-r*Cos(alpha)); }
FlareExample(void) : shape(shape_prog, shapes::SpiralSphere()) , n_flares(32) , queries(n_flares) { std::vector<Vec3f> light_positions(n_flares); for(GLuint i=0; i!=n_flares; ++i) { const float rand_max = float(RAND_MAX); auto angle = FullCircles(std::rand()/rand_max); light_positions[i] = Vec3f( 7.0f*Cos(angle), 0.2f*(std::rand()/rand_max)-0.1f, 7.0f*Sin(angle) ); } shape_prog.light_position.Set(light_positions); shape_prog.color_1 = Vec3f(0.3f, 0.3f, 0.5f); shape_prog.color_2 = Vec3f(0.8f, 0.8f, 1.0f); Texture::Active(0); shape_prog.metal_tex.Set(0); metal_texture << TextureTarget::_2D << TextureMinFilter::LinearMipmapLinear << TextureMagFilter::Linear << TextureWrap::Repeat << images::BrushedMetalUByte( 512, 512, 5120, -12, +12, 32, 64 ) << TextureMipmap(); Texture::Active(1); UniformSampler(flare_prog, "FlareTex").Set(1); flare_texture << TextureTarget::_2D << TextureMinFilter::LinearMipmapLinear << TextureMagFilter::Linear << images::LoadTexture("flare_1") << TextureMipmap(); (TextureTarget::_2D|0) << TextureWrap::MirroredRepeat; (TextureTarget::_2D|1) << TextureWrap::Repeat; lights.Bind(); try { light_pos.Bind(Buffer::Target::Array); Buffer::Data(Buffer::Target::Array, light_positions); light_prog.Use(); VertexArrayAttrib light_attr(light_prog, "Position"); light_attr.Setup<Vec3f>(); light_attr.Enable(); flare_prog.Use(); VertexArrayAttrib flare_attr(flare_prog, "Position"); flare_attr.Setup<Vec3f>(); flare_attr.Enable(); } catch(Error&) { } gl.ClearColor(0.1f, 0.1f, 0.1f, 0.0f); gl.ClearDepth(1.0f); gl.Enable(Capability::ProgramPointSize); gl.Enable(Capability::DepthTest); gl.Enable(Capability::CullFace); gl.CullFace(Face::Back); gl.BlendFunc(BlendFn::SrcAlpha, BlendFn::One); }
func FxDischargeStop(object target, proplist effect, int reason, bool temporary) { if(temporary) return; Sound("Ball::ball_discharge", false, 70); var flashparticle = { Alpha = 100, Size = DischargeSize * 2, R = pR, G = pG, B = pB, Rotation = PV_Random(0,360), BlitMode = GFX_BLIT_Additive, }; CreateParticle("StarSpark", 0, 0, 0, 0, 10, flashparticle, 5); for(var o in FindObjects(Find_Distance(DischargeSize), Find_Func("CanBeHit", this))) { var angle = Angle(GetX(), GetY(), o->GetX(), o->GetY()); o->AddBallHitEffect(); o->Fling(Sin(angle, 8), -Cos(angle, 8)); WeaponDamage(o, DischargeDamage); } for(var r = 5; r < DischargeSize; r += 5) { for(var i = 0; i < 360; i+= 1) { var props = { Size = PV_Linear(4, 0), Rotation = PV_Random(0, 360), R = pR, G = pG, B = pB, Alpha = PV_Linear(255,0), BlitMode = GFX_BLIT_Additive, }; var x = Sin(i, r + RandomX(-2, 2)); var y = -Cos(i, r + RandomX(-2, 2)); CreateParticle("StarSpark", x, y, 0, 0, 25, props, 2); } } var props = { Size = PV_Linear(20, 200), R = pR, G = pG, B = pB, Alpha = PV_Linear(180, 0), BlitMode = GFX_BLIT_Additive, }; CreateParticle("Shockwave2", 0, 0, 0, 0, 10, props, 1); Sound("Ball::ball_after_discharge", false, 30); Idle(); }
//Used to assign actions to keyboard presses. void key(unsigned char ch,int x,int y) { //change the mode of viewing the scene if(ch == '1') { mode = 0; dim = 860; th = 0; ph = 0; outside=1; } //change the mode of viewing the scene else if(ch == '2') { mode = 1; dim = 800; th = 0; ph = 0; xOffset = 0; yOffset = 0; zOffset = -1600; outside=1; } //reset angle using 4 if(ch == '4') { th=0; ph=0; } //reset zoom using 5 else if(ch == '5') dim=860; //reset first person location using 6 else if(ch == '6') { xOffset = 0; yOffset = 0; zOffset = -1600; outside = 1; } else if(ch == '7') { minHrOffset=0; } //exit using esc else if(ch == 27) exit(0); //zoom out else if(ch == '[') dim += 30; //zoom in else if(ch == ']') dim -= 30; //FIRST PERSON NAVIGATION WITH WASD else if(ch == 'w' || ch == 'W') { xOffset -= 20*Sin(th); zOffset += 20*Cos(th); checkOffsets(); } else if(ch == 's' || ch == 'S') { xOffset += 20*Sin(th); zOffset -= 20*Cos(th); checkOffsets(); } else if(ch == 'a' || ch == 'A') { xOffset -= 20*Sin(th-90); zOffset += 20*Cos(th-90); checkOffsets(); } else if(ch == 'd' || ch == 'D') { xOffset += 20*Sin(th-90); zOffset -= 20*Cos(th-90); checkOffsets(); } else if(ch == 't' || ch == 'T') { minHrOffset-=5; if(minHrOffset < -minOfHr) minHrOffset = -minOfHr; } else if(ch == 'y' || ch == 'Y') { minHrOffset+=5; if(minHrOffset > (59-minOfHr)) minHrOffset = (59-minOfHr); } else if(ch == 'g' || ch == 'G') { hrDayOffset--; if(hrDayOffset < 0) hrDayOffset = 0; } else if(ch == 'h' || ch == 'H') { hrDayOffset++; if(hrDayOffset > 24) hrDayOffset = 24; } else if(ch == 'u' || ch == 'U') { minHrOffset = 0; } else if(ch == 'j' || ch == 'J') { hrDayOffset = 0; } //ensures dimension is never too small to fit arch. if(dim < 0) dim = 0; Project(fov, asp, dim); //Tells GLUT to redisplay. glutPostRedisplay(); }
void BillboardSet::UpdateVertexBuffer(const FrameInfo& frame) { // If using animation LOD, accumulate time and see if it is time to update if (animationLodBias_ > 0.0f && lodDistance_ > 0.0f) { animationLodTimer_ += animationLodBias_ * frame.timeStep_ * ANIMATION_LOD_BASESCALE; if (animationLodTimer_ >= lodDistance_) animationLodTimer_ = fmodf(animationLodTimer_, lodDistance_); else { // No LOD if immediate update forced if (!forceUpdate_) return; } } unsigned numBillboards = billboards_.Size(); unsigned enabledBillboards = 0; const Matrix3x4& worldTransform = node_->GetWorldTransform(); Matrix3x4 billboardTransform = relative_ ? worldTransform : Matrix3x4::IDENTITY; Vector3 billboardScale = scaled_ ? worldTransform.Scale() : Vector3::ONE; // First check number of enabled billboards for (unsigned i = 0; i < numBillboards; ++i) { if (billboards_[i].enabled_) ++enabledBillboards; } sortedBillboards_.Resize(enabledBillboards); unsigned index = 0; // Then set initial sort order and distances for (unsigned i = 0; i < numBillboards; ++i) { Billboard& billboard = billboards_[i]; if (billboard.enabled_) { sortedBillboards_[index++] = &billboard; if (sorted_) billboard.sortDistance_ = frame.camera_->GetDistanceSquared(billboardTransform * billboards_[i].position_); } } batches_[0].geometry_->SetDrawRange(TRIANGLE_LIST, 0, enabledBillboards * 6, false); bufferDirty_ = false; forceUpdate_ = false; if (!enabledBillboards) return; if (sorted_) { Sort(sortedBillboards_.Begin(), sortedBillboards_.End(), CompareBillboards); Vector3 worldPos = node_->GetWorldPosition(); // Store the "last sorted position" now previousOffset_ = (worldPos - frame.camera_->GetNode()->GetWorldPosition()); } float* dest = (float*)vertexBuffer_->Lock(0, enabledBillboards * 4, true); if (!dest) return; for (unsigned i = 0; i < enabledBillboards; ++i) { Billboard& billboard = *sortedBillboards_[i]; Vector2 size(billboard.size_.x_ * billboardScale.x_, billboard.size_.y_ * billboardScale.y_); unsigned color = billboard.color_.ToUInt(); float rotationMatrix[2][2]; rotationMatrix[0][0] = Cos(billboard.rotation_); rotationMatrix[0][1] = Sin(billboard.rotation_); rotationMatrix[1][0] = -rotationMatrix[0][1]; rotationMatrix[1][1] = rotationMatrix[0][0]; dest[0] = billboard.position_.x_; dest[1] = billboard.position_.y_; dest[2] = billboard.position_.z_; ((unsigned&)dest[3]) = color; dest[4] = billboard.uv_.min_.x_; dest[5] = billboard.uv_.min_.y_; dest[6] = -size.x_ * rotationMatrix[0][0] + size.y_ * rotationMatrix[0][1]; dest[7] = -size.x_ * rotationMatrix[1][0] + size.y_ * rotationMatrix[1][1]; dest[8] = billboard.position_.x_; dest[9] = billboard.position_.y_; dest[10] = billboard.position_.z_; ((unsigned&)dest[11]) = color; dest[12] = billboard.uv_.max_.x_; dest[13] = billboard.uv_.min_.y_; dest[14] = size.x_ * rotationMatrix[0][0] + size.y_ * rotationMatrix[0][1]; dest[15] = size.x_ * rotationMatrix[1][0] + size.y_ * rotationMatrix[1][1]; dest[16] = billboard.position_.x_; dest[17] = billboard.position_.y_; dest[18] = billboard.position_.z_; ((unsigned&)dest[19]) = color; dest[20] = billboard.uv_.max_.x_; dest[21] = billboard.uv_.max_.y_; dest[22] = size.x_ * rotationMatrix[0][0] - size.y_ * rotationMatrix[0][1]; dest[23] = size.x_ * rotationMatrix[1][0] - size.y_ * rotationMatrix[1][1]; dest[24] = billboard.position_.x_; dest[25] = billboard.position_.y_; dest[26] = billboard.position_.z_; ((unsigned&)dest[27]) = color; dest[28] = billboard.uv_.min_.x_; dest[29] = billboard.uv_.max_.y_; dest[30] = -size.x_ * rotationMatrix[0][0] - size.y_ * rotationMatrix[0][1]; dest[31] = -size.x_ * rotationMatrix[1][0] - size.y_ * rotationMatrix[1][1]; dest += 32; } vertexBuffer_->Unlock(); vertexBuffer_->ClearDataLost(); }
/* * Draws the boat */ void Boat::draw () { // dimensions // total length is 1 // total width is .6 double boatLength=1; double boatWidth=.5; double deckFrontEdge=.4; double deckBackEdge=-.6; double deckLeftEdge=-boatWidth/2; double deckRightEdge=boatWidth/2; double sideInsetWidth=.2; double frontInsetLength=boatWidth/2; double backInsetLength=.3; double deckThickness=.1; double deckSurfaceHeight=.2; double frontCornerX=deckFrontEdge-frontInsetLength; double backCornerX=deckBackEdge+backInsetLength; double deckSideLength=boatLength-(frontInsetLength+backInsetLength); double deckEndWidth=boatWidth-(2*sideInsetWidth); double hullHeightOverWater=deckSurfaceHeight-deckThickness; double hullHeightUnderWater=-.2; // prepare to draw glPushMatrix(); glTranslated(pos.x, pos.y, pos.z); // Rotate to match wave glRotated(angleToWave, vectorToWave.x,vectorToWave.y,vectorToWave.z); glRotated(heading,0,1,0); // pitch and roll are not being used to determine boat position //glRotated(pitch,0,0,1); //glRotated(roll,1,0,0); glEnable(GL_TEXTURE_2D); glColor3f(1,1,1); glBindTexture(GL_TEXTURE_2D,metalTexture); // begin drawing // Deck glBegin(GL_POLYGON); glNormal3f(0,1,0); glTexCoord2f(0,frontInsetLength/boatLength); glVertex3f(frontCornerX,deckSurfaceHeight,deckLeftEdge); glTexCoord2f(boatWidth/boatLength,frontInsetLength/boatLength); glVertex3f(frontCornerX,deckSurfaceHeight,deckRightEdge); glTexCoord2f(boatWidth/boatLength,(boatLength-backInsetLength)/boatLength); glVertex3f(backCornerX,deckSurfaceHeight,deckRightEdge); glTexCoord2f(((boatWidth/2)-sideInsetWidth)/boatLength,1); glVertex3f(deckBackEdge,deckSurfaceHeight,deckRightEdge-sideInsetWidth); glTexCoord2f(sideInsetWidth/boatLength,1); glVertex3f(deckBackEdge,deckSurfaceHeight,deckLeftEdge+sideInsetWidth); glTexCoord2f(0,(boatLength-backInsetLength)/boatLength); glVertex3f(backCornerX,deckSurfaceHeight,deckLeftEdge ); glEnd(); // deck curved top glBegin(GL_POLYGON); glNormal3f(0,1,0); for (double i=0;i<=180;i=i+5) { glTexCoord2f( ((boatWidth/boatLength)/2)+(Cos(i)*(boatWidth/2)), ( (boatWidth/2)*(1-(Sin(i))))/boatLength ); glVertex3f( frontCornerX+(Sin(i)*deckRightEdge), deckSurfaceHeight, Cos(i)*deckRightEdge); } glEnd(); // deck curved front glBegin(GL_QUAD_STRIP); glNormal3f(0,1,0); for (double i=0;i<=180;i=i+5) { glNormal3f(Sin(i),0,Cos(i)); glTexCoord2f( (i/180)*PI*deckRightEdge,0); glVertex3f( frontCornerX+(Sin(i)*deckRightEdge),deckSurfaceHeight,Cos(i)*deckRightEdge); glTexCoord2f( (i/180)*PI*deckRightEdge,deckThickness/(PI*deckRightEdge)); glVertex3f( frontCornerX+(Sin(i)*deckRightEdge),deckSurfaceHeight-deckThickness,Cos(i)*deckRightEdge); } glEnd(); // Flat Sides glBegin(GL_QUADS); // deck back side glNormal3f(-1,0,0); glTexCoord2f(0,0); glVertex3f(deckBackEdge,deckSurfaceHeight,deckLeftEdge+sideInsetWidth); glTexCoord2f( deckEndWidth/boatLength,0); glVertex3f(deckBackEdge,deckSurfaceHeight,deckRightEdge-sideInsetWidth); glTexCoord2f( deckEndWidth/boatLength,deckThickness/boatLength); glVertex3f(deckBackEdge,deckSurfaceHeight-deckThickness,deckRightEdge-sideInsetWidth); glTexCoord2f(0,deckThickness/boatLength); glVertex3f(deckBackEdge,deckSurfaceHeight-deckThickness,deckLeftEdge+sideInsetWidth); // deck left side glNormal3f(0,0,-1); glTexCoord2f(0,0); glVertex3f(frontCornerX,deckSurfaceHeight,deckLeftEdge); glTexCoord2f( deckSideLength/boatLength,0); glVertex3f(backCornerX,deckSurfaceHeight,deckLeftEdge); glTexCoord2f( deckSideLength/boatLength,deckThickness/boatLength); glVertex3f(backCornerX,deckSurfaceHeight-deckThickness,deckLeftEdge); glTexCoord2f(0,deckThickness/boatLength); glVertex3f(frontCornerX,deckSurfaceHeight-deckThickness,deckLeftEdge); // deck right side glNormal3f(0,0,1); glTexCoord2f(0,0); glVertex3f(backCornerX,deckSurfaceHeight,deckRightEdge); glTexCoord2f( deckSideLength/boatLength,0); glVertex3f(frontCornerX,deckSurfaceHeight,deckRightEdge); glTexCoord2f( deckSideLength/boatLength,deckThickness/boatLength); glVertex3f(frontCornerX,deckSurfaceHeight-deckThickness,deckRightEdge); glTexCoord2f(0,deckThickness/boatLength); glVertex3f(backCornerX,deckSurfaceHeight-deckThickness,deckRightEdge); // deck left corner side glNormal3f(-2/3,0,-3/2); glTexCoord2f(0,0); glVertex3f(backCornerX,deckSurfaceHeight,deckLeftEdge); glTexCoord2f(.36/boatLength,0); glVertex3f(deckBackEdge,deckSurfaceHeight,deckLeftEdge+sideInsetWidth); glTexCoord2f(.36/boatLength,deckThickness/boatLength); glVertex3f(deckBackEdge,deckSurfaceHeight-deckThickness,deckLeftEdge+sideInsetWidth); glTexCoord2f(0,deckThickness/boatLength); glVertex3f(backCornerX,deckSurfaceHeight-deckThickness,deckLeftEdge); // deck right corner side glNormal3f(-2/3,0,3/2); glTexCoord2f(0,0); glVertex3f(deckBackEdge,deckSurfaceHeight,deckRightEdge-sideInsetWidth); glTexCoord2f(.36/boatLength,0); glVertex3f(backCornerX,deckSurfaceHeight,deckRightEdge); glTexCoord2f(.36/boatLength,deckThickness/boatLength); glVertex3f(backCornerX,deckSurfaceHeight-deckThickness,deckRightEdge); glTexCoord2f(0,deckThickness/boatLength); glVertex3f(deckBackEdge,deckSurfaceHeight-deckThickness,deckRightEdge-sideInsetWidth); glEnd(); // Hull //front curved surface glBegin(GL_TRIANGLES); for (double i=0;i<180;i=i+5) { glNormal3f(Sin(i), -1, Cos(i)); glTexCoord2f(.5,.5); glVertex3f(frontCornerX,hullHeightUnderWater,0); glTexCoord2f(.5+Cos(i), .5+Sin(i)); glVertex3f( frontCornerX+(Sin(i)*deckRightEdge),hullHeightOverWater,Cos(i)*deckRightEdge); glTexCoord2f(.5+Cos(i+5), .5+Sin(i+5)); glVertex3f( frontCornerX+(Sin(i+5)*deckRightEdge),hullHeightOverWater,Cos(i+5)*deckRightEdge); } glEnd(); // right side of hull glBegin(GL_QUADS); glNormal3f(0,-1,1); glTexCoord2f(0,0); glVertex3f(backCornerX,hullHeightOverWater,deckRightEdge); glTexCoord2f(deckSideLength/boatLength,0); glVertex3f(frontCornerX,hullHeightOverWater,deckRightEdge); glTexCoord2f(deckSideLength/boatLength,.424/boatLength); glVertex3f(frontCornerX,hullHeightUnderWater,0); glTexCoord2f(0,.424/boatLength); glVertex3f(backCornerX,hullHeightUnderWater,0); // left side of hull glNormal3f(0,-1,-1); glTexCoord2f(0,0); glVertex3f(frontCornerX,hullHeightOverWater,deckLeftEdge); glTexCoord2f(deckSideLength/boatLength,0); glVertex3f(backCornerX,hullHeightOverWater,deckLeftEdge); glTexCoord2f(deckSideLength/boatLength,.424/boatLength); glVertex3f(backCornerX,hullHeightUnderWater,0); glTexCoord2f(0,.424/boatLength); glVertex3f(frontCornerX,hullHeightUnderWater,0); glEnd(); // back side of hull glBegin(GL_TRIANGLES); glNormal3f(-1,-1,0); glTexCoord2f(0,0); glVertex3f(deckBackEdge,hullHeightOverWater,deckLeftEdge+sideInsetWidth); glTexCoord2f( deckEndWidth/boatLength,0); glVertex3f(deckBackEdge,hullHeightOverWater,deckRightEdge-sideInsetWidth); glTexCoord2f( (deckEndWidth/boatLength)/2,.424/boatLength); glVertex3f(backCornerX,hullHeightUnderWater,0); // left corner side of hull glNormal3f(-2/3,-1,-3/2); glTexCoord2f(0,0); glVertex3f(backCornerX,hullHeightOverWater,deckLeftEdge); glTexCoord2f(.25,0); glVertex3f(deckBackEdge,hullHeightOverWater,deckLeftEdge+sideInsetWidth); glTexCoord2f(.125,.25); glVertex3f(backCornerX,hullHeightUnderWater,0); // right corner side of hull glNormal3f(-2/3,-1,3/2); glTexCoord2f(0,0); glVertex3f(deckBackEdge,hullHeightOverWater,deckRightEdge-sideInsetWidth); glTexCoord2f(.25,0); glVertex3f(backCornerX,hullHeightOverWater,deckRightEdge); glTexCoord2f(.125,.25); glVertex3f(backCornerX,hullHeightUnderWater,0); glEnd(); // Cannon base double turretheight1=.12;//.05; double turretradius1=.18;//.14 double turretheight2=.03;//.1 double turretradius2=.14;//.18 glColor3f(color.r(),color.g(),color.b()); // top of upper turret glBegin(GL_POLYGON); glNormal3f( 0,1, 0); for(double i=0;i<360;i+=5) { glTexCoord2f(.5+Cos(i)*.5, .5+.5*Sin(i)); glVertex3d(turretradius2*Sin(i),deckSurfaceHeight+turretheight1+turretheight2,turretradius2*Cos(i)); } glEnd(); // upper turret sides glBegin(GL_QUAD_STRIP); for(double i=0;i<=360;i+=5) { glNormal3f(Sin(i),0, Cos(i)); glTexCoord2f(i/360,0); glVertex3d(turretradius2*Sin(i),deckSurfaceHeight+turretheight1,turretradius2*Cos(i)); glTexCoord2f(i/360,.1); glVertex3d(turretradius2*Sin(i),deckSurfaceHeight+turretheight1+turretheight2,turretradius2*Cos(i)); } glEnd(); glColor3f(1,1,1); // top of lower turret glBegin(GL_POLYGON); glNormal3f( 0,1, 0); for(double i=0;i<360;i+=5) { glTexCoord2f(.5+Cos(i)*.5, .5+.5*Sin(i)); glVertex3d(turretradius1*Sin(i),deckSurfaceHeight+turretheight1,turretradius1*Cos(i)); } glEnd(); // lower turret sides glBegin(GL_QUAD_STRIP); for(double i=0;i<=360;i+=5) { glNormal3f(Sin(i),0, Cos(i)); glTexCoord2f(i/360,0); glVertex3d(turretradius1*Sin(i),deckSurfaceHeight,turretradius1*Cos(i)); glTexCoord2f(i/360,.1); glVertex3d(turretradius1*Sin(i),deckSurfaceHeight+turretheight1,turretradius1*Cos(i)); } glEnd(); double centerOfSphere=deckSurfaceHeight+turretheight1+turretheight2+.1; // Cannon barrel drawCannonBarrel(centerOfSphere); glPopMatrix(); }
// // Draw vertex in polar coordinates // static void Vertex(double th,double ph) { glVertex3d(Sin(th)*Cos(ph),Cos(th)*Cos(ph),Sin(ph)); }
global func CosX(iA,iMin,iMax) { return(Cos(iA,(iMax-iMin)/2)+(iMax+iMin)/2); }
/* Implementation *************************************************************/ void CFreqSyncAcq::ProcessDataInternal(CParameter& ReceiverParam) { int i, j; int iMaxIndex_fxp; FXP rMaxValue_fxp; int iNumDetPeaks_fxp; int iDiffTemp; CReal rLevDiff; _BOOLEAN bNoPeaksLeft_fxp; CFRealVector vecrPSDPilPoin_fxp(3); FILE* pFile_fxp; if (bAquisition == TRUE) { /* Do not transfer any data to the next block if no frequency acquisition was successfully done */ iOutputBlockSize = 0; /* Add new symbol in history (shift register) */ vecrFFTHistory_fxp.AddEnd(*pvecInputData, iInputBlockSize); /* Start algorithm when history memory is filled -------------------- */ /* Wait until history memory is filled for the first FFT operation. ("> 1" since, e.g., if we would have only one buffer, we can start immediately) */ if (iAquisitionCounter > 1) { /* Decrease counter */ iAquisitionCounter--; } else { /* Copy vector to matlib vector and calculate real-valued FFTW */ const int iStartIdx = iHistBufSize - iFrAcFFTSize; for (i = 0; i < iFrAcFFTSize; i++) { vecrFFTInput_fxp[i] = vecrFFTHistory_fxp[i + iStartIdx]*(((FXP) (1.0))/((FXP) (6535.0))); } /* Calculate power spectrum (X = real(F)^2 + imag(F)^2) */ vecrSqMagFFTOut_fxp = SqMag(rfft(vecrFFTInput_fxp * vecrHammingWin_fxp, FftPlan)); /* Calculate moving average for better estimate of PSD */ vvrPSDMovAv_fxp.Add(vecrSqMagFFTOut_fxp); /* Wait until we have sufficient data for averaging */ if (iAverageCounter > 1) { /* Decrease counter */ iAverageCounter--; } else { /* Get PSD estimate */ const CFRealVector vecrPSD_fxp(vvrPSDMovAv_fxp.GetAverage()); /* ------------------------------------------------------------- Low pass filtering over frequency axis. We do the filtering from both sides, once from right to left and then from left to the right side. Afterwards, these results are averaged This way, the noise floor is estimated */ // TODO: Introduce offset to debar peak at DC frequency (cause by DC offset of // sound cards). Set "iStartFilt" in Init() routine! const int iStartFilt = 0; // <- no offset right now /* Reset vectors for intermediate filtered result */ vecrFiltResLR_fxp.Reset((CFReal) 0); vecrFiltResRL_fxp.Reset((CFReal) 0); /* From the left edge to the right edge */ vecrFiltResLR_fxp[iStartFilt] = vecrPSD_fxp[iStartFilt]; for (i = iStartFilt + 1; i < iHalfBuffer; i++) { vecrFiltResLR_fxp[i] = (vecrFiltResLR_fxp[i - 1] - vecrPSD_fxp[i]) * LAMBDA_FREQ_IIR_FILT_fxp + vecrPSD_fxp[i]; } /* From the right edge to the left edge */ vecrFiltResRL_fxp[iHalfBuffer - 1] = vecrPSD_fxp[iHalfBuffer - 1]; for (i = iHalfBuffer - 2; i >= iStartFilt; i--) { vecrFiltResRL_fxp[i] = (vecrFiltResRL_fxp[i + 1] - vecrPSD_fxp[i]) * LAMBDA_FREQ_IIR_FILT_fxp + vecrPSD_fxp[i]; } /* Average RL and LR filter outputs */ vecrFiltRes_fxp = (vecrFiltResLR_fxp + vecrFiltResRL_fxp) * (((FXP) (1.0))/((FXP) (2.0))); #ifdef _DEBUG_ #if 0 /* Stores curves for PSD estimation and filtering */ FILE* pFile2 = fopen("test/freqacqFilt.dat", "w"); for (i = 0; i < iHalfBuffer; i++) fprintf(pFile2, "%e %e\n", vecrPSD[i], vecrFiltRes[i]); fclose(pFile2); #endif #endif /* Equalize PSD by "noise floor estimate" */ for (i = 0; i < iHalfBuffer; i++) { /* Make sure we do not devide by zero */ if (vecrFiltRes_fxp[i] != (FXP) 0) vecrPSD_fxp[i] *= (((FXP) (1.0))/(vecrFiltRes_fxp[i])); else vecrPSD_fxp[i] = 0.0; } /* Correlate known frequency-pilot structure with equalized power spectrum */ for (i = 0; i < iSearchWinSize; i++) { vecrPSDPilCor_fxp[i] = vecrPSD_fxp[i + veciTableFreqPilots[0]] + vecrPSD_fxp[i + veciTableFreqPilots[1]] + vecrPSD_fxp[i + veciTableFreqPilots[2]]; } /* Detect peaks --------------------------------------------- */ /* Get peak indices of detected peaks */ iNumDetPeaks_fxp = 0; for (i = iStartDCSearch; i < iEndDCSearch; i++) { /* Test peaks against a bound */ if (vecrPSDPilCor_fxp[i] > rPeakBoundFiltToSig_fxp) { veciPeakIndex_fxp[iNumDetPeaks_fxp] = i; iNumDetPeaks_fxp++; } } /* Check, if at least one peak was detected */ if (iNumDetPeaks_fxp > 0) { /* --------------------------------------------------------- The following test shall exclude sinusoid interferers in the received spectrum */ CVector<int> vecbFlagVec_fxp(iNumDetPeaks_fxp, 1); /* Check all detected peaks in the "PSD-domain" if there are at least two peaks with approx the same power at the correct places (positions of the desired pilots) */ for (i = 0; i < iNumDetPeaks_fxp; i++) { /* Fill the vector with the values at the desired pilot positions */ vecrPSDPilPoin_fxp[0] = vecrPSD_fxp[veciPeakIndex_fxp[i] + veciTableFreqPilots[0]]; vecrPSDPilPoin_fxp[1] = vecrPSD_fxp[veciPeakIndex_fxp[i] + veciTableFreqPilots[1]]; vecrPSDPilPoin_fxp[2] = vecrPSD_fxp[veciPeakIndex_fxp[i] + veciTableFreqPilots[2]]; /* Sort, to extract the highest and second highest peak */ vecrPSDPilPoin_fxp = Sort(vecrPSDPilPoin_fxp); /* Debar peak, if it is much higher than second highest peak (most probably a sinusoid interferer). The highest peak is stored at "vecrPSDPilPoin[2]". Also test for lowest peak */ if ((vecrPSDPilPoin_fxp[1] * (((FXP) (1.0))/vecrPSDPilPoin_fxp[2]) < MAX_RAT_PEAKS_AT_PIL_POS_HIGH_fxp) && (vecrPSDPilPoin_fxp[0] * (((FXP) (1.0))/vecrPSDPilPoin_fxp[2]) < MAX_RAT_PEAKS_AT_PIL_POS_LOW_fxp)) { /* Reset "good-flag" */ vecbFlagVec_fxp[i] = 0; } } /* Get maximum ------------------------------------------ */ /* First, get the first valid peak entry and init the maximum with this value. We also detect, if a peak is left */ bNoPeaksLeft_fxp = TRUE; for (i = 0; i < iNumDetPeaks_fxp; i++) { if (vecbFlagVec_fxp[i] == 1) { /* At least one peak is left */ bNoPeaksLeft_fxp = FALSE; /* Init max value */ iMaxIndex_fxp = veciPeakIndex_fxp[i]; rMaxValue_fxp = vecrPSDPilCor_fxp[veciPeakIndex_fxp[i]]; } } if (bNoPeaksLeft_fxp == FALSE) { /* Actual maximum detection, take the remaining peak which has the highest value */ for (i = 0; i < iNumDetPeaks_fxp; i++) { if ((vecbFlagVec_fxp[i] == 1) && (vecrPSDPilCor_fxp[veciPeakIndex_fxp[i]] > rMaxValue_fxp)) { iMaxIndex_fxp = veciPeakIndex_fxp[i]; rMaxValue_fxp = vecrPSDPilCor_fxp[veciPeakIndex_fxp[i]]; } } /* ----------------------------------------------------- An acquisition frequency offest estimation was found */ /* Calculate frequency offset and set global parameter for offset */ ReceiverParam.rFreqOffsetAcqui = (_REAL) iMaxIndex_fxp / iFrAcFFTSize; /* Reset acquisition flag */ bAquisition = FALSE; /* Send out the data stored for FFT calculation ----- */ /* This does not work for bandpass filter. TODO: make this possible for bandpass filter, too */ if (bUseRecFilter == FALSE) { iOutputBlockSize = iHistBufSize; /* Frequency offset correction */ const _REAL rNormCurFreqOffsFst = (_REAL) 2.0 * crPi * (ReceiverParam.rFreqOffsetAcqui - rInternIFNorm); for (i = 0; i < iHistBufSize; i++) { /* Multiply with exp(j omega t) */ (*pvecOutputData)[i] = (_REAL) vecrFFTHistory_fxp[i] * _COMPLEX(Cos(i * rNormCurFreqOffsFst), Sin(-i * rNormCurFreqOffsFst)); } /* Init "exp-step" for regular frequency shift which is used in tracking mode to get contiuous mixing signal */ cCurExp = _COMPLEX(Cos(iHistBufSize * rNormCurFreqOffsFst), Sin(-iHistBufSize * rNormCurFreqOffsFst)); } } } } } } else { /* If synchronized DRM input stream is used, overwrite the detected frequency offest estimate by the desired frequency, because we know this value */ if (bSyncInput == TRUE) { ReceiverParam.rFreqOffsetAcqui = (_REAL) ReceiverParam.iIndexDCFreq / ReceiverParam.iFFTSizeN; } /* Use the same block size as input block size */ iOutputBlockSize = iInputBlockSize; /* Frequency offset correction -------------------------------------- */ /* Total frequency offset from acquisition and tracking (we calculate the normalized frequency offset) */ const _REAL rNormCurFreqOffset = (_REAL) 2.0 * crPi * (ReceiverParam.rFreqOffsetAcqui + ReceiverParam.rFreqOffsetTrack - rInternIFNorm); /* New rotation vector for exp() calculation */ const _COMPLEX cExpStep = _COMPLEX(Cos(rNormCurFreqOffset), Sin(rNormCurFreqOffset)); /* Input data is real, make complex and compensate for frequency offset */ for (i = 0; i < iOutputBlockSize; i++) { (*pvecOutputData)[i] = (_REAL)(*pvecInputData)[i] * Conj(cCurExp); /* Rotate exp-pointer on step further by complex multiplication with precalculated rotation vector cExpStep. This saves us from calling sin() and cos() functions all the time (iterative calculation of these functions) */ cCurExp *= cExpStep; } /* Bandpass filter -------------------------------------------------- */ if (bUseRecFilter == TRUE) BPFilter.Process(*pvecOutputData); } }
/* * OpenGL (GLUT) calls this routine to display the scene */ void display() { const double len=2.0; // Length of axes // Erase the window and the depth buffer glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); // Enable Z-buffering in OpenGL glEnable(GL_DEPTH_TEST); // Enable face culling in OpenGL glEnable(GL_CULL_FACE); // Undo previous transformations glLoadIdentity(); // Perspective - set eye position double Ex = -2*dim*Sin(th)*Cos(ph); double Ey = +2*dim *Sin(ph); double Ez = +2*dim*Cos(th)*Cos(ph); gluLookAt(Ex,Ey,Ez , 0,0,0 , 0,Cos(ph),0); if(light){ // Translate intensity to color vectors float Ambient[] = {0.01*ambient ,0.01*ambient ,0.01*ambient ,1.0}; float Diffuse[] = {0.01*diffuse ,0.01*diffuse ,0.01*diffuse ,1.0}; float Specular[] = {0.01*specular,0.01*specular,0.01*specular,1.0}; // Light position float Position[] = {distance*Cos(zh),ylight,distance*Sin(zh),1.0}; // Draw light position as ball (still no lighting here) glColor3f(1,1,1); glPushMatrix(); glTranslatef(Position[0],Position[1],Position[2]); glScalef(0.1, 0.1, 0.1); sphere(1.0, 1.0, 1.0, 1); glPopMatrix(); // OpenGL should normalize normal vectors glEnable(GL_NORMALIZE); // Enable lighting glEnable(GL_LIGHTING); // glColor sets ambient and diffuse color materials glColorMaterial(GL_FRONT_AND_BACK,GL_AMBIENT_AND_DIFFUSE); glEnable(GL_COLOR_MATERIAL); // Enable light 0 glEnable(GL_LIGHT0); // Set ambient, diffuse, specular components and position of light 0 glLightfv(GL_LIGHT0,GL_AMBIENT ,Ambient); glLightfv(GL_LIGHT0,GL_DIFFUSE ,Diffuse); glLightfv(GL_LIGHT0,GL_SPECULAR,Specular); glLightfv(GL_LIGHT0,GL_POSITION,Position); }else{ glDisable(GL_LIGHTING); } if(fly){ movingHelicopter(); }else{ helicopter(0); } // Draw axes - no lighting from here on glDisable(GL_LIGHTING); glColor3f(1,1,1); if(axes){ // Draw axes glBegin(GL_LINES); glVertex3d(0.0,0.0,0.0); glVertex3d(len,0.0,0.0); glVertex3d(0.0,0.0,0.0); glVertex3d(0.0,len,0.0); glVertex3d(0.0,0.0,0.0); glVertex3d(0.0,0.0,len); glEnd(); // Label axes glRasterPos3d(len,0.0,0.0); Print("X"); glRasterPos3d(0.0,len,0.0); Print("Y"); glRasterPos3d(0.0,0.0,len); Print("Z"); } // Display parameters glWindowPos2i(5,5); Print("Angle=%d,%d Dim=%.1f FOV=%d Projection=%s Light=%s", th,ph,dim,fov,"Perspective",light?"On":"Off"); if (light) { glWindowPos2i(5,45); Print("Distance=%d Elevation=%.1f", distance, ylight); glWindowPos2i(5,25); Print("Ambient=%d Diffuse=%d Specular=%d Emission=%d Shininess=%.0f",ambient,diffuse,specular,emission,shinyvec[0]); } // Check for any errors that have occurred ErrCheck("display"); // Render the scene and make it visible glFlush(); glutSwapBuffers(); }
void NormalShot::update(Game* game) { Shot::update(game); const Vec2 vec = Vec2(Cos(rad), Sin(rad)) * 15.0; pos += vec; }
void fountain(unsigned int stone_tex, unsigned int water_tex) { const double pi2 = M_PI * 2; const double delta = pi2 / 103; const double radius = .74; double i; float white[] = {221.0/255.0,213.0/255.0,242.0/255.0,1}; float shinyvec[1]; shinyvec[0] = 64.0; glMaterialfv(GL_FRONT_AND_BACK,GL_SHININESS,shinyvec); glMaterialfv(GL_FRONT_AND_BACK,GL_SPECULAR,white); glPushMatrix(); // Transforms glScaled(.15,.15,.15); // Color of polys glColor3f(0.3,0.3,0.3); // Cylinder for base cylinder(0,0,0, 0,0, .2,1, 103,stone_tex, water_tex, 0); // Bowl at base glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D,stone_tex); glBegin(GL_TRIANGLE_FAN); glNormal3f(0,1,0); glTexCoord2f(.5,.5); glVertex3f(0,0,0); for (i=0.0;i<=pi2;i+=delta) { double x = 1.1 * cos(i); double z = 1.1 * sin(i); glTexCoord2f(cos(i),sin(i)); glVertex3f(x,.2,z); } glEnd(); glDisable(GL_TEXTURE_2D); // Weird shape for body for(i=0.0;i<=360;i+=2) { fountain_side(i,stone_tex); } //water on top shinyvec[0] = 4.0; glMaterialfv(GL_FRONT_AND_BACK,GL_SHININESS,shinyvec); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D,water_tex); glColor3f(.055,.055,.055); glBegin(GL_TRIANGLE_FAN); glNormal3f(0,1,0); glTexCoord2f(.5,.5); glVertex3f(0,1.2,0); for (i=0.0;i<=pi2;i+=delta) { double x = radius * cos(i); double z = radius * sin(i); glTexCoord2f(cos(i),sin(i)); glVertex3f(x,1.27,z); } glEnd(); glDisable(GL_TEXTURE_2D); // Lotus at the particle emitter // big blades grass_blade(.25,1.25,.25, .5,.1666666,.33333333, 90,0,0, stone_tex); grass_blade(-.3,1.25,.25, .5,.1666666,.33333333, 0,0,0, stone_tex); grass_blade(-.25,1.25,-.3, .5,.1666666,.33333333, 270,0,0, stone_tex); grass_blade(.3,1.25,-.25, .5,.1666666,.33333333, 180,0,0, stone_tex); // smaller blades grass_blade(.3*Cos(45),1.25,.3*Sin(45), .3,.1,.2, 45,-20,0, stone_tex); grass_blade(.3*Cos(135)-.2,1.25,.3*Sin(135)-.2, .3,.1,.2, -45,-20,0, stone_tex); grass_blade(.3*Cos(225)+.1,1.25,.3*Sin(225)-.1, .3,.1,.2, -135,-20,0, stone_tex); grass_blade(.3*Cos(315)+.2,1.25,.3*Sin(315)+.1, .3,.1,.2, 135,-20,0, stone_tex); glPopMatrix(); }
void hourglass_side(float thy,unsigned int glass_tex) { // Materials float white[] = {221.0/255.0,213.0/255.0,242.0/255.0,1}; float shinyvec[1]; shinyvec[0] = 16.0; glMaterialfv(GL_FRONT_AND_BACK,GL_SHININESS,shinyvec); glMaterialfv(GL_FRONT_AND_BACK,GL_SPECULAR,white); glPushMatrix(); // Transforms glRotated(thy,0,1,0); // Texture glEnable(GL_TEXTURE_2D); glTexEnvi(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE,GL_MODULATE); glBindTexture(GL_TEXTURE_2D,glass_tex); // Color glColor4f(.1,.1,.1,.8); // Enable blend for transparency glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA,GL_SRC_ALPHA); const double pi2 = M_PI; const double costhy = Cos(thy); const double costhyp = Cos(thy+1); const double sinthy = Sin(thy); const double sinthyp = Sin(thy); double i; double delta = pi2 / 51.5; glBegin(GL_QUADS); for (i=0.0;i<=pi2;i+=delta) { double x0 = cos(i); double x1 = cos(i+delta); double ny0 = -sin(i); double ny1 = -sin(i+delta); // Upper left glNormal3f(costhy,ny1,sinthy); glTexCoord2f(costhy,(i+delta)/pi2); glVertex3f(x1,(i+delta)/pi2,.03); // Upper right glNormal3f(costhyp,ny1,sinthyp); glTexCoord2f(costhyp,(i+delta)/pi2); glVertex3f(x1,(i+delta)/pi2,-.03); // Lower Right glNormal3f(costhyp,ny0,sinthyp); glTexCoord2f(costhyp,i/pi2); glVertex3f(x0,i/pi2,-.03); // Lower left glNormal3f(costhy,ny0,sinthy); glTexCoord2f(costhy,i/pi2); glVertex3f(x0,i/pi2,.03); } glEnd(); glDisable(GL_BLEND); glPopMatrix(); glDisable(GL_TEXTURE_2D); }
/** * player 以确定得姿势(指倒着跑和正跑),跑到 target 所需要的周期数 * This function returns the minimum cycles for a player to go to a target position with * a certain posture, forward or backward. * @param player the player to caculate. * @param target the target position to go to. * @param inverse true means running backwards. * @param buffer * @return an integer to show the minimum cycles caculated. */ int Dasher::CycleNeedToPointWithCertainPosture(const PlayerState & player, Vector target, const bool inverse, double *buf) { int cycle = 0; //用的周期 const double & decay = player.GetPlayerDecay(); const double & speedmax = player.GetEffectiveSpeedMax(); const double & stamina = player.GetStamina(); const double & stamina_inc_max = player.GetStaminaIncMax(); const double & dash_max = ServerParam::instance().maxDashPower(); const Vector & pos = player.GetPos(); const Vector & vel = player.GetVel(); const double accrate = player.GetDashPowerRate() * player.GetEffort(); double speed = vel.Mod(); const Vector predict_pos_1 = pos + vel; const Vector predict_pos_2 = predict_pos_1 + vel * decay; const double dir = (target - pos).Dir(); double dis = (target - predict_pos_1).Mod(); const double kick_area = player.IsGoalie()? ServerParam::instance().catchAreaLength(): (player.GetKickableArea() - GETBALL_BUFFER); if (dis <= kick_area){ dis = pos.Dist(target); if (buf) *buf = 0; return 1; } double facing; if (player.IsBodyDirValid()) { facing = player.GetBodyDir(); } else if (speed > 0.26){ facing = vel.Dir(); } else { facing = dir; //认为不用转身 } double diffang = fabs(GetNormalizeAngleDeg(dir - facing)); const double oneturnang = player.GetMaxTurnAngle(); const double stamina_recovery_thr = ServerParam::instance().recoverDecThr() * ServerParam::instance().staminaMax(); double angbuf = FLOAT_EPS; angbuf = ASin(kick_area / dis); angbuf = Max(angbuf , 15.0); if (inverse) { diffang = 180.0 - diffang; facing = GetNormalizeAngleDeg(180.0 + facing); } //I 调整阶段 if(diffang <= angbuf){ //不需要转身 target = (target - pos).Rotate(-facing); dis = fabs(target.X()); double y = fabs(target.Y()); if(y < kick_area){ dis -= sqrt(kick_area * kick_area - y * y); } speed *= Cos(vel.Dir() - facing); //身体方向上的投影 } else if(diffang <= oneturnang){ cycle += 1; target -= predict_pos_1; speed *= Cos(vel.Dir() - dir); //取得目标方向的投影 speed *= decay;//进行投影.垂直方向1个周期后衰减到10+厘米了,并且在1turn时可加入考虑修正掉 dis = target.Mod(); dis -= kick_area; } else{ //认为转身两下(不细致) cycle += 2; target -= predict_pos_2; speed *= Cos(vel.Dir() - dir); //取得目标方向的投影 speed *= decay * decay;//进行投影.垂直方向1个周期后衰减到10+厘米了,并且在1turn时可加入考虑修正掉 dis = target.Mod(); dis -= kick_area; } if (dis <= 0){ if(buf != NULL){ *buf = -dis / ( speed / decay); *buf = Min(*buf , 0.99); } return Max(cycle, 0); } //II 加速 & 消耗体力阶段 const double stamina_used_per_cycle = inverse? dash_max * 2.0: dash_max; const int full_cyc = int((stamina - stamina_recovery_thr) / (stamina_used_per_cycle - stamina_inc_max)); //满体力阶段 int acc_cyc = 0;//加速阶段 const double speedmax_thr = speedmax * decay * 0.98; const double accmax = accrate * dash_max; while(acc_cyc < full_cyc && speed < speedmax_thr){ speed += accmax; if(speed > speedmax){ speed = speedmax; } dis -= speed; if(dis <= 0){//还没加速到最大就跑到了... cycle += acc_cyc + 1; if(buf != NULL){ *buf = -dis /( speed / decay ); *buf = Min(*buf , 0.99); } return Max(cycle, 0); } speed *= decay; ++ acc_cyc; } cycle += acc_cyc; //III 满体匀速阶段 int aver_cyc = full_cyc - acc_cyc; double aver_cyc_dis = aver_cyc * speedmax; if(aver_cyc_dis >= dis){ if(buf != NULL){ double realcyc = cycle + dis / speedmax; cycle = int( ceil(realcyc) ); *buf = cycle - realcyc; return Max(cycle, 0); } else{ cycle = int(ceil( cycle + dis / speedmax)); return Max(cycle, 0); } } else{ cycle += aver_cyc; dis -= aver_cyc_dis; } //IV 没体(0消耗)减速阶段 double acc_tired = stamina_inc_max * accrate; double speed_tired = acc_tired / (1 - decay); double speed_tired_thr = speed_tired * decay; speed *= decay; while(dis > 0 && fabs(speed - speed_tired_thr) > 0.004){ speed += acc_tired; dis -= speed; speed *= decay; ++cycle; } if(dis <= 0){ if(buf != NULL){ *buf = -dis / ( speed / decay); *buf = Min(*buf , 0.99); } return Max(cycle, 0); } //V 没体(0消耗)匀速阶段 if( buf != NULL){ double realcyc = cycle + dis / speed_tired; cycle = int( ceil( realcyc ) ); *buf = cycle - realcyc; return Max(cycle, 0); } else{ cycle = cycle + int(ceil ( dis / speed_tired)); return Max(cycle, 0); } }
// // Les entrées de la fonction d'asservissement // // Utilise les tableaux PosLRTA et VitLRTA, et pire encore, les modifie !!! // Ils doivent donc etre mis a jour avant chaque appel !!!!!!!!!!!!!!!!!!!! // Utilise également IntervalleTemps et VEqui // // Les sorties de la fonction d'asservissement // //--Modifie les valeurs du tableau Commande[] void Asservissement_Controle() { // Calculer la commande en fonction de la position, de la vitesse, de la commande et des différents réglages // (gains et systeme de prédiction) définis dans Params.c for (i = 0; i < 4; i++) { // // Récupération des données réelles // predPosLRTA[i] = PosLRTA[i]; predVitLRTA[i] = VitLRTA[i]; // // Mise é jour des intégrales // intLRTA[i] += IntervalleTemps * (ancLRTA[i] + PosLRTA[i] - 2.0F * ConsLRTA[i]) * 0.5F; ancLRTA[i] = PosLRTA[i]; } // // Mise en mémoire de la commande actuelle pour s'en servir plus tard // histURT[indexHistorique][0] = ULRTA[1]; histURT[indexHistorique][1] = ULRTA[2]; indexHistorique++; if (indexHistorique == ESTIMATEUR_TEMPS_DE_REACTION + 1) { indexHistorique = 0; } // // Calcul de la commande future en anticipant sur les positions et vitesses futures // for (i = 0; i < ESTIMATEUR_TEMPS_DE_REACTION; i++) { // // Intégration des accélérations et vitesses suivant les lois de la dynamique // predVitLRTA[1] += ESTIMATEUR_GAIN_POUSEE * ESTIMATEUR_PAS_DE_TEMPS_MOYEN * histURT[(indexHistorique + i) % (ESTIMATEUR_TEMPS_DE_REACTION + 1)][0]; predVitLRTA[2] += ESTIMATEUR_GAIN_POUSEE * ESTIMATEUR_PAS_DE_TEMPS_MOYEN * histURT[(indexHistorique + i) % (ESTIMATEUR_TEMPS_DE_REACTION + 1)][1]; predPosLRTA[1] += ESTIMATEUR_GAIN_INTEGRATION * ESTIMATEUR_PAS_DE_TEMPS_MOYEN * predVitLRTA[1]; predPosLRTA[2] += ESTIMATEUR_GAIN_INTEGRATION * ESTIMATEUR_PAS_DE_TEMPS_MOYEN * predVitLRTA[2]; } // // Calcul des commandes // for (i = 0; i < 4; i++) { if (CONTROLE_LRTA[i]) { ULRTA[i] = -GAINS_PRO[i] * (predPosLRTA[i] - ConsLRTA[i]) - GAINS_DER[i] * predVitLRTA[i] - GAINS_INT[i] * intLRTA[i]; if(i == 0) { // Bornage de la commande lacet if(ULRTA[0] > UL_MAX) { ULRTA[0] = UL_MAX; printf(" BUL"); } else if(ULRTA[0] < UL_MIN) { ULRTA[0] = UL_MIN; printf(" BUL"); } } else if(i == 3) { // Bornage de la commande altitude if(ULRTA[3] > UA_MAX) { ULRTA[3] = UA_MAX; printf(" BUA"); } else if(ULRTA[3] < UA_MIN) { ULRTA[3] = UA_MIN; printf(" BUA"); } } else { // Bornage des commandes R&T if(ULRTA[i] > URT_MAX) { ULRTA[i] = URT_MAX; printf(" BURT"); } else if(ULRTA[i] < URT_MIN) { ULRTA[i] = URT_MIN; printf(" BURT"); } } } else { ULRTA[i] = 0.0F; } } // // Assignation des commandes sur les différents moteurs // CPAA = Cos(PosLRTA[1]) * Cos(PosLRTA[2]); // Prise en compte des angles RT pour CPAA = 1.0F / CPAA; // calculer la poussée utile (projeté sur Z) Commande[0] = Vactu + CPA * CPAA * ULRTA[3] + CPL * ULRTA[0] + CPT * ULRTA[2]; Commande[1] = Vactu + CPA * CPAA * ULRTA[3] + CPL * ULRTA[0] - CPT * ULRTA[2]; Commande[2] = Vactu + CPA * CPAA * ULRTA[3] - CPL * ULRTA[0] + CPR * ULRTA[1]; Commande[3] = Vactu + CPA * CPAA * ULRTA[3] - CPL * ULRTA[0] - CPR * ULRTA[1]; }
/* * OpenGL (GLUT) calls this routine to display the scene */ void display() { int i,j; const double len=2.0; // Length of axes // Light position and colors float Ambient[] = {0.3,0.3,0.3,1.0}; float Diffuse[] = {1.0,1.0,1.0,1.0}; float Position[] = {Cos(zh),Ylight,Sin(zh),1.0}; // Erase the window and the depth buffer glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT|GL_STENCIL_BUFFER_BIT); // Enable Z-buffering in OpenGL glEnable(GL_DEPTH_TEST); // Undo previous transformations glLoadIdentity(); // Perspective - set eye position if (proj) { double Ex = -2*dim*Sin(th)*Cos(ph); double Ey = +2*dim *Sin(ph); double Ez = +2*dim*Cos(th)*Cos(ph); gluLookAt(Ex,Ey,Ez , 0,0,0 , 0,Cos(ph),0); } // Orthogonal - set world orientation else { glRotatef(ph,1,0,0); glRotatef(th,0,1,0); } // Draw light position as sphere (still no lighting here) glColor3f(1,1,1); glPushMatrix(); glTranslated(Position[0],Position[1],Position[2]); glutSolidSphere(0.03,10,10); glPopMatrix(); // OpenGL should normalize normal vectors glEnable(GL_NORMALIZE); // Enable lighting glEnable(GL_LIGHTING); // glColor sets ambient and diffuse color materials glColorMaterial(GL_FRONT_AND_BACK,GL_AMBIENT_AND_DIFFUSE); glEnable(GL_COLOR_MATERIAL); // Enable light 0 glEnable(GL_LIGHT0); // Set ambient, diffuse, specular components and position of light 0 glLightfv(GL_LIGHT0,GL_AMBIENT ,Ambient); glLightfv(GL_LIGHT0,GL_DIFFUSE ,Diffuse); glLightfv(GL_LIGHT0,GL_POSITION,Position); // Draw floor glEnable(GL_TEXTURE_2D); glEnable(GL_POLYGON_OFFSET_FILL); glPolygonOffset(1,1); glColor3f(1,1,1); glNormal3f(0,1,0); for (j=-Dfloor;j<Dfloor;j++) { glBegin(GL_QUAD_STRIP); for (i=-Dfloor;i<=Dfloor;i++) { glTexCoord2f(i,j); glVertex3f(i,Yfloor,j); glTexCoord2f(i,j+1); glVertex3f(i,Yfloor,j+1); } glEnd(); } glDisable(GL_POLYGON_OFFSET_FILL); glDisable(GL_TEXTURE_2D); // Draw scene glColor3f(1,1,0); scene(); // Save what is glEnabled glPushAttrib(GL_ENABLE_BIT); // Draw shadow switch (mode) { // No shadow case 0: break; // Draw flattened scene case 1: glPushMatrix(); ShadowProjection(Position,E,N); scene(); glPopMatrix(); break; // Transformation with lighting disabled case 2: glDisable(GL_LIGHTING); // Draw flattened scene glPushMatrix(); ShadowProjection(Position,E,N); scene(); glPopMatrix(); break; // Set shadow color case 3: glDisable(GL_LIGHTING); glColor3f(0.3,0.3,0.3); // Draw flattened scene glPushMatrix(); ShadowProjection(Position,E,N); scene(); glPopMatrix(); break; // Blended shadows case 4: glDisable(GL_LIGHTING); // Blended color glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA); glColor4f(0,0,0,0.4); // Draw flattened scene glPushMatrix(); ShadowProjection(Position,E,N); scene(); glPopMatrix(); break; // Blended shadows Z-buffer masked case 5: glDisable(GL_LIGHTING); // Draw blended glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA); glColor4f(0,0,0,0.4); // Make Z-buffer read-only glDepthMask(0); // Draw flattened scene glPushMatrix(); ShadowProjection(Position,E,N); scene(); glPopMatrix(); // Make Z-buffer read-write glDepthMask(1); break; // Blended with stencil buffer case 6: glDisable(GL_LIGHTING); // Enable stencil operations glEnable(GL_STENCIL_TEST); /* * Step 1: Set stencil buffer to 1 where there are shadows */ // Existing value of stencil buffer doesn't matter glStencilFunc(GL_ALWAYS,1,0xFFFFFFFF); // Set the value to 1 (REF=1 in StencilFunc) // only if Z-buffer would allow write glStencilOp(GL_KEEP,GL_KEEP,GL_REPLACE); // Make Z-buffer and color buffer read-only glDepthMask(0); glColorMask(0,0,0,0); // Draw flattened scene glPushMatrix(); ShadowProjection(Position,E,N); scene(); glPopMatrix(); // Make Z-buffer and color buffer read-write glDepthMask(1); glColorMask(1,1,1,1); /* * Step 2: Draw shadow masked by stencil buffer */ // Set the stencil test draw where stencil buffer is > 0 glStencilFunc(GL_LESS,0,0xFFFFFFFF); // Make the stencil buffer read-only glStencilOp(GL_KEEP,GL_KEEP,GL_KEEP); // Enable blending glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA); glColor4f(0,0,0,0.5); // Draw the shadow over the entire floor glBegin(GL_QUADS); glVertex3f(-Dfloor,Yfloor,-Dfloor); glVertex3f(+Dfloor,Yfloor,-Dfloor); glVertex3f(+Dfloor,Yfloor,+Dfloor); glVertex3f(-Dfloor,Yfloor,+Dfloor); glEnd(); break; default: break; } // Undo glEnables glPopAttrib(); // Draw axes - no lighting from here on glDisable(GL_LIGHTING); glColor3f(1,1,1); if (axes) { glBegin(GL_LINES); glVertex3d(0.0,0.0,0.0); glVertex3d(len,0.0,0.0); glVertex3d(0.0,0.0,0.0); glVertex3d(0.0,len,0.0); glVertex3d(0.0,0.0,0.0); glVertex3d(0.0,0.0,len); glEnd(); // Label axes glRasterPos3d(len,0.0,0.0); Print("X"); glRasterPos3d(0.0,len,0.0); Print("Y"); glRasterPos3d(0.0,0.0,len); Print("Z"); } // Display parameters glWindowPos2i(5,5); Print("Angle=%d,%d Dim=%.1f Projection=%s Light Elevation=%.1f", th,ph,dim,proj?"Perpective":"Orthogonal",Ylight); glWindowPos2i(5,25); Print(text[mode]); // Render the scene and make it visible ErrCheck("display"); glFlush(); glutSwapBuffers(); }
void Batch::Prepare(View* view, bool setModelTransform) const { if (!vertexShader_ || !pixelShader_) return; Graphics* graphics = view->GetGraphics(); Renderer* renderer = view->GetRenderer(); Node* cameraNode = camera_ ? camera_->GetNode() : 0; Light* light = lightQueue_ ? lightQueue_->light_ : 0; Texture2D* shadowMap = lightQueue_ ? lightQueue_->shadowMap_ : 0; // Set pass / material-specific renderstates if (pass_ && material_) { bool isShadowPass = pass_->GetType() == PASS_SHADOW; BlendMode blend = pass_->GetBlendMode(); // Turn additive blending into subtract if the light is negative if (light && light->IsNegative()) { if (blend == BLEND_ADD) blend = BLEND_SUBTRACT; else if (blend == BLEND_ADDALPHA) blend = BLEND_SUBTRACTALPHA; } graphics->SetBlendMode(blend); renderer->SetCullMode(isShadowPass ? material_->GetShadowCullMode() : material_->GetCullMode(), camera_); if (!isShadowPass) { const BiasParameters& depthBias = material_->GetDepthBias(); graphics->SetDepthBias(depthBias.constantBias_, depthBias.slopeScaledBias_); } graphics->SetDepthTest(pass_->GetDepthTestMode()); graphics->SetDepthWrite(pass_->GetDepthWrite()); } // Set shaders first. The available shader parameters and their register/uniform positions depend on the currently set shaders graphics->SetShaders(vertexShader_, pixelShader_); // Set global (per-frame) shader parameters if (graphics->NeedParameterUpdate(SP_FRAME, (void*)0)) view->SetGlobalShaderParameters(); // Set camera shader parameters unsigned cameraHash = overrideView_ ? (unsigned)(size_t)camera_ + 4 : (unsigned)(size_t)camera_; if (graphics->NeedParameterUpdate(SP_CAMERA, reinterpret_cast<void*>(cameraHash))) view->SetCameraShaderParameters(camera_, true, overrideView_); // Set viewport shader parameters IntRect viewport = graphics->GetViewport(); IntVector2 viewSize = IntVector2(viewport.Width(), viewport.Height()); unsigned viewportHash = viewSize.x_ | (viewSize.y_ << 16); if (graphics->NeedParameterUpdate(SP_VIEWPORT, reinterpret_cast<void*>(viewportHash))) { // During renderpath commands the G-Buffer or viewport texture is assumed to always be viewport-sized view->SetGBufferShaderParameters(viewSize, IntRect(0, 0, viewSize.x_, viewSize.y_)); } // Set model or skinning transforms if (setModelTransform && graphics->NeedParameterUpdate(SP_OBJECTTRANSFORM, worldTransform_)) { if (geometryType_ == GEOM_SKINNED) { graphics->SetShaderParameter(VSP_SKINMATRICES, reinterpret_cast<const float*>(worldTransform_), 12 * numWorldTransforms_); } else graphics->SetShaderParameter(VSP_MODEL, *worldTransform_); // Set the orientation for billboards, either from the object itself or from the camera if (geometryType_ == GEOM_BILLBOARD) { if (numWorldTransforms_ > 1) graphics->SetShaderParameter(VSP_BILLBOARDROT, worldTransform_[1].RotationMatrix()); else graphics->SetShaderParameter(VSP_BILLBOARDROT, cameraNode->GetWorldRotation().RotationMatrix()); } } // Set zone-related shader parameters BlendMode blend = graphics->GetBlendMode(); // If the pass is additive, override fog color to black so that shaders do not need a separate additive path bool overrideFogColorToBlack = blend == BLEND_ADD || blend == BLEND_ADDALPHA; unsigned zoneHash = (unsigned)(size_t)zone_; if (overrideFogColorToBlack) zoneHash += 0x80000000; if (zone_ && graphics->NeedParameterUpdate(SP_ZONE, reinterpret_cast<void*>(zoneHash))) { graphics->SetShaderParameter(VSP_AMBIENTSTARTCOLOR, zone_->GetAmbientStartColor()); graphics->SetShaderParameter(VSP_AMBIENTENDCOLOR, zone_->GetAmbientEndColor().ToVector4() - zone_->GetAmbientStartColor().ToVector4()); const BoundingBox& box = zone_->GetBoundingBox(); Vector3 boxSize = box.Size(); Matrix3x4 adjust(Matrix3x4::IDENTITY); adjust.SetScale(Vector3(1.0f / boxSize.x_, 1.0f / boxSize.y_, 1.0f / boxSize.z_)); adjust.SetTranslation(Vector3(0.5f, 0.5f, 0.5f)); Matrix3x4 zoneTransform = adjust * zone_->GetInverseWorldTransform(); graphics->SetShaderParameter(VSP_ZONE, zoneTransform); graphics->SetShaderParameter(PSP_AMBIENTCOLOR, zone_->GetAmbientColor()); graphics->SetShaderParameter(PSP_FOGCOLOR, overrideFogColorToBlack ? Color::BLACK : zone_->GetFogColor()); float farClip = camera_->GetFarClip(); float fogStart = Min(zone_->GetFogStart(), farClip); float fogEnd = Min(zone_->GetFogEnd(), farClip); if (fogStart >= fogEnd * (1.0f - M_LARGE_EPSILON)) fogStart = fogEnd * (1.0f - M_LARGE_EPSILON); float fogRange = Max(fogEnd - fogStart, M_EPSILON); Vector4 fogParams(fogEnd / farClip, farClip / fogRange, 0.0f, 0.0f); Node* zoneNode = zone_->GetNode(); if (zone_->GetHeightFog() && zoneNode) { Vector3 worldFogHeightVec = zoneNode->GetWorldTransform() * Vector3(0.0f, zone_->GetFogHeight(), 0.0f); fogParams.z_ = worldFogHeightVec.y_; fogParams.w_ = zone_->GetFogHeightScale() / Max(zoneNode->GetWorldScale().y_, M_EPSILON); } graphics->SetShaderParameter(PSP_FOGPARAMS, fogParams); } // Set light-related shader parameters if (lightQueue_) { if (graphics->NeedParameterUpdate(SP_VERTEXLIGHTS, lightQueue_) && graphics->HasShaderParameter(VS, VSP_VERTEXLIGHTS)) { Vector4 vertexLights[MAX_VERTEX_LIGHTS * 3]; const PODVector<Light*>& lights = lightQueue_->vertexLights_; for (unsigned i = 0; i < lights.Size(); ++i) { Light* vertexLight = lights[i]; Node* vertexLightNode = vertexLight->GetNode(); LightType type = vertexLight->GetLightType(); // Attenuation float invRange, cutoff, invCutoff; if (type == LIGHT_DIRECTIONAL) invRange = 0.0f; else invRange = 1.0f / Max(vertexLight->GetRange(), M_EPSILON); if (type == LIGHT_SPOT) { cutoff = Cos(vertexLight->GetFov() * 0.5f); invCutoff = 1.0f / (1.0f - cutoff); } else { cutoff = -1.0f; invCutoff = 1.0f; } // Color float fade = 1.0f; float fadeEnd = vertexLight->GetDrawDistance(); float fadeStart = vertexLight->GetFadeDistance(); // Do fade calculation for light if both fade & draw distance defined if (vertexLight->GetLightType() != LIGHT_DIRECTIONAL && fadeEnd > 0.0f && fadeStart > 0.0f && fadeStart < fadeEnd) fade = Min(1.0f - (vertexLight->GetDistance() - fadeStart) / (fadeEnd - fadeStart), 1.0f); Color color = vertexLight->GetEffectiveColor() * fade; vertexLights[i * 3] = Vector4(color.r_, color.g_, color.b_, invRange); // Direction vertexLights[i * 3 + 1] = Vector4(-(vertexLightNode->GetWorldDirection()), cutoff); // Position vertexLights[i * 3 + 2] = Vector4(vertexLightNode->GetWorldPosition(), invCutoff); } if (lights.Size()) graphics->SetShaderParameter(VSP_VERTEXLIGHTS, vertexLights[0].Data(), lights.Size() * 3 * 4); } } if (light && graphics->NeedParameterUpdate(SP_LIGHT, light)) { // Deferred light volume batches operate in a camera-centered space. Detect from material, zone & pass all being null bool isLightVolume = !material_ && !pass_ && !zone_; Matrix3x4 cameraEffectiveTransform = camera_->GetEffectiveWorldTransform(); Vector3 cameraEffectivePos = cameraEffectiveTransform.Translation(); Node* lightNode = light->GetNode(); Matrix3 lightWorldRotation = lightNode->GetWorldRotation().RotationMatrix(); graphics->SetShaderParameter(VSP_LIGHTDIR, lightWorldRotation * Vector3::BACK); float atten = 1.0f / Max(light->GetRange(), M_EPSILON); graphics->SetShaderParameter(VSP_LIGHTPOS, Vector4(lightNode->GetWorldPosition(), atten)); if (graphics->HasShaderParameter(VS, VSP_LIGHTMATRICES)) { switch (light->GetLightType()) { case LIGHT_DIRECTIONAL: { Matrix4 shadowMatrices[MAX_CASCADE_SPLITS]; unsigned numSplits = lightQueue_->shadowSplits_.Size(); for (unsigned i = 0; i < numSplits; ++i) CalculateShadowMatrix(shadowMatrices[i], lightQueue_, i, renderer, Vector3::ZERO); graphics->SetShaderParameter(VSP_LIGHTMATRICES, shadowMatrices[0].Data(), 16 * numSplits); } break; case LIGHT_SPOT: { Matrix4 shadowMatrices[2]; CalculateSpotMatrix(shadowMatrices[0], light, Vector3::ZERO); bool isShadowed = shadowMap && graphics->HasTextureUnit(TU_SHADOWMAP); if (isShadowed) CalculateShadowMatrix(shadowMatrices[1], lightQueue_, 0, renderer, Vector3::ZERO); graphics->SetShaderParameter(VSP_LIGHTMATRICES, shadowMatrices[0].Data(), isShadowed ? 32 : 16); } break; case LIGHT_POINT: { Matrix4 lightVecRot(lightNode->GetWorldRotation().RotationMatrix()); // HLSL compiler will pack the parameters as if the matrix is only 3x4, so must be careful to not overwrite // the next parameter #ifdef URHO3D_OPENGL graphics->SetShaderParameter(VSP_LIGHTMATRICES, lightVecRot.Data(), 16); #else graphics->SetShaderParameter(VSP_LIGHTMATRICES, lightVecRot.Data(), 12); #endif } break; } } float fade = 1.0f; float fadeEnd = light->GetDrawDistance(); float fadeStart = light->GetFadeDistance(); // Do fade calculation for light if both fade & draw distance defined if (light->GetLightType() != LIGHT_DIRECTIONAL && fadeEnd > 0.0f && fadeStart > 0.0f && fadeStart < fadeEnd) fade = Min(1.0f - (light->GetDistance() - fadeStart) / (fadeEnd - fadeStart), 1.0f); // Negative lights will use subtract blending, so write absolute RGB values to the shader parameter graphics->SetShaderParameter(PSP_LIGHTCOLOR, Color(light->GetEffectiveColor().Abs(), light->GetEffectiveSpecularIntensity()) * fade); graphics->SetShaderParameter(PSP_LIGHTDIR, lightWorldRotation * Vector3::BACK); graphics->SetShaderParameter(PSP_LIGHTPOS, Vector4((isLightVolume ? (lightNode->GetWorldPosition() - cameraEffectivePos) : lightNode->GetWorldPosition()), atten)); if (graphics->HasShaderParameter(PS, PSP_LIGHTMATRICES)) { switch (light->GetLightType()) { case LIGHT_DIRECTIONAL: { Matrix4 shadowMatrices[MAX_CASCADE_SPLITS]; unsigned numSplits = lightQueue_->shadowSplits_.Size(); for (unsigned i = 0; i < numSplits; ++i) { CalculateShadowMatrix(shadowMatrices[i], lightQueue_, i, renderer, isLightVolume ? cameraEffectivePos : Vector3::ZERO); } graphics->SetShaderParameter(PSP_LIGHTMATRICES, shadowMatrices[0].Data(), 16 * numSplits); } break; case LIGHT_SPOT: { Matrix4 shadowMatrices[2]; CalculateSpotMatrix(shadowMatrices[0], light, cameraEffectivePos); bool isShadowed = lightQueue_->shadowMap_ != 0; if (isShadowed) { CalculateShadowMatrix(shadowMatrices[1], lightQueue_, 0, renderer, isLightVolume ? cameraEffectivePos : Vector3::ZERO); } graphics->SetShaderParameter(PSP_LIGHTMATRICES, shadowMatrices[0].Data(), isShadowed ? 32 : 16); } break; case LIGHT_POINT: { Matrix4 lightVecRot(lightNode->GetWorldRotation().RotationMatrix()); // HLSL compiler will pack the parameters as if the matrix is only 3x4, so must be careful to not overwrite // the next parameter #ifdef URHO3D_OPENGL graphics->SetShaderParameter(PSP_LIGHTMATRICES, lightVecRot.Data(), 16); #else graphics->SetShaderParameter(PSP_LIGHTMATRICES, lightVecRot.Data(), 12); #endif } break; } } // Set shadow mapping shader parameters if (shadowMap) { { // Calculate point light shadow sampling offsets (unrolled cube map) unsigned faceWidth = shadowMap->GetWidth() / 2; unsigned faceHeight = shadowMap->GetHeight() / 3; float width = (float)shadowMap->GetWidth(); float height = (float)shadowMap->GetHeight(); #ifdef URHO3D_OPENGL float mulX = (float)(faceWidth - 3) / width; float mulY = (float)(faceHeight - 3) / height; float addX = 1.5f / width; float addY = 1.5f / height; #else float mulX = (float)(faceWidth - 4) / width; float mulY = (float)(faceHeight - 4) / height; float addX = 2.5f / width; float addY = 2.5f / height; #endif // If using 4 shadow samples, offset the position diagonally by half pixel if (renderer->GetShadowQuality() & SHADOWQUALITY_HIGH_16BIT) { addX -= 0.5f / width; addY -= 0.5f / height; } graphics->SetShaderParameter(PSP_SHADOWCUBEADJUST, Vector4(mulX, mulY, addX, addY)); } { // Calculate shadow camera depth parameters for point light shadows and shadow fade parameters for // directional light shadows, stored in the same uniform Camera* shadowCamera = lightQueue_->shadowSplits_[0].shadowCamera_; float nearClip = shadowCamera->GetNearClip(); float farClip = shadowCamera->GetFarClip(); float q = farClip / (farClip - nearClip); float r = -q * nearClip; const CascadeParameters& parameters = light->GetShadowCascade(); float viewFarClip = camera_->GetFarClip(); float shadowRange = parameters.GetShadowRange(); float fadeStart = parameters.fadeStart_ * shadowRange / viewFarClip; float fadeEnd = shadowRange / viewFarClip; float fadeRange = fadeEnd - fadeStart; graphics->SetShaderParameter(PSP_SHADOWDEPTHFADE, Vector4(q, r, fadeStart, 1.0f / fadeRange)); } { float intensity = light->GetShadowIntensity(); float fadeStart = light->GetShadowFadeDistance(); float fadeEnd = light->GetShadowDistance(); if (fadeStart > 0.0f && fadeEnd > 0.0f && fadeEnd > fadeStart) intensity = Lerp(intensity, 1.0f, Clamp((light->GetDistance() - fadeStart) / (fadeEnd - fadeStart), 0.0f, 1.0f)); float pcfValues = (1.0f - intensity); float samples = renderer->GetShadowQuality() >= SHADOWQUALITY_HIGH_16BIT ? 4.0f : 1.0f; graphics->SetShaderParameter(PSP_SHADOWINTENSITY, Vector4(pcfValues / samples, intensity, 0.0f, 0.0f)); } float sizeX = 1.0f / (float)shadowMap->GetWidth(); float sizeY = 1.0f / (float)shadowMap->GetHeight(); graphics->SetShaderParameter(PSP_SHADOWMAPINVSIZE, Vector4(sizeX, sizeY, 0.0f, 0.0f)); Vector4 lightSplits(M_LARGE_VALUE, M_LARGE_VALUE, M_LARGE_VALUE, M_LARGE_VALUE); if (lightQueue_->shadowSplits_.Size() > 1) lightSplits.x_ = lightQueue_->shadowSplits_[0].farSplit_ / camera_->GetFarClip(); if (lightQueue_->shadowSplits_.Size() > 2) lightSplits.y_ = lightQueue_->shadowSplits_[1].farSplit_ / camera_->GetFarClip(); if (lightQueue_->shadowSplits_.Size() > 3) lightSplits.z_ = lightQueue_->shadowSplits_[2].farSplit_ / camera_->GetFarClip(); graphics->SetShaderParameter(PSP_SHADOWSPLITS, lightSplits); } } // Set material-specific shader parameters and textures if (material_) { if (graphics->NeedParameterUpdate(SP_MATERIAL, material_)) { // Update shader parameter animations material_->UpdateShaderParameterAnimations(); const HashMap<StringHash, MaterialShaderParameter>& parameters = material_->GetShaderParameters(); for (HashMap<StringHash, MaterialShaderParameter>::ConstIterator i = parameters.Begin(); i != parameters.End(); ++i) graphics->SetShaderParameter(i->first_, i->second_.value_); } const SharedPtr<Texture>* textures = material_->GetTextures(); for (unsigned i = 0; i < MAX_MATERIAL_TEXTURE_UNITS; ++i) { TextureUnit unit = (TextureUnit)i; if (textures[i] && graphics->HasTextureUnit(unit)) graphics->SetTexture(i, textures[i]); } } // Set light-related textures if (light) { if (shadowMap && graphics->HasTextureUnit(TU_SHADOWMAP)) graphics->SetTexture(TU_SHADOWMAP, shadowMap); if (graphics->HasTextureUnit(TU_LIGHTRAMP)) { Texture* rampTexture = light->GetRampTexture(); if (!rampTexture) rampTexture = renderer->GetDefaultLightRamp(); graphics->SetTexture(TU_LIGHTRAMP, rampTexture); } if (graphics->HasTextureUnit(TU_LIGHTSHAPE)) { Texture* shapeTexture = light->GetShapeTexture(); if (!shapeTexture && light->GetLightType() == LIGHT_SPOT) shapeTexture = renderer->GetDefaultLightSpot(); graphics->SetTexture(TU_LIGHTSHAPE, shapeTexture); } } // Set zone texture if necessary if (zone_ && graphics->HasTextureUnit(TU_ZONE)) graphics->SetTexture(TU_ZONE, zone_->GetZoneTexture()); }
/* * Calculate rotation matrix from angles in 3D. */ void operator^=(DOUBLEmatrix3D &t3dRotation, const ANGLE3D &a3dAngles) { const ANGLE &h=a3dAngles(1); // heading const ANGLE &p=a3dAngles(2); // pitch const ANGLE &b=a3dAngles(3); // banking t3dRotation(1,1) = Cos(h)*Cos(b)+Sin(p)*Sin(h)*Sin(b); t3dRotation(1,2) = Sin(p)*Sin(h)*Cos(b)-Cos(h)*Sin(b); t3dRotation(1,3) = Cos(p)*Sin(h); t3dRotation(2,1) = Cos(p)*Sin(b); t3dRotation(2,2) = Cos(p)*Cos(b); t3dRotation(2,3) = -Sin(p); t3dRotation(3,1) = Sin(p)*Cos(h)*Sin(b)-Sin(h)*Cos(b); t3dRotation(3,2) = Sin(p)*Cos(h)*Cos(b)+Sin(h)*Sin(b); t3dRotation(3,3) = Cos(p)*Cos(h); }
void Boat::drawCannonBarrel(double height) { double length=.22; double radius=.09; double thickness=.02; double inc=4; // transform glPushMatrix(); glTranslated(0,height,0); glRotated(cannonHorizAngle,0,1,0); glRotated(cannonVertAngle,0,0,1); // Begin drawing // Sphere glPushMatrix(); glScaled(.15,.15,.15); for (double i=0;i<180;i+=inc) { glBegin(GL_QUAD_STRIP); for (double j=0;j<=360;j+=inc) { glNormal3f( Cos(j)*Sin(i), Cos(i), Sin(j)*Sin(i)); glTexCoord2f(j/360, i/180); glVertex3f(Cos(j+0 )*Sin(i+0 ), Cos(i+0 ), Sin(j+0 )*Sin(i+0 )); glNormal3f( Cos(j)*Sin(i+inc), Cos(i+inc), Sin(j)*Sin(i+inc)); glTexCoord2f(j/360, (i+inc)/180); glVertex3f(Cos(j+0 )*Sin(i+inc), Cos(i+inc), Sin(j+0 )*Sin(i+inc)); } glEnd(); } glPopMatrix(); // Outside surface glBegin(GL_QUAD_STRIP); for(double i=0;i<=360;i+=5) { glNormal3f( 0,Sin(i), Cos(i)); glTexCoord2f(i/360,0); glVertex3d(0,Sin(i)*radius,Cos(i)*radius); glTexCoord2f(i/360,.2); glVertex3d(length,Sin(i)*radius,Cos(i)*radius); } glEnd(); // Inside surface glBegin(GL_QUAD_STRIP); for(double i=0;i<=360;i+=5) { glNormal3f( 0,-Sin(i), -Cos(i)); glTexCoord2f(i/360,0); glVertex3d(0,Sin(i)*(radius-thickness),Cos(i)*(radius-thickness) ); glTexCoord2f(i/360,.2); glVertex3d(length,Sin(i)*(radius-thickness),Cos(i)*(radius-thickness) ); } glEnd(); // End glBegin(GL_QUAD_STRIP); glNormal3f( 1,0,0); for(int i=0;i<=360;i+=5) { glTexCoord2f(.5+Sin(i)*.5, .5+Cos(i)*.5 ); glVertex3d(length,Sin(i)*(radius-thickness),Cos(i)*(radius-thickness) ); glTexCoord2f(.5+Sin(i)*.45, .5+Cos(i)*.45 ); glVertex3d(length,Sin(i)*radius,Cos(i)*radius); } glEnd(); // Black spot inside glBegin(GL_POLYGON); glColor3f(0,0,0); glNormal3f(-1,0,0); for(int i=0;i<=360;i+=5) { glVertex3d(.15,Sin(i)*(radius-thickness),Cos(i)*(radius-thickness)); } glEnd(); glPopMatrix(); }
/* * Calculate inverse rotation matrix from angles in 3D. */ void operator!=(DOUBLEmatrix3D &t3dRotation, const ANGLE3D &a3dAngles) { const ANGLE &h=a3dAngles(1); // heading const ANGLE &p=a3dAngles(2); // pitch const ANGLE &b=a3dAngles(3); // banking // to make inverse of rotation matrix, we only need to transpose it t3dRotation(1,1) = Cos(h)*Cos(b)+Sin(p)*Sin(h)*Sin(b); t3dRotation(2,1) = Sin(p)*Sin(h)*Cos(b)-Cos(h)*Sin(b); t3dRotation(3,1) = Cos(p)*Sin(h); t3dRotation(1,2) = Cos(p)*Sin(b); t3dRotation(2,2) = Cos(p)*Cos(b); t3dRotation(3,2) = -Sin(p); t3dRotation(1,3) = Sin(p)*Cos(h)*Sin(b)-Sin(h)*Cos(b); t3dRotation(2,3) = Sin(p)*Cos(h)*Cos(b)+Sin(h)*Sin(b); t3dRotation(3,3) = Cos(p)*Cos(h); }
// // Draw the window // void Ex01opengl::paintGL() { // Wall time (seconds) float t = 0.001*time.elapsed(); // Clear screen and Z-buffer glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Set view glLoadIdentity(); if (fov) glTranslated(0,0,-2*dim); glRotated(ph,1,0,0); glRotated(th,0,1,0); // Enable lighting if (light) { // Translate intensity to color vectors float Ambient[] = {0.3,0.3,0.3,1.0}; float Diffuse[] = {0.8,0.8,0.8,1.0}; float Specular[] = {1.0,1.0,1.0,1.0}; float Position[] = {(float)(3*Cos(90*t)),3.0,(float)(3*Sin(90*t)),1.0}; // Draw light position (no lighting yet) glColor3f(1,1,1); ball(Position[0],Position[1],Position[2] , 0.1); // OpenGL should normalize normal vectors glEnable(GL_NORMALIZE); // Enable lighting glEnable(GL_LIGHTING); // glColor sets ambient and diffuse color materials glColorMaterial(GL_FRONT_AND_BACK,GL_AMBIENT_AND_DIFFUSE); glEnable(GL_COLOR_MATERIAL); // Enable light 0 glEnable(GL_LIGHT0); // Set ambient, diffuse, specular components and position of light 0 glLightfv(GL_LIGHT0,GL_AMBIENT ,Ambient); glLightfv(GL_LIGHT0,GL_DIFFUSE ,Diffuse); glLightfv(GL_LIGHT0,GL_SPECULAR,Specular); glLightfv(GL_LIGHT0,GL_POSITION,Position); } // Apply shader if (mode) { shader.bind(); shader.setUniformValue("time",t); } // Draw scene if (obj) obj->display(); // Release shader if (mode) shader.release(); // Disable lighting glDisable(GL_LIGHTING); // Draw Axes glColor3f(1,1,1); glBegin(GL_LINES); glVertex3d(0,0,0); glVertex3d(1,0,0); glVertex3d(0,0,0); glVertex3d(0,1,0); glVertex3d(0,0,0); glVertex3d(0,0,1); glEnd(); // Emit angles to display emit angles(QString::number(th)+","+QString::number(ph)); }
/* Implementation *************************************************************/ void CSyncUsingPil::ProcessDataInternal(CParameter& ReceiverParam) { int i; /**************************************************************************\ * Frame synchronization detection * \**************************************************************************/ _BOOLEAN bSymbolIDHasChanged = FALSE; if ((bSyncInput == FALSE) && (bAquisition == TRUE)) { #ifdef USE_DRM_FRAME_SYNC_IR_BASED /* DRM frame synchronization using impulse response ----------------- */ /* We assume that the current received OFDM symbol is the first symbol in a DRM frame and estimate the channel transfer function at the pilot positions (the positions of pilots in the first OFDM symbol in a DRM frame). Then we calculate an FFT to get the impulse response of the channel. If the assumption was correct and this really was the correct OFDM symbol, we will get something which looks like an impulse response (contains peaks -> peak-to-average ratio is high). If not, we will certainly get only noise -> no peaks -> peak to average ratio is small. This is because the transmitted values at the pilot positions are different from the values at the pilot cells when transmitting the correct OFDM symbol (which we assumed) */ /* Pick pilot positions and calculate "test" channel estimation */ int iCurIndex = 0; for (i = 0; i < iNumCarrier; i++) { if (_IsScatPil(ReceiverParam.matiMapTab[0][i])) { /* Get channel estimate */ veccChan[iCurIndex] = (*pvecInputData)[i] / ReceiverParam.matcPilotCells[0][i]; /* We have to introduce a new index because not on all carriers is a pilot */ iCurIndex++; } } /* Calculate abs(IFFT) for getting estimate of impulse response */ vecrTestImpResp = Abs(Ifft(veccChan, FftPlan)); /* Calculate peak to average */ const CReal rResultIREst = Max(vecrTestImpResp) / Sum(vecrTestImpResp); /* Store correlation results in a shift register for finding the peak */ vecrCorrHistory.AddEnd(rResultIREst); #else /* DRM frame synchronization based on time pilots ------------------- */ /* Calculate correlation of received cells with pilot pairs */ CReal rResultPilPairCorr = (CReal) 0.0; for (i = 0; i < iNumPilPairs; i++) { /* Actual correlation */ const CComplex cCorrRes = (*pvecInputData)[vecPilCorr[i].iIdx1] * Conj(vecPilCorr[i].cPil1) * Conj((*pvecInputData)[vecPilCorr[i].iIdx2]) * vecPilCorr[i].cPil2 * cR_HH; rResultPilPairCorr += Real(cCorrRes); } /* Store correlation results in a shift register for finding the peak */ vecrCorrHistory.AddEnd(rResultPilPairCorr); #endif /* Finding beginning of DRM frame in results ------------------------ */ /* Wait until history is filled completly */ if (iInitCntFraSy > 0) iInitCntFraSy--; else { /* Search for maximum */ int iMaxIndex = 0; CReal rMaxValue = -_MAXREAL; for (i = 0; i < iNumSymPerFrame; i++) { if (vecrCorrHistory[i] > rMaxValue) { rMaxValue = vecrCorrHistory[i]; iMaxIndex = i; } } /* For initial frame synchronization, use maximum directly */ if (bInitFrameSync == TRUE) { /* Reset init flag */ bInitFrameSync = FALSE; /* Set symbol ID index according to received data */ iSymbCntFraSy = iNumSymPerFrame - iMaxIndex - 1; } else { /* If maximum is in the middle of the interval (check frame sync) */ if (iMaxIndex == iMiddleOfInterval) { if (iSymbCntFraSy == iNumSymPerFrame - iMiddleOfInterval - 1) { /* Reset flags */ bBadFrameSync = FALSE; bFrameSyncWasOK = TRUE; /* Post Message for GUI (Good frame sync) */ PostWinMessage(MS_FRAME_SYNC, 0); /* green */ } else { if (bBadFrameSync == TRUE) { /* Reset symbol ID index according to received data */ iSymbCntFraSy = iNumSymPerFrame - iMiddleOfInterval - 1; /* Inform that symbol ID has changed */ bSymbolIDHasChanged = TRUE; /* Reset flag */ bBadFrameSync = FALSE; PostWinMessage(MS_FRAME_SYNC, 2); /* red */ } else { /* One false detected frame sync should not reset the actual frame sync because the measurement could be wrong. Sometimes the frame sync detection gets false results. If the next time the frame sync is still unequal to the measurement, then correct it */ bBadFrameSync = TRUE; if (bFrameSyncWasOK == TRUE) { /* Post Message that frame sync was wrong but was not yet corrected (yellow light) */ PostWinMessage(MS_FRAME_SYNC, 1); /* yellow */ } else PostWinMessage(MS_FRAME_SYNC, 2); /* red */ } /* Set flag for bad sync */ bFrameSyncWasOK = FALSE; } } } } } else { /* Frame synchronization has successfully finished, show always green light */ PostWinMessage(MS_FRAME_SYNC, 0); } /* Set current symbol ID and flag in extended data of output vector */ (*pvecOutputData).GetExData().iSymbolID = iSymbCntFraSy; (*pvecOutputData).GetExData().bSymbolIDHasChanged = bSymbolIDHasChanged; /* Increase symbol counter and take care of wrap around */ iSymbCntFraSy++; if (iSymbCntFraSy >= iNumSymPerFrame) iSymbCntFraSy = 0; /**************************************************************************\ * Using Frequency pilot information * \**************************************************************************/ if ((bSyncInput == FALSE) && (bTrackPil == TRUE)) { CComplex cFreqOffEstVecSym = CComplex((CReal) 0.0, (CReal) 0.0); for (i = 0; i < NUM_FREQ_PILOTS; i++) { /* The old pilots must be rotated due to timing corrections */ const CComplex cOldFreqPilCorr = Rotate(cOldFreqPil[i], iPosFreqPil[i], (*pvecInputData).GetExData().iCurTimeCorr); /* Calculate the inner product of the sum */ const CComplex cCurPilMult = (*pvecInputData)[iPosFreqPil[i]] * Conj(cOldFreqPilCorr); /* Save "old" frequency pilots for next symbol. Special treatment for robustness mode D (carriers 7 and 21) necessary (See 8.4.2.2) */ if ((ReceiverParam.GetWaveMode() == RM_ROBUSTNESS_MODE_E) && (i < 2)) { cOldFreqPil[i] = -(*pvecInputData)[iPosFreqPil[i]]; } else cOldFreqPil[i] = (*pvecInputData)[iPosFreqPil[i]]; #ifdef USE_SAMOFFS_TRACK_FRE_PIL /* Get phase difference for sample rate offset estimation. Average the vector, real and imaginary part separately */ IIR1(cFreqPilotPhDiff[i], cCurPilMult, rLamSamRaOff); #endif /* Calculate estimation of frequency offset */ cFreqOffEstVecSym += cCurPilMult; } /* Frequency offset ------------------------------------------------- */ /* Correct frequency offset estimation for resample offset corrections. When a sample rate offset correction was applied, the frequency offset is shifted proportional to this correction. The correction is mandatory if large sample rate offsets occur */ /* Get sample rate offset change */ const CReal rDiffSamOffset = rPrevSamRateOffset - ReceiverParam.rResampleOffset; /* Save current resample offset for next symbol */ rPrevSamRateOffset = ReceiverParam.rResampleOffset; /* Correct sample-rate offset correction according to the proportional rule. Use relative DC frequency offset plus relative average offset of frequency pilots to the DC frequency. Normalize this offset so that it can be used as a phase correction for frequency offset estimation */ CReal rPhaseCorr = (ReceiverParam.rFreqOffsetAcqui + ReceiverParam.rFreqOffsetTrack + rAvFreqPilDistToDC) * rDiffSamOffset / SOUNDCRD_SAMPLE_RATE / rNormConstFOE; /* Actual correction (rotate vector) */ cFreqOffVec *= CComplex(Cos(rPhaseCorr), Sin(rPhaseCorr)); /* Average vector, real and imaginary part separately */ IIR1(cFreqOffVec, cFreqOffEstVecSym, rLamFreqOff); /* Calculate argument */ const CReal rFreqOffsetEst = Angle(cFreqOffVec); /* Correct measurement average for actually applied frequency correction */ cFreqOffVec *= CComplex(Cos(-rFreqOffsetEst), Sin(-rFreqOffsetEst)); #ifndef USE_FRQOFFS_TRACK_GUARDCORR /* Integrate the result for controling the frequency offset, normalize estimate */ ReceiverParam.rFreqOffsetTrack += rFreqOffsetEst * rNormConstFOE; #endif #ifdef USE_SAMOFFS_TRACK_FRE_PIL /* Sample rate offset ----------------------------------------------- */ /* Calculate estimation of sample frequency offset. We use the different frequency offset estimations of the frequency pilots. We normalize them with the distance between them and average the result (/ 2.0) */ CReal rSampFreqOffsetEst = ((Angle(cFreqPilotPhDiff[1]) - Angle(cFreqPilotPhDiff[0])) / (iPosFreqPil[1] - iPosFreqPil[0]) + (Angle(cFreqPilotPhDiff[2]) - Angle(cFreqPilotPhDiff[0])) / (iPosFreqPil[2] - iPosFreqPil[0])) / (CReal) 2.0; /* Integrate the result for controling the resampling */ ReceiverParam.rResampleOffset += CONTR_SAMP_OFF_INTEGRATION * rSampFreqOffsetEst; #endif #ifdef _DEBUG_ /* Save frequency and sample rate tracking */ static FILE* pFile = fopen("test/freqtrack.dat", "w"); fprintf(pFile, "%e %e\n", SOUNDCRD_SAMPLE_RATE * ReceiverParam.rFreqOffsetTrack, ReceiverParam.rResampleOffset); fflush(pFile); #endif } /* If synchronized DRM input stream is used, overwrite the detected frequency offest estimate by "0", because we know this value */ if (bSyncInput == TRUE) ReceiverParam.rFreqOffsetTrack = (CReal) 0.0; /* Do not ship data before first frame synchronization was done. The flag "bAquisition" must not be set to FALSE since in that case we would run into an infinite loop since we would not ever ship any data. But since the flag is set after this module, we should be fine with that. */ if ((bInitFrameSync == TRUE) && (bSyncInput == FALSE)) iOutputBlockSize = 0; else { iOutputBlockSize = iNumCarrier; /* Copy data from input to the output. Data is not modified in this module */ for (i = 0; i < iOutputBlockSize; i++) (*pvecOutputData)[i] = (*pvecInputData)[i]; } }
//Used to display the scene. void display() { glClearColor(skyColor[0],skyColor[1],skyColor[2],skyColor[3]); glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); glLoadIdentity(); float Ambient[] = {0.3 ,0.3 ,0.3 ,1.0}; float Diffuse[] = {1.0 ,1.0 ,1.0 ,1.0}; if(mode == 0) { //Set up perspective projection double Ex = 5*dim*Sin(th)*Cos(ph); double Ey = 5*dim*Sin(ph); double Ez = -5*dim*Cos(th)*Cos(ph); gluLookAt(Ex,Ey,Ez ,0,0,0, 0,Cos(ph),0); } else { //Set up first person projection double Cx = -5*dim*Sin(th)*Cos(ph) + xOffset; double Cy = 5*dim*Sin(ph) + yOffset; double Cz = 5*dim*Cos(th)*Cos(ph) + zOffset; gluLookAt(xOffset,yOffset,zOffset ,Cx,Cy,Cz, 0,Cos(ph),0); } //Enable depth test. glEnable(GL_DEPTH_TEST); glEnable(GL_NORMALIZE); float hrMin = minOfHr+minHrOffset; float dayHr = (hourOfDay+hrDayOffset-6)%12; float relativeTime = (dayHr + hrMin/60)*3.1415926/11; float light0Position[] = {0,0,0,1.0}; float light1Position[] = {-5*dim, dim, -5*dim, 1.0}; if(outside) { light0Position[1]=5*dim*sin(relativeTime); light0Position[2]=5*dim*cos(relativeTime); } else { light0Position[0]=5*dim; light0Position[1]=dim; light0Position[2]=5*dim; } //make sphere at position of light if(outside) { int offsetTime = (hourOfDay+minHrOffset)%24; if(offsetTime >=6 && offsetTime <=17) glColor4f(1,1,1,1); else glColor4f(0.5,0.5,0.5,1); sphere(light0Position[0], light0Position[1], light0Position[2], 100,100,100); } //enable textures glEnable(GL_TEXTURE_2D); glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); //enable lighting glEnable(GL_LIGHTING); glColorMaterial(GL_FRONT_AND_BACK,GL_AMBIENT_AND_DIFFUSE); glEnable(GL_COLOR_MATERIAL); //set light to be at position glLightfv(GL_LIGHT0,GL_POSITION,light0Position); //enable light 0 glEnable(GL_LIGHT0); //set ambient and diffuse components of light 0 glLightfv(GL_LIGHT0,GL_AMBIENT ,Ambient); glLightfv(GL_LIGHT0,GL_DIFFUSE ,Diffuse); if(!outside) { glLightfv(GL_LIGHT1,GL_POSITION,light1Position); glEnable(GL_LIGHT1); glLightfv(GL_LIGHT1,GL_AMBIENT ,Ambient); glLightfv(GL_LIGHT1,GL_DIFFUSE ,Diffuse); } else{ glDisable(GL_LIGHT1); } //make arches glCallList(cathedralList); glCallList(pewList); glCallList(towerList); glCallList(treeList); glCallList(floorList); glCallList(crossList); glColor4f(0.0,0.75,0.0,1.0); glBindTexture(GL_TEXTURE_2D, groundTexture); //grass glBegin(GL_QUADS); glNormal3d(0.0,1.0,0.0); glTexCoord2f(0.0,0.0); glVertex3f(-5*dim,-10.0,-5*dim); glNormal3d(0.0,1.0,0.0); glTexCoord2f(0.0,5*dim/4); glVertex3f(-5*dim,-10.0,5*dim); glNormal3d(0.0,1.0,0.0); glTexCoord2f(5*dim/4,5*dim/4); glVertex3f(5*dim,-10.0,5*dim); glNormal3d(0.0,1.0,0.0); glTexCoord2f(5*dim/4,0.0); glVertex3f(5*dim,-10.0,-5*dim); glEnd(); drawStainedGlass(stainedGlassTexture, stainedGlassTexture2); glDisable(GL_TEXTURE_2D); //Print projection type in bottom left corner glColor3f(1,1,1); glWindowPos2i(5,5); if(mode == 0) { Print("Projection Type: Perspective"); glWindowPos2i(5,25); Print("Dimension: %.0f", dim); } else { Print("Projection Type: First Person"); glWindowPos2i(5,25); Print("User Location: { %.3f, %.3f, %.3f }", xOffset, yOffset, zOffset); } glWindowPos2i(5,65); Print("Time: %.2d:%.2d",hourOfDay,minOfHr); glWindowPos2i(5,45); Print("Offset Time: %.2d:%.2d",(int)(hourOfDay+hrDayOffset)%12,(int)hrMin); //check for errors ErrCheck("display"); //Render scene glFlush(); glutSwapBuffers(); }
void CSyncUsingPil::InitInternal(CParameter& ReceiverParam) { int i; _COMPLEX cPhaseCorTermDivi; /* Init base class for modifying the pilots (rotation) */ CPilotModiClass::InitRot(ReceiverParam); /* Init internal parameters from global struct */ iNumCarrier = ReceiverParam.iNumCarrier; eCurRobMode = ReceiverParam.GetWaveMode(); /* Check if symbol number per frame has changed. If yes, reset the symbol counter */ if (iNumSymPerFrame != ReceiverParam.iNumSymPerFrame) { /* Init internal counter for symbol number */ iSymbCntFraSy = 0; /* Refresh parameter */ iNumSymPerFrame = ReceiverParam.iNumSymPerFrame; } /* Allocate memory for histories. Init history with small values, because we search for maximum! */ vecrCorrHistory.Init(iNumSymPerFrame, -_MAXREAL); /* Set middle of observation interval */ iMiddleOfInterval = iNumSymPerFrame / 2; #ifdef USE_DRM_FRAME_SYNC_IR_BASED /* DRM frame synchronization using impulse response, inits--------------- */ /* Get number of pilots in first symbol of a DRM frame */ iNumPilInFirstSym = 0; for (i = 0; i < iNumCarrier; i++) { if (_IsScatPil(ReceiverParam.matiMapTab[0][i])) iNumPilInFirstSym++; } /* Init vector for "test" channel estimation result */ veccChan.Init(iNumPilInFirstSym); vecrTestImpResp.Init(iNumPilInFirstSym); /* Init plans for FFT (faster processing of Fft and Ifft commands) */ FftPlan.Init(iNumPilInFirstSym); #else /* DRM frame synchronization based on time pilots, inits ---------------- */ /* Allocate memory for storing pilots and indices. Since we do not know the resulting "iNumPilPairs" we allocate memory for the worst case, i.e. "iNumCarrier" */ vecPilCorr.Init(iNumCarrier); /* Store pilots and indices for calculating the correlation. Use only first symbol of "matcPilotCells", because there are the pilots for Frame-synchronization */ iNumPilPairs = 0; for (i = 0; i < iNumCarrier - 1; i++) { /* Only successive pilots (in frequency direction) are used */ if (_IsPilot(ReceiverParam.matiMapTab[0][i]) && _IsPilot(ReceiverParam.matiMapTab[0][i + 1])) { /* Store indices and complex numbers */ vecPilCorr[iNumPilPairs].iIdx1 = i; vecPilCorr[iNumPilPairs].iIdx2 = i + 1; vecPilCorr[iNumPilPairs].cPil1 = ReceiverParam.matcPilotCells[0][i]; vecPilCorr[iNumPilPairs].cPil2 = ReceiverParam.matcPilotCells[0][i + 1]; iNumPilPairs++; } } /* Calculate channel correlation in frequency direction. Use rectangular shaped PDS with the length of the guard-interval */ const CReal rArgSinc = (CReal) ReceiverParam.iGuardSize / ReceiverParam.iFFTSizeN; const CReal rArgExp = crPi * rArgSinc; cR_HH = Sinc(rArgSinc) * CComplex(Cos(rArgExp), -Sin(rArgExp)); #endif /* Frequency offset estimation ------------------------------------------ */ /* Get position of frequency pilots */ int iFreqPilCount = 0; int iAvPilPos = 0; for (i = 0; i < iNumCarrier - 1; i++) { if (_IsFreqPil(ReceiverParam.matiMapTab[0][i])) { /* For average frequency pilot position to DC carrier */ iAvPilPos += i + ReceiverParam.iCarrierKmin; iPosFreqPil[iFreqPilCount] = i; iFreqPilCount++; } } /* Average distance of the frequency pilots from the DC carrier. Needed for corrections for sample rate offset changes. Normalized to sample rate! */ rAvFreqPilDistToDC = (CReal) iAvPilPos / NUM_FREQ_PILOTS / ReceiverParam.iFFTSizeN; /* Init memory for "old" frequency pilots */ for (i = 0; i < NUM_FREQ_PILOTS; i++) cOldFreqPil[i] = CComplex((CReal) 0.0, (CReal) 0.0); /* Nomalization constant for frequency offset estimation */ rNormConstFOE = (CReal) 1.0 / ((CReal) 2.0 * crPi * ReceiverParam.iSymbolBlockSize); /* Init time constant for IIR filter for frequency offset estimation */ rLamFreqOff = IIR1Lam(TICONST_FREQ_OFF_EST, (CReal) SOUNDCRD_SAMPLE_RATE / ReceiverParam.iSymbolBlockSize); /* Init vector for averaging the frequency offset estimation */ cFreqOffVec = CComplex((CReal) 0.0, (CReal) 0.0); /* Init value for previous estimated sample rate offset with the current setting. This can be non-zero if, e.g., an initial sample rate offset was set by command line arguments */ rPrevSamRateOffset = ReceiverParam.rResampleOffset; #ifdef USE_SAMOFFS_TRACK_FRE_PIL /* Inits for sample rate offset estimation algorithm -------------------- */ /* Init memory for actual phase differences */ for (i = 0; i < NUM_FREQ_PILOTS; i++) cFreqPilotPhDiff[i] = CComplex((CReal) 0.0, (CReal) 0.0); /* Init time constant for IIR filter for sample rate offset estimation */ rLamSamRaOff = IIR1Lam(TICONST_SAMRATE_OFF_EST, (CReal) SOUNDCRD_SAMPLE_RATE / ReceiverParam.iSymbolBlockSize); #endif /* Define block-sizes for input and output */ iInputBlockSize = iNumCarrier; iMaxOutputBlockSize = iNumCarrier; }
inline static void ToCartesian( double r, double theta, DPoint center, DPoint& p ) { p.x = center.x + r*Cos( theta ); p.y = center.y + r*Sin( theta ); }
/* * OpenGL (GLUT) calls this routine to display the scene */ void display() { int ndm[] = {31,28,31,30,31,30,31,31,30,31,30,31}; int doy = zh/360; int mo,dy,hr,mn; int id; // Sun angle float fh = doy*360.0/365.0; // Light direction float Position[] = {Cos(fh),0.0,Sin(fh),0.0}; // Time of day id = (zh+(int)fh)%360; hr = (id/15)%24; mn = 4*(id%15); // Compute month and day dy = doy+1; for (mo=0;dy>ndm[mo];mo++) dy -= ndm[mo]; fh = (dy-1)/(float)ndm[mo]; mo++; // Erase the window and the depth buffer glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); // Enable Z-buffering in OpenGL glEnable(GL_DEPTH_TEST); // Set tranformation glLoadIdentity(); glRotatef(ph,1,0,0); glRotatef(th,0,1,0); // OpenGL should normalize normal vectors glEnable(GL_NORMALIZE); // Enable lighting glEnable(GL_LIGHTING); // Enable light 0 glEnable(GL_LIGHT0); // Set position of light 0 glLightfv(GL_LIGHT0,GL_POSITION,Position); // Texture for this month glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D,day[mo-1]); // Texture for next month glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D,day[mo%12]); // Rotate Z up and inclined 23.5 degrees glRotated(-90,1,0,0); glRotated(-23.5,0,1,0); // Draw planet glColor3f(1,1,1); glEnable(GL_TEXTURE_2D); // Rotation around spin axis glRotated(zh,0,0,1); // Solid gluQuadricDrawStyle(ball,GLU_FILL); // Calculate normals gluQuadricNormals(ball,GLU_SMOOTH); // Apply Textures gluQuadricTexture(ball,1); // Enable shader glUseProgram(shader); // Set textures id = glGetUniformLocation(shader,"DayTex0"); if (id>=0) glUniform1i(id,0); id = glGetUniformLocation(shader,"DayTex1"); if (id>=0) glUniform1i(id,1); id = glGetUniformLocation(shader,"NightTex"); if (id>=0) glUniform1i(id,2); id = glGetUniformLocation(shader,"CloudGloss"); if (id>=0) glUniform1i(id,3); id = glGetUniformLocation(shader,"mode"); if (id>=0) glUniform1i(id,mode); id = glGetUniformLocation(shader,"frac"); if (id>=0) glUniform1f(id,fh); // Draw the ball gluSphere(ball,2.0,72,72); // Shader off glUseProgram(0); // No lighting from here on glDisable(GL_LIGHTING); // Axes glBegin(GL_LINES); glVertex3f(0,0,+2.5); glVertex3f(0,0,-2.5); glEnd(); // Display parameters glColor3f(1,1,1); glWindowPos2i(5,5); Print("FPS=%d Dim=%.1f %d/%.2d %.2d:%.2d UTC %s", FramesPerSecond(),dim,mo,dy,hr,mn,text[mode]); // Render the scene and make it visible ErrCheck("display"); glFlush(); glutSwapBuffers(); }
/* called by GUI */ Icon::Icon(User *user, void *d) { char *infos = (char *) d; ifile = NULL; ofile = NULL; char *action = NULL; vref = NULL; char icon[URL_LEN]; *icon = 0; /* parameters transmission */ for (char *pt = strtok(infos, "&"); pt ; pt = strtok(NULL, "&")) { if (! stringcmp(pt, "<url=")) { pt = getParam(pt); strcpy(names.url, pt); taken = true; } else if (! stringcmp(pt, "<file=")) { pt = getParam(pt); ifile = strdup(pt); } else if (! stringcmp(pt, "<ofile=")) { pt = getParam(pt); strcpy(names.url, pt); } else if (! stringcmp(pt, "<name=")) { pt = getParam(pt); strcpy(names.named, pt); } else if (! stringcmp(pt, "<icon=")) { pt = getParam(pt); strcpy(icon, pt); } else if (! stringcmp(pt, "<action=")) { pt = getParam(pt); action = strdup(pt); } else if (! stringcmp(pt, "<vref=")) { pt = strchr(pt, '='); pt++; char *p2; if ((p2 = strchr(pt, '>'))) *p2 = 0; vref = strdup(pt); } } if (vref) { // local saved document exists parser(vref); // get the last loaded texture int texid = Texture::getIdByUrl(names.url); Texture *tclast = Texture::getEntryById(texid); if (! tclast) { tex = new char[sizeof(ICO_DEF) + 1]; strcpy(tex, ICO_DEF); // default texture } else { tex = new char[strlen(tclast->url) + 1]; strcpy(tex, tclast->url); } taken = false; } else { // new document named interactively by hand /* position */ float off = 0.4; pos.x = user->pos.x + off * Cos(user->pos.az); pos.y = user->pos.y + off * Sin(user->pos.az); pos.z = user->pos.z + 0.6; // visible by eyes pos.az = user->pos.az + M_PI_2; /* texture */ if (*icon) { tex = new char[strlen(icon) + 1]; strcpy(tex, icon); } else { // default binding icon to document char ext[8] = ""; memset(ext, 0, sizeof(ext)); if (Format::getExt(names.url, ext)) { tex = new char[URL_LEN]; Format::getImgByExt(ext, tex); } else { tex = new char[sizeof(ICO_DEF) + 1]; strcpy(tex, ICO_DEF); } } if (ifile) { // private local document if (*names.url) { // public url given by user Cache::download(ifile, ofile, "inout"); } else { // build local ofile in ~/public_html/vreng/ ofile = new char[URL_LEN]; sprintf(ofile, "%s/public_html", getenv("HOME")); if (access(ofile, R_OK|W_OK|X_OK) == 0) { strcat(ofile, "/vreng/"); if (access(ofile, R_OK|W_OK|X_OK) == -1) mkdir(ofile, 0755); strcat(ofile, ifile); FILE *fin, *fout; if ((fin = File::openFile(ifile, "r")) && (fout = File::openFile(ofile, "w"))) { char buf[2]; while (fread(buf, 1, 1, fin)) fwrite(buf, 1, 1, fout); File::closeFile(fin); File::closeFile(fout); chmod(ofile, 0644); //FIXME: define local http_server sprintf(names.url, "http://%s/~%s/vreng/%s", DEF_HTTP_SERVER, getenv("USER"), ifile); } else { error("can't open %s or %s: %s (%d)", ifile, ofile, strerror(errno), errno); free(ifile); ifile = NULL; delete[] ofile; } } else { error("can't access %s", ofile); free(ifile); ifile = NULL; delete[] ofile; } } } makeSolid(); } // local creation defaults(); enableBehavior(REMOVABLE); enableBehavior(NO_ELEMENTARY_MOVE); setRenderPrior(RENDER_HIGH); initializeMobileObject(1); ttl = (taken) ? MAXFLOAT : 0; initImposedMovement(ttl); disablePermanentMovement(); // network creation createVolatileNetObject(PROPS); // document's owner setOwner(); trace(DBG_WO, "Icon: url=%s icon=%s name=%s owner=%s", urlName(), tex, getInstance(), ownerName()); if (action) { if (! stringcmp(action, "pin")) pin(this, NULL, 0L, 0L); else if (! stringcmp(action, "push")) push(this, NULL, 0L, 0L); else if (! stringcmp(action, "carry")) carry(this, NULL, 0L, 0L); } }
/* * OpenGL (GLUT) calls this routine to display the scene */ void display() { // Length of axes const double len=1.2; // Eye position double Ex = -2*dim*Cos(ph); double Ey = +2*dim*Sin(ph); double Ez = 0; // Erase the window and the depth buffer glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); // Set perspective glLoadIdentity(); gluLookAt(Ex,Ey,Ez , 0,0,0 , 0,Cos(ph),0); // Draw scene glEnable(GL_DEPTH_TEST); // Rotate Z up glRotated(-90,1,0,0); /* * Draw solar system */ if (mode<0) { glRotated(th,0,0,1); // View angle SolarSystem(); } /* * Draw planet */ else { glRotated(th,1,0,0); // Declination glRotated(zh,0,0,1); // Spin around axes DrawPlanet(mode); } /* * Draw axes - no textures from here */ glColor3f(1,1,1); if (axes) { glBegin(GL_LINES); glVertex3d(0.0,0.0,0.0); glVertex3d(len,0.0,0.0); glVertex3d(0.0,0.0,0.0); glVertex3d(0.0,len,0.0); glVertex3d(0.0,0.0,0.0); glVertex3d(0.0,0.0,len); glEnd(); // Label axes glRasterPos3d(len,0.0,0.0); Print("X"); glRasterPos3d(0.0,len,0.0); Print("Y"); glRasterPos3d(0.0,0.0,len); Print("Z"); } // Display parameters glWindowPos2i(5,5); Print("Angle=%d,%d Dim=%.1f Object=%s",th,ph,2*dim,mode<0?"Solar System":planet[mode].name); if (mode<0) Print(" Magnification %d Year %.1f",mag,2000+day/365.25); // Render the scene and make it visible ErrCheck("display"); glFlush(); glutSwapBuffers(); }
func FxHomeCallTimer(object target, proplist fx, int time) { if(!master) { KillBall(); return -1; } if(GetEffect("Blocked", this)) { ox=GetX(); oy=GetY(); return; } DrawParticleLine("Flash", 0, 0, ox-GetX(), oy-GetY(), 1, 0, 0, 15, hometrailparticles); if(time%7 == 0) { for(var i = 0; i < 360; i+=5) { CreateParticle("Flash", Sin(i, 3), -Cos(i, 5), 0, 0, 10, hometrailparticles2, 2); } } fx.x = master->GetX(); fx.y = master->GetY(); var angle = Angle(GetX(), GetY(), fx.x, fx.y, 10); var txdir = Sin(angle, Speed + 12, 10); var tydir = -Cos(angle, Speed + 12, 10); SetXDir((GetXDir() + (txdir - GetXDir())/2)); SetYDir((GetYDir() + (tydir - GetYDir())/2)); CheckForEnemies(HomeCallSize); ox=GetX(); oy=GetY(); var dst = Distance(GetX(), GetY(), fx.x, fx.y); if(dst < 8) { AddShield(master); Sound("Ball::ball_shield", false, 20); var particles = { Prototype = Particles_Glimmer(), R = pR, G = pG, B = pB, Alpha = 255, Size = PV_Linear(10, 0), OnCollision = PC_Bounce(), }; CreateParticle("StarSpark", 0, 0, PV_Random(-60,60), PV_Random(-60, 60), 25, particles, 5); var particle = { Alpha = PV_Linear(255, 0), Size = 50, R = pR, G = pG, B = pB, BlitMode = GFX_BLIT_Additive, }; master->CreateParticle("StarSpark", 0, 0, 0, 0, 7, particle, 4); FollowMaster(); return -1; } }
void TestConvergence(Integrator const& integrator, Time const& beginning_of_convergence) { Length const q_initial = 1 * Metre; Speed const v_initial = 0 * Metre / Second; Speed const v_amplitude = 1 * Metre / Second; AngularFrequency const ω = 1 * Radian / Second; Instant const t_initial; #if defined(_DEBUG) Instant const t_final = t_initial + 10 * Second; #else Instant const t_final = t_initial + 100 * Second; #endif Time step = beginning_of_convergence; int const step_sizes = 50; double const step_reduction = 1.1; std::vector<double> log_step_sizes; log_step_sizes.reserve(step_sizes); std::vector<double> log_q_errors; log_step_sizes.reserve(step_sizes); std::vector<double> log_p_errors; log_step_sizes.reserve(step_sizes); std::vector<ODE::SystemState> solution; ODE harmonic_oscillator; harmonic_oscillator.compute_acceleration = std::bind(ComputeHarmonicOscillatorAcceleration, _1, _2, _3, /*evaluations=*/nullptr); IntegrationProblem<ODE> problem; problem.equation = harmonic_oscillator; ODE::SystemState const initial_state = {{q_initial}, {v_initial}, t_initial}; problem.initial_state = &initial_state; problem.t_final = t_final; ODE::SystemState final_state; problem.append_state = [&final_state](ODE::SystemState const& state) { final_state = state; }; for (int i = 0; i < step_sizes; ++i, step /= step_reduction) { integrator.Solve(problem, step); Time const t = final_state.time.value - t_initial; Length const& q = final_state.positions[0].value; Speed const& v = final_state.velocities[0].value; double const log_q_error = std::log10( AbsoluteError(q / q_initial, Cos(ω * t))); double const log_p_error = std::log10( AbsoluteError(v / v_amplitude, -Sin(ω * t))); if (log_q_error <= -13 || log_p_error <= -13) { // If we keep going the effects of finite precision will drown out // convergence. break; } log_step_sizes.push_back(std::log10(step / Second)); log_q_errors.push_back(log_q_error); log_p_errors.push_back(log_p_error); } double const q_convergence_order = Slope(log_step_sizes, log_q_errors); double const q_correlation = PearsonProductMomentCorrelationCoefficient(log_step_sizes, log_q_errors); LOG(INFO) << "Convergence order in q : " << q_convergence_order; LOG(INFO) << "Correlation : " << q_correlation; #if !defined(_DEBUG) EXPECT_THAT(RelativeError(integrator.order, q_convergence_order), Lt(0.02)); EXPECT_THAT(q_correlation, AllOf(Gt(0.99), Lt(1.01))); #endif double const v_convergence_order = Slope(log_step_sizes, log_p_errors); double const v_correlation = PearsonProductMomentCorrelationCoefficient(log_step_sizes, log_p_errors); LOG(INFO) << "Convergence order in p : " << v_convergence_order; LOG(INFO) << "Correlation : " << v_correlation; #if !defined(_DEBUG) // SPRKs with odd convergence order have a higher convergence order in p. EXPECT_THAT( RelativeError(integrator.order + (integrator.order % 2), v_convergence_order), Lt(0.02)); EXPECT_THAT(v_correlation, AllOf(Gt(0.99), Lt(1.01))); #endif }