ControlRequest(Task<ChordFilePlayTaskStackSize, void(*)(ChordFile*), ChordFile*>* pt): ChordIndex(0), PlayTask(pt) { SetState(StopState); }
void Item::SaveToDB (SQLTransaction& trans) { uint32 guid = GetGUIDLow(); switch (uState) { case ITEM_NEW: case ITEM_CHANGED: { uint8 index = 0; PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(uState == ITEM_NEW ? CHAR_ADD_ITEM_INSTANCE : CHAR_UPDATE_ITEM_INSTANCE); stmt->setUInt32(index, GetEntry()); stmt->setUInt32(++index, GUID_LOPART(GetOwnerGUID())); stmt->setUInt32(++index, GUID_LOPART(GetUInt64Value(ITEM_FIELD_CREATOR))); stmt->setUInt32(++index, GUID_LOPART(GetUInt64Value(ITEM_FIELD_GIFTCREATOR))); stmt->setUInt32(++index, GetCount()); stmt->setUInt32(++index, GetUInt32Value(ITEM_FIELD_DURATION)); std::ostringstream ssSpells; for (uint8 i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i) ssSpells << GetSpellCharges(i) << " "; stmt->setString(++index, ssSpells.str()); stmt->setUInt32(++index, GetUInt32Value(ITEM_FIELD_FLAGS)); std::ostringstream ssEnchants; for (uint8 i = 0; i < MAX_ENCHANTMENT_SLOT; ++i) { ssEnchants << GetEnchantmentId(EnchantmentSlot(i)) << " "; ssEnchants << GetEnchantmentDuration(EnchantmentSlot(i)) << " "; ssEnchants << GetEnchantmentCharges(EnchantmentSlot(i)) << " "; } stmt->setString(++index, ssEnchants.str()); stmt->setInt32(++index, GetItemRandomPropertyId()); stmt->setUInt32(++index, GetUInt32Value(ITEM_FIELD_DURABILITY)); stmt->setUInt32(++index, GetUInt32Value(ITEM_FIELD_CREATE_PLAYED_TIME)); stmt->setString(++index, m_text); stmt->setUInt32(++index, guid); trans->Append(stmt); if ((uState == ITEM_CHANGED) && HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAG_WRAPPED)) { stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPDATE_GIFT_OWNER); stmt->setUInt32(0, GUID_LOPART(GetOwnerGUID())); stmt->setUInt32(1, guid); trans->Append(stmt); } break; } case ITEM_REMOVED: { PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ITEM_INSTANCE); stmt->setUInt32(0, guid); trans->Append(stmt); if (HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAG_WRAPPED)) { stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GIFT); stmt->setUInt32(0, guid); trans->Append(stmt); } delete this; return; } case ITEM_UNCHANGED: break; } SetState(ITEM_UNCHANGED); }
void ComboBox::HandleMouseEnter( int /*x*/, int /*y*/ ) { if( GetState() == NORMAL ) { SetState( PRELIGHT ); } }
//---------------------------------------------------------------------------------- CMaterialPhong::CMaterialPhong() { SetState(CMaterialState::eUnloaded); }
bool Bot::FixedUpdate() { bool ret = true; switch (state) { case BotState::idle: LOG("IDLE STATE"); // Check if the Unit is a player Unit if (unit->team == App->AI->playerTeam) { if (unit->ArrivedToDestination()) CheckForEnemies(); } else { CheckForEnemies(); } break; case BotState::attack: LOG("ATTACK STATE"); if (App->AI->botList.find(target) != -1) { //If this Unit Evades when low life, Set the state to flee if (flees) { if (unit->GetHP() < unit->GetMaxHP() / 4) //flee when less than 10% health { SetState(flee); break; } } //Check if target is on the Attack Range if (EnemyOnRange(target->unit, unit, attackRange)) { //TODO: 3 - Attack target if (!unit->ArrivedToDestination()) unit->Stop(); //Attack Unit //Attack according to attackspeed if (attackTimer.ReadSec() >= attackSpeed) { attackTimer.Start(); target->OnAttack(damage, this); } } //If is not on the attack range, chase him else if (unit->team == App->AI->playerTeam || father != NULL || EnemyOnRange(target->unit, unit, sightRange)) { //TODO: 2 - Chase target // Compare target position with unit position if (targetPos != target->GetPos() || unit->isTargetReached()) { C_DynArray<iPoint> newPath; fPoint unitPos = unit->GetPosition(); fPoint targetPos = target->unit->GetPosition(); iPoint unitTile = App->map->WorldToMap(round(unitPos.x), round(unitPos.y)); iPoint enemyTile = App->map->WorldToMap(round(targetPos.x), round(targetPos.y)); App->pathFinding->GetNewPath(unitTile, enemyTile, newPath); unit->SetNewPath(newPath); } } else { SetState(idle); } } else { SetState(idle); } break; case BotState::flee: LOG("FLEE STATE"); if (unit->ArrivedToDestination()) { if (DistanceBetweenUnits(target->unit, unit) < sightRange * 1.5f) { // flees in random direction int x = (rand() % 60) + unit->GetPosition().x; int y = (rand() % 60) + unit->GetPosition().y; C_DynArray<iPoint> newPath; fPoint unitPos = unit->GetPosition(); iPoint unitTile = App->map->WorldToMap(round(unitPos.x), round(unitPos.y)); App->pathFinding->GetNewPath(unitTile, { x, y }, newPath); unit->SetNewPath(newPath); } else { SetState(idle); } } break; } return ret; }
//------------------------------------------------------------------------------------------------ std::vector<Bullet*> Person::Fire() { std::vector<Bullet*> bullets; if (!mIsActive) return bullets; if (mState == NORMAL) { mIsFiring = true; mHasFired = true; if (mGunIndex == KNIFE) { SetState(ATTACKING); gSfxManager->PlaySample(mGuns[mGunIndex]->mGun->mFireSound,mX,mY); //return true; } else if (mGunIndex == GRENADE) { if (mGuns[mGunIndex]->mClipAmmo != 0) { SetState(ATTACKING); gSfxManager->PlaySample(mGuns[mGunIndex]->mGun->mFireSound,mX,mY); } } else { if (mGuns[mGunIndex]->mClipAmmo != 0) { Bullet* bullet; float h = 24*sinf(mFacingAngle); float w = 24*cosf(mFacingAngle); float theta = mFacingAngle; float speed = 0.3f*mGuns[mGunIndex]->mGun->mBulletSpeed; if (mGuns[mGunIndex]->mGun->mId == 7) { theta -= mGuns[mGunIndex]->mGun->mSpread/2;//m0.36f; float step = mGuns[mGunIndex]->mGun->mSpread/5; for (int i=0; i<6; i++) { theta += (rand()%11)/100.0f-0.05f; bullet = new Bullet(mX+w,mY+h,mX,mY,theta,speed,abs(mGuns[mGunIndex]->mGun->mDamage+rand()%17-8),this); bullets.push_back(bullet); mBullets->push_back(bullet); theta += step;//0.144f; } } else if (mGuns[mGunIndex]->mGun->mId == 8) { theta -= mGuns[mGunIndex]->mGun->mSpread/2;//0.36f; float step = mGuns[mGunIndex]->mGun->mSpread/3; for (int i=0; i<4; i++) { theta += (rand()%10)/100.0f-0.05f; bullet = new Bullet(mX+w,mY+h,mX,mY,theta,speed,abs(mGuns[mGunIndex]->mGun->mDamage+rand()%17-8),this); bullets.push_back(bullet); mBullets->push_back(bullet); theta += step; //0.24f; } } else { if (mRecoilAngle*1000.0f >= 0.1f) { theta += (rand()%(int)ceilf(mRecoilAngle*1000.0f))/1000.0f-(mRecoilAngle*0.5f); //theta = mFacingAngle + (rand()%100)/400.0f-0.125f; } bullet = new Bullet(mX+w,mY+h,mX,mY,theta,speed,abs(mGuns[mGunIndex]->mGun->mDamage+rand()%17-8),this); bullets.push_back(bullet); mBullets->push_back(bullet); } gParticleEngine->GenerateParticles(BULLETSHELL,mX+10*cosf(mFacingAngle),mY+10*sinf(mFacingAngle),1); SetState(ATTACKING); mGuns[mGunIndex]->mClipAmmo--; //JSample *test = mEngine->LoadSample("sfx/m249.wav"); gSfxManager->PlaySample(mGuns[mGunIndex]->mGun->mFireSound,mX,mY); mMuzzleFlashTime = 50.0f; mMuzzleFlashAngle = mFacingAngle; mMuzzleFlashIndex = mGuns[mGunIndex]->mGun->mType*3 + rand()%3; mRadarTime = 2000.0f; mRadarX = mX; mRadarY = mY; //return true; } else { SetState(DRYFIRING); gSfxManager->PlaySample(mGuns[mGunIndex]->mGun->mDryFireSound,mX,mY); //return; } } } return bullets; //return false; }
void IInputHandler::Enable(bool val) { SetState(val ? InputState::None : InputState::Disabled); }
void Environment::Update( Point3D* viewPosition ) { if( !automaticStateChange || changeTimer.is_paused() ) return; if( viewPosition != NULL ) { this->viewPosition.x = viewPosition->x; this->viewPosition.y = viewPosition->y; this->viewPosition.z = viewPosition->z; } if( currentStateTimer.get_ticks() > changeRate ) { SetState( nextState ); return; } if( noChange && hasInit ) { hasInit = true; return; } currentSkyColor.r += skyColorChangeRate.r * changeTimer.get_ticks(); currentSkyColor.g += skyColorChangeRate.g * changeTimer.get_ticks(); currentSkyColor.b += skyColorChangeRate.b * changeTimer.get_ticks(); currentFogColor.r += fogColorChangeRate.r * changeTimer.get_ticks(); currentFogColor.g += fogColorChangeRate.g * changeTimer.get_ticks(); currentFogColor.b += fogColorChangeRate.b * changeTimer.get_ticks(); currentFogExp += fogExpRate * changeTimer.get_ticks(); if( light != NULL ) { currentLightColor.r += lightColorChangeRate.r * changeTimer.get_ticks(); currentLightColor.g += lightColorChangeRate.g * changeTimer.get_ticks(); currentLightColor.b += lightColorChangeRate.b * changeTimer.get_ticks(); currentlightPosition.x += lightPositionChangeRate.x * changeTimer.get_ticks(); currentlightPosition.y += lightPositionChangeRate.y * changeTimer.get_ticks(); currentlightPosition.z += lightPositionChangeRate.z * changeTimer.get_ticks(); } changeTimer.start(); //Fog GLfloat fogColor[4] = { currentFogColor.r, currentFogColor.g, currentFogColor.b, 0.0}; glFogfv (GL_FOG_COLOR, fogColor); glFogf (GL_FOG_DENSITY, static_cast<float>( currentFogExp ) ); // Set Sky Color glClearColor( currentSkyColor.r, currentSkyColor.g, currentSkyColor.b, 0 ); if( light != NULL ) { if( currentlightPosition.y < 0 ) { glDisable( light ); } else { glEnable( light ); } float lightpos[4] = { currentlightPosition.x + this->viewPosition.x, currentlightPosition.y + this->viewPosition.y, currentlightPosition.z + this->viewPosition.z, 1.f }; glLightfv( light, GL_POSITION, lightpos ); float diff[4] = { currentLightColor.r, currentLightColor.g, currentLightColor.b, 1.f }; glLightfv( light, GL_DIFFUSE, diff ); } }
void Character::Update(){ if(mMoveTime){ if(mState == STATE_STOP) SetState(STATE_RUN); Vector3 nextPos = mPosition; Vector3 delta = mTargetPosition - mPosition; float dist = delta.Length2D(); clock_t etime = clock() - mMoveTime; float ntime = (dist / mMoveSpeed) * 1000; if(ntime <= etime || dist < 0.001f){ mMoveTime = 0; nextPos.x = mTargetPosition.x; nextPos.y = mTargetPosition.y; SetState(STATE_STOP); }else{ float dt = etime / ntime; nextPos.x = delta.x*dt + mPosition.x; nextPos.y = delta.y*dt + mPosition.y; mMoveTime = clock(); } bool hasStopped = false; if(mCharacterType == CHR_PLAYER){ Ray forwardRay; Vector3 forwardPos; forwardRay.mPoint = mPosition; forwardRay.mPoint.z += MAX_CHAR_STEP_HEIGHT; forwardRay.mDirection = delta; forwardRay.mDirection.Normalise(); if(gScene->CastRay(forwardRay, forwardPos, 5.0f) && (forwardPos.z > (nextPos.z + MAX_CHAR_STEP_HEIGHT)) && (forwardPos.Distance2Dsq(nextPos) < mPosition.Distance2Dsq(nextPos))) { float dZ = forwardPos.z - mPosition.z; float gradient = (dZ * dZ) / mPosition.Distance2Dsq(forwardPos); if(gradient > 0.55f){ hasStopped = true; mMoveTime = 0; SetState(STATE_STOP); } } } if(!hasStopped){ Vector3 downPos; Ray downRay; downRay.mPoint = nextPos; downRay.mPoint.z += MAX_CHAR_STEP_HEIGHT; downRay.mDirection = Vector3(0.0f, 0.0f, -1.0f); float zWithGrav = nextPos.z - (GRAVITY_PER_MS * etime); if(gScene->CastRayDown(downRay, downPos) && downPos.z > zWithGrav){ if(mCharacterType == CHR_PLAYER){ float dZ = downPos.z - nextPos.z; float gradient = (dZ * dZ) / mPosition.Distance2Dsq(nextPos); if(gradient > 0.55f && dZ > 0.5f){ hasStopped = true; mMoveTime = 0; SetState(STATE_STOP); } } if(!hasStopped) nextPos.z = downPos.z; }else{ nextPos.z = zWithGrav; } mPosition = nextPos; } UpdateTransform(); } }
void Item::SaveToDB() { uint32 guid = GetGUIDLow(); switch (uState) { case ITEM_NEW: { std::string text = m_text; CharacterDatabase.escape_string(text); CharacterDatabase.PExecute( "DELETE FROM item_instance WHERE guid = '%u'", guid ); std::ostringstream ss; ss << "INSERT INTO item_instance (guid,owner_guid,data,text) VALUES (" << guid << "," << GetOwnerGuid().GetCounter() << ",'"; for(uint16 i = 0; i < m_valuesCount; ++i ) ss << GetUInt32Value(i) << " "; ss << "', '" << text << "')"; CharacterDatabase.Execute( ss.str().c_str() ); } break; case ITEM_CHANGED: { std::string text = m_text; CharacterDatabase.escape_string(text); std::ostringstream ss; ss << "UPDATE item_instance SET data = '"; for(uint16 i = 0; i < m_valuesCount; ++i ) ss << GetUInt32Value(i) << " "; ss << "', owner_guid = '" << GetOwnerGuid().GetCounter(); ss << "', text = '" << text << "' WHERE guid = '" << guid << "'"; CharacterDatabase.Execute( ss.str().c_str() ); if (HasFlag(ITEM_FIELD_FLAGS, ITEM_DYNFLAG_WRAPPED)) CharacterDatabase.PExecute("UPDATE character_gifts SET guid = '%u' WHERE item_guid = '%u'", GetOwnerGuid().GetCounter(), GetGUIDLow()); } break; case ITEM_REMOVED: { CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", guid); if (HasFlag(ITEM_FIELD_FLAGS, ITEM_DYNFLAG_WRAPPED)) CharacterDatabase.PExecute("DELETE FROM character_gifts WHERE item_guid = '%u'", GetGUIDLow()); if (HasSavedLoot()) CharacterDatabase.PExecute("DELETE FROM item_loot WHERE guid = '%u'", GetGUIDLow()); delete this; return; } case ITEM_UNCHANGED: return; } if (m_lootState == ITEM_LOOT_CHANGED || m_lootState == ITEM_LOOT_REMOVED) CharacterDatabase.PExecute("DELETE FROM item_loot WHERE guid = '%u'", GetGUIDLow()); if (m_lootState == ITEM_LOOT_NEW || m_lootState == ITEM_LOOT_CHANGED) { if(Player* owner = GetOwner()) { // save money as 0 itemid data if (loot.gold) CharacterDatabase.PExecute("INSERT INTO item_loot (guid,owner_guid,itemid,amount,suffix,property) " "VALUES (%u, %u, 0, %u, 0, 0)", GetGUIDLow(), owner->GetGUIDLow(), loot.gold); // save items and quest items (at load its all will added as normal, but this not important for item loot case) for (size_t i = 0; i < loot.GetMaxSlotInLootFor(owner); ++i) { QuestItem *qitem = NULL; LootItem *item = loot.LootItemInSlot(i,owner,&qitem); if(!item) continue; // questitems use the blocked field for other purposes if (!qitem && item->is_blocked) continue; CharacterDatabase.PExecute("INSERT INTO item_loot (guid,owner_guid,itemid,amount,suffix,property) " "VALUES (%u, %u, %u, %u, %u, %i)", GetGUIDLow(), owner->GetGUIDLow(), item->itemid, item->count, item->randomSuffix, item->randomPropertyId); } } } if (m_lootState != ITEM_LOOT_NONE && m_lootState != ITEM_LOOT_TEMPORARY) SetLootState(ITEM_LOOT_UNCHANGED); SetState(ITEM_UNCHANGED); }
void SpeechRecognition::WaitForAudioData(SpeechEvent* aEvent) { SetState(STATE_STARTING); }
inline void ScheduledRoutine::PendingSuspend() { SetState(State::PENDING_SUSPEND); }
//========================================================= // MaintainSchedule - does all the per-think schedule maintenance. // ensures that the monster leaves this function with a valid // schedule! //========================================================= void CBaseMonster :: MaintainSchedule ( void ) { Schedule_t *pNewSchedule; int i; // UNDONE: Tune/fix this 10... This is just here so infinite loops are impossible for ( i = 0; i < 10; i++ ) { if ( m_pSchedule != NULL && TaskIsComplete() ) { NextScheduledTask(); } // validate existing schedule if ( !FScheduleValid() || m_MonsterState != m_IdealMonsterState ) { // if we come into this block of code, the schedule is going to have to be changed. // if the previous schedule was interrupted by a condition, GetIdealState will be // called. Else, a schedule finished normally. // Notify the monster that his schedule is changing ScheduleChange(); // Call GetIdealState if we're not dead and one or more of the following... // - in COMBAT state with no enemy (it died?) // - conditions bits (excluding SCHEDULE_DONE) indicate interruption, // - schedule is done but schedule indicates it wants GetIdealState called // after successful completion (by setting bits_COND_SCHEDULE_DONE in iInterruptMask) // DEAD & SCRIPT are not suggestions, they are commands! if ( m_IdealMonsterState != MONSTERSTATE_DEAD && (m_IdealMonsterState != MONSTERSTATE_SCRIPT || m_IdealMonsterState == m_MonsterState) ) { if ( (m_afConditions && !HasConditions(bits_COND_SCHEDULE_DONE)) || (m_pSchedule && (m_pSchedule->iInterruptMask & bits_COND_SCHEDULE_DONE)) || ((m_MonsterState == MONSTERSTATE_COMBAT) && (m_hEnemy == NULL)) ) { GetIdealState(); } } if ( HasConditions( bits_COND_TASK_FAILED ) && m_MonsterState == m_IdealMonsterState ) { if ( m_failSchedule != SCHED_NONE ) pNewSchedule = GetScheduleOfType( m_failSchedule ); else pNewSchedule = GetScheduleOfType( SCHED_FAIL ); // schedule was invalid because the current task failed to start or complete ALERT ( at_aiconsole, "Schedule Failed at %d!\n", m_iScheduleIndex ); ChangeSchedule( pNewSchedule ); } else { SetState( m_IdealMonsterState ); if ( m_MonsterState == MONSTERSTATE_SCRIPT || m_MonsterState == MONSTERSTATE_DEAD ) pNewSchedule = CBaseMonster::GetSchedule(); else pNewSchedule = GetSchedule(); ChangeSchedule( pNewSchedule ); } } if ( m_iTaskStatus == TASKSTATUS_NEW ) { Task_t *pTask = GetTask(); ASSERT( pTask != NULL ); TaskBegin(); StartTask( pTask ); } // UNDONE: Twice?!!! if ( m_Activity != m_IdealActivity ) { SetActivity ( m_IdealActivity ); } if ( !TaskIsComplete() && m_iTaskStatus != TASKSTATUS_NEW ) break; } if ( TaskIsRunning() ) { Task_t *pTask = GetTask(); ASSERT( pTask != NULL ); RunTask( pTask ); } // UNDONE: We have to do this so that we have an animation set to blend to if RunTask changes the animation // RunTask() will always change animations at the end of a script! // Don't do this twice if ( m_Activity != m_IdealActivity ) { SetActivity ( m_IdealActivity ); } }
//========================================================= // GetSchedule - Decides which type of schedule best suits // the monster's current state and conditions. Then calls // monster's member function to get a pointer to a schedule // of the proper type. //========================================================= Schedule_t *CBaseMonster :: GetSchedule ( void ) { switch ( m_MonsterState ) { case MONSTERSTATE_PRONE: { return GetScheduleOfType( SCHED_BARNACLE_VICTIM_GRAB ); break; } case MONSTERSTATE_NONE: { ALERT ( at_aiconsole, "MONSTERSTATE IS NONE!\n" ); break; } case MONSTERSTATE_IDLE: { if ( HasConditions ( bits_COND_HEAR_SOUND ) ) { return GetScheduleOfType( SCHED_ALERT_FACE ); } else if ( FRouteClear() ) { // no valid route! return GetScheduleOfType( SCHED_IDLE_STAND ); } else { // valid route. Get moving return GetScheduleOfType( SCHED_IDLE_WALK ); } break; } case MONSTERSTATE_ALERT: { if ( HasConditions( bits_COND_ENEMY_DEAD ) && LookupActivity( ACT_VICTORY_DANCE ) != ACTIVITY_NOT_AVAILABLE ) { return GetScheduleOfType ( SCHED_VICTORY_DANCE ); } if ( HasConditions(bits_COND_LIGHT_DAMAGE | bits_COND_HEAVY_DAMAGE) ) { if ( fabs( FlYawDiff() ) < (1.0 - m_flFieldOfView) * 60 ) // roughly in the correct direction { return GetScheduleOfType( SCHED_TAKE_COVER_FROM_ORIGIN ); } else { return GetScheduleOfType( SCHED_ALERT_SMALL_FLINCH ); } } else if ( HasConditions ( bits_COND_HEAR_SOUND ) ) { return GetScheduleOfType( SCHED_ALERT_FACE ); } else { return GetScheduleOfType( SCHED_ALERT_STAND ); } break; } case MONSTERSTATE_COMBAT: { if ( HasConditions( bits_COND_ENEMY_DEAD ) ) { // clear the current (dead) enemy and try to find another. m_hEnemy = NULL; if ( GetEnemy() ) { ClearConditions( bits_COND_ENEMY_DEAD ); return GetSchedule(); } else { SetState( MONSTERSTATE_ALERT ); return GetSchedule(); } } if ( HasConditions(bits_COND_NEW_ENEMY) ) { return GetScheduleOfType ( SCHED_WAKE_ANGRY ); } else if (HasConditions(bits_COND_LIGHT_DAMAGE) && !HasMemory( bits_MEMORY_FLINCHED) ) { return GetScheduleOfType( SCHED_SMALL_FLINCH ); } else if ( !HasConditions(bits_COND_SEE_ENEMY) ) { // we can't see the enemy if ( !HasConditions(bits_COND_ENEMY_OCCLUDED) ) { // enemy is unseen, but not occluded! // turn to face enemy return GetScheduleOfType( SCHED_COMBAT_FACE ); } else { // chase! return GetScheduleOfType( SCHED_CHASE_ENEMY ); } } else { // we can see the enemy if ( HasConditions(bits_COND_CAN_RANGE_ATTACK1) ) { return GetScheduleOfType( SCHED_RANGE_ATTACK1 ); } if ( HasConditions(bits_COND_CAN_RANGE_ATTACK2) ) { return GetScheduleOfType( SCHED_RANGE_ATTACK2 ); } if ( HasConditions(bits_COND_CAN_MELEE_ATTACK1) ) { return GetScheduleOfType( SCHED_MELEE_ATTACK1 ); } if ( HasConditions(bits_COND_CAN_MELEE_ATTACK2) ) { return GetScheduleOfType( SCHED_MELEE_ATTACK2 ); } if ( !HasConditions(bits_COND_CAN_RANGE_ATTACK1 | bits_COND_CAN_MELEE_ATTACK1) ) { // if we can see enemy but can't use either attack type, we must need to get closer to enemy return GetScheduleOfType( SCHED_CHASE_ENEMY ); } else if ( !FacingIdeal() ) { //turn return GetScheduleOfType( SCHED_COMBAT_FACE ); } else { ALERT ( at_aiconsole, "No suitable combat schedule!\n" ); } } break; } case MONSTERSTATE_DEAD: { return GetScheduleOfType( SCHED_DIE ); break; } case MONSTERSTATE_SCRIPT: { ASSERT( m_pCine != NULL ); if ( !m_pCine ) { ALERT( at_aiconsole, "Script failed for %s\n", STRING(pev->classname) ); CineCleanup(); return GetScheduleOfType( SCHED_IDLE_STAND ); } return GetScheduleOfType( SCHED_AISCRIPT ); } default: { ALERT ( at_aiconsole, "Invalid State for GetSchedule!\n" ); break; } } return &slError[ 0 ]; }
void CTAAirMoveType::Update() { float3& pos = owner->pos; float3& speed = owner->speed; // This is only set to false after the plane has finished constructing if (useHeading) { useHeading = false; SetState(AIRCRAFT_TAKEOFF); } // Allow us to stop if wanted if (wantToStop) ExecuteStop(); float3 lastSpeed = speed; if (owner->stunned) { wantedSpeed = ZeroVector; UpdateAirPhysics(); } else { #ifdef DIRECT_CONTROL_ALLOWED if (owner->directControl) { DirectControlStruct* dc = owner->directControl; SetState(AIRCRAFT_FLYING); float3 forward = dc->viewDir; float3 flatForward = forward; flatForward.y = 0; flatForward.Normalize(); float3 right = forward.cross(UpVector); float3 nextPos = pos + speed; wantedSpeed = ZeroVector; if (dc->forward) wantedSpeed += flatForward; if (dc->back) wantedSpeed -= flatForward; if (dc->right) wantedSpeed += right; if (dc->left) wantedSpeed -= right; wantedSpeed.Normalize(); wantedSpeed *= maxSpeed; if (!nextPos.CheckInBounds()) { speed = ZeroVector; } UpdateAirPhysics(); wantedHeading = GetHeadingFromVector(flatForward.x, flatForward.z); } else #endif { if (reservedPad) { CUnit* unit = reservedPad->GetUnit(); float3 relPos = unit->localmodel->GetPiecePos(reservedPad->GetPiece()); float3 pos = unit->pos + unit->frontdir * relPos.z + unit->updir * relPos.y + unit->rightdir * relPos.x; if (padStatus == 0) { if (aircraftState != AIRCRAFT_FLYING && aircraftState != AIRCRAFT_TAKEOFF) SetState(AIRCRAFT_FLYING); goalPos = pos; if (pos.distance2D(owner->pos) < 400) { padStatus = 1; } } else if (padStatus == 1) { if (aircraftState != AIRCRAFT_FLYING) SetState(AIRCRAFT_FLYING); flyState = FLY_LANDING; goalPos = pos; reservedLandingPos = pos; wantedHeight = pos.y - ground->GetHeight(pos.x, pos.z); if (owner->pos.distance(pos) < 3 || aircraftState == AIRCRAFT_LANDED) { padStatus = 2; } } else { if (aircraftState != AIRCRAFT_LANDED) SetState(AIRCRAFT_LANDED); owner->pos = pos; owner->AddBuildPower(unit->unitDef->buildSpeed / 30, unit); owner->currentFuel = std::min(owner->unitDef->maxFuel, owner->currentFuel + (owner->unitDef->maxFuel / (GAME_SPEED * owner->unitDef->refuelTime))); if (owner->health >= owner->maxHealth - 1 && owner->currentFuel >= owner->unitDef->maxFuel) { airBaseHandler->LeaveLandingPad(reservedPad); reservedPad = 0; padStatus = 0; goalPos = oldGoalPos; SetState(AIRCRAFT_TAKEOFF); } } } // Main state handling switch (aircraftState) { case AIRCRAFT_LANDED: UpdateLanded(); break; case AIRCRAFT_TAKEOFF: UpdateTakeoff(); break; case AIRCRAFT_FLYING: UpdateFlying(); break; case AIRCRAFT_LANDING: UpdateLanding(); break; case AIRCRAFT_HOVERING: UpdateHovering(); break; case AIRCRAFT_CRASHING: break; } } } // Banking requires deltaSpeed.y = 0 deltaSpeed = speed - lastSpeed; deltaSpeed.y = 0; // Turn and bank and move UpdateHeading(); UpdateBanking(aircraftState == AIRCRAFT_HOVERING); // updates dirs owner->UpdateMidPos(); // Push other units out of the way if (pos != oldpos && aircraftState != AIRCRAFT_TAKEOFF && padStatus == 0) { oldpos = pos; if (!dontCheckCol && collide) { vector<CUnit*> nearUnits = qf->GetUnitsExact(pos, owner->radius + 6); vector<CUnit*>::iterator ui; for (ui = nearUnits.begin(); ui != nearUnits.end(); ++ui) { if ((*ui)->transporter) continue; float sqDist = (pos-(*ui)->pos).SqLength(); float totRad = owner->radius + (*ui)->radius; if (sqDist < totRad * totRad && sqDist != 0) { float dist = sqrt(sqDist); float3 dif = pos - (*ui)->pos; dif /= dist; if ((*ui)->mass >= 100000 || (*ui)->immobile) { pos -= dif * (dist - totRad); owner->UpdateMidPos(); owner->speed *= 0.99f; } else { float part = owner->mass / (owner->mass + (*ui)->mass); pos -= dif * (dist - totRad) * (1 - part); owner->UpdateMidPos(); CUnit* u = (CUnit*) (*ui); u->pos += dif * (dist - totRad) * (part); u->UpdateMidPos(); float colSpeed = -owner->speed.dot(dif) + u->speed.dot(dif); owner->speed += dif * colSpeed * (1 - part); u->speed -= dif * colSpeed * (part); } } } } if (pos.x < 0) { pos.x += 0.6f; owner->midPos.x += 0.6f; } else if (pos.x > float3::maxxpos) { pos.x -= 0.6f; owner->midPos.x -= 0.6f; } if (pos.z < 0) { pos.z += 0.6f; owner->midPos.z += 0.6f; } else if (pos.z > float3::maxzpos) { pos.z -= 0.6f; owner->midPos.z -= 0.6f; } } }
void Item::SaveToDB(SQLTransaction& trans) { bool isInTransaction = !(trans.null()); if (!isInTransaction) trans = CharacterDatabase.BeginTransaction(); uint32 guid = GetGUIDLow(); switch (uState) { case ITEM_NEW: case ITEM_CHANGED: { uint8 index = 0; PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(uState == ITEM_NEW ? CHAR_REP_ITEM_INSTANCE : CHAR_UPD_ITEM_INSTANCE); stmt->setUInt32( index, GetEntry()); stmt->setUInt32(++index, GUID_LOPART(GetOwnerGUID())); stmt->setUInt32(++index, GUID_LOPART(GetUInt64Value(ITEM_FIELD_CREATOR))); stmt->setUInt32(++index, GUID_LOPART(GetUInt64Value(ITEM_FIELD_GIFTCREATOR))); stmt->setUInt32(++index, GetCount()); stmt->setUInt32(++index, GetUInt32Value(ITEM_FIELD_DURATION)); std::ostringstream ssSpells; for (uint8 i = 0; i < MAX_ITEM_PROTO_SPELLS; ++i) ssSpells << GetSpellCharges(i) << ' '; stmt->setString(++index, ssSpells.str()); stmt->setUInt32(++index, GetUInt32Value(ITEM_FIELD_FLAGS)); std::ostringstream ssEnchants; for (uint8 i = 0; i < MAX_ENCHANTMENT_SLOT; ++i) { ssEnchants << GetEnchantmentId(EnchantmentSlot(i)) << ' '; ssEnchants << GetEnchantmentDuration(EnchantmentSlot(i)) << ' '; ssEnchants << GetEnchantmentCharges(EnchantmentSlot(i)) << ' '; } stmt->setString(++index, ssEnchants.str()); stmt->setInt16 (++index, GetItemRandomPropertyId()); stmt->setUInt16(++index, GetUInt32Value(ITEM_FIELD_DURABILITY)); stmt->setUInt32(++index, GetUInt32Value(ITEM_FIELD_CREATE_PLAYED_TIME)); stmt->setString(++index, m_text); stmt->setUInt32(++index, guid); trans->Append(stmt); if ((uState == ITEM_CHANGED) && HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAG_WRAPPED)) { stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_GIFT_OWNER); stmt->setUInt32(0, GUID_LOPART(GetOwnerGUID())); stmt->setUInt32(1, guid); trans->Append(stmt); } break; } case ITEM_REMOVED: { PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ITEM_INSTANCE); stmt->setUInt32(0, guid); trans->Append(stmt); if (HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAG_WRAPPED)) { stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GIFT); stmt->setUInt32(0, guid); trans->Append(stmt); } if (!isInTransaction) CharacterDatabase.CommitTransaction(trans); // Delete the items if this is a container if (!loot.isLooted()) ItemContainerDeleteLootMoneyAndLootItemsFromDB(); delete this; return; } case ITEM_UNCHANGED: break; } SetState(ITEM_UNCHANGED); if (!isInTransaction) CharacterDatabase.CommitTransaction(trans); }
//------------------------------------------------------------------------------------------------ void Person::Update(float dt) { if (mGuns[mGunIndex] == NULL) { printf("isPlayerOnline: %i\n",mIsPlayerOnline); printf("invalid gunindex: %i\n",mGunIndex); return; } mStateTime += dt; if (mState == DEAD) { if (mStateTime >= 15000.0f) { //P: time for deadbody = 15 secs //orig : 2 sec mFadeTime -= dt; if (mFadeTime < 0.0f) { mFadeTime = 0.0f; } } return; } //P: HEALTH REGEN (adds as HP the mRegenPoints per desired mRegenTimer) if (mMoveState == NOTMOVING) { mRegen += dt/1000.0f; if (mRegen >= mRegenTimer) { // + mRegenPoints HP per mRegenTimer second(s) if (mHealth != 0) { mHealth += mRegenPoints; mRegen = 0.0f; } } if (mHealth > 100) { //for safety and bug avoidance reasons, cause it could be done otherwise, but this is optimum. mHealth = 100; } } //P: Bleeding (removes as HP the mBleedPoints per desired mBleedTimer) // BUGS: Score won't update and round may not end. Also no blood decal is spawns on every update and speed not decreases if (mHealth < 100) { mBleeding += dt/1000.0f; if (mBleeding >= mBleedTimer) { // - mBleedPoints HP per mBleedTimer second(s) if (mHealth != 0) { //mHealth -= mBleedPoints; Person::TakeDamage(mBleedPoints); mBleeding = 0.0f; } } if (mHealth <= 0) { mHealth = 0; // idk if this is necessary Die(); } } mWalkAngle = mAngle; if (mIsActive) { if (mMoveState == NOTMOVING) { if (!mIsPlayerOnline) { mSpeed -= .0005f*dt; if (mSpeed < 0) { mSpeed = 0; } } mStepTime = 240.0f; } else if (mMoveState == MOVING) { if (!mIsPlayerOnline) { mSpeed += .0005f*dt; if (mSpeed > mMaxSpeed) { mSpeed = mMaxSpeed; } } if (mRecoilAngle < mGuns[mGunIndex]->mGun->mSpread*0.5f) { //HERE mRecoilAngle += mGuns[mGunIndex]->mGun->mSpread/50.0f*dt; if (mRecoilAngle > mGuns[mGunIndex]->mGun->mSpread*0.5f) { mRecoilAngle = mGuns[mGunIndex]->mGun->mSpread*0.5f; } } } } if (!mIsPlayerOnline) { mOldX = mX; mOldY = mY; mX += mSpeed * cosf(mAngle) * dt; mY += mSpeed * sinf(mAngle) * dt; } //JSprite::Update(dt); if (mGuns[mGunIndex]->mGun->mId == 7 || mGuns[mGunIndex]->mGun->mId == 8) { //HERE mRecoilAngle = mGuns[mGunIndex]->mGun->mSpread; } mLastFireAngle = mRotation; if (mState == NORMAL) { if (mGuns[mGunIndex]->mGun->mId != 7 && mGuns[mGunIndex]->mGun->mId != 8) { mRecoilAngle -= mGuns[mGunIndex]->mGun->mSpread/100.0f*dt; if (mRecoilAngle < 0) { mRecoilAngle = 0.0f; } } } else if (mState == ATTACKING) { if (mMoveState == NOTMOVING) { mRecoilAngle += mGuns[mGunIndex]->mGun->mSpread/500.0f*dt; } else if (mMoveState == MOVING) { mRecoilAngle += mGuns[mGunIndex]->mGun->mSpread/50.0f*dt; } if (mGuns[mGunIndex]->mGun->mId == 16 || mGuns[mGunIndex]->mGun->mId == 21 || mGuns[mGunIndex]->mGun->mId == 22 || mGuns[mGunIndex]->mGun->mId == 23) { mRecoilAngle = mGuns[mGunIndex]->mGun->mSpread; } if (mRecoilAngle > mGuns[mGunIndex]->mGun->mSpread) { mRecoilAngle = mGuns[mGunIndex]->mGun->mSpread; } if (mRecoilAngle*500.0f >= 0.1f && mStateTime < 100.0f) { mLastFireAngle += (rand()%(int)ceilf(mRecoilAngle*500.0f))/1000.0f-(mRecoilAngle/4.0f); } if (mStateTime >= mGuns[mGunIndex]->mGun->mDelay) { if (mGunIndex == GRENADE) { mStateTime = mGuns[mGunIndex]->mGun->mDelay; } else { SetState(NORMAL); } } } else if (mState == RELOADING) { if (mStateTime >= mGuns[mGunIndex]->mGun->mReloadDelay) { mGuns[mGunIndex]->mRemainingAmmo -= (mGuns[mGunIndex]->mGun->mClip-mGuns[mGunIndex]->mClipAmmo); mGuns[mGunIndex]->mClipAmmo = mGuns[mGunIndex]->mGun->mClip; if (mGuns[mGunIndex]->mRemainingAmmo < 0) { mGuns[mGunIndex]->mClipAmmo = mGuns[mGunIndex]->mGun->mClip + mGuns[mGunIndex]->mRemainingAmmo ; mGuns[mGunIndex]->mRemainingAmmo = 0; } SetState(NORMAL); } if (mGuns[mGunIndex]->mGun->mId != 7 && mGuns[mGunIndex]->mGun->mId != 8) { mRecoilAngle -= mGuns[mGunIndex]->mGun->mSpread/100.0f*dt; if (mRecoilAngle < 0.0f) { mRecoilAngle = 0.0f; } } } else if (mState == DRYFIRING) { if (mGunIndex == PRIMARY) { if (mStateTime >= 250.0f) { SetState(NORMAL); mNumDryFire++; } } else if (mGunIndex == SECONDARY) { SetState(NORMAL); mNumDryFire++; } else if (mGunIndex == KNIFE) { if (mStateTime >= mGuns[mGunIndex]->mGun->mDelay) { SetState(NORMAL); } } } else if (mState == SWITCHING) { if (mGunIndex == PRIMARY || mGunIndex == SECONDARY) { float delay = mGuns[mGunIndex]->mGun->mDelay*0.75f; if (delay < 150.0f) delay = 150.0f; if (mStateTime >= delay) { SetState(NORMAL); } } else { if (mStateTime >= 150.0f) { SetState(NORMAL); } } } if (!mIsPlayerOnline) { if (mNumDryFire > 3) { Reload(); } } if (mIsFlashed) { mFlashTime -= dt/mFlashIntensity; if (mFlashTime < 0.0f) { mFlashTime = 0.0f; mIsFlashed = false; } } //P: Same thing as regen just add a timer mMuzzleFlashTime -= dt; if (mMuzzleFlashTime < 0.0f) { mMuzzleFlashTime = 0.0f; } mRadarTime -= dt; if (mRadarTime < 0.0f) { mRadarTime = 0.0f; } mCurrentAnimation->Update(dt,mKeyFrame); mInvincibleTime -= dt; if (mInvincibleTime < 0.0f) { mInvincibleTime = 0.0f; } }
void CHoverAirMoveType::UpdateFlying() { const float3& pos = owner->pos; const float3& speed = owner->speed; // Direction to where we would like to be float3 goalVec = goalPos - pos; owner->restTime = 0; // don't change direction for waypoints we just flew over and missed slightly if (flyState != FLY_LANDING && owner->commandAI->HasMoreMoveCommands()) { float3 goalDir = goalVec; if ((goalDir != ZeroVector) && (goalDir.UnsafeANormalize()).SqDistance(goalVec) < 1.0f) { goalVec = owner->frontdir; } } const float goalDistSq2D = goalVec.SqLength2D(); const float gHeight = UseSmoothMesh()? std::max(smoothGround->GetHeight(pos.x, pos.z), ground->GetApproximateHeight(pos.x, pos.z)): ground->GetHeightAboveWater(pos.x, pos.z); const bool closeToGoal = (flyState == FLY_ATTACKING)? (goalDistSq2D < ( 400.0f)): (goalDistSq2D < (maxDrift * maxDrift)) && (math::fabs(gHeight - pos.y + wantedHeight) < maxDrift); if (closeToGoal) { switch (flyState) { case FLY_CRUISING: { const bool trans = (dynamic_cast<CTransportUnit*>(owner) != NULL); const bool noland = dontLand || !autoLand; // NOTE: should CMD_LOAD_ONTO be here? const bool hasLoadCmds = trans && !owner->commandAI->commandQue.empty() && (owner->commandAI->commandQue.front().GetID() == CMD_LOAD_ONTO || owner->commandAI->commandQue.front().GetID() == CMD_LOAD_UNITS); // [?] transport aircraft need some time to detect that they can pickup const bool canLoad = trans && (++waitCounter < ((GAME_SPEED << 1) - 5)); if (noland || (canLoad && hasLoadCmds)) { if (trans) { wantedSpeed = ZeroVector; SetState(AIRCRAFT_HOVERING); if (waitCounter > (GAME_SPEED << 1)) { wantedHeight = orgWantedHeight; } } else { wantedSpeed = ZeroVector; if (!owner->commandAI->HasMoreMoveCommands()) wantToStop = true; SetState(AIRCRAFT_HOVERING); } } else { wantedHeight = orgWantedHeight; SetState(AIRCRAFT_LANDING); } return; } case FLY_CIRCLING: // break; if ((++waitCounter) > ((GAME_SPEED * 3) + 10)) { if (airStrafe) { float3 relPos = pos - circlingPos; if (relPos.x < 0.0001f && relPos.x > -0.0001f) { relPos.x = 0.0001f; } relPos.y = 0.0f; relPos.Normalize(); static CMatrix44f rot(0.0f,fastmath::PI/4.0f,0.0f); float3 newPos = rot.Mul(relPos); // Make sure the point is on the circle newPos = newPos * goalDistance; // Go there in a straight line goalPos = circlingPos + newPos; } waitCounter = 0; } break; case FLY_ATTACKING: { if (airStrafe) { float3 relPos = pos - circlingPos; if (relPos.x < 0.0001f && relPos.x > -0.0001f) { relPos.x = 0.0001f; } relPos.y = 0; relPos.Normalize(); CMatrix44f rot; if (gs->randFloat() > 0.5f) { rot.RotateY(0.6f + gs->randFloat() * 0.6f); } else { rot.RotateY(-(0.6f + gs->randFloat() * 0.6f)); } float3 newPos = rot.Mul(relPos); newPos = newPos * goalDistance; // Go there in a straight line goalPos = circlingPos + newPos; } break; } case FLY_LANDING: { break; } } } // not there yet, so keep going goalVec.y = 0.0f; // if we are close to our goal and not in attack mode, // we should go slow enough to be able to break in time const float goalDist = goalVec.Length() + 0.1f; const float approachSpeed = (flyState != FLY_ATTACKING && goalDist < brakeDistance)? (goalDist / (speed.Length2D() + 0.01f) * decRate): maxSpeed; wantedSpeed = (goalVec / goalDist) * approachSpeed; UpdateAirPhysics(); // Point toward goal or forward - unless we just passed it to get to another goal if ((flyState == FLY_ATTACKING) || (flyState == FLY_CIRCLING)) { goalVec = circlingPos - pos; } else { const bool b0 = (flyState != FLY_LANDING && (owner->commandAI->HasMoreMoveCommands())); const bool b1 = (goalDist < 120.0f) && ((goalVec.SafeNormalize()).SqDistance(goalVec) > 1.0f); if (b0 && b1) { goalVec = owner->frontdir; } else { goalVec = goalPos - pos; } } if (goalVec.SqLength2D() > 1.0f) { wantedHeading = GetHeadingFromVector(goalVec.x, goalVec.z); } }
//------------------------------------------------------------------------------------------------ void Person::SwitchNext() { if (mState == RELOADING) { //SetState(NORMAL); if (mSoundId != -1) { mSoundSystem->StopSample(mSoundId); mSoundId = -1; } } else if (mState == ATTACKING) { //SetState(NORMAL); } int gunindex = mGunIndex; for (int i=0; i<5; i++) { gunindex++; if (gunindex > 4) { gunindex = 0; } if (mGuns[gunindex] != NULL) break; } if (gunindex == mGunIndex) return; mGunIndex = gunindex; if (mGunIndex == PRIMARY) { gSfxManager->PlaySample(gDeploySound,mX,mY); } /*if (mGunIndex == PRIMARY) { if (mGuns[SECONDARY] != NULL) { mGunIndex = SECONDARY; } else { mGunIndex = KNIFE; } } else if (mGunIndex == SECONDARY) { if (mGuns[KNIFE] != NULL) { mGunIndex = KNIFE; } else { mGunIndex = PRIMARY; gSfxManager->PlaySample(gDeploySound,mX,mY); } } else if (mGunIndex == KNIFE) { if (mGuns[PRIMARY] != NULL) { mGunIndex = PRIMARY; gSfxManager->PlaySample(gDeploySound,mX,mY); } else if (mGuns[SECONDARY] != NULL) { mGunIndex = SECONDARY; } }*/ mRecoilAngle = 0.0f; mNumDryFire = 0; SetState(SWITCHING); }
bool CHoverAirMoveType::Update() { const float3& pos = owner->pos; float3& speed = owner->speed; AAirMoveType::Update(); if (owner->stunned || owner->beingBuilt) { wantedSpeed = ZeroVector; wantToStop = true; } // Allow us to stop if wanted if (wantToStop) { ExecuteStop(); } const float3 lastSpeed = speed; if (owner->fpsControlPlayer != NULL) { SetState(AIRCRAFT_FLYING); const FPSUnitController& con = owner->fpsControlPlayer->fpsController; const float3 forward = con.viewDir; const float3 right = forward.cross(UpVector); const float3 nextPos = pos + speed; float3 flatForward = forward; flatForward.y = 0.0f; flatForward.Normalize(); wantedSpeed = ZeroVector; if (con.forward) wantedSpeed += flatForward; if (con.back ) wantedSpeed -= flatForward; if (con.right ) wantedSpeed += right; if (con.left ) wantedSpeed -= right; wantedSpeed.Normalize(); wantedSpeed *= maxSpeed; if (!nextPos.IsInBounds()) { speed = ZeroVector; } UpdateAirPhysics(); wantedHeading = GetHeadingFromVector(flatForward.x, flatForward.z); } else { if (reservedPad != NULL) { MoveToRepairPad(); if (padStatus >= PAD_STATUS_LANDING) { flyState = FLY_LANDING; } } // Main state handling switch (aircraftState) { case AIRCRAFT_LANDED: UpdateLanded(); break; case AIRCRAFT_TAKEOFF: UpdateTakeoff(); break; case AIRCRAFT_FLYING: UpdateFlying(); break; case AIRCRAFT_LANDING: UpdateLanding(); break; case AIRCRAFT_HOVERING: UpdateHovering(); break; case AIRCRAFT_CRASHING: break; } } // Banking requires deltaSpeed.y = 0 deltaSpeed = speed - lastSpeed; deltaSpeed.y = 0.0f; // Turn and bank and move; update dirs UpdateHeading(); UpdateBanking(aircraftState == AIRCRAFT_HOVERING); return (HandleCollisions()); }
void ProcessEvent(unsigned int me, simtime_t now, int event_type, event_content_type *event_content, unsigned int size, void * ptr) { int w; event_content_type new_event_content; new_event_content.cell = -1; new_event_content.second_cell = -1; new_event_content.channel = -1; new_event_content.call_term_time = -1; simtime_t handoff_time; simtime_t timestamp=0; lp_state_type * pointer; pointer = (lp_state_type*)ptr; switch(event_type) { case INIT: pointer = (lp_state_type *)malloc(sizeof(lp_state_type)); if (pointer == NULL){ printf("ERROR in malloc!\n"); exit(EXIT_FAILURE); } SetState(pointer); // pointer->channels = NULL; pointer->contatore_canali = CHANNELS_PER_CELL; pointer->cont_chiamate_entranti = -1; pointer->cont_chiamate_complete = 0; pointer->cont_handoff_uscita = 0; pointer->cont_bloccate_in_partenza = 0; pointer->cont_bloccate_in_handoff = 0; pointer->handoffs_entranti = 0; // power_management = true; // variable_ta = true; // fading_recheck = true; // INIT is not considered as an event pointer->contatore_eventi = 0; // pointer->time = now; // Load the predefined values // variable_ta = true; complete_calls = COMPLETE_CALLS; ta = TA; ta_durata = TA_DURATA; ta_cambio = TA_CAMBIO; channels_per_cell = CHANNELS_PER_CELL; power_management = true; // Read runtime parameters char **arguments = (char **)event_content; for(w = 0; w < size; w += 2) { if(strcmp(arguments[w],"complete-calls") == 0) { complete_calls = parseInt(arguments[w + 1]); } else if(strcmp(arguments[w],"ta") == 0) { ta = parseDouble(arguments[w + 1]); } else if(strcmp(arguments[w],"ta-durata") == 0) { ta_durata = parseDouble(arguments[w + 1]); } else if(strcmp(arguments[w],"ta-cambio") == 0) { ta_cambio = parseDouble(arguments[w + 1]); } else if(strcmp(arguments[w],"channels-per-cell") == 0) { channels_per_cell = parseInt(arguments[w + 1]); } else if(strcmp(arguments[w],"complete-time") == 0) { complete_time = parseInt(arguments[w + 1]); } else if(strcmp(arguments[w],"no-power-management") == 0) { w -= 1; power_management = false; } else if(strcmp(arguments[w],"power-management") == 0) { w -= 1; power_management = true; } else if(strcmp(arguments[w],"variable-ta") == 0) { w -= 1; variable_ta = true; } else if(strcmp(arguments[w],"fading-recheck") == 0) { fading_recheck = true; } else if(strcmp(arguments[w],"complete-time") == 0) { complete_time = parseInt(arguments[w + 1]); } } ref_ta = ta; // Show current configuration, only once if(me == 0) { printf("CURRENT CONFIGURATION:\nCOMPLETE CALLS: %d\nTA: %f\nTA_DURATA: %f\nTA_CAMBIO: %f\nCHANNELS_PER_CELL: %d\nCOMPLETE_TIME: %d\n", complete_calls, ta, ta_durata, ta_cambio, channels_per_cell, complete_time); printf("POWER MANAGMENT: %d\nFADING RECHECK: %d\nVARIABLE TA: %d\n", power_management, fading_recheck, variable_ta); fflush(stdout); } pointer->contatore_canali = channels_per_cell; for (w = 0; w < pointer->contatore_canali / (sizeof(int) * 8) + 1; w++) pointer->channel_state[w] = 0; pointer->buff_topology = (_PCS_routing*)malloc(sizeof(_PCS_routing)); if(pointer->buff_topology == NULL){ printf("Chiamata a malloc errata sulla topologia della rete!\n"); exit(EXIT_FAILURE); } set_my_topology(me, pointer->buff_topology); timestamp = (simtime_t) (20 * Random()); ScheduleNewEvent(me, timestamp, START_CALL, NULL, 0); if (fading_recheck) { timestamp = now + (simtime_t) (FADING_RECHECK_FREQUENCY); ScheduleNewEvent(me, timestamp, FADING_RECHECK, NULL, 0); } break; case START_CALL: pointer->time = now; //make_copy(pointer->cont_chiamate_entranti, pointer->cont_chiamate_entranti+1); pointer->cont_chiamate_entranti++; //make_copy(pointer->contatore_eventi, pointer->contatore_eventi+1); pointer->contatore_eventi++; if (pointer->contatore_canali == 0) { //make_copy(pointer->cont_bloccate_in_partenza, pointer->cont_bloccate_in_partenza+1); pointer->cont_bloccate_in_partenza++; } else { pointer->contatore_canali--; //make_copy(pointer->contatore_canali, pointer->contatore_canali-1); #ifdef ACCURATE_SIMULATION new_event_content.channel = allocation(me, pointer); #endif // Determine call duration switch (DISTRIBUZIONE_DURATA) { case UNIFORME: new_event_content.call_term_time = now+ (simtime_t) (ta_durata * Random()); break; case ESPONENZIALE: new_event_content.call_term_time = now + (simtime_t)( Expent(ta_durata )); break; default: new_event_content.call_term_time = now+ (simtime_t) (5 * Random() ); } // Determine whether the call will be handed-off or not switch (DISTRIBUZIONE_CAMBIOCELLA) { case UNIFORME: handoff_time = now+ (simtime_t) ((ta_cambio) * Random() ); break; case ESPONENZIALE: handoff_time = now+ (simtime_t)( Expent( ta_cambio )); break; default: handoff_time = now+ (simtime_t) (5 * Random() ); } if( new_event_content.call_term_time <= handoff_time) { ScheduleNewEvent(me,new_event_content.call_term_time,END_CALL,&new_event_content,sizeof(new_event_content)); } else { new_event_content.cell = __FindReceiver(me,pointer); new_event_content.second_cell = -1; ScheduleNewEvent(me,handoff_time,HANDOFF_LEAVE,&new_event_content,sizeof(new_event_content)); // #ifdef PRE_SCHEDULING new_event_content.call_term_time = new_event_content.call_term_time; ScheduleNewEvent(new_event_content.cell,handoff_time,HANDOFF_RECV,&new_event_content,sizeof(new_event_content)); // #endif } } // if (pointer->contatore_canali == 0) if (variable_ta) ta = recompute_ta(ref_ta, now); // Determine the time at which the call will end switch (DISTRIBUZIONE) { case UNIFORME: timestamp= now+ (simtime_t) (ta * Random() ); break; case ESPONENZIALE: timestamp= now+ (simtime_t)( Expent( ta )); break; default: timestamp= now+ (simtime_t) (5 * Random()); } ScheduleNewEvent(me, timestamp, START_CALL, NULL, 0); break; case END_CALL: pointer->time = now; // make_copy(pointer->contatore_eventi, pointer->contatore_eventi+1); pointer->contatore_eventi++; //make_copy(pointer->contatore_canali, pointer->contatore_canali+1); pointer->contatore_canali++; //make_copy(pointer->cont_chiamate_complete, pointer->cont_chiamate_complete+1); pointer->cont_chiamate_complete++; #ifdef ACCURATE_SIMULATION deallocation(me, pointer, event_content->channel); #endif break; case HANDOFF_LEAVE: pointer->time = now; //make_copy(pointer->contatore_eventi, pointer->contatore_eventi+1); pointer->contatore_eventi++; //make_copy(pointer->contatore_canali, pointer->contatore_canali+1); pointer->contatore_canali++; //make_copy(pointer->cont_handoff_uscita, pointer->cont_handoff_uscita+1); pointer->cont_handoff_uscita++; #ifdef ACCURATE_SIMULATION deallocation(me, pointer, event_content->channel); #endif // #ifndef PRE_SCHEDULING // new_event_content.call_term_time = event_content->call_term_time + 0.00005; // ScheduleNewEvent(event_content->cell, now + 0.00003 , HANDOFF_RECV, &new_event_content, sizeof(new_event_content)); // #endif break; case HANDOFF_RECV: pointer->time = now; //handoff_counter++; //make_copy(pointer->handoffs_entranti, pointer->handoffs_entranti+1); pointer->handoffs_entranti++; //make_copy(pointer->cont_chiamate_entranti, pointer->cont_chiamate_entranti+1); //make_copy(pointer->contatore_eventi, pointer->contatore_eventi+1); pointer->contatore_eventi++; pointer->cont_chiamate_entranti++; if (pointer->contatore_canali == 0) //make_copy(pointer->cont_bloccate_in_handoff, pointer->cont_bloccate_in_handoff+1); pointer->cont_bloccate_in_handoff++; else { //make_copy(pointer->contatore_canali, pointer->contatore_canali-1); pointer->contatore_canali--; #ifdef ACCURATE_SIMULATION new_event_content.channel = allocation(me, pointer); #endif new_event_content.call_term_time = event_content->call_term_time; switch (DISTRIBUZIONE_CAMBIOCELLA) { case UNIFORME: handoff_time = now+ (simtime_t) ((ta_cambio) * Random()); break; case ESPONENZIALE: handoff_time = now+ (simtime_t)( Expent( ta_cambio )); break; default: handoff_time = now+ (simtime_t) (5 * Random()); } if (Random() < 0.5) handoff_time *= 10; if( new_event_content.call_term_time <= handoff_time ) { ScheduleNewEvent(me , new_event_content.call_term_time, END_CALL, &new_event_content, sizeof(new_event_content)); } else { new_event_content.cell = __FindReceiver(me,ptr); #ifdef NO_UNCERTAINTY new_event_content.second_cell = -1; #endif ScheduleNewEvent(me , new_event_content.call_term_time, HANDOFF_LEAVE, &new_event_content, sizeof(new_event_content)); } } break; case FADING_RECHECK: // pointer->time = now; if (pointer->check_fading == true) { //make_copy(pointer->check_fading, false); pointer->check_fading = false; } else { //make_copy(pointer->check_fading, true); pointer->check_fading = true; } timestamp = now + (simtime_t) (FADING_RECHECK_FREQUENCY); ScheduleNewEvent(me, timestamp, FADING_RECHECK, NULL, 0); break; default: fprintf(stderr, " pointer simulation: error - inconsistent event (me = %d - event type = %d)\n", me, event_type); break; } // switch(event->type) }
/** * @brief The handler for Interrupt that is generated on SPI at the end of DMA transfer. * @param None * @retval None */ void SPI_DMA_IntHandler(void) { unsigned long ucTxFinished, ucRxFinished; unsigned short data_to_recv = 0; ucTxFinished = DMA_GetFlagStatus(CC3000_SPI_TX_DMA_TCFLAG ); ucRxFinished = DMA_GetFlagStatus(CC3000_SPI_RX_DMA_TCFLAG ); switch(sSpiInformation.ulSpiState) { case eSPI_STATE_READ_IRQ: // Both Done if (ucTxFinished && ucRxFinished) { /* Clear SPI_DMA Interrupt Pending Flags */ DMA_ClearFlag(CC3000_SPI_TX_DMA_TCFLAG | CC3000_SPI_RX_DMA_TCFLAG); sSpiInformation.ulSpiState = eSPI_STATE_READ_PROCEED; uint16_t *pnetlen = (uint16_t *) &sSpiInformation.pRxPacket[READ_OFFSET_TO_LENGTH]; data_to_recv = ntohs(*pnetlen); if (data_to_recv) { /* We will read ARRAY_SIZE(spi_readCommand) + data_to_recv. is it odd? */ if ((data_to_recv + arraySize(spi_readCommand)) & 1) { /* Odd so make it even */ data_to_recv++; } /* Read the whole payload in at the beginning of the buffer * Will it fit? */ SPARK_ASSERT(data_to_recv <= arraySize(wlan_rx_buffer)); SpiIO(eRead,sSpiInformation.pRxPacket,data_to_recv, FALSE); } } break; case eSPI_STATE_READ_PROCEED: // // All the data was read - finalize handling by switching to the task // and calling from task Event Handler // if (ucRxFinished) { /* Clear SPI_DMA Interrupt Pending Flags */ DMA_ClearFlag(CC3000_SPI_TX_DMA_TCFLAG | CC3000_SPI_RX_DMA_TCFLAG); SpiPauseSpi(); SetState(eSPI_STATE_IDLE, eDeAssert); // Call out to the Unsolicited handler // It will handle the event or leave it there for an outstanding opcode // It it handles it the it Will resume the SPI ISR // It it dose not handles it and there are not outstanding Opcodes the it Will resume the SPI ISR sSpiInformation.SPIRxHandler(sSpiInformation.pRxPacket); } break; case eSPI_STATE_FIRST_WRITE: case eSPI_STATE_WRITE_PROCEED: if (ucTxFinished) { /* Loop until SPI busy */ while (SPI_I2S_GetFlagStatus(CC3000_SPI, SPI_I2S_FLAG_BSY ) != RESET) { } /* Clear SPI_DMA Interrupt Pending Flags */ DMA_ClearFlag(CC3000_SPI_TX_DMA_TCFLAG | CC3000_SPI_RX_DMA_TCFLAG); if ( sSpiInformation.ulSpiState == eSPI_STATE_FIRST_WRITE) { sSpiInformation.ulSpiState = eSPI_STATE_WRITE_PROCEED; } else { SetState(eSPI_STATE_IDLE, eDeAssert); } } break; default: INVALID_CASE(sSpiInformation.ulSpiState); break; } }
void cPlayer::Stop() { switch(GetState()) { case STATE_WALKUP: SetState(STATE_LOOKUP); break; case STATE_WALKRIGHT: SetState(STATE_LOOKRIGHT); break; case STATE_WALKDOWN: SetState(STATE_LOOKDOWN); break; case STATE_WALKLEFT: SetState(STATE_LOOKLEFT); break; case STATE_SKILLWALKUP: SetState(STATE_SKILLUP); break; case STATE_SKILLWALKRIGHT: SetState(STATE_SKILLRIGHT); break; case STATE_SKILLWALKDOWN: SetState(STATE_SKILLDOWN); break; case STATE_SKILLWALKLEFT: SetState(STATE_SKILLLEFT); break; case STATE_ATTACKUP: SetState(STATE_LOOKUP); break; case STATE_ATTACKRIGHT: SetState(STATE_LOOKRIGHT); break; case STATE_ATTACKDOWN: SetState(STATE_LOOKDOWN); break; case STATE_ATTACKLEFT: SetState(STATE_LOOKLEFT); break; case STATE_DAMAGEUP: SetState(STATE_LOOKUP); break; case STATE_DAMAGERIGHT: SetState(STATE_LOOKRIGHT); break; case STATE_DAMAGEDOWN: SetState(STATE_LOOKDOWN); break; case STATE_DAMAGELEFT: SetState(STATE_LOOKLEFT); break; case STATE_SUPERATTACK: SetState(STATE_LOOKDOWN); break; } }
void Item::SaveToDB() { uint32 guid = GetGUIDLow(); switch (uState) { case ITEM_NEW: { static SqlStatementID delItem ; static SqlStatementID insItem ; SqlStatement stmt = CharacterDatabase.CreateStatement(delItem, "DELETE FROM item_instance WHERE guid = ?"); stmt.PExecute(guid); std::ostringstream ss; for (uint16 i = 0; i < m_valuesCount; ++i) ss << GetUInt32Value(i) << " "; stmt = CharacterDatabase.CreateStatement(insItem, "INSERT INTO item_instance (guid,owner_guid,data) VALUES (?, ?, ?)"); stmt.PExecute(guid, GetOwnerGuid().GetCounter(), ss.str().c_str()); } break; case ITEM_CHANGED: { static SqlStatementID updInstance ; static SqlStatementID updGifts ; SqlStatement stmt = CharacterDatabase.CreateStatement(updInstance, "UPDATE item_instance SET data = ?, owner_guid = ? WHERE guid = ?"); std::ostringstream ss; for (uint16 i = 0; i < m_valuesCount; ++i) ss << GetUInt32Value(i) << " "; stmt.PExecute(ss.str().c_str(), GetOwnerGuid().GetCounter(), guid); if (HasFlag(ITEM_FIELD_FLAGS, ITEM_DYNFLAG_WRAPPED)) { stmt = CharacterDatabase.CreateStatement(updGifts, "UPDATE character_gifts SET guid = ? WHERE item_guid = ?"); stmt.PExecute(GetOwnerGuid().GetCounter(), GetGUIDLow()); } } break; case ITEM_REMOVED: { static SqlStatementID delItemText; static SqlStatementID delInst ; static SqlStatementID delGifts ; static SqlStatementID delLoot ; if (uint32 item_text_id = GetUInt32Value(ITEM_FIELD_ITEM_TEXT_ID)) { SqlStatement stmt = CharacterDatabase.CreateStatement(delItemText, "DELETE FROM item_text WHERE id = ?"); stmt.PExecute(item_text_id); } SqlStatement stmt = CharacterDatabase.CreateStatement(delInst, "DELETE FROM item_instance WHERE guid = ?"); stmt.PExecute(guid); if (HasFlag(ITEM_FIELD_FLAGS, ITEM_DYNFLAG_WRAPPED)) { stmt = CharacterDatabase.CreateStatement(delGifts, "DELETE FROM character_gifts WHERE item_guid = ?"); stmt.PExecute(GetGUIDLow()); } if (HasSavedLoot()) { stmt = CharacterDatabase.CreateStatement(delLoot, "DELETE FROM item_loot WHERE guid = ?"); stmt.PExecute(GetGUIDLow()); } delete this; return; } case ITEM_UNCHANGED: return; } if (m_lootState == ITEM_LOOT_CHANGED || m_lootState == ITEM_LOOT_REMOVED) { static SqlStatementID delLoot ; SqlStatement stmt = CharacterDatabase.CreateStatement(delLoot, "DELETE FROM item_loot WHERE guid = ?"); stmt.PExecute(GetGUIDLow()); } if (m_lootState == ITEM_LOOT_NEW || m_lootState == ITEM_LOOT_CHANGED) { if (Player* owner = GetOwner()) { static SqlStatementID saveGold ; static SqlStatementID saveLoot ; // save money as 0 itemid data if (loot.gold) { SqlStatement stmt = CharacterDatabase.CreateStatement(saveGold, "INSERT INTO item_loot (guid,owner_guid,itemid,amount,property) VALUES (?, ?, 0, ?, 0)"); stmt.PExecute(GetGUIDLow(), owner->GetGUIDLow(), loot.gold); } SqlStatement stmt = CharacterDatabase.CreateStatement(saveLoot, "INSERT INTO item_loot (guid,owner_guid,itemid,amount,property) VALUES (?, ?, ?, ?, ?)"); // save items and quest items (at load its all will added as normal, but this not important for item loot case) for (size_t i = 0; i < loot.GetMaxSlotInLootFor(owner); ++i) { QuestItem* qitem = NULL; LootItem* item = loot.LootItemInSlot(i, owner, &qitem); if (!item) continue; // questitems use the blocked field for other purposes if (!qitem && item->is_blocked) continue; stmt.addUInt32(GetGUIDLow()); stmt.addUInt32(owner->GetGUIDLow()); stmt.addUInt32(item->itemid); stmt.addUInt8(item->count); stmt.addInt32(item->randomPropertyId); stmt.Execute(); } } } if (m_lootState != ITEM_LOOT_NONE && m_lootState != ITEM_LOOT_TEMPORARY) SetLootState(ITEM_LOOT_UNCHANGED); SetState(ITEM_UNCHANGED); }
void duIMPanelNode::Expand(BOOL fExpand) { if (fExpand) { duPlugin *pNextSibling = GetNextSibling(); while (pNextSibling) { LPCTSTR lpszType = pNextSibling->GetType(); if (lstrcmpi(lpszType, _T("scrollbar")) == 0) { pNextSibling = pNextSibling->GetNextSibling(); continue; } if (lstrcmpi(lpszType, _T("impanelnode")) == 0) { duIMPanelNode *pIMPanelNode = (duIMPanelNode *)pNextSibling; if (pIMPanelNode->GetLevel() == GetLevel()) break; } pNextSibling->SetVisible(TRUE); pNextSibling = pNextSibling->GetNextSibling(); } } else { duPlugin *pNextSibling = GetNextSibling(); while (pNextSibling) { LPCTSTR lpszType = pNextSibling->GetType(); if (lstrcmpi(lpszType, _T("scrollbar")) == 0) { pNextSibling = pNextSibling->GetNextSibling(); continue; } if (lstrcmpi(lpszType, _T("impanelnode")) == 0) { duIMPanelNode *pIMPanelNode = (duIMPanelNode *)pNextSibling; if (pIMPanelNode->GetLevel() == GetLevel()) break; } pNextSibling->SetVisible(FALSE); pNextSibling = pNextSibling->GetNextSibling(); } SetState(DU_STATE_CHECKED); } duPlugin *pParent = GetParent(); if (lstrcmpi(pParent->GetType(), _T("listboxex")) == 0) { duListBoxEx *pListBoxEx = (duListBoxEx *)pParent; pListBoxEx->RefreshPane(); Plugin_Redraw(pListBoxEx, TRUE); } NotifyUser(DUM_IMPEXPAND, (WPARAM)fExpand, NULL); }
void CTAAirMoveType::UpdateFlying() { float3 &pos = owner->pos; float3 &speed = owner->speed; // Direction to where we would like to be float3 dir = goalPos - pos; owner->restTime = 0; // don't change direction for waypoints we just flew over and missed slightly if (flyState != FLY_LANDING && (owner->commandAI->HasMoreMoveCommands() && dir.Length2D() < 100) && (goalPos - pos).Normalize().distance(dir) < 1) { dir = owner->frontdir; } // are we there yet? bool closeToGoal = (dir.SqLength2D() < maxDrift * maxDrift) && (fabs(ground->GetHeight(pos.x, pos.z) - pos.y + wantedHeight) < maxDrift); if (flyState == FLY_ATTACKING) closeToGoal = (dir.SqLength2D() < 400); if (closeToGoal) { // pretty close switch (flyState) { case FLY_CRUISING: if (dontLand || (++waitCounter < 55 && dynamic_cast<CTransportUnit*>(owner)) || !autoLand) { // transport aircraft need some time to detect that they can pickup if (dynamic_cast<CTransportUnit*>(owner)) { wantedSpeed = ZeroVector; if (waitCounter > 60) { wantedHeight = orgWantedHeight; } } else { //wantedSpeed = ZeroVector; if (!owner->commandAI->HasMoreMoveCommands()) wantToStop=true; // SetState(AIRCRAFT_HOVERING); } } else { wantedHeight = orgWantedHeight; SetState(AIRCRAFT_LANDING); } return; case FLY_CIRCLING: // break; waitCounter++; if (waitCounter > 100) { if (owner->unitDef->airStrafe) { float3 relPos = pos - circlingPos; if (relPos.x < 0.0001f && relPos.x > -0.0001f) relPos.x = 0.0001f; relPos.y = 0; relPos.Normalize(); CMatrix44f rot; rot.RotateY(1.0f); float3 newPos = rot.Mul(relPos); // Make sure the point is on the circle newPos = newPos.Normalize() * goalDistance; //Go there in a straight line goalPos = circlingPos + newPos; } waitCounter = 0; } break; case FLY_ATTACKING: { if (owner->unitDef->airStrafe) { float3 relPos = pos - circlingPos; if (relPos.x < 0.0001f && relPos.x > -0.0001f) relPos.x = 0.0001f; relPos.y = 0; relPos.Normalize(); CMatrix44f rot; if (gs->randFloat() > 0.5f) rot.RotateY(0.6f + gs->randFloat() * 0.6f); else rot.RotateY(-(0.6f + gs->randFloat() * 0.6f)); float3 newPos = rot.Mul(relPos); newPos = newPos.Normalize() * goalDistance; // Go there in a straight line goalPos = circlingPos + newPos; } break; } case FLY_LANDING: { break; } } } // not there yet, so keep going dir.y = 0; float realMax = maxSpeed; float dist = dir.Length2D(); // If we are close to our goal, we should go slow enough to be able to break in time // new additional rule: if in attack mode or if we have more move orders then this is // an intermediate waypoint, don't slow down (FIXME) /// if (flyState != FLY_ATTACKING && dist < breakDistance && !owner->commandAI->HasMoreMoveCommands()) { if (flyState != FLY_ATTACKING && dist < breakDistance) { realMax = dist / (speed.Length2D() + 0.01f) * decRate; } wantedSpeed = dir.Normalize() * realMax; UpdateAirPhysics(); // Point toward goal or forward - unless we just passed it to get to another goal if ((flyState == FLY_ATTACKING) || (flyState == FLY_CIRCLING)) { dir = circlingPos - pos; } else if (flyState != FLY_LANDING && (owner->commandAI->HasMoreMoveCommands() && dist < 120) && (goalPos - pos).Normalize().distance(dir) > 1) { dir = owner->frontdir; } else { dir = goalPos - pos; } if (dir.SqLength2D() > 1) { int h = GetHeadingFromVector(dir.x, dir.z); wantedHeading = (h == 0)? wantedHeading: h; } }
void Volume::HandleVoldResponse(int aResponseCode, nsCWhitespaceTokenizer& aTokenizer) { MOZ_ASSERT(XRE_IsParentProcess()); MOZ_ASSERT(MessageLoop::current() == XRE_GetIOMessageLoop()); // The volume name will have already been parsed, and the tokenizer will point // to the token after the volume name switch (aResponseCode) { case ::ResponseCode::VolumeListResult: { // Each line will look something like: // // sdcard /mnt/sdcard 1 // nsDependentCSubstring mntPoint(aTokenizer.nextToken()); SetMountPoint(mntPoint); nsresult errCode; nsCString state(aTokenizer.nextToken()); if (state.EqualsLiteral("X")) { // Special state for creating fake volumes which can't be shared. mCanBeShared = false; SetState(nsIVolume::STATE_MOUNTED); } else { SetState((STATE)state.ToInteger(&errCode)); } break; } case ::ResponseCode::VolumeStateChange: { // Format of the line looks something like: // // Volume sdcard /mnt/sdcard state changed from 7 (Shared-Unmounted) to 1 (Idle-Unmounted) // // So we parse out the state after the string " to " while (aTokenizer.hasMoreTokens()) { nsAutoCString token(aTokenizer.nextToken()); if (token.EqualsLiteral("to")) { nsresult errCode; token = aTokenizer.nextToken(); STATE newState = (STATE)(token.ToInteger(&errCode)); if (newState == nsIVolume::STATE_MOUNTED) { // We set the state to STATE_CHECKMNT here, and the once the // AutoMounter detects that the volume is actually accessible // then the AutoMounter will set the volume as STATE_MOUNTED. SetState(nsIVolume::STATE_CHECKMNT); } else { if (State() == nsIVolume::STATE_CHECKING && newState == nsIVolume::STATE_IDLE) { LOG("Mount of volume '%s' failed", NameStr()); SetState(nsIVolume::STATE_MOUNT_FAIL); } else { SetState(newState); } } break; } } break; } case ::ResponseCode::VolumeDiskInserted: SetMediaPresent(true); break; case ::ResponseCode::VolumeDiskRemoved: // fall-thru case ::ResponseCode::VolumeBadRemoval: SetMediaPresent(false); break; default: LOG("Volume: %s unrecognized reponse code (ignored)", NameStr()); break; } }
void CTAAirMoveType::UpdateLanding() { float3& pos = owner->pos; float3& speed = owner->speed; // We want to land, and therefore cancel our speed first wantedSpeed = ZeroVector; waitCounter++; // Hang around for a while so queued commands have a chance to take effect if (waitCounter < 30) { UpdateAirPhysics(); return; } if (reservedLandingPos.x < 0) { if (CanLandAt(pos)) { // found a landing spot reservedLandingPos = pos; goalPos = pos; owner->physicalState = CSolidObject::OnGround; owner->Block(); owner->physicalState = CSolidObject::Flying; owner->Deactivate(); owner->cob->Call(COBFN_StopMoving); } else { if (goalPos.distance2D(pos) < 30) { goalPos = goalPos + gs->randVector() * 300; goalPos.CheckInBounds(); } flyState = FLY_LANDING; UpdateFlying(); return; } } // We should wait until we actually have stopped smoothly if (speed.SqLength2D() > 1) { UpdateFlying(); return; } // We have stopped, time to land float gah = ground->GetApproximateHeight(pos.x, pos.z); float h = 0.0f; // if aircraft submergible and above water we want height of ocean floor if ((owner->unitDef->canSubmerge) && (gah < 0)) { h = pos.y - gah; wantedHeight = gah; } else { h = pos.y - ground->GetHeight(pos.x, pos.z); wantedHeight = -2; } UpdateAirPhysics(); if (h <= 0) { SetState(AIRCRAFT_LANDED); pos.y = gah; } }
void ComboBox::HandleMouseLeave( int /*x*/, int /*y*/ ) { if( GetState() == PRELIGHT ) { SetState( NORMAL ); } }
void ComboBox::HandleMouseButtonEvent( sf::Mouse::Button button, bool press, int x, int y ) { if( GetState() == State::ACTIVE ) { if( m_scrollbar ) { sf::Event event; event.type = press ? sf::Event::MouseButtonPressed : sf::Event::MouseButtonReleased; event.mouseButton.button = button; event.mouseButton.x = x - static_cast<int>( GetAllocation().left ); event.mouseButton.y = y - static_cast<int>( GetAllocation().top ); ReleaseModal(); m_scrollbar->SetActiveWidget(); m_scrollbar->HandleEvent( event ); SetActiveWidget(); GrabModal(); auto scrollbar_allocation = m_scrollbar->GetAllocation(); scrollbar_allocation.left += GetAllocation().left; scrollbar_allocation.top += GetAllocation().top; if( scrollbar_allocation.contains( static_cast<float>( x ), static_cast<float>( y ) ) ) { return; } } if( !press || ( button != sf::Mouse::Left ) ) { return; } m_active = false; if( ( m_highlighted_item != NONE ) && ( m_active_item != m_highlighted_item ) ) { m_active_item = m_highlighted_item; GetSignals().Emit( OnSelect ); } m_highlighted_item = NONE; if( IsMouseInWidget() ) { SetState( State::PRELIGHT ); } else { SetState( State::NORMAL ); } Invalidate(); return; } if( press && ( button == sf::Mouse::Left ) && IsMouseInWidget() ) { m_active = true; m_highlighted_item = NONE; SetState( State::ACTIVE ); GetSignals().Emit( OnOpen ); Invalidate(); } }