void Tornado::Update() { ACTIVITYTIME -= Time::DeltaTime; if (ACTIVITYTIME <= 0) { parameter.isDead = true; Sound::GetInstance().StopSE(SE_ID::STRONGWIND_SE); return; } //world.SetCollideSelect(shared_from_this(), ACTOR_ID::STAGE_ACTOR, COL_ID::TORNADO_STAGE_COL); world.SetCollideSelect(shared_from_this(), ACTOR_ID::CASTLE_ACTOR , COL_ID::TORNADO_CASTLE_COL); world.SetCollideSelect(shared_from_this(), ACTOR_ID::CASTLE_BREAK_ACTOR, COL_ID::TORNADO_CASTLE_COL); //world.SetCollideSelect(shared_from_this(), ACTOR_ID::ISLAND_ACTOR , COL_ID::TORNADO_ISLAND_COL); isHit = false; //velocity.y = -GRAVITY; position += velocity * speed * Time::DeltaTime; parameter.velocity = Vector3(velocity.x, 0.0f, velocity.z).Normalized() * speed; parameter.mat = Matrix4::Scale(scale) * Matrix4::Translate(position); UpdateParticles(); }
void World::Step() { float delta = (float)mTimer.GetDelta(); delta = min(delta, 0.1f); timeBank += delta; deltaTime = 0.01f; deltaTimeScaled = deltaTime * DeltaTimeScalingFactor; deltaTimeScaledSquared = deltaTimeScaled * deltaTimeScaled; #if DEBUG || 1 timeBank = deltaTime + (deltaTime/2); #endif //while(timeBank > deltaTime) { //CalculateViscoElasticity(); UpdateGrid(); CalculateDensity(); CalculatePressure(); UpdateParticles(); DoCollision(); timeBank -= deltaTime; } }
void cWorld3D::Update(float afTimeStep) { START_TIMING(Physics); if(mpPhysicsWorld) mpPhysicsWorld->Update(afTimeStep); STOP_TIMING(Physics); START_TIMING(Entities); UpdateEntities(afTimeStep); STOP_TIMING(Entities); START_TIMING(Bodies); UpdateBodies(afTimeStep); STOP_TIMING(Bodies); START_TIMING(Particles); UpdateParticles(afTimeStep); STOP_TIMING(Particles); START_TIMING(Lights); UpdateLights(afTimeStep); STOP_TIMING(Lights); START_TIMING(SoundEntities); UpdateSoundEntities(afTimeStep); STOP_TIMING(SoundEntities); }
void SimpleParticle::Update(TimeValue t,INode *node) { if (node) { if (tvalid!=t || !valid) UpdateParticles(t,node); } UpdateMesh(t); }
// |----------------------------------------------------------------------------| // | Logic() | // |----------------------------------------------------------------------------| bool ParticleSystem::Logic() { DebugLog ("ParticleSystem: Logic() called.", DB_LOGIC, 10); // Increment the frame time. float time = TimerManager::GetRef()->GetTime() / 1000; m_accumulatedTime += time; // Set emit particle to false for now. bool emitParticle = false; // Check if it is time to emit a new particle or not. if(m_accumulatedTime > (m_particleSpawnFrequency)) { m_accumulatedTime = 0.0f; emitParticle = true; } if(m_spawnParticles && (emitParticle == true) && (m_particles.size() < (m_maxParticles - 1))) { // Emit new particles. EmitParticle(); } // Update the position of the particles. UpdateParticles(); // Release old particles. KillParticles(); return true; }
void CShootingObject::StartParticles (CParticlesObject*& pParticles, LPCSTR particles_name, const Fvector& pos, const Fvector& vel, bool auto_remove_flag) { if(!particles_name) return; if(pParticles != NULL) { UpdateParticles(pParticles, pos, vel); return; } pParticles = CParticlesObject::Create(particles_name,(BOOL)auto_remove_flag); UpdateParticles(pParticles, pos, vel); pParticles->Play(); }
void M2Object::update(size_t deltaTime, size_t accumTime) { deltaTime_ = deltaTime; globalTime = accumTime; if (animManager->IsPaused()) deltaTime = 0; if (!animManager->IsParticlePaused()) deltaTime = animManager->GetTimeDiff(); if (animated) animManager->Tick(deltaTime); if (animated) { if (ind) { animating(animManager->GetAnim()); } else { if (!animcalc) { animating(animManager->GetAnim()); } } } UpdateParticles(deltaTime/1000.0f); }
void ParticleSystem::Render(int deltaTime, const glm::mat4x4& mvp, const glm::vec3& camPos){ mTime += deltaTime; UpdateParticles(deltaTime); RenderParticles(mvp,camPos); mCurrVB = mCurrTFB; mCurrTFB = (mCurrTFB + 1) & 0x1; }
void CPowerMode::ShowParticles() { ::EnterCriticalSection(&m_cs); if(m_hAttachWnd != NULL) { ClearParticles(m_hAttachWnd); UpdateParticles(); DrawParticles(m_hAttachWnd); } ::LeaveCriticalSection(&m_cs); }
void ParticleSystem::Render(int DeltaTimeMillis, const Matrix4f& VP, const Vector3f& CameraPos) { m_time += DeltaTimeMillis; UpdateParticles(DeltaTimeMillis); RenderParticles(VP, CameraPos); m_currVB = m_currTFB; m_currTFB = (m_currTFB + 1) & 0x1; }
void ParticleSystem::Render(int DeltaTimeMillis, const glm::vec3 CameraPos, const glm::mat4 VP) { m_time += DeltaTimeMillis; UpdateParticles(DeltaTimeMillis); RenderParticles(VP, CameraPos); m_currVB = m_currTFB; m_currTFB = (m_currTFB + 1) & 0x1; }
void CParticlesPlayer::StopParticles(const shared_str& ps_name, u16 bone_id, bool bDestroy) { if (BI_NONE==bone_id) { for(BoneInfoVecIt it=m_Bones.begin(); it!=m_Bones.end(); it++) it->StopParticles (ps_name, bDestroy); } else { SBoneInfo* bi = get_bone_info(bone_id); VERIFY(bi); bi->StopParticles (ps_name, bDestroy); } UpdateParticles(); }
void Particle::Frame(float frameTime) { // Release old particles. KillParticles(); // Emit new particles. EmitParticles(frameTime); // Update the position of the particles. UpdateParticles(frameTime); }
void CShootingObject::StartParticles (CParticlesObject*& pParticles, LPCSTR particles_name, const Fvector& pos, const Fvector& vel, bool auto_remove_flag) { if(!particles_name) return; if(pParticles != NULL) { UpdateParticles(pParticles, pos, vel); return; } pParticles = CParticlesObject::Create(particles_name,(BOOL)auto_remove_flag); UpdateParticles(pParticles, pos, vel); CSpectator* tmp_spectr = smart_cast<CSpectator*>(Level().CurrentControlEntity()); bool in_hud_mode = IsHudModeNow(); if (in_hud_mode && tmp_spectr && (tmp_spectr->GetActiveCam() != CSpectator::eacFirstEye)) { in_hud_mode = false; } pParticles->Play(in_hud_mode); }
void cWorld3D::PreUpdate(float afTotalTime, float afTimeStep) { mpSound->GetSoundHandler()->SetSilent(true); while(afTotalTime>0) { if(mpPhysicsWorld) mpPhysicsWorld->Update(afTimeStep); UpdateParticles(afTimeStep); afTotalTime -= afTimeStep; } mpSound->GetSoundHandler()->SetSilent(false); }
/* ================ idBarrel::Think ================ */ void idBarrel::Think( void ) { if ( thinkFlags & TH_THINK ) { if ( !FollowInitialSplinePath() ) { BecomeInactive( TH_THINK ); } } BarrelThink(); #ifdef _DENTONMOD if ( thinkFlags & TH_UPDATEWOUNDPARTICLES ) UpdateParticles(); #endif }
bool ParticleSystemClass::Frame(float frameTime, ID3D11DeviceContext* deviceContext, D3DXVECTOR3 emitterPosition, D3DXVECTOR3 camPos) { bool result; KillParticles(); EmitParticles(frameTime, emitterPosition); UpdateParticles(frameTime, camPos); result = UpdateBuffers(deviceContext); //updating dynamic vertex buffer with new position of each particle if(!result) { return false; } return true; }
void Renderer::MainLoop(std::vector<Particle> &particles) { SDL_Event event; bool done = false; double time = 0.0; const double dt = 0.01; double currentTime = SDL_GetTicks() / 1000.0; double accumulator = 0.0; while (!done) { while (SDL_PollEvent(&event) != 0) { if (event.type == SDL_QUIT) done = true; } const double newTime = SDL_GetTicks() / 1000.0; const double frameTime = newTime - currentTime; currentTime = newTime; accumulator += frameTime; while (accumulator >= dt) { UpdateParticles(dt, particles); accumulator -= dt; time += dt; } SDL_RenderClear(_renderer); SDL_Rect dest = { 0, 0, 5, 5 }; for (auto &p : particles) { dest.x = p.position.x; dest.y = p.position.y; SDL_RenderCopy(_renderer, _square, NULL, &dest); } SDL_RenderPresent(_renderer); } }
bool ParticleSystemClass::Frame(float frameTime, ID3D11DeviceContext* deviceContext) { bool result; // Release old particles. KillParticles(); // Emit new particles. EmitParticles(frameTime); // Update the position of the particles. UpdateParticles(frameTime); // Update the dynamic vertex buffer with the new position of each particle. result = UpdateBuffers(deviceContext); if(!result) { return false; } return true; }
void DrawParticles(R3Scene *scene) { // Get current time (in seconds) since start of execution double current_time = GetTime(); static double previous_time = 0; static double time_lost_taking_videos = 0; // for switching back and forth // between recording and not // recording smoothly // program just started up? if (previous_time == 0) previous_time = current_time; // time passed since starting double delta_time = current_time - previous_time; if (save_video) { // in video mode, the time that passes only depends on the frame rate ... delta_time = VIDEO_FRAME_DELAY; // ... but we need to keep track how much time we gained and lost so that we can arbitrarily switch back and forth ... time_lost_taking_videos += (current_time - previous_time) - VIDEO_FRAME_DELAY; } else { // real time simulation delta_time = current_time - previous_time; } // Update particles UpdateParticles(scene, current_time - time_lost_taking_videos, delta_time, integration_type); // Generate new particles GenerateParticles(scene, current_time - time_lost_taking_videos, delta_time); // Render particles if (show_particles) RenderParticles(scene, current_time - time_lost_taking_videos, delta_time); // Remember previous time previous_time = current_time; }
/*!**************************************************************************** @Function RenderScene @Return bool true if no error occured @Description Main rendering loop function of the program. The shell will call this function every frame. eglSwapBuffers() will be performed by PVRShell automatically. PVRShell will also manage important OS events. Will also manage relevent OS events. The user has access to these events through an abstraction layer provided by PVRShell. ******************************************************************************/ bool OGLES2ParticleSystem::RenderScene() { HandleInput(); UpdateParticles(); UpdateFramerateCounter(); float time_delta = PVRShellGetTime() / 10000.0f; PVRTVec3 vFrom = PVRTVec3((float) sin(time_delta) * 50.0f, 30.0f, (float) cos(time_delta) * 50.0f); m_mView = PVRTMat4::LookAtRH(vFrom, PVRTVec3(0.0f, 5.0f, 0.0f), PVRTVec3(0.0f, 1.0f, 0.0f)); m_mViewProjection = m_mProjection * m_mView; // Clear colour and depth buffers glClearColor(0.0f, 0.0f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Enables depth testing glEnable(GL_DEPTH_TEST); // Render floor RenderFloor(); for (unsigned int i=0; i < g_cuiNumSpheres; i++) RenderSphere(g_caSpheres[i].aPosition, g_caSpheres[i].fRadius); // Render particles RenderParticles(); // Display info text. char lower_buffer[64]; unsigned int numParticles = m_pParticleSystem->GetNumberOfParticles(); sprintf(lower_buffer, "No. of Particles: %d", numParticles); m_Print3D.DisplayDefaultTitle("Particle System", NULL, ePVRTPrint3DSDKLogo); m_Print3D.Print3D(2.0f, 90.0f, 1.0f, 0xFFFFFFFF, "No. of Particles: %d", numParticles); m_Print3D.Flush(); return true; }
//Frame Particle System bool CParticleSystem::Frame(ID3D11DeviceContext* deviceContext, float frameTime, CCamera* mainCamera) { bool result; //Release previous Particles KillParticles(); //Emit new Particles EmitParticles(frameTime); //Update positions of Particles UpdateParticles(frameTime); //Update Buffers (Dynamic) result = UpdateBuffers(deviceContext, mainCamera); if (!result) { return false; } return true; }
void Update(float delta) { cameraangle.prev[0] = cameraangle.curr[0]; cameraangle.prev[1] = cameraangle.curr[1]; if( mousedown == 1 ) { cameraangle.curr[0] -= mousedx * 0.004f; cameraangle.curr[1] -= mousedy * 0.004f; } // clamp to [-pi, pi] if( cameraangle.curr[1] >= 1.5f ) cameraangle.curr[1] = 1.5f; if( cameraangle.curr[1] <= -1.5f ) cameraangle.curr[1] = -1.5f; if( timeout > DELAY ) UpdateParticles(delta, false); else ++timeout; }
/*========================================================================= // Name: Game_Loop() // Desc: The main loop for the game //=======================================================================*/ static void Game_Loop() { if (!bPause) { if (!bGameOver) { cluster.dropCount--; /* Decrease time until the next fall */ if (cluster.dropCount == 0) { if (MoveCluster(0)) /* If cluster "collides"... */ NewCluster(); /* then create a new one ;) */ } /* Increase Level */ if (((level == 0) && (lines >= 10)) || ((level == 1) && (lines >= 20)) || ((level == 2) && (lines >= 40)) || ((level == 3) && (lines >= 80)) || ((level == 4) && (lines >= 100)) || ((level == 5) && (lines >= 120)) || ((level == 6) && (lines >= 140)) || ((level == 7) && (lines >= 160)) || ((level == 8) && (lines >= 180)) || ((level == 9) && (lines >= 200))) { level++; PutSound(&sndNextlevel); } } else { GameOverAnimation(); } if (bCrazy) /* If crazy mode is actived... */ BoxDrawMove(); /* ... change box settings! */ MoveStars(); /* Move stars */ UpdateParticles(); /* Move particles */ } DrawScene(); }
void WindFlow::Update() { //ダッシュ終了までは座標配列を更新 int size = player.ReturnDashPosStorage().size(); if (size > 0 && !isSetting) { dashPositions.clear(); for (int i = 0; i < size; i++) { if (i % 5 == 0) { //地を這うように配置 Vector3 pos = Vector3(player.ReturnDashPosStorage().at(i).x, HeightMin, player.ReturnDashPosStorage().at(i).z); dashPositions.push_back(pos); } } } //ダッシュ終了後は座標配列を更新しない else if (size == 0) { isSetting = true; } //パーティクル更新 UpdateParticles(); //タックルされたら移動 move += vec * speed * Time::DeltaTime; //システム寿命が来たらアクターも寿命に if (ps_parameter.isDead) { Sound::GetInstance().StopSE(SE_ID::MIDDLE_WIND_SE); parameter.isDead = true; } }
//Main loop of the system void GPUParticleSystem::Update(ID3D11Device* device, ID3D11DeviceContext* deviceContext, float dt) { EmitParticles(deviceContext, dt); UpdateParticles(deviceContext, dt); elapsedTime += dt; //Timer that allows the system to select numbers from the random texture const float timer = 1.0f; if (elapsedTime > timer) { elapsedTime -= timer; } //Handles the rotation of the camera DirectX::XMMATRIX matRot; DirectX::XMMATRIX matTrans; matRot = DirectX::XMMatrixRotationY(rot); matTrans = DirectX::XMMatrixTranslation(0.0f, 0.0f, 0.0f); DirectX::XMMATRIX matFinal = matTrans * matRot; DirectX::XMStoreFloat4x4(&m_World, matFinal); }
void UpdateTick(GameState *gs) { if(!gs) return; /* Keys currently pressed down */ Uint8 *keys = SDL_GetKeyState(NULL); if(SDL_GetTicks() - gs->board[0].last_guided_move > gs->board[0].move_delay) { if(keys[SDLK_s]){ MoveActiveCouple(gs, 0, DOWN); gs->board[0].last_forced_move = SDL_GetTicks(); } if(keys[SDLK_a]) MoveActiveCouple(gs, 0, LEFT); if(keys[SDLK_d]) MoveActiveCouple(gs, 0, RIGHT); gs->board[0].last_guided_move = SDL_GetTicks(); } if(SDL_GetTicks() - gs->board[1].last_guided_move > gs->board[1].move_delay && gs->human_players > 1) { if(keys[SDLK_h]){ MoveActiveCouple(gs, 1, DOWN); gs->board[1].last_forced_move = SDL_GetTicks(); } if(keys[SDLK_g]) MoveActiveCouple(gs, 1, LEFT); if(keys[SDLK_j]) MoveActiveCouple(gs, 1, RIGHT); gs->board[1].last_guided_move = SDL_GetTicks(); } if(SDL_GetTicks() - gs->board[2].last_guided_move > gs->board[2].move_delay && gs->human_players > 2) { if(keys[SDLK_SEMICOLON]){ MoveActiveCouple(gs, 2, DOWN); gs->board[2].last_forced_move = SDL_GetTicks(); } if(keys[SDLK_l]) MoveActiveCouple(gs, 2, LEFT); if(keys[SDLK_QUOTE]) MoveActiveCouple(gs, 2, RIGHT); gs->board[2].last_guided_move = SDL_GetTicks(); } if(SDL_GetTicks() - gs->board[3].last_guided_move > gs->board[3].move_delay && gs->human_players > 3) { if(keys[SDLK_DOWN]){ MoveActiveCouple(gs, 3, DOWN); gs->board[3].last_forced_move = SDL_GetTicks(); } if(keys[SDLK_LEFT]) MoveActiveCouple(gs, 3, LEFT); if(keys[SDLK_RIGHT]) MoveActiveCouple(gs, 3, RIGHT); gs->board[3].last_guided_move = SDL_GetTicks(); } int losers = 0; for(unsigned p = 0; p < gs->player_count; p++) { if(gs->board[p].lost == false && gs->board[p].won == false){ if(gs->active_couple[p] == NULL){ /* Spawn new random piece for our player. */ gs->active_couple[p] = GenerateNewCouple(gs); Sint16 x1, x2, y1, y2; x1 = gs->active_couple[p]->p[0]->x; x2 = gs->active_couple[p]->p[1]->x; y1 = gs->active_couple[p]->p[0]->y; y2 = gs->active_couple[p]->p[1]->y; if(gs->board[p].b[x1][y1] != NULL){ gs->board[p].lost = true; delete gs->active_couple[p]->p[0]; delete gs->active_couple[p]->p[1]; delete gs->active_couple[p]; } else{ gs->board[p].b[x1][y1] = gs->active_couple[p]->p[0]; gs->board[p].b[x2][y2] = gs->active_couple[p]->p[1]; } } else { if(SDL_GetTicks() - gs->board[p].last_forced_move > 500 && gs->board[p].lost == false && gs->board[p].won == false){ CPUTick(gs,p); MoveActiveCouple(gs, p, DOWN); gs->board[p].last_forced_move = SDL_GetTicks(); } FallPieces(gs, p); } } else if(gs->board[p].lost){ OjammAttack(gs,p); losers++; } } if(losers == gs->player_count - 1){ for(unsigned p = 0; p < gs->player_count; p++){ if(gs->board[p].lost != true){ gs->playing = false; } } } UpdateParticles(gs->particles); }
void CPhysicsShellHolder::UpdateCL () { inherited::UpdateCL (); //обновить присоединенные партиклы UpdateParticles (); }
bool InitScene() { SetWindowText(hwnd, TITLE); Quadron::qGLExtensions::QueryFeatures(hdc); hascompute = (Quadron::qGLExtensions::ARB_compute_shader && Quadron::qGLExtensions::ARB_shader_storage_buffer_object); #ifdef _DEBUG if( Quadron::qGLExtensions::ARB_debug_output ) { glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, 0, GL_TRUE); glDebugMessageCallback(ReportGLError, 0); } #endif glClearColor(0.0f, 0.125f, 0.3f, 1.0f); glClearDepth(1.0); glEnable(GL_CULL_FACE); glCullFace(GL_BACK); glDepthFunc(GL_LEQUAL); glEnable(GL_DEPTH_TEST); // load objects if( !GLCreateMeshFromQM("../media/meshes/teapot.qm", &teapot) ) { MYERROR("Could not load teapot"); return false; } if( !GLCreateMeshFromQM("../media/meshes/cube.qm", &box) ) { MYERROR("Could not load box"); return false; } // calculate scene bounding box OpenGLAABox tmpbox; float world[16]; float tmp[16]; GLMatrixIdentity(world); for( int i = 0; i < numobjects; ++i ) { const SceneObject& obj = objects[i]; // scaling * rotation * translation GLMatrixScaling(tmp, obj.scale[0], obj.scale[1], obj.scale[2]); GLMatrixRotationAxis(world, obj.angle, 0, 1, 0); GLMatrixMultiply(world, tmp, world); GLMatrixTranslation(tmp, obj.position[0], obj.position[1], obj.position[2]); GLMatrixMultiply(world, world, tmp); if( obj.type == 0 ) tmpbox = box->GetBoundingBox(); else if( obj.type == 1 ) tmpbox = teapot->GetBoundingBox(); tmpbox.TransformAxisAligned(world); scenebox.Add(tmpbox.Min); scenebox.Add(tmpbox.Max); } // create render targets framebuffer = new OpenGLFramebuffer(screenwidth, screenheight); framebuffer->AttachTexture(GL_COLOR_ATTACHMENT0, GLFMT_A16B16G16R16F); framebuffer->AttachTexture(GL_DEPTH_ATTACHMENT, GLFMT_D32F); if( !framebuffer->Validate() ) return false; shadowmap = new OpenGLFramebuffer(SHADOWMAP_SIZE, SHADOWMAP_SIZE); shadowmap->AttachTexture(GL_COLOR_ATTACHMENT0, GLFMT_G32R32F, GL_LINEAR); shadowmap->AttachRenderbuffer(GL_DEPTH_ATTACHMENT, GLFMT_D24S8); if( !shadowmap->Validate() ) return false; blurredshadow = new OpenGLFramebuffer(SHADOWMAP_SIZE, SHADOWMAP_SIZE); blurredshadow->AttachTexture(GL_COLOR_ATTACHMENT0, GLFMT_G32R32F, GL_LINEAR); if( !blurredshadow->Validate() ) return false; screenquad = new OpenGLScreenQuad(); // textures if( !GLCreateTextureFromFile("../media/textures/wood2.jpg", true, &texture1) ) { MYERROR("Could not load texture"); return false; } if( !GLCreateTextureFromFile("../media/textures/marble2.png", true, &texture2) ) { MYERROR("Could not load texture"); return false; } if( !GLCreateTextureFromFile("../media/textures/static_sky.jpg", true, &texture3, GLTEX_FLIPX) ) { MYERROR("Could not load texture"); return false; } // create buffers workgroupsx = (screenwidth + (screenwidth % 16)) / 16; workgroupsy = (screenheight + (screenheight % 16)) / 16; size_t numtiles = workgroupsx * workgroupsy; size_t headsize = 16; // start, count, pad, pad size_t nodesize = 16; // light index, next, pad, pad if( hascompute ) { glGenBuffers(1, &headbuffer); glGenBuffers(1, &nodebuffer); glGenBuffers(1, &lightbuffer); glGenBuffers(1, &counterbuffer); glBindBuffer(GL_SHADER_STORAGE_BUFFER, headbuffer); glBufferData(GL_SHADER_STORAGE_BUFFER, numtiles * headsize, 0, GL_STATIC_DRAW); glBindBuffer(GL_SHADER_STORAGE_BUFFER, nodebuffer); glBufferData(GL_SHADER_STORAGE_BUFFER, numtiles * nodesize * 1024, 0, GL_STATIC_DRAW); // 4 MB glBindBuffer(GL_SHADER_STORAGE_BUFFER, lightbuffer); glBufferData(GL_SHADER_STORAGE_BUFFER, NUM_LIGHTS * sizeof(LightParticle), 0, GL_DYNAMIC_DRAW); UpdateParticles(0, true); glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0); glBindBuffer(GL_ATOMIC_COUNTER_BUFFER, counterbuffer); glBufferData(GL_ATOMIC_COUNTER_BUFFER, sizeof(GLuint), 0, GL_DYNAMIC_DRAW); glBindBuffer(GL_ATOMIC_COUNTER_BUFFER, 0); } // load effects if( !GLCreateEffectFromFile("../media/shadersGL/basic2D.vert", 0, "../media/shadersGL/basic2D.frag", &basic2D) ) { MYERROR("Could not load basic 2D shader"); return false; } if( !GLCreateEffectFromFile("../media/shadersGL/basic2D.vert", 0, "../media/shadersGL/boxblur3x3.frag", &boxblur3x3) ) { MYERROR("Could not load blur shader"); return false; } if( !GLCreateEffectFromFile("../media/shadersGL/basic2D.vert", 0, "../media/shadersGL/gammacorrect.frag", &gammacorrect) ) { MYERROR("Could not load gamma correction shader"); return false; } if( !GLCreateEffectFromFile("../media/shadersGL/shadowmap_variance.vert", 0, "../media/shadersGL/shadowmap_variance.frag", &varianceshadow) ) { MYERROR("Could not load shadowmap shader"); return false; } if( !GLCreateEffectFromFile("../media/shadersGL/blinnphong_variance.vert", 0, "../media/shadersGL/blinnphong_variance.frag", &shadowedlight) ) { MYERROR("Could not load shadowed light shader"); return false; } if( !GLCreateEffectFromFile("../media/shadersGL/ambient.vert", 0, "../media/shadersGL/ambient.frag", &ambient) ) { MYERROR("Could not load ambient shader"); return false; } if( hascompute ) { // light accumulation shader if( !GLCreateEffectFromFile("../media/shadersGL/lightaccum.vert", 0, "../media/shadersGL/lightaccum.frag", &lightaccum) ) { MYERROR("Could not load light accumulation shader"); return false; } // light culling shader if( !GLCreateComputeProgramFromFile("../media/shadersGL/lightcull.comp", &lightcull) ) { MYERROR("Could not load light culling shader"); return false; } lightcull->SetInt("depthSampler", 0); lightcull->SetInt("numLights", NUM_LIGHTS); lightaccum->SetInt("sampler0", 0); } float white[] = { 1, 1, 1, 1 }; shadowedlight->SetVector("matSpecular", white); shadowedlight->SetInt("sampler0", 0); shadowedlight->SetInt("sampler1", 1); boxblur3x3->SetInt("sampler0", 0); basic2D->SetInt("sampler0", 0); gammacorrect->SetInt("sampler0", 0); float angles[2] = { 0.25f, -0.7f }; cameraangle = angles; return true; }
static void PlayGame() { Uint8 *keystate; int quit = 0; int turn; int prev_ticks = 0, cur_ticks = 0; /* for keeping track of timing */ int awaiting_respawn = 0; /* framerate counter variables */ int start_time, end_time; int frames_drawn = 0; /* respawn timer */ int respawn_timer = -1; prev_ticks = SDL_GetTicks(); start_time = time(NULL); /* Reset the score counters. */ player.score = 0; opponent.score = 0; /* Start sound playback. */ StartAudio(); StartMusic(); /* Start the music update thread. */ music_update_thread = SDL_CreateThread(UpdateMusicThread, NULL); if (music_update_thread == NULL) { printf("Unable to start music update thread.\n"); } /* Start the game! */ while ((quit == 0) && network_ok) { /* Determine how many milliseconds have passed since the last frame, and update our motion scaling. */ prev_ticks = cur_ticks; cur_ticks = SDL_GetTicks(); time_scale = (double)(cur_ticks-prev_ticks)/30.0; /* Update SDL's internal input state information. */ SDL_PumpEvents(); /* Grab a snapshot of the keyboard. */ keystate = SDL_GetKeyState(NULL); /* Lock the mutex so we can access the player's data. */ SDL_LockMutex(player_mutex); /* If this is a network game, take note of variables set by the network thread. These are handled differently for a scripted opponent. */ if (opponent_type == OPP_NETWORK) { /* Has the opponent respawned? */ if (network_opponent_respawn) { printf("Remote player has respawned.\n"); opponent.shields = 100; network_opponent_respawn = 0; awaiting_respawn = 0; } /* Has the local player been hit? */ if (local_player_hit) { local_player_hit--; player.shields -= PHASER_DAMAGE; ShowPhaserHit(&player); /* No need to check for death, the other computer will tell us. */ } } /* Update phasers. */ player.firing -= time_scale; if (player.firing < 0) player.firing = 0; opponent.firing -= time_scale; if (opponent.firing < 0) opponent.firing = 0; ChargePhasers(&player); /* If the local player is destroyed, the respawn timer will start counting. During this time the controls are disabled and explosion sequence occurs. */ if (respawn_timer >= 0) { respawn_timer++; if (respawn_timer >= ((double)RESPAWN_TIME / time_scale)) { respawn_timer = -1; InitPlayer(&player); /* Set the local_player_respawn flag so the network thread will notify the opponent of the respawn. */ local_player_respawn = 1; SetStatusMessage("GOOD LUCK, WARRIOR!"); } } /* Respond to input and network events, but not if we're in a respawn. */ if (respawn_timer == -1) { if (keystate[SDLK_q] || keystate[SDLK_ESCAPE]) quit = 1; /* Left and right arrow keys control turning. */ turn = 0; if (keystate[SDLK_LEFT]) turn += 10; if (keystate[SDLK_RIGHT]) turn -= 10; /* Forward and back arrow keys activate thrusters. */ player.accel = 0; if (keystate[SDLK_UP]) player.accel = PLAYER_FORWARD_THRUST; if (keystate[SDLK_DOWN]) player.accel = PLAYER_REVERSE_THRUST; /* Spacebar fires phasers. */ if (keystate[SDLK_SPACE]) { if (CanPlayerFire(&player)) { FirePhasers(&player); /* If it's a hit, either notify the opponent or exact the damage. Create a satisfying particle burst. */ if (!awaiting_respawn && CheckPhaserHit(&player,&opponent)) { ShowPhaserHit(&opponent); DamageOpponent(); /* If that killed the opponent, set the "awaiting respawn" state, to prevent multiple kills. */ if (opponent.shields <= 0 && opponent_type == OPP_NETWORK) awaiting_respawn = 1; } } } /* Turn. */ player.angle += turn * time_scale; if (player.angle < 0) player.angle += 360; if (player.angle >= 360) player.angle -= 360; /* If this is a network game, the remote player will tell us if we've died. Otherwise we have to check for failed shields. */ if (((opponent_type == OPP_NETWORK) && local_player_dead) || (player.shields <= 0)) { printf("Local player has been destroyed.\n"); local_player_dead = 0; /* Kaboom! */ KillPlayer(); /* Respawn. */ respawn_timer = 0; } } /* If this is a player vs. computer game, give the computer a chance. */ if (opponent_type == OPP_COMPUTER) { if (RunGameScript() != 0) { fprintf(stderr, "Ending game due to script error.\n"); quit = 1; } /* Check for phaser hits against the player. */ if (opponent.firing) { if (CheckPhaserHit(&opponent,&player)) { ShowPhaserHit(&player); player.shields -= PHASER_DAMAGE; /* Did that destroy the player? */ if (respawn_timer < 0 && player.shields <= 0) { KillPlayer(); respawn_timer = 0; } } } ChargePhasers(&opponent); UpdatePlayer(&opponent); } /* Update the player's position. */ UpdatePlayer(&player); /* Update the status information. */ SetPlayerStatusInfo(player.score, player.shields, player.charge); SetOpponentStatusInfo(opponent.score, opponent.shields); /* Make the camera follow the player (but impose limits). */ camera_x = player.world_x - SCREEN_WIDTH/2; camera_y = player.world_y - SCREEN_HEIGHT/2; if (camera_x < 0) camera_x = 0; if (camera_x >= WORLD_WIDTH-SCREEN_WIDTH) camera_x = WORLD_WIDTH-SCREEN_WIDTH-1; if (camera_y < 0) camera_y = 0; if (camera_y >= WORLD_HEIGHT-SCREEN_HEIGHT) camera_y = WORLD_HEIGHT-SCREEN_HEIGHT-1; /* Update the particle system. */ UpdateParticles(); /* Keep OpenAL happy. */ UpdateAudio(&player, &opponent); /* Redraw everything. */ DrawBackground(screen, camera_x, camera_y); DrawParallax(screen, camera_x, camera_y); DrawParticles(screen, camera_x, camera_y); if (opponent.firing) DrawPhaserBeam(&opponent, screen, camera_x, camera_y); if (player.firing) DrawPhaserBeam(&player, screen, camera_x, camera_y); if (respawn_timer < 0) DrawPlayer(&player); if (!awaiting_respawn) DrawPlayer(&opponent); UpdateStatusDisplay(screen); /* Release the mutex so the networking system can get it. It doesn't stay unlocked for very long, but the networking system should still have plenty of time. */ SDL_UnlockMutex(player_mutex); /* Flip the page. */ SDL_Flip(screen); frames_drawn++; } end_time = time(NULL); if (start_time == end_time) end_time++; /* Display the average framerate. */ printf("Drew %i frames in %i seconds, for a framerate of %.2f fps.\n", frames_drawn, end_time-start_time, (float)frames_drawn/(float)(end_time-start_time)); /* Terminate the music update thread. */ if (music_update_thread != NULL) { SDL_KillThread(music_update_thread); music_update_thread = NULL; } /* Stop audio playback. */ StopAudio(); StopMusic(); }