Example #1
0
/**
 * Propagate a livery change to a group's children.
 * @param g Group.
 */
void PropagateChildLivery(const Group *g)
{
	/* Company colour data is indirectly cached. */
	Vehicle *v;
	FOR_ALL_VEHICLES(v) {
		if (v->group_id == g->index && (!v->IsGroundVehicle() || v->IsFrontEngine())) {
			for (Vehicle *u = v; u != nullptr; u = u->Next()) {
				u->colourmap = PAL_NONE;
				u->InvalidateNewGRFCache();
			}
		}
	}

	Group *cg;
	FOR_ALL_GROUPS(cg) {
		if (cg->parent == g->index) {
			if (!HasBit(cg->livery.in_use, 0)) cg->livery.colour1 = g->livery.colour1;
			if (!HasBit(cg->livery.in_use, 1)) cg->livery.colour2 = g->livery.colour2;
			PropagateChildLivery(cg);
		}
	}
}
Example #2
0
bool Controller::AssignFields(templateIO& myArr, std::string type, Vehicle& neededUnit, VehicleGun& newGun)
{
	neededUnit.SetName(myArr.myStringArr[0]);
	neededUnit.SetArmor(true, 0, myArr.myIntArr[0]);
	neededUnit.SetArmor(true, 90, myArr.myIntArr[1]);
	neededUnit.SetArmor(true, 180, myArr.myIntArr[2]);
	neededUnit.SetArmor(false, 0, myArr.myIntArr[3]);
	neededUnit.SetArmor(false, 90, myArr.myIntArr[4]);
	neededUnit.SetArmor(false, 180, myArr.myIntArr[5]);
	neededUnit.SetBDurability(myArr.myIntArr[6]);
	neededUnit.SetTDurability(myArr.myIntArr[7]);
	neededUnit.SetADurability(100);
	neededUnit.SetTMDurability(100);
	neededUnit.SetEDurability(100);
	neededUnit.SetEngineFueled(true);
	neededUnit.MyGun->SetAmmoType(newGun.GetAmmoType());
	neededUnit.MyGun->SetArmorPiercing(newGun.GetArmorPiercing());
	neededUnit.MyGun->SetDamage(newGun.GetDamage());
	neededUnit.MyGun->SetName(newGun.GetName());
	return true;
}
Example #3
0
void 
display(void)
{
	glClearColor(1,1,1,1);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
    glColorMaterial( GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE );

	convertToView();

	glMatrixMode(GL_MODELVIEW);
    glLoadMatrixf( modelViewMatrix );
	glColor4f(1,1,1,1);
	drawFloor(textures[FLOORID]);
	drawWalls(textures[WALLID]);


	//draw the items on the screen
    glRotatef(angle,0,1,0); //rotate the square

	//draw the snowman
	snowman.display();
	snowman2.display();
	snowman3.display();

	//draw the car

	vehicle.display(translateToThirdPerson,
					textures[SIRENID],
					textures[VEHICLEID],
					firstPersonView,
					overheadView);


	

//scoreboard
	sb.setMsg2(msgDamage);

	//draw the Snowdift
	snowcave.display(textures[FLOORID]);
	snowcave2.display(textures[FLOORID]);

	//pond display
	pond.display(textures[PONDID],textures[WATERID]);

	//gifts
	//for (int i=0; i<giftCount;i++)
	//	gifts[i].display();
	glPushMatrix();
	for (int i=0; i<giftCount;i++)
		gifts[i].display();
	glPopMatrix();

	// Tractor Beam Function
	pullInObject();

	glPopMatrix();


	//ScoreBoard()
	glPushMatrix();
	glLoadIdentity();
	if(!overheadView)
		glTranslatef(sbOrigin.x,sbOrigin.y,sbOrigin.z);
	else
		glTranslatef(0,0,-40);

	sb.display(overheadView);
	glPopMatrix();

	drawCieling();


	npc.display(textures[FLOORID]);

	//draw the snowballs in flight
	displayProjectiles();

	glFlush();
    glutSwapBuffers();
}
Example #4
0
void keyBoard( unsigned char key, int x, int y )
{
	static int angle =0;
	 
	if(!gameInPlay)
		return;
    switch( key )  {
		case ' ':
				vehicle.setSpeed(vehicle.getSpeed() + 0.06f);
				break;
		case 0:
				vehicle.setSpeed(-vehicle.getSpeed());
				break;

        case 'i':
			firstPersonRotate.x+=0.2;
			break;
        case 'I':
			firstPersonRotate.x-=0.2;
            break;
        case 'w':
			firstPersonRotate.z+=0.2;
            break;
        case 'W':
			firstPersonRotate.z-=0.2;
            break;
        case 'a':
            translate(1,0,0);
            break;
        case 'd':
            translate(-1,0,0);
            break;
        case 's':
            translate(0,-1,0);
            break;
        case 'S':
            translate(0,1,0);
            break;
		case 'x':
			shadowx++;
			//translate(1,0,0);
			break;
		case 'X':
			shadowx--;
			//translate(1,0,0);
			break;
		case 'z':
			//translate(0,0,1);
			shadowz++;
			break;
		case 'Z':
			//translate(0,0,1);
			shadowz--;
			break;
		case 'y':
			//translate(0,0,1);
			shadowy++;
			break;
		case 'Y':
			//translate(0,0,1);
			shadowy--;
			break;
		case 'p':
			//currMap.printState();
			currMap.printState();
			break;
    }
	vehicle.shadowX=shadowx;
	vehicle.shadowY=shadowy;
	vehicle.shadowZ=shadowz;
	//cout <<" firstPersonRotate = "<<firstPersonRotate.x<<","<<firstPersonRotate.y<<","<<firstPersonRotate.z<<endl;
	//cout <<"Shadow "<<shadowx<<" ,"<<shadowy<<","<<shadowz<<endl;
	//translateToThirdPerson.x += shadowx;
	//translateToThirdPerson.y +=shadowy;
	translateToThirdPerson.y +=shadowz;
    display();
}
Example #5
0
/**
 * Loads the craft from a YAML file.
 * @param node YAML node.
 * @param mod Mod for the saved game.
 * @param save Pointer to the saved game.
 */
void Craft::load(const YAML::Node &node, const Mod *mod, SavedGame *save)
{
	MovingTarget::load(node);
	_id = node["id"].as<int>(_id);
	_fuel = node["fuel"].as<int>(_fuel);
	_damage = node["damage"].as<int>(_damage);

	size_t j = 0;
	for (YAML::const_iterator i = node["weapons"].begin(); i != node["weapons"].end(); ++i)
	{
		if (_rules->getWeapons() > j)
		{
			std::string type = (*i)["type"].as<std::string>();
			if (type != "0" && mod->getCraftWeapon(type))
			{
				CraftWeapon *w = new CraftWeapon(mod->getCraftWeapon(type), 0);
				w->load(*i);
				_weapons[j] = w;
			}
			else
			{
				_weapons[j] = 0;
			}
			j++;
		}
	}

	_items->load(node["items"]);
	for (std::map<std::string, int>::iterator i = _items->getContents()->begin(); i != _items->getContents()->end();)
	{
		if (std::find(mod->getItemsList().begin(), mod->getItemsList().end(), i->first) == mod->getItemsList().end())
		{
			_items->getContents()->erase(i++);
		}
		else
		{
			++i;
		}
	}
	for (YAML::const_iterator i = node["vehicles"].begin(); i != node["vehicles"].end(); ++i)
	{
		std::string type = (*i)["type"].as<std::string>();
		if (mod->getItem(type))
		{
			Vehicle *v = new Vehicle(mod->getItem(type), 0, 4);
			v->load(*i);
			_vehicles.push_back(v);
		}
	}
	_status = node["status"].as<std::string>(_status);
	_lowFuel = node["lowFuel"].as<bool>(_lowFuel);
	_mission = node["mission"].as<bool>(_mission);
	_interceptionOrder = node["interceptionOrder"].as<int>(_interceptionOrder);
	if (const YAML::Node name = node["name"])
	{
		_name = Language::utf8ToWstr(name.as<std::string>());
	}
	if (const YAML::Node &dest = node["dest"])
	{
		std::string type = dest["type"].as<std::string>();
		int id = dest["id"].as<int>();
		if (type == "STR_BASE")
		{
			returnToBase();
		}
		else if (type == "STR_UFO")
		{
			for (std::vector<Ufo*>::iterator i = save->getUfos()->begin(); i != save->getUfos()->end(); ++i)
			{
				if ((*i)->getId() == id)
				{
					setDestination(*i);
					break;
				}
			}
		}
		else if (type == "STR_WAYPOINT")
		{
			for (std::vector<Waypoint*>::iterator i = save->getWaypoints()->begin(); i != save->getWaypoints()->end(); ++i)
			{
				if ((*i)->getId() == id)
				{
					setDestination(*i);
					break;
				}
			}
		}
		else if (type == "STR_ALIEN_BASE")
		{
			for (std::vector<AlienBase*>::iterator i = save->getAlienBases()->begin(); i != save->getAlienBases()->end(); ++i)
			{
				if ((*i)->getId() == id)
				{
					setDestination(*i);
					break;
				}
			}
		}
		else
		{
			// Backwards compatibility
			if (type == "STR_ALIEN_TERROR")
				type = "STR_TERROR_SITE";
			for (std::vector<MissionSite*>::iterator i = save->getMissionSites()->begin(); i != save->getMissionSites()->end(); ++i)
			{
				if ((*i)->getId() == id && (*i)->getDeployment()->getMarkerName() == type)
				{
					setDestination(*i);
					break;
				}
			}
		}
	}
	_takeoff = node["takeoff"].as<int>(_takeoff);
	_inBattlescape = node["inBattlescape"].as<bool>(_inBattlescape);
	if (_inBattlescape)
		setSpeed(0);
}
        void UpdateAI(const uint32 uiDiff)
        {
            npc_escortAI::UpdateAI(uiDiff);

            if (!UpdateVictim())
                return;

            if (uiBuffTimer <= uiDiff)
            {
                if (!me->HasAura(SPELL_SHIELD))
                    DoCastSpellShield();

                uiBuffTimer = urand(30000, 45000);
            }else uiBuffTimer -= uiDiff;

            if (uiChargeTimer <= uiDiff)
            {
                Map::PlayerList const& players = me->GetMap()->GetPlayers();
                if (me->GetMap()->IsDungeon() && !players.isEmpty())
                {
                    for (Map::PlayerList::const_iterator itr = players.begin(); itr != players.end(); ++itr)
                    {
                        Player* player = itr->getSource();
                        if (player && !player->isGameMaster() && me->IsInRange(player, 8.0f, 25.0f, false))
                        {
                            DoResetThreat();
                            me->AddThreat(player, 1.0f);
                            DoCast(player, SPELL_CHARGE);
                            break;
                        }
                    }
                }
                uiChargeTimer = 5000;
            }else uiChargeTimer -= uiDiff;

            //dosen't work at all
            if (uiShieldBreakerTimer <= uiDiff)
            {
                Vehicle* vehicle = me->GetVehicleKit();
                if (!vehicle)
                    return;

                if (Unit* pPassenger = vehicle->GetPassenger(SEAT_ID_0))
                {
                    Map::PlayerList const& players = me->GetMap()->GetPlayers();
                    if (me->GetMap()->IsDungeon() && !players.isEmpty())
                    {
                        for (Map::PlayerList::const_iterator itr = players.begin(); itr != players.end(); ++itr)
                        {
                            Player* player = itr->getSource();
                            if (player && !player->isGameMaster() && me->IsInRange(player, 10.0f, 30.0f, false))
                            {
                                pPassenger->CastSpell(player, SPELL_SHIELD_BREAKER, true);
                                break;
                            }
                        }
                    }
                }
                uiShieldBreakerTimer = 7000;
            }else uiShieldBreakerTimer -= uiDiff;

            DoMeleeAttackIfReady();
        }
Example #7
0
void SSControlSurf::UpdateDrawObjs()
{
    SubSurface::UpdateDrawObjs();

    Vehicle* veh = VehicleMgr.GetVehicle();
    if ( !veh )
    {
        return;
    }
    Geom* geom = veh->FindGeom( m_CompID );
    if ( geom )
    {
        vector< VspSurf > surf_vec;
        geom->GetSurfVec( surf_vec );
        int ncopy = geom->GetNumSymmCopies();

        m_HingeDO.m_PntVec.clear();
        m_HingeDO.m_LineWidth = 2.0;
        m_HingeDO.m_Type = DrawObj::VSP_LINES;
        m_HingeDO.m_GeomID = m_ID + string( "_ss_hinge" );
        m_HingeDO.m_GeomChanged = true;

        m_ArrowDO.m_PntVec.clear();
        m_ArrowDO.m_Type = DrawObj::VSP_SHADED_TRIS;
        m_ArrowDO.m_GeomID = m_ID + string( "_ss_arrow" );
        m_ArrowDO.m_GeomChanged = true;

        for ( int i = 0; i < 4; i++ )
        {
            m_ArrowDO.m_MaterialInfo.Ambient[i] = 0.2;
            m_ArrowDO.m_MaterialInfo.Diffuse[i] = 0.1;
            m_ArrowDO.m_MaterialInfo.Specular[i] = 0.7;
            m_ArrowDO.m_MaterialInfo.Emission[i] = 0.0;
        }
        m_ArrowDO.m_MaterialInfo.Diffuse[3] = 0.5;
        m_ArrowDO.m_MaterialInfo.Shininess = 5.0;


        int isurf = m_MainSurfIndx();

        vector < int > symms = geom->GetSymmIndexs( isurf );
        assert( ncopy == symms.size() );

        int npt = m_UWStart.size();

        for ( int s = 0 ; s < ncopy ; s++ )
        {
            VspSurf* surf = &( surf_vec[ symms[ s ] ] );

            vec3d pst, pend;
            for ( int i = 0; i < npt; i++ )
            {
                pst = pst + surf->CompPnt01( m_UWStart[i].x(), m_UWStart[i].y() );
                pend = pend + surf->CompPnt01( m_UWEnd[i].x(), m_UWEnd[i].y() );
            }
            pst = pst / ( 1.0 * npt );
            pend = pend / ( 1.0 * npt );

            vec3d pmid = ( pst + pend ) * 0.5;

            vec3d dir = pend - pst;
            double len = dir.mag();
            dir.normalize();

            m_HingeDO.m_PntVec.push_back( pst );
            m_HingeDO.m_PntVec.push_back( pend );

            MakeCircleArrow( pmid, dir, 0.25, m_HingeDO, m_ArrowDO );
        }
        m_ArrowDO.m_NormVec = vector <vec3d> ( m_ArrowDO.m_PntVec.size() );
    }
}
Example #8
0
//--------------------------------------------------------------
void testApp::mouseDragged(int x, int y, int button){
 
    Vehicle v;
    v.setup(mouseX, mouseY);
    vehicles.push_back(v);
}
Example #9
0
/**
 * Check the validity of some of the caches.
 * Especially in the sense of desyncs between
 * the cached value and what the value would
 * be when calculated from the 'base' data.
 */
static void CheckCaches()
{
	/* Return here so it is easy to add checks that are run
	 * always to aid testing of caches. */
	if (_debug_desync_level <= 1) return;

	/* Check the town caches. */
	SmallVector<TownCache, 4> old_town_caches;
	Town *t;
	FOR_ALL_TOWNS(t) {
		MemCpyT(old_town_caches.Append(), &t->cache);
	}

	extern void RebuildTownCaches();
	RebuildTownCaches();
	RebuildSubsidisedSourceAndDestinationCache();

	uint i = 0;
	FOR_ALL_TOWNS(t) {
		if (MemCmpT(old_town_caches.Get(i), &t->cache) != 0) {
			DEBUG(desync, 2, "town cache mismatch: town %i", (int)t->index);
		}
		i++;
	}

	/* Check company infrastructure cache. */
	SmallVector<CompanyInfrastructure, 4> old_infrastructure;
	Company *c;
	FOR_ALL_COMPANIES(c) MemCpyT(old_infrastructure.Append(), &c->infrastructure);

	extern void AfterLoadCompanyStats();
	AfterLoadCompanyStats();

	i = 0;
	FOR_ALL_COMPANIES(c) {
		if (MemCmpT(old_infrastructure.Get(i), &c->infrastructure) != 0) {
			DEBUG(desync, 2, "infrastructure cache mismatch: company %i", (int)c->index);
		}
		i++;
	}

	/* Strict checking of the road stop cache entries */
	const RoadStop *rs;
	FOR_ALL_ROADSTOPS(rs) {
		if (IsStandardRoadStopTile(rs->xy)) continue;

		assert(rs->GetEntry(DIAGDIR_NE) != rs->GetEntry(DIAGDIR_NW));
		rs->GetEntry(DIAGDIR_NE)->CheckIntegrity(rs);
		rs->GetEntry(DIAGDIR_NW)->CheckIntegrity(rs);
	}

	Vehicle *v;
	FOR_ALL_VEHICLES(v) {
		extern void FillNewGRFVehicleCache(const Vehicle *v);
		if (v != v->First() || v->vehstatus & VS_CRASHED || !v->IsPrimaryVehicle()) continue;

		uint length = 0;
		for (const Vehicle *u = v; u != NULL; u = u->Next()) length++;

		NewGRFCache        *grf_cache = CallocT<NewGRFCache>(length);
		VehicleCache       *veh_cache = CallocT<VehicleCache>(length);
		GroundVehicleCache *gro_cache = CallocT<GroundVehicleCache>(length);
		TrainCache         *tra_cache = CallocT<TrainCache>(length);

		length = 0;
		for (const Vehicle *u = v; u != NULL; u = u->Next()) {
			FillNewGRFVehicleCache(u);
			grf_cache[length] = u->grf_cache;
			veh_cache[length] = u->vcache;
			switch (u->type) {
				case VEH_TRAIN:
					gro_cache[length] = Train::From(u)->gcache;
					tra_cache[length] = Train::From(u)->tcache;
					break;
				case VEH_ROAD:
					gro_cache[length] = RoadVehicle::From(u)->gcache;
					break;
				default:
					break;
			}
			length++;
		}

		switch (v->type) {
			case VEH_TRAIN:    Train::From(v)->ConsistChanged(CCF_TRACK); break;
			case VEH_ROAD:     RoadVehUpdateCache(RoadVehicle::From(v)); break;
			case VEH_AIRCRAFT: UpdateAircraftCache(Aircraft::From(v));   break;
			case VEH_SHIP:     Ship::From(v)->UpdateCache();             break;
			default: break;
		}

		length = 0;
		for (const Vehicle *u = v; u != NULL; u = u->Next()) {
			FillNewGRFVehicleCache(u);
			if (memcmp(&grf_cache[length], &u->grf_cache, sizeof(NewGRFCache)) != 0) {
				DEBUG(desync, 2, "newgrf cache mismatch: type %i, vehicle %i, company %i, unit number %i, wagon %i", (int)v->type, v->index, (int)v->owner, v->unitnumber, length);
			}
			if (memcmp(&veh_cache[length], &u->vcache, sizeof(VehicleCache)) != 0) {
				DEBUG(desync, 2, "vehicle cache mismatch: type %i, vehicle %i, company %i, unit number %i, wagon %i", (int)v->type, v->index, (int)v->owner, v->unitnumber, length);
			}
			switch (u->type) {
				case VEH_TRAIN:
					if (memcmp(&gro_cache[length], &Train::From(u)->gcache, sizeof(GroundVehicleCache)) != 0) {
						DEBUG(desync, 2, "train ground vehicle cache mismatch: vehicle %i, company %i, unit number %i, wagon %i", v->index, (int)v->owner, v->unitnumber, length);
					}
					if (memcmp(&tra_cache[length], &Train::From(u)->tcache, sizeof(TrainCache)) != 0) {
						DEBUG(desync, 2, "train cache mismatch: vehicle %i, company %i, unit number %i, wagon %i", v->index, (int)v->owner, v->unitnumber, length);
					}
					break;
				case VEH_ROAD:
					if (memcmp(&gro_cache[length], &RoadVehicle::From(u)->gcache, sizeof(GroundVehicleCache)) != 0) {
						DEBUG(desync, 2, "road vehicle ground vehicle cache mismatch: vehicle %i, company %i, unit number %i, wagon %i", v->index, (int)v->owner, v->unitnumber, length);
					}
					break;
				default:
					break;
			}
			length++;
		}

		free(grf_cache);
		free(veh_cache);
		free(gro_cache);
		free(tra_cache);
	}

	/* Check whether the caches are still valid */
	FOR_ALL_VEHICLES(v) {
		byte buff[sizeof(VehicleCargoList)];
		memcpy(buff, &v->cargo, sizeof(VehicleCargoList));
		v->cargo.InvalidateCache();
		assert(memcmp(&v->cargo, buff, sizeof(VehicleCargoList)) == 0);
	}

	Station *st;
	FOR_ALL_STATIONS(st) {
		for (CargoID c = 0; c < NUM_CARGO; c++) {
			byte buff[sizeof(StationCargoList)];
			memcpy(buff, &st->goods[c].cargo, sizeof(StationCargoList));
			st->goods[c].cargo.InvalidateCache();
			assert(memcmp(&st->goods[c].cargo, buff, sizeof(StationCargoList)) == 0);
		}
	}
}
void CFAPI::updateFollowerAcclr(int step, double time, Vehicle& veh, Vehicle predVeh) {

	// Followers controlled by car follow model.
	// Create a new vehicle state with same state as current vehicle.
	// Acclr for new state is calculated here. Position and velocity
	// will be calculated in future when time = currTime + reactionTime;
	Vehicle followerNewState(veh.getId(),
							veh.getPosX(),
							veh.getVel(),
							veh.getAcclr(),
							veh.getHdwayTime(),
							veh.hasSafetyDev(),
							veh.getSafetyDevStartTime());

	double newAcclr = 0.0;
	double newHdwayTime = 0.0;

	if((veh.hasSafetyDev()) &&
		(time >= veh.getSafetyDevStartTime()))
		{
		if(m_adjHdwayTime == HDWAY_SAFE)
		    {
			newAcclr = m_cfModel->getAcclrRespInNetSafe(time, veh, predVeh, newHdwayTime);
		    }
		else
			{
			newAcclr = m_cfModel->getAcclrRespInNetResume(time, veh, predVeh, newHdwayTime);
			}

		std::cout << "Recv safety message: Veh: " << veh.getId()
					<< " at time " << time << std::endl;
		}
	else
		{
		newAcclr = m_cfModel->getAcclrResp(time, veh, predVeh, newHdwayTime);
		}

	// Adjust for unrealistic acclr and decclr values
	if(newAcclr > ACCLR_LIMIT)
		{
		newAcclr = ACCLR_LIMIT;
		}
	if(newAcclr < DECCLR_LIMIT)
		{
		newAcclr = DECCLR_LIMIT;
		}
	std::cout << "Next Acclr: Veh " << veh.getId()
						<< " acclr " << newAcclr << std::endl;

	followerNewState.setAcclr(newAcclr);
	followerNewState.setHdwayTime(newHdwayTime);
	m_vehStateTable[step + m_factor].push_back(followerNewState);
}
Example #11
0
//==== Parm Changed ====//
void LinkMgrSingleton::ParmChanged( const string& pid, bool start_flag  )
{
    //==== Find Parm Ptr ===//
    Parm* parm_ptr = ParmMgr.FindParm( pid );
    if ( !parm_ptr )
        return;

    //==== Check For Advanced Links ====//
    bool adv_link_flag = AdvLinkMgr.IsInputParm( pid );

    //==== Look for Reg Links  ====//
    vector < Link* > parm_link_vec;
    for ( int i = 0 ; i < ( int )m_LinkVec.size() ; i++ )
    {
        if ( m_LinkVec[i]->GetParmA() == pid )
        {
            parm_link_vec.push_back( m_LinkVec[i] );
        }
    }

    //==== Check Links ====//
    bool reg_link_flag = false;
    if ( parm_link_vec.size() )
    {
        reg_link_flag = true;
    }

    //==== Abort if No Links ====//
    if ( !adv_link_flag && !reg_link_flag )
        return;

    //==== Set Link Update Flag ====//
    parm_ptr->SetLinkUpdateFlag( true );
    m_UpdatedParmVec.push_back( parm_ptr->GetID() );

    //==== Update Linked Parms ====//
    for ( int i = 0 ; i < ( int )parm_link_vec.size() ; i++ )
    {
        Link* pl = parm_link_vec[i];
        Parm* pB = ParmMgr.FindParm( pl->GetParmB() );

        if ( pB && ! pB->GetLinkUpdateFlag() )       // Prevent Circular
        {
            double offset = 0.0;
            if ( pl->GetOffsetFlag() )
            {
                offset = pl->m_Offset();
            }
            double scale = 1.0;
            if ( pl->GetScaleFlag() )
            {
                scale = pl->m_Scale();
            }

            double val = parm_ptr->Get() * scale + offset;

            if ( pl->GetLowerLimitFlag() && val < pl->m_LowerLimit() )      // Constraints
            {
                val = pl->m_LowerLimit();
            }

            if ( pl->GetUpperLimitFlag() && val > pl->m_UpperLimit() )      // Constraints
            {
                val = pl->m_UpperLimit();
            }

            pB->SetFromLink( val );
        }
    }

    //==== Update Adv Link ===//
    if ( adv_link_flag )
    {
        AdvLinkMgr.UpdateLinks( pid );
    }

    //==== Clean Up ====/
    if ( start_flag )      
    {
        for ( int i = 0 ; i < ( int )m_UpdatedParmVec.size() ; i++ )
        {
            Parm* p = ParmMgr.FindParm( m_UpdatedParmVec[i] );
            if ( p )
            {
                p->SetLinkUpdateFlag( false );
            }
        }
        m_UpdatedParmVec.clear();

        Vehicle* veh = VehicleMgr.GetVehicle();
        if ( veh )
        {
            veh->ParmChanged( parm_ptr, Parm::SET );
        }
    }
}
Example #12
0
 virtual double GetDiscountRate(Vehicle& vehicle)
 {
     return vehicle.GetBaseDiscountRate();
 }
Example #13
0
void option4()
{
    string inSSN;
    string choice;
    string test;
    string inData;
    Person testUpdatePerson;
    PersonFile * pPersonFile = new PersonFile;
    Person * pPerson = new Person;
    VehicleFile * pVehicleFile = new VehicleFile;
    Vehicle * pVehicle = new Vehicle;
    State * pState = new State;
    County * pCounty = new County;
    VMake * pVMake = new VMake;
    Color * pColor = new Color;
    VType * pVType = new VType;

    while(true)
    {

        PrintHeading4();
        getline(cin,inSSN);
        cin.sync();
        if(inSSN[0] == 'q' || inSSN[0] == 'Q') break;
        *pPerson = pPersonFile->SearchBySSN(inSSN);

        //Ensuring that the Record does not alrady exist
        if(pPerson->IsFound() == true || pPerson->IsDeleted())
        {
            cout << "\n\t\t\tRecord for SSN: " << SSNHyphens(inSSN) << " already exists." << endl;
            test = UserWait();
            if(test[0] == 'q' || test[0] =='Q')
                break;         
            
            continue;
        }
        //This Block only runs if the SSN was not found in the file
        //SetFound is run so the Person can be displayed as before they are written out
        pPerson->SetFound(true);
        pPerson->SetSSN(Trim(inSSN));

        while(true)
        {
            cout << "\n\n\t\tEnter new OLN: ";
            getline(cin, inData);
            cin.sync();
            testUpdatePerson = pPersonFile->SearchByOLN(inData);
             //IsDeleted is included because duplicate OLNs cause issues with SearchByOLN
            if(testUpdatePerson.IsFound() || testUpdatePerson.IsDeleted())
            {
                cout << "\n\t\tOLN Already Exists in File. Choose Different OLN." << endl;
                UserWait();
                system("clear");
                continue;
            }
            break;
        }

        pPerson->SetOLN(Trim(inData));

        cout << "\n\n\t\tEnter new Last Name     : ";
        getline(cin, inData);
        cin.sync();
        pPerson->SetLastName(Trim(inData));

        cout << "\n\n\t\tEnter new First Name    : ";
        getline(cin, inData);
        cin.sync();
        pPerson->SetFirstName(Trim(inData));

        cout << "\n\n\t\tEnter new Middle Initial: ";
        getline(cin, inData);
        cin.sync();
        pPerson->SetMI(Trim(inData));

        cout << "\n\n\t\tEnter new Street Address: ";
        getline(cin, inData);
        cin.sync();
        pPerson->SetStreet(Trim(inData));

        cout << "\n\n\t\tEnter new City          : ";
        getline(cin, inData);
        cin.sync();
        pPerson->SetCity(Trim(inData));

        system("clear");
        cout << "\n\t\tNow Displaying Codes for: State";
        pState->DisplayStates();
        cout << "\n\n\t\tEnter State Code        : ";
        getline(cin, inData);
        cin.sync();
        pPerson->SetStateCode(Trim(inData));

        //Only prompts for County if State is Alabama
        if(pPerson->GetStateCode() != "02")
        {
            pPerson->SetCountyCode("00");
        }
        else
        {
            system("clear");
            cout << "\n\t\tNow Displaying Codes for: County";
            pCounty->DisplayCounties();
            cout << "\n\n\t\tEnter County Code       : ";
            getline(cin, inData);
            cin.sync();
            pPerson->SetCountyCode(Trim(inData));
        } 

        cout << "\n\n\t\tEnter new Zip Code      : ";
        getline(cin, inData);
        cin.sync();
        //Like SSN, the Set takes care of removing hyphens
        pPerson->SetZip(Trim(inData));

        system("clear");
        pPerson->DisplayPerson();
        cout << "\n\t\tAdd Vehicle for this Record? (Y/N): " << flush;
        getline(cin, choice);
        cin.sync();



        //Everything in this if block is Populating the Vehicle Record
        if(choice[0] == 'y' || choice[0] =='Y')
        {
            UserInputVehicle(*pPerson, *pVehicle);
        }



        system("clear");
        pPerson->DisplayPerson();
        pVehicle->DisplayVehicle();
        cout << "\n\t\tCommit Record to File? (Y/N): " << flush;
        getline(cin, choice);
        cin.sync();
        if(choice[0] != 'y' && choice[0] !='Y')
        {
            cout << "\n\t\tRecord not Committed to File. " << endl;
            test = UserWait();
            if(test[0] == 'q' || test[0] =='Q')
                break;         
            continue;         
        }

        pPersonFile->AddPerson(*pPerson);
        pVehicleFile->AddVehicle(*pVehicle);
        cout << "\n\t\tRecord Committed to File." << endl;
        test = UserWait();
        if(test[0] == 'q' || test[0] =='Q')
            break;
    }

    delete pPerson;
    delete pPersonFile;
    delete pVehicle;
    delete pVehicleFile;
    delete pState;
    delete pCounty;
}
void CfdMeshScreen::CallBack( Fl_Widget* w )
{
    bool update_flag = true;

    if ( w == m_CfdMeshUI->rigorLimitButton )
    {
        if ( m_CfdMeshUI->rigorLimitButton->value() )
        {
            CfdMeshMgr.GetGridDensityPtr()->SetRigorLimit( true );
        }
        else
        {
            CfdMeshMgr.GetGridDensityPtr()->SetRigorLimit( false );
        }
    }
    else if ( w == m_CfdMeshUI->farMeshButton )
    {
        if ( m_CfdMeshUI->farMeshButton->value() )
        {
            CfdMeshMgr.GetCfdSettingsPtr()->SetFarMeshFlag( true );
        }
        else
        {
            CfdMeshMgr.GetCfdSettingsPtr()->SetFarMeshFlag( false );
        }
    }
    else if ( w == m_CfdMeshUI->halfMeshButton )
    {
        if ( m_CfdMeshUI->halfMeshButton->value() )
        {
            CfdMeshMgr.GetCfdSettingsPtr()->SetHalfMeshFlag( true );
        }
        else
        {
            CfdMeshMgr.GetCfdSettingsPtr()->SetHalfMeshFlag( false );
        }
    }
    else if ( w == m_CfdMeshUI->finalMeshButton )
    {
        redirecter redir( std::cout, CfdMeshMgr.m_OutStream );
        CfdMeshMgr.GenerateMesh();

        // Hide all geoms.
        Vehicle* veh = m_ScreenMgr->GetVehiclePtr();
        veh->HideAll();
    }
    else if ( w == m_CfdMeshUI->addDefaultsButton )
    {
        CfdMeshMgr.AddDefaultSourcesCurrGeom();
    }

//  else if ( m_FarXScaleSlider->GuiChanged( w ) )
//  {
//      double val = m_FarXScaleSlider->GetVal();
//      bool change = false;
//
//      if ( CfdMeshMgr.GetFarAbsSizeFlag() )
//      {
//          CfdMeshMgr.SetFarAbsSizeFlag( false );
//          change = true;
//      }
//
//      CfdMeshMgr.SetFarXScale( val );
//      CfdMeshMgr.UpdateDomain();
//      char xstr[255];
//      sprintf( xstr, "%0.4f", CfdMeshMgr.GetFarLength() );
//      cfdMeshUI->farXScaleAbsInput->value(xstr);
//
//      if ( change )
//          CfdMeshMgr.SetFarAbsSizeFlag( true );
//
//      update_flag = false;
//  }
//  else if ( m_FarYScaleSlider->GuiChanged( w ) )
//  {
//      double val = m_FarYScaleSlider->GetVal();
//      bool change = false;
//
//      if ( CfdMeshMgr.GetFarAbsSizeFlag() )
//      {
//          CfdMeshMgr.SetFarAbsSizeFlag( false );
//          change = true;
//      }
//
//      CfdMeshMgr.SetFarYScale( val );
//      CfdMeshMgr.UpdateDomain();
//      char ystr[255];
//      sprintf( ystr, "%0.4f", CfdMeshMgr.GetFarWidth() );
//      cfdMeshUI->farYScaleAbsInput->value(ystr);
//
//      if ( change )
//          CfdMeshMgr.SetFarAbsSizeFlag( true );
//
//      update_flag = false;
//  }
//  else if ( m_FarZScaleSlider->GuiChanged( w ) )
//  {
//      double val = m_FarZScaleSlider->GetVal();
//      bool change = false;
//
//      if ( CfdMeshMgr.GetFarAbsSizeFlag() )
//      {
//          CfdMeshMgr.SetFarAbsSizeFlag( false );
//          change = true;
//      }
//
//      CfdMeshMgr.SetFarZScale( val );
//      CfdMeshMgr.UpdateDomain();
//      char zstr[255];
//      sprintf( zstr, "%0.4f", CfdMeshMgr.GetFarHeight() );
//      cfdMeshUI->farZScaleAbsInput->value(zstr);
//
//      if ( change )
//          CfdMeshMgr.SetFarAbsSizeFlag( true );
//
//      update_flag = false;
//  }

//  else if ( w == cfdMeshUI->SourceNameInput )
//  {
//      CfdMeshMgr.GUI_Val( "SourceName", cfdMeshUI->SourceNameInput->value() );
//  }

    else if ( w == m_CfdMeshUI->compChoice )
    {
        //==== Load List of Parts for Comp ====//
        int id = m_CfdMeshUI->compChoice->value();
        CfdMeshMgr.SetCurrSourceGeomID( m_GeomVec[ id ] );
        CfdMeshMgr.SetCurrMainSurfIndx( 0 );
    }
    else if ( w == m_CfdMeshUI->surfChoice )
    {
        int id = m_CfdMeshUI->surfChoice->value();
        CfdMeshMgr.SetCurrMainSurfIndx( id );
    }
    else if ( w == m_CfdMeshUI->wakeCompChoice )
    {
        //==== Load List of Parts for Comp ====//
        int id = m_CfdMeshUI->wakeCompChoice->value();
        CfdMeshMgr.SetWakeGeomID( m_WingGeomVec[ id ] );
    }
    else if ( w == m_CfdMeshUI->farCompChoice )
    {
        //==== Load List of Parts for Comp ====//
        int id = m_CfdMeshUI->farCompChoice->value();
        CfdMeshMgr.GetCfdSettingsPtr()->SetFarGeomID( m_GeomVec[ id ] );
    }
    else if ( w == m_CfdMeshUI->sourceBrowser )
    {
        CfdMeshMgr.GUI_Val( "SourceID", m_CfdMeshUI->sourceBrowser->value() - 1 );
    }
    else if ( w == m_CfdMeshUI->setChoice )
    {
        CfdMeshMgr.GetCfdSettingsPtr()->m_SelectedSetIndex = m_CfdMeshUI->setChoice->value();
    }
    else if ( w == m_CfdMeshUI->addSourceButton )
    {
        int type = m_CfdMeshUI->sourceTypeChoice->value();
        if ( type >= 0 && type < vsp::NUM_SOURCE_TYPES )
        {
            CfdMeshMgr.AddSource( type );
        }
    }
    else if ( w == m_CfdMeshUI->deleteSourceButton )
    {
        CfdMeshMgr.DeleteCurrSource();
    }
    else if ( w == m_CfdMeshUI->adjLenDownButton )
    {
        CfdMeshMgr.AdjustAllSourceLen( 1.0 / 1.1 );
    }
    else if ( w == m_CfdMeshUI->adjLenUpButton )
    {
        CfdMeshMgr.AdjustAllSourceLen( 1.1 );
    }
    else if ( w == m_CfdMeshUI->adjLenDownDownButton )
    {
        CfdMeshMgr.AdjustAllSourceLen( 1.0 / 1.5 );
    }
    else if ( w == m_CfdMeshUI->adjLenUpUpButton )
    {
        CfdMeshMgr.AdjustAllSourceLen( 1.5 );
    }
    else if ( w == m_CfdMeshUI->adjRadDownButton )
    {
        CfdMeshMgr.AdjustAllSourceRad( 1.0 / 1.1 );
    }
    else if ( w == m_CfdMeshUI->adjRadUpButton )
    {
        CfdMeshMgr.AdjustAllSourceRad( 1.1 );
    }
    else if ( w == m_CfdMeshUI->adjRadDownDownButton )
    {
        CfdMeshMgr.AdjustAllSourceRad( 1.0 / 1.5 );
    }
    else if ( w == m_CfdMeshUI->adjRadUpUpButton )
    {
        CfdMeshMgr.AdjustAllSourceRad( 1.5 );
    }

    else if ( w == m_CfdMeshUI->datButton )
    {
        string newfile = m_ScreenMgr->GetSelectFileScreen()->FileChooser( "Select NASCART .dat file.", "*.dat" );
        if ( newfile.compare( "" ) != 0 )
        {
            CfdMeshMgr.GetCfdSettingsPtr()->SetExportFileName( newfile, vsp::CFD_DAT_FILE_NAME );
        }
    }
    else if ( w == m_CfdMeshUI->keyButton )
    {
        string newfile = m_ScreenMgr->GetSelectFileScreen()->FileChooser( "Select NASCART .key file.", "*.key" );
        if ( newfile.compare( "" ) != 0 )
        {
            CfdMeshMgr.GetCfdSettingsPtr()->SetExportFileName( newfile, vsp::CFD_KEY_FILE_NAME );
        }
    }
    else if ( w == m_CfdMeshUI->objButton  )
    {
        string newfile = m_ScreenMgr->GetSelectFileScreen()->FileChooser( "Select .obj file.", "*.obj" );
        if ( newfile.compare( "" ) != 0 )
        {
            CfdMeshMgr.GetCfdSettingsPtr()->SetExportFileName( newfile, vsp::CFD_OBJ_FILE_NAME );
        }
    }
    else if ( w == m_CfdMeshUI->polyButton )
    {
        string newfile = m_ScreenMgr->GetSelectFileScreen()->FileChooser( "Select .poly file.", "*.poly" );
        if ( newfile.compare( "" ) != 0 )
        {
            CfdMeshMgr.GetCfdSettingsPtr()->SetExportFileName( newfile, vsp::CFD_POLY_FILE_NAME );
        }
    }
    else if ( w == m_CfdMeshUI->stlButton )
    {
        string newfile = m_ScreenMgr->GetSelectFileScreen()->FileChooser( "Select .stl file.", "*.stl" );
        if ( newfile.compare( "" ) != 0 )
        {
            CfdMeshMgr.GetCfdSettingsPtr()->SetExportFileName( newfile, vsp::CFD_STL_FILE_NAME );
        }
    }
    else if ( w == m_CfdMeshUI->triButton )
    {
        string newfile = m_ScreenMgr->GetSelectFileScreen()->FileChooser( "Select .tri file.", "*.tri" );
        if ( newfile.compare( "" ) != 0 )
        {
            CfdMeshMgr.GetCfdSettingsPtr()->SetExportFileName( newfile, vsp::CFD_TRI_FILE_NAME );
        }
    }
    else if ( w == m_CfdMeshUI->gmshButton )
    {
        string newfile = m_ScreenMgr->GetSelectFileScreen()->FileChooser( "Select .msh file.", "*.msh" );
        if ( newfile.compare( "" ) != 0 )
        {
            CfdMeshMgr.GetCfdSettingsPtr()->SetExportFileName( newfile, vsp::CFD_GMSH_FILE_NAME );
        }
    }
    else if ( w == m_CfdMeshUI->srfButton )
    {
        string newfile = m_ScreenMgr->GetSelectFileScreen()->FileChooser( "Select .srf file.", "*.srf" );
        if ( newfile.compare( "" ) != 0 )
        {
            CfdMeshMgr.GetCfdSettingsPtr()->SetExportFileName( newfile, vsp::CFD_SRF_FILE_NAME );
        }
    }
    else if ( w == m_CfdMeshUI->tkeyButton )
    {
        string newfile = m_ScreenMgr->GetSelectFileScreen()->FileChooser( "Select .tkey file.", "*.tkey" );
        if ( newfile.compare( "" ) != 0 )
	    {
            CfdMeshMgr.GetCfdSettingsPtr()->SetExportFileName( newfile, vsp::CFD_TKEY_FILE_NAME );
	    }
    }

    else if ( w == m_CfdMeshUI->addWakeButton )
    {
        bool flag = !!( m_CfdMeshUI->addWakeButton->value() );

        vector<string> geomVec = m_Vehicle->GetGeomVec();
        string wakeGeomID = CfdMeshMgr.GetWakeGeomID();
        Geom* g = m_Vehicle->FindGeom( wakeGeomID );
        if ( g )
        {
            g->SetWakeActiveFlag( flag );
        }
    }
    else if ( w == m_CfdMeshUI->farBoxGenButton )
    {
        CfdMeshMgr.GetCfdSettingsPtr()->SetFarCompFlag( false );
    }
    else if ( w == m_CfdMeshUI->farComponentGenButton )
    {
        CfdMeshMgr.GetCfdSettingsPtr()->SetFarCompFlag( true );
    }
    else if ( w == m_CfdMeshUI->farCenLocButton )
    {
        CfdMeshMgr.GetCfdSettingsPtr()->SetFarManLocFlag( false );
    }
    else if ( w == m_CfdMeshUI->farManLocButton )
    {
        CfdMeshMgr.GetCfdSettingsPtr()->SetFarManLocFlag( true );
    }
    else if ( w == m_CfdMeshUI->farRelSizeButton )
    {
        CfdMeshMgr.GetCfdSettingsPtr()->SetFarAbsSizeFlag( false );
    }
    else if ( w == m_CfdMeshUI->farAbsSizeButton )
    {
        CfdMeshMgr.GetCfdSettingsPtr()->SetFarAbsSizeFlag( true );
    }
//  else if ( w == m_CfdMeshUI->farXScaleAbsInput )
//  {
//      bool change = false;
//
//      if ( !CfdMeshMgr.GetFarAbsSizeFlag() )
//      {
//          CfdMeshMgr.SetFarAbsSizeFlag( true );
//          change = true;
//      }
//
//      double val = atof( m_CfdMeshUI->farXScaleAbsInput->value() );
//      CfdMeshMgr.SetFarLength( val );
//      CfdMeshMgr.UpdateDomain();
//      double scale = CfdMeshMgr.GetFarXScale();
//      m_FarXScaleSlider.SetVal( scale );
//      m_FarXScaleSlider.UpdateGui();
//
//      update_flag = false;
//
//      if ( change )
//          CfdMeshMgr.SetFarAbsSizeFlag( false );
//  }
//
//  else if ( w == m_CfdMeshUI->farYScaleAbsInput )
//  {
//      bool change = false;
//
//      if ( !CfdMeshMgr.GetFarAbsSizeFlag() )
//      {
//          CfdMeshMgr.SetFarAbsSizeFlag( true );
//          change = true;
//      }
//
//      double val = atof( m_CfdMeshUI->farYScaleAbsInput->value() );
//      CfdMeshMgr.SetFarWidth( val );
//      CfdMeshMgr.UpdateDomain();
//      double scale = CfdMeshMgr.GetFarYScale();
//      m_FarYScaleSlider.SetVal( scale );
//      m_FarYScaleSlider.UpdateGui();
//
//      update_flag = false;
//
//      if ( change )
//          CfdMeshMgr.SetFarAbsSizeFlag( false );
//  }
//
//  else if ( w == m_CfdMeshUI->farZScaleAbsInput )
//  {
//      bool change = false;
//
//      if ( !CfdMeshMgr.GetFarAbsSizeFlag() )
//      {
//          CfdMeshMgr.SetFarAbsSizeFlag( true );
//          change = true;
//      }
//
//      double val = atof( m_CfdMeshUI->farZScaleAbsInput->value() );
//      CfdMeshMgr.SetFarHeight( val );
//      CfdMeshMgr.UpdateDomain();
//      double scale = CfdMeshMgr.GetFarZScale();
//      m_FarZScaleSlider.SetVal( scale );
//      m_FarZScaleSlider.UpdateGui();
//
//      update_flag = false;
//
//      if ( change )
//          CfdMeshMgr.SetFarAbsSizeFlag( false );
//  }

    if ( update_flag )
    {
        Update();
    }

    m_ScreenMgr->SetUpdateFlag( true );

}
/**
 * Change the company's company-colour
 * @param tile unused
 * @param flags operation to perform
 * @param p1 bitstuffed:
 * p1 bits 0-7 scheme to set
 * p1 bits 8-9 set in use state or first/second colour
 * @param p2 new colour for vehicles, property, etc.
 * @param text unused
 * @return the cost of this operation or an error
 */
CommandCost CmdSetCompanyColour(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
	Colours colour = Extract<Colours, 0, 4>(p2);
	LiveryScheme scheme = Extract<LiveryScheme, 0, 8>(p1);
	byte state = GB(p1, 8, 2);

	if (scheme >= LS_END || state >= 3 || colour == INVALID_COLOUR) return CMD_ERROR;

	Company *c = Company::Get(_current_company);

	/* Ensure no two companies have the same primary colour */
	if (scheme == LS_DEFAULT && state == 0) {
		const Company *cc;
		FOR_ALL_COMPANIES(cc) {
			if (cc != c && cc->colour == colour) return CMD_ERROR;
		}
	}

	if (flags & DC_EXEC) {
		switch (state) {
			case 0:
				c->livery[scheme].colour1 = colour;

				/* If setting the first colour of the default scheme, adjust the
				 * original and cached company colours too. */
				if (scheme == LS_DEFAULT) {
					_company_colours[_current_company] = colour;
					c->colour = colour;
					CompanyAdminUpdate(c);
				}
				break;

			case 1:
				c->livery[scheme].colour2 = colour;
				break;

			case 2:
				c->livery[scheme].in_use = colour != 0;

				/* Now handle setting the default scheme's in_use flag.
				 * This is different to the other schemes, as it signifies if any
				 * scheme is active at all. If this flag is not set, then no
				 * processing of vehicle types occurs at all, and only the default
				 * colours will be used. */

				/* If enabling a scheme, set the default scheme to be in use too */
				if (colour != 0) {
					c->livery[LS_DEFAULT].in_use = true;
					break;
				}

				/* Else loop through all schemes to see if any are left enabled.
				 * If not, disable the default scheme too. */
				c->livery[LS_DEFAULT].in_use = false;
				for (scheme = LS_DEFAULT; scheme < LS_END; scheme++) {
					if (c->livery[scheme].in_use) {
						c->livery[LS_DEFAULT].in_use = true;
						break;
					}
				}
				break;

			default:
				break;
		}
		ResetVehicleColourMap();
		MarkWholeScreenDirty();

		/* All graph related to companies use the company colour. */
		InvalidateWindowData(WC_INCOME_GRAPH, 0);
		InvalidateWindowData(WC_OPERATING_PROFIT, 0);
		InvalidateWindowData(WC_DELIVERED_CARGO, 0);
		InvalidateWindowData(WC_PERFORMANCE_HISTORY, 0);
		InvalidateWindowData(WC_COMPANY_VALUE, 0);
		/* The smallmap owner view also stores the company colours. */
		BuildOwnerLegend();
		InvalidateWindowData(WC_SMALLMAP, 0, 1);

		/* Company colour data is indirectly cached. */
		Vehicle *v;
		FOR_ALL_VEHICLES(v) {
			if (v->owner == _current_company) v->InvalidateNewGRFCache();
		}

		extern void UpdateObjectColours(const Company *c);
		UpdateObjectColours(c);
	}
	return CommandCost();
}
        void UpdateAI(const uint32 diff)
        {
            if (!UpdateVictim())
                return;

            events.Update(diff);

            if (me->HasUnitState(UNIT_STAT_CASTING))
                return;
            
            if (events.GetTimer() > 15000 && !me->IsWithinMeleeRange(me->getVictim()))
                DoCastAOE(SPELL_PETRIFY_BREATH, true);
        
            if (!left && !right)
                DoCast(me, SPELL_STONE_SHOUT, true);

            switch(events.GetEvent())
            {
                case EVENT_NONE: break;
                case EVENT_SMASH:
                    if (left && right)
                    {
                        if (me->IsWithinMeleeRange(me->getVictim()))
                            DoCastVictim(SPELL_TWO_ARM_SMASH, true);
                    }
                    else if (left || right)
                    {
                        if (me->IsWithinMeleeRange(me->getVictim()))
                            DoCastVictim(SPELL_ONE_ARM_SMASH, true);
                    }
                    events.RescheduleEvent(EVENT_SMASH, 15000);
                    break;
                case EVENT_SWEEP:
                    if (left)
                        DoCastAOE(SPELL_ARM_SWEEP, true);
                    events.RescheduleEvent(EVENT_SWEEP, 15000);
                    break;
                case EVENT_GRIP:
                    if (right && instance)
                    {
                        if (Unit* RightArm = vehicle->GetPassenger(1))
                        {
                            me->MonsterTextEmote(EMOTE_STONE, 0, true);
                            DoScriptText(SAY_GRAB_PLAYER, me);
                            // Grip up to 3 players
                            for (int32 n = 0; n < RAID_MODE(1, 3); ++n)
                            {
                                if (Unit *pTarget = SelectTarget(SELECT_TARGET_RANDOM, 1, 40, true))
                                    GripTargetGUID[n] = pTarget->GetGUID();
                            }
                            RightArm->ToCreature()->AI()->DoAction(ACTION_GRIP);
                        }
                    }
                    events.RescheduleEvent(EVENT_GRIP, 40000);
                    break;
                case EVENT_SHOCKWAVE:
                    if (left)
                    {
                        DoScriptText(SAY_SHOCKWAVE, me);
                        DoCastAOE(SPELL_SHOCKWAVE, true);
                        DoCastAOE(SPELL_SHOCKWAVE_VISUAL, true);
                    }
                    events.RescheduleEvent(EVENT_SHOCKWAVE, urand(15000, 25000));
                    break;
                case EVENT_EYEBEAM:
                    if (Unit *pTarget = SelectTarget(SELECT_TARGET_FARTHEST, 0, 50, true))
                    {
                        if (Creature* EyeBeam = me->SummonCreature(NPC_EYEBEAM_1,pTarget->GetPositionX(),pTarget->GetPositionY()+3,pTarget->GetPositionZ(),0,TEMPSUMMON_TIMED_DESPAWN,10000))
                        {
                            EyeBeam->CastSpell(me, SPELL_EYEBEAM_VISUAL_1, true);
                            EyeBeam->AI()->AttackStart(pTarget);
                        }
                        if (Creature* EyeBeam = me->SummonCreature(NPC_EYEBEAM_2,pTarget->GetPositionX(),pTarget->GetPositionY()-3,pTarget->GetPositionZ(),0,TEMPSUMMON_TIMED_DESPAWN,10000))
                        {
                            EyeBeam->CastSpell(me, SPELL_EYEBEAM_VISUAL_2, true);
                            EyeBeam->AI()->AttackStart(pTarget);
                        }
                    }
                    events.RescheduleEvent(EVENT_EYEBEAM, 20000);
                    break;
                case EVENT_LEFT:
                    if (Unit* LeftArm = me->SummonCreature(NPC_LEFT_ARM, me->GetPositionX(), me->GetPositionY(), me->GetPositionZ(), me->GetOrientation()))
                    {
                        LeftArm->EnterVehicle(vehicle, 0);
                        DoCast(me, SPELL_ARM_RESPAWN, true);
                        me->MonsterTextEmote(EMOTE_LEFT, 0, true);
                        if (instance)
                            instance->DoStopTimedAchievement(ACHIEVEMENT_TIMED_TYPE_EVENT, ACHIEV_DISARMED_START_EVENT);
                    }
                    events.CancelEvent(EVENT_LEFT);
                    break;                
                case EVENT_RIGHT:
                    if (Unit* RightArm = me->SummonCreature(NPC_RIGHT_ARM, me->GetPositionX(), me->GetPositionY(), me->GetPositionZ(), me->GetOrientation()))
                    {
                        RightArm->EnterVehicle(vehicle, 1);
                        DoCast(me, SPELL_ARM_RESPAWN, true);
                        me->MonsterTextEmote(EMOTE_RIGHT, 0, true);
                        if (instance)
                            instance->DoStopTimedAchievement(ACHIEVEMENT_TIMED_TYPE_EVENT, ACHIEV_DISARMED_START_EVENT);
                    }
                    events.CancelEvent(EVENT_RIGHT);
                    break;
            }

            DoMeleeAttackIfReady();
        }
Example #17
0
void GUI::paintEvent(QPaintEvent *event) {
    event->accept();
    //rysowanie pojazdu
    if(this->vehicles.size() == 0 || currentVehicle < 0 || currentVehicle >= vehicles.size()) return;

    QPainter painter(this);


    Vehicle v = this->vehicles[currentVehicle];
    double length = v.getLength();
    unsigned axles = v.getAxlesNumber();
    double positions[axles];
    for(unsigned i = 0; i < axles; i++) {
        positions[i] = v.getAxlePosition(i);
    }

    const double scale = 1000 / this->scale_length; //1000pix = 24m;

    QPoint vehicleStart, vehicleEnd;
    vehicleStart.setX(this->startx);
    vehicleEnd.setX(this->startx + length * scale);
    vehicleStart.setY(this->starty);
    vehicleEnd.setY(this->starty + this->v_height);

    QRect vehicle;
    vehicle.setTopLeft(vehicleStart);
    vehicle.setBottomRight(vehicleEnd);

    painter.drawRoundedRect(vehicle, 40, 10);
    painter.fillRect(vehicle, QColor(0, 0, 0, 70));


    for(unsigned i = 0; i < axles; i++) {
        //sprawdz warunek na podniesionÄ… oÅ›
        unsigned axle_offset_y = 0;
        if(axles == 5 && v.is5up() && i == 2) axle_offset_y = -5;// 3 os auta 5 os. z podniesionÄ… osiÄ…
        QPoint center;
        center.setX(this->startx + scale * positions[i]);
        center.setY(this->starty + this->v_height + axle_offset_y);

        painter.setBrush(QWidget::palette().color(QWidget::backgroundRole()));
        painter.setPen(QWidget::palette().color(QWidget::backgroundRole()));
        painter.drawEllipse(center, this->wheel_size + 5, this->wheel_size + 5);
        painter.setPen(Qt::black);
        painter.setBrush(Qt::black);
        painter.drawEllipse(center, this->wheel_size, this->wheel_size);
        painter.setBrush(Qt::white);
        painter.drawEllipse(center, this->wheel_size - 5, this->wheel_size - 5);
    }

    const unsigned scale_offset = 100;
    QPoint scaleStart, scaleEnd;
    scaleStart.setX(this->startx);
    scaleStart.setY(this->starty + this->v_height + scale_offset);
    scaleEnd.setX(this->startx + scale * this->scale_length);
    scaleEnd.setY(this->starty + this->v_height + scale_offset);

    painter.drawLine(scaleStart, scaleEnd);

    //rysuj skale co 4m
    for(int pos = 0; pos <= this->scale_length; pos += 4) {
        QPoint scaleTop, scaleBottom, scaleCenter;

        scaleTop.setX(this->startx + pos * scale);
        scaleTop.setY(this->starty + this->v_height + scale_offset - 10);
        scaleBottom.setX(this->startx + pos * scale);
        scaleBottom.setY(this->starty + this->v_height + scale_offset + 10);
        scaleCenter.setX(this->startx + pos * scale);
        scaleCenter.setY(this->starty + this->v_height + scale_offset);

        painter.drawLine(scaleTop, scaleBottom);
        painter.drawText(scaleCenter, QString::number(pos) + QString("m"));
    }

    //rysuj wartości położenia dla osi
    //długość pojazdu
    QPoint vehicleLengthStart, vehicleLengthEnd;
    QPoint scaleTop, scaleBottom, scaleCenter;

    vehicleLengthStart.setX(this->startx);
    vehicleLengthEnd.setX(this->startx + length * scale);
    vehicleLengthStart.setY(this->starty + this->v_height + 70);
    vehicleLengthEnd.setY(this->starty + this->v_height + 70);

    painter.drawLine(vehicleLengthStart, vehicleLengthEnd);
    scaleCenter.setX((this->startx + length * scale + this->startx) / 2);
    scaleCenter.setY(this->starty + this->v_height + 70);

    painter.drawText(scaleCenter, QString().sprintf("%.2f", length) + QString("m"));

    //podzialka na początku i końcu
    scaleTop.setX(this->startx);
    scaleTop.setY(this->starty + this->v_height + 70 - 10);
    scaleBottom.setX(this->startx);
    scaleBottom.setY(this->starty + this->v_height + 70 + 10);
    painter.drawLine(scaleTop, scaleBottom);

    scaleTop.setX(this->startx + length * scale);
    scaleTop.setY(this->starty + this->v_height + 70 - 10);
    scaleBottom.setX(this->startx + length * scale);
    scaleBottom.setY(this->starty + this->v_height + 70 + 10);
    painter.drawLine(scaleTop, scaleBottom);

    //odległości między osiami
    double start = 0;
    double end = 0;
    //poczÄ…tek do osi 1
    start = 0;
    end = positions[0];
    scaleStart.setX(this->startx);
    scaleEnd.setX(this->startx + end * scale);
    scaleStart.setY(this->starty + this->v_height + 40);
    scaleEnd.setY(this->starty + this->v_height + 40);

    painter.drawLine(scaleStart, scaleEnd);
    scaleCenter.setX((this->startx + end * scale + this->startx) / 2);
    scaleCenter.setY(this->starty + this->v_height + 40);

    painter.drawText(scaleCenter, QString().sprintf("%.2f", end) + QString("m"));

    //podzialka na początku i końcu
    scaleTop.setX(this->startx);
    scaleTop.setY(this->starty + this->v_height + 40 - 10);
    scaleBottom.setX(this->startx);
    scaleBottom.setY(this->starty + this->v_height + 40 + 10);
    painter.drawLine(scaleTop, scaleBottom);

    scaleTop.setX(this->startx + end * scale);
    scaleTop.setY(this->starty + this->v_height + 40 - 10);
    scaleBottom.setX(this->startx + end * scale);
    scaleBottom.setY(this->starty + this->v_height + 40 + 10);
    painter.drawLine(scaleTop, scaleBottom);

    for(unsigned axle = 0; axle < axles - 1; axle++) {
        start = end;
        end = positions[axle + 1];
        scaleStart.setX(this->startx + start * scale);
        scaleEnd.setX(this->startx + end * scale);
        scaleStart.setY(starty + this->v_height + 40);
        scaleEnd.setY(starty + this->v_height + 40);

        painter.drawLine(scaleStart, scaleEnd);
        scaleCenter.setX((this->startx + end * scale + this->startx + start * scale) / 2);
        scaleCenter.setY(this->starty + this->v_height + 40);

        painter.drawText(scaleCenter, QString().sprintf("%.2f", end - start) + QString("m"));

        //podzialka na początku i końcu
        scaleTop.setX(this->startx + start * scale);
        scaleTop.setY(this->starty + this->v_height + 40 - 10);
        scaleBottom.setX(this->startx + start * scale);
        scaleBottom.setY(this->starty + this->v_height + 40 + 10);
        painter.drawLine(scaleTop, scaleBottom);

        scaleTop.setX(this->startx + end * scale);
        scaleTop.setY(this->starty + this->v_height + 40 - 10);
        scaleBottom.setX(this->startx + end * scale);
        scaleBottom.setY(this->starty + this->v_height + 40 + 10);
        painter.drawLine(scaleTop, scaleBottom);
    }
    //koniec pojazdu

    start = end;
    end = length;
    scaleStart.setX(this->startx + start * scale);
    scaleEnd.setX(this->startx + end * scale);
    scaleStart.setY(this->starty + this->v_height + 40);
    scaleEnd.setY(this->starty + this->v_height + 40);

    painter.drawLine(scaleStart, scaleEnd);
    scaleCenter.setX((this->startx + end * scale + this->startx + start * scale) / 2);
    scaleCenter.setY(this->starty + this->v_height + 40);

    painter.drawText(scaleCenter, QString().sprintf("%.2f", end - start) + QString("m"));

    //podzialka na początku i końcu
    scaleTop.setX(this->startx + start * scale);
    scaleTop.setY(this->starty + this->v_height + 40 - 10);
    scaleBottom.setX(this->startx + start * scale);
    scaleBottom.setY(this->starty + this->v_height + 40 + 10);
    painter.drawLine(scaleTop, scaleBottom);

    scaleTop.setX(this->startx + end * scale);
    scaleTop.setY(this->starty + this->v_height + 40 - 10);
    scaleBottom.setX(this->startx + end * scale);
    scaleBottom.setY(this->starty + this->v_height + 40 + 10);
    painter.drawLine(scaleTop, scaleBottom);

}
Example #18
0
/**
 * Replace a whole vehicle chain
 * @param chain vehicle chain to let autoreplace/renew operator on
 * @param flags command flags
 * @param wagon_removal remove wagons when the resulting chain occupies more tiles than the old did
 * @param nothing_to_do is set to 'false' when something was done (only valid when not failed)
 * @return cost or error
 */
static CommandCost ReplaceChain(Vehicle **chain, DoCommandFlag flags, bool wagon_removal, bool *nothing_to_do)
{
	Vehicle *old_head = *chain;
	assert(old_head->IsPrimaryVehicle());

	CommandCost cost = CommandCost(EXPENSES_NEW_VEHICLES, 0);

	if (old_head->type == VEH_TRAIN) {
		/* Store the length of the old vehicle chain, rounded up to whole tiles */
		uint16 old_total_length = CeilDiv(Train::From(old_head)->gcache.cached_total_length, TILE_SIZE) * TILE_SIZE;

		int num_units = 0; ///< Number of units in the chain
		for (Train *w = Train::From(old_head); w != NULL; w = w->GetNextUnit()) num_units++;

		Train **old_vehs = CallocT<Train *>(num_units); ///< Will store vehicles of the old chain in their order
		Train **new_vehs = CallocT<Train *>(num_units); ///< New vehicles corresponding to old_vehs or NULL if no replacement
		Money *new_costs = MallocT<Money>(num_units);   ///< Costs for buying and refitting the new vehicles

		/* Collect vehicles and build replacements
		 * Note: The replacement vehicles can only successfully build as long as the old vehicles are still in their chain */
		int i;
		Train *w;
		for (w = Train::From(old_head), i = 0; w != NULL; w = w->GetNextUnit(), i++) {
			assert(i < num_units);
			old_vehs[i] = w;

			CommandCost ret = BuildReplacementVehicle(old_vehs[i], (Vehicle**)&new_vehs[i], true);
			cost.AddCost(ret);
			if (cost.Failed()) break;

			new_costs[i] = ret.GetCost();
			if (new_vehs[i] != NULL) *nothing_to_do = false;
		}
		Train *new_head = (new_vehs[0] != NULL ? new_vehs[0] : old_vehs[0]);

		/* Note: When autoreplace has already failed here, old_vehs[] is not completely initialized. But it is also not needed. */
		if (cost.Succeeded()) {
			/* Separate the head, so we can start constructing the new chain */
			Train *second = Train::From(old_head)->GetNextUnit();
			if (second != NULL) cost.AddCost(CmdMoveVehicle(second, NULL, DC_EXEC | DC_AUTOREPLACE, true));

			assert(Train::From(new_head)->GetNextUnit() == NULL);

			/* Append engines to the new chain
			 * We do this from back to front, so that the head of the temporary vehicle chain does not change all the time.
			 * That way we also have less trouble when exceeding the unitnumber limit.
			 * OTOH the vehicle attach callback is more expensive this way :s */
			Train *last_engine = NULL; ///< Shall store the last engine unit after this step
			if (cost.Succeeded()) {
				for (int i = num_units - 1; i > 0; i--) {
					Train *append = (new_vehs[i] != NULL ? new_vehs[i] : old_vehs[i]);

					if (RailVehInfo(append->engine_type)->railveh_type == RAILVEH_WAGON) continue;

					if (new_vehs[i] != NULL) {
						/* Move the old engine to a separate row with DC_AUTOREPLACE. Else
						 * moving the wagon in front may fail later due to unitnumber limit.
						 * (We have to attach wagons without DC_AUTOREPLACE.) */
						CmdMoveVehicle(old_vehs[i], NULL, DC_EXEC | DC_AUTOREPLACE, false);
					}

					if (last_engine == NULL) last_engine = append;
					cost.AddCost(CmdMoveVehicle(append, new_head, DC_EXEC, false));
					if (cost.Failed()) break;
				}
				if (last_engine == NULL) last_engine = new_head;
			}

			/* When wagon removal is enabled and the new engines without any wagons are already longer than the old, we have to fail */
			if (cost.Succeeded() && wagon_removal && new_head->gcache.cached_total_length > old_total_length) cost = CommandCost(STR_ERROR_TRAIN_TOO_LONG_AFTER_REPLACEMENT);

			/* Append/insert wagons into the new vehicle chain
			 * We do this from back to front, so we can stop when wagon removal or maximum train length (i.e. from mammoth-train setting) is triggered.
			 */
			if (cost.Succeeded()) {
				for (int i = num_units - 1; i > 0; i--) {
					assert(last_engine != NULL);
					Vehicle *append = (new_vehs[i] != NULL ? new_vehs[i] : old_vehs[i]);

					if (RailVehInfo(append->engine_type)->railveh_type == RAILVEH_WAGON) {
						/* Insert wagon after 'last_engine' */
						CommandCost res = CmdMoveVehicle(append, last_engine, DC_EXEC, false);

						/* When we allow removal of wagons, either the move failing due
						 * to the train becoming too long, or the train becoming longer
						 * would move the vehicle to the empty vehicle chain. */
						if (wagon_removal && (res.Failed() ? res.GetErrorMessage() == STR_ERROR_TRAIN_TOO_LONG : new_head->gcache.cached_total_length > old_total_length)) {
							CmdMoveVehicle(append, NULL, DC_EXEC | DC_AUTOREPLACE, false);
							break;
						}

						cost.AddCost(res);
						if (cost.Failed()) break;
					} else {
						/* We have reached 'last_engine', continue with the next engine towards the front */
						assert(append == last_engine);
						last_engine = last_engine->GetPrevUnit();
					}
				}
			}

			/* Sell superfluous new vehicles that could not be inserted. */
			if (cost.Succeeded() && wagon_removal) {
				assert(new_head->gcache.cached_total_length <= _settings_game.vehicle.max_train_length * TILE_SIZE);
				for (int i = 1; i < num_units; i++) {
					Vehicle *wagon = new_vehs[i];
					if (wagon == NULL) continue;
					if (wagon->First() == new_head) break;

					assert(RailVehInfo(wagon->engine_type)->railveh_type == RAILVEH_WAGON);

					/* Sell wagon */
					CommandCost ret = DoCommand(0, wagon->index, 0, DC_EXEC, GetCmdSellVeh(wagon));
					assert(ret.Succeeded());
					new_vehs[i] = NULL;

					/* Revert the money subtraction when the vehicle was built.
					 * This value is different from the sell value, esp. because of refitting */
					cost.AddCost(-new_costs[i]);
				}
			}

			/* The new vehicle chain is constructed, now take over orders and everything... */
			if (cost.Succeeded()) cost.AddCost(CopyHeadSpecificThings(old_head, new_head, flags));

			if (cost.Succeeded()) {
				/* Success ! */
				if ((flags & DC_EXEC) != 0 && new_head != old_head) {
					*chain = new_head;
				}

				/* Transfer cargo of old vehicles and sell them */
				for (int i = 0; i < num_units; i++) {
					Vehicle *w = old_vehs[i];
					/* Is the vehicle again part of the new chain?
					 * Note: We cannot test 'new_vehs[i] != NULL' as wagon removal might cause to remove both */
					if (w->First() == new_head) continue;

					if ((flags & DC_EXEC) != 0) TransferCargo(w, new_head, true);

					/* Sell the vehicle.
					 * Note: This might temporarly construct new trains, so use DC_AUTOREPLACE to prevent
					 *       it from failing due to engine limits. */
					cost.AddCost(DoCommand(0, w->index, 0, flags | DC_AUTOREPLACE, GetCmdSellVeh(w)));
					if ((flags & DC_EXEC) != 0) {
						old_vehs[i] = NULL;
						if (i == 0) old_head = NULL;
					}
				}

				if ((flags & DC_EXEC) != 0) CheckCargoCapacity(new_head);
			}

			/* If we are not in DC_EXEC undo everything, i.e. rearrange old vehicles.
			 * We do this from back to front, so that the head of the temporary vehicle chain does not change all the time.
			 * Note: The vehicle attach callback is disabled here :) */
			if ((flags & DC_EXEC) == 0) {
				/* Separate the head, so we can reattach the old vehicles */
				Train *second = Train::From(old_head)->GetNextUnit();
				if (second != NULL) CmdMoveVehicle(second, NULL, DC_EXEC | DC_AUTOREPLACE, true);

				assert(Train::From(old_head)->GetNextUnit() == NULL);

				for (int i = num_units - 1; i > 0; i--) {
					CommandCost ret = CmdMoveVehicle(old_vehs[i], old_head, DC_EXEC | DC_AUTOREPLACE, false);
					assert(ret.Succeeded());
				}
			}
		}

		/* Finally undo buying of new vehicles */
		if ((flags & DC_EXEC) == 0) {
			for (int i = num_units - 1; i >= 0; i--) {
				if (new_vehs[i] != NULL) {
					DoCommand(0, new_vehs[i]->index, 0, DC_EXEC, GetCmdSellVeh(new_vehs[i]));
					new_vehs[i] = NULL;
				}
			}
		}

		free(old_vehs);
		free(new_vehs);
		free(new_costs);
	} else {
		/* Build and refit replacement vehicle */
		Vehicle *new_head = NULL;
		cost.AddCost(BuildReplacementVehicle(old_head, &new_head, true));

		/* Was a new vehicle constructed? */
		if (cost.Succeeded() && new_head != NULL) {
			*nothing_to_do = false;

			/* The new vehicle is constructed, now take over orders and everything... */
			cost.AddCost(CopyHeadSpecificThings(old_head, new_head, flags));

			if (cost.Succeeded()) {
				/* The new vehicle is constructed, now take over cargo */
				if ((flags & DC_EXEC) != 0) {
					TransferCargo(old_head, new_head, true);
					*chain = new_head;
				}

				/* Sell the old vehicle */
				cost.AddCost(DoCommand(0, old_head->index, 0, flags, GetCmdSellVeh(old_head)));
			}

			/* If we are not in DC_EXEC undo everything */
			if ((flags & DC_EXEC) == 0) {
				DoCommand(0, new_head->index, 0, DC_EXEC, GetCmdSellVeh(new_head));
			}
		}
	}

	return cost;
}
/*
 * Finds the best trajectory according to WEIGHTED_COST_FUNCTIONS (global).
 * 
 * @param: ref_state - [s, s_dot, s_ddot, d, d_dot, d_ddot]
 * @param: target_vehicle - id of leading vehicle (int) which can be used to retrieve
      that vehicle from the "predictions" dictionary. This is the vehicle that 
      we are setting our trajectory relative to.
 * @param: delta - a length 6 array indicating the offset we are aiming for between us
      and the target_vehicle.
      So if at time 5 the target vehicle will be at [100, 10, 0, 0, 0, 0] 
      and delta is [-10, 0, 0, 4, 0, 0], 
      then our goal state for t = 5 will be [90, 10, 0, 4, 0, 0]. 
      This would correspond to a goal of 
      "follow 10 meters behind and 4 meters to the right of target vehicle"
 * @param: T - the desired time at which we will be at the goal (relative to now as t=0)
 * @param: predictions - dictionary of {v_id : vehicle }. Each vehicle has a method 
      vehicle.state_in(time) which returns a length 6 array giving that vehicle's
      expected [s, s_dot, s_ddot, d, d_dot, d_ddot] state at that time.
 * 
 * @return: (best_s, best_d, best_t) where best_s are the 6 coefficients representing s(t)
      best_d gives coefficients for d(t) and best_t gives duration associated w/ 
      this trajectory.
 */
struct trajectory* Ptg::PTG(struct state* ref_state, int8_t target_vehicle, struct state* delta, double T, std::map<int8_t, Vehicle>* predictions)
{
  struct trajectory* best_traj = NULL;

  if (target_vehicle > -1)
  {
    Vehicle* target = &predictions->at(target_vehicle);

    // generate alternative goals
    std::vector<struct goal> all_goals;
    double timestep = 0.2;
    double t = T - 4 * timestep;
    while (t <= T + 4 * timestep) // loop 8 times = 8 traj
    {
      struct state target_state = target->state_in(t);
      target_state.add(&delta->s, &delta->d);

      struct model goal_s = target_state.s;
      struct model goal_d = target_state.d;
      struct goal goals;
      goals.s = goal_s;
      goals.d = goal_d;
      goals.t = t;

      all_goals.push_back(goals);

      t += timestep;
    }

    // find best trajectory
    std::map<double, struct trajectory*> cost_traj;
    for (std::vector<struct goal>::iterator it=all_goals.begin(); it!=all_goals.end(); ++it)
    {
      double cost = 0;
      struct trajectory* traj = new trajectory();

      struct model s_goal = it->s;
      struct model d_goal = it->d;
      double t = it->t;
      JMT(traj->s_coeffs, &ref_state->s, &s_goal, t);
      JMT(traj->d_coeffs, &ref_state->d, &d_goal, t);
      traj->T = t;

      cost = calculate_cost(traj, target_vehicle, delta, T, predictions);

      cost_traj[cost] = traj; // Sort by cost
#ifdef VISUAL_DEBUG
      graph->plot_trajectory(ref_state->s.m, traj);
#endif // VISUAL_DEBUG
    }

    if (cost_traj.size() > 0)
    {
      best_traj = cost_traj.begin()->second; // Minimum cost
    }
  }
  else
  {
    printf("[ERROR] Can not find vehicle with id: %d\n", target_vehicle);
  }

  return best_traj;
}
Example #20
0
/**
 * Autoreplaces a vehicle
 * Trains are replaced as a whole chain, free wagons in depot are replaced on their own
 * @param tile not used
 * @param flags type of operation
 * @param p1 Index of vehicle
 * @param p2 not used
 * @param text unused
 * @return the cost of this operation or an error
 */
CommandCost CmdAutoreplaceVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
	Vehicle *v = Vehicle::GetIfValid(p1);
	if (v == NULL) return CMD_ERROR;

	CommandCost ret = CheckOwnership(v->owner);
	if (ret.Failed()) return ret;

	if (!v->IsInDepot()) return CMD_ERROR;
	if (v->vehstatus & VS_CRASHED) return CMD_ERROR;

	bool free_wagon = false;
	if (v->type == VEH_TRAIN) {
		Train *t = Train::From(v);
		if (t->IsArticulatedPart() || t->IsRearDualheaded()) return CMD_ERROR;
		free_wagon = !t->IsFrontEngine();
		if (free_wagon && t->First()->IsFrontEngine()) return CMD_ERROR;
	} else {
		if (!v->IsPrimaryVehicle()) return CMD_ERROR;
	}

	const Company *c = Company::Get(_current_company);
	bool wagon_removal = c->settings.renew_keep_length;

	/* Test whether any replacement is set, before issuing a whole lot of commands that would end in nothing changed */
	Vehicle *w = v;
	bool any_replacements = false;
	while (w != NULL) {
		EngineID e;
		CommandCost cost = GetNewEngineType(w, c, e);
		if (cost.Failed()) return cost;
		any_replacements |= (e != INVALID_ENGINE);
		w = (!free_wagon && w->type == VEH_TRAIN ? Train::From(w)->GetNextUnit() : NULL);
	}

	CommandCost cost = CommandCost(EXPENSES_NEW_VEHICLES, 0);
	bool nothing_to_do = true;

	if (any_replacements) {
		bool was_stopped = free_wagon || ((v->vehstatus & VS_STOPPED) != 0);

		/* Stop the vehicle */
		if (!was_stopped) cost.AddCost(CmdStartStopVehicle(v, true));
		if (cost.Failed()) return cost;

		assert(v->IsStoppedInDepot());

		/* We have to construct the new vehicle chain to test whether it is valid.
		 * Vehicle construction needs random bits, so we have to save the random seeds
		 * to prevent desyncs and to replay newgrf callbacks during DC_EXEC */
		SavedRandomSeeds saved_seeds;
		SaveRandomSeeds(&saved_seeds);
		if (free_wagon) {
			cost.AddCost(ReplaceFreeUnit(&v, flags & ~DC_EXEC, &nothing_to_do));
		} else {
			cost.AddCost(ReplaceChain(&v, flags & ~DC_EXEC, wagon_removal, &nothing_to_do));
		}
		RestoreRandomSeeds(saved_seeds);

		if (cost.Succeeded() && (flags & DC_EXEC) != 0) {
			CommandCost ret;
			if (free_wagon) {
				ret = ReplaceFreeUnit(&v, flags, &nothing_to_do);
			} else {
				ret = ReplaceChain(&v, flags, wagon_removal, &nothing_to_do);
			}
			assert(ret.Succeeded() && ret.GetCost() == cost.GetCost());
		}

		/* Restart the vehicle */
		if (!was_stopped) cost.AddCost(CmdStartStopVehicle(v, false));
	}

	if (cost.Succeeded() && nothing_to_do) cost = CommandCost(STR_ERROR_AUTOREPLACE_NOTHING_TO_DO);
	return cost;
}
Example #21
0
            void UpdateAI(uint32 const diff)
            {
                if (!UpdateVictim())
                    return;

                events.Update(diff);

                if (me->HasUnitState(UNIT_STATE_CASTING))
                    return;

                while (uint32 eventId = events.ExecuteEvent())
                {
                    switch (eventId)
                    {
                        case EVENT_MELEE_CHECK:
                            if (!me->IsWithinMeleeRange(me->getVictim()))
                                DoCast(SPELL_PETRIFY_BREATH);
                            events.ScheduleEvent(EVENT_MELEE_CHECK, 1 * IN_MILLISECONDS);
                            break;
                        case EVENT_SWEEP:
                            if (left)
                                DoCast(me->FindNearestCreature(NPC_ARM_SWEEP_STALKER, 500.0f, true), SPELL_ARM_SWEEP, true);
                            events.ScheduleEvent(EVENT_SWEEP, 25 * IN_MILLISECONDS);
                            break;
                        case EVENT_SMASH:
                            if (left && right)
                                DoCastVictim(SPELL_TWO_ARM_SMASH);
                            else if (left || right)
                                DoCastVictim(SPELL_ONE_ARM_SMASH);
                            events.ScheduleEvent(EVENT_SMASH, 15 * IN_MILLISECONDS);
                            break;
                        case EVENT_STONE_SHOUT:
                            DoCast(SPELL_STONE_SHOUT);
                            events.ScheduleEvent(EVENT_STONE_SHOUT, 2 * IN_MILLISECONDS);
                            break;
                        case EVENT_ENRAGE:
                            DoCast(SPELL_BERSERK);
                            Talk(SAY_BERSERK);
                            break;
                        case EVENT_RESPAWN_LEFT_ARM:
                        case EVENT_RESPAWN_RIGHT_ARM:
                        {
                            if (vehicle)
                            {
                                int8 seat = eventId == EVENT_RESPAWN_LEFT_ARM ? 0 : 1;
                                uint32 entry = eventId == EVENT_RESPAWN_LEFT_ARM ? NPC_LEFT_ARM : NPC_RIGHT_ARM;
                                vehicle->InstallAccessory(entry, seat, true, TEMPSUMMON_MANUAL_DESPAWN, 0);
                            }
                            break;
                        }
                        case EVENT_STONE_GRIP:
                        {
                            if (right)
                            {
                                DoCast(SPELL_STONE_GRIP);
                                Talk(SAY_GRAB_PLAYER);
                                Talk(EMOTE_STONE_GRIP);
                            }
                            events.ScheduleEvent(EVENT_STONE_GRIP, 25 * IN_MILLISECONDS);
                            break;
                        }
                        case EVENT_FOCUSED_EYEBEAM:
                            if (Unit* eyebeamTargetUnit = SelectTarget(SELECT_TARGET_FARTHEST, 0, 0, true))
                            {
                                eyebeamTarget = eyebeamTargetUnit->GetGUID();
                                DoCast(me, SPELL_SUMMON_FOCUSED_EYEBEAM, true);
                            }
                            events.ScheduleEvent(EVENT_FOCUSED_EYEBEAM, urand(15, 35) * IN_MILLISECONDS);
                            break;
                    }
                }

                DoMeleeAttackIfReady();
            }
Example #22
0
void AddArticulatedParts(Vehicle *first)
{
	VehicleType type = first->type;
	if (!HasBit(EngInfo(first->engine_type)->callback_mask, CBM_VEHICLE_ARTIC_ENGINE)) return;

	Vehicle *v = first;
	for (uint i = 1; i < MAX_ARTICULATED_PARTS; i++) {
		bool flip_image;
		EngineID engine_type = GetNextArticPart(i, first->engine_type, first, &flip_image);
		if (engine_type == INVALID_ENGINE) return;

		/* In the (very rare) case the GRF reported wrong number of articulated parts
		 * and we run out of available vehicles, bail out. */
		if (!Vehicle::CanAllocateItem()) return;

		const Engine *e_artic = Engine::Get(engine_type);
		switch (type) {
			default: NOT_REACHED();

			case VEH_TRAIN: {
				Train *front = Train::From(first);
				Train *t = new Train();
				v->SetNext(t);
				v = t;

				t->subtype = 0;
				t->track = front->track;
				t->railtype = front->railtype;
				t->tcache.first_engine = front->engine_type; // needs to be set before first callback

				t->spritenum = e_artic->u.rail.image_index;
				if (e_artic->CanCarryCargo()) {
					t->cargo_type = e_artic->GetDefaultCargoType();
					t->cargo_cap = e_artic->u.rail.capacity;  // Callback 36 is called when the consist is finished
				} else {
					t->cargo_type = front->cargo_type; // Needed for livery selection
					t->cargo_cap = 0;
				}

				t->SetArticulatedPart();
			} break;

			case VEH_ROAD: {
				RoadVehicle *front = RoadVehicle::From(first);
				RoadVehicle *rv = new RoadVehicle();
				v->SetNext(rv);
				v = rv;

				rv->subtype = 0;
				rv->rcache.first_engine = front->engine_type; // needs to be set before first callback
				rv->rcache.cached_veh_length = 8; // Callback is called when the consist is finished
				rv->state = RVSB_IN_DEPOT;

				rv->roadtype = front->roadtype;
				rv->compatible_roadtypes = front->compatible_roadtypes;

				rv->spritenum = e_artic->u.road.image_index;
				if (e_artic->CanCarryCargo()) {
					rv->cargo_type = e_artic->GetDefaultCargoType();
					rv->cargo_cap = e_artic->u.road.capacity;  // Callback 36 is called when the consist is finished
				} else {
					rv->cargo_type = front->cargo_type; // Needed for livery selection
					rv->cargo_cap = 0;
				}

				rv->SetArticulatedPart();
			} break;
		}

		/* get common values from first engine */
		v->direction = first->direction;
		v->owner = first->owner;
		v->tile = first->tile;
		v->x_pos = first->x_pos;
		v->y_pos = first->y_pos;
		v->z_pos = first->z_pos;
		v->build_year = first->build_year;
		v->vehstatus = first->vehstatus & ~VS_STOPPED;

		v->cargo_subtype = 0;
		v->max_speed = 0;
		v->max_age = 0;
		v->engine_type = engine_type;
		v->value = 0;
		v->cur_image = SPR_IMG_QUERY;
		v->random_bits = VehicleRandomBits();

		if (flip_image) v->spritenum++;

		VehicleMove(v, false);
	}
}
Example #23
0
 void Reset()
 {
     _Reset();
     if (vehicle)
         vehicle->RemoveAllPassengers();
 }
Example #24
0
int main()
{
    cout << endl << "Boolean test" << endl;
    AWS::Boolean boolean("boolean");

    boolean.setValue(true);
    cout << boolean.valueAsString() << endl;
    cout << (boolean.value() == true ? "T" : "F") << endl;

    boolean.setStringValue("FaLsE");
    cout << boolean.valueAsString() << endl;
    cout << (boolean.value() == true ? "T" : "F") << endl;

    boolean.setStringValue("trUE");
    cout << boolean.valueAsString() << endl;
    cout << (boolean.value() == true ? "T" : "F") << endl;

    cout << endl << "Integer test" << endl;
    AWS::Integer integer("integer");

    integer.setStringValue("35");
    cout << integer.value() << endl;
    cout << integer.valueAsString() << endl;
    cout << "is 35: " << (integer.value() == 35 ? "T" : "F") << endl;

    integer.setStringValue("-5");
    cout << integer.value() << endl;
    cout << integer.valueAsString() << endl;
    cout << "is -5: " << (integer.value() == -5 ? "T" : "F") << endl;

    integer.setValue(10);
    cout << integer.value() << endl;
    cout << integer.valueAsString() << endl;
    cout << "is 10: " << (integer.value() == 10 ? "T" : "F") << endl;

    try
    {
        integer.setStringValue("684654851684654681680468406840165416149");
        cout << integer.value() << endl;
        cout << integer.valueAsString() << endl;
        cout << "is -5: " << (integer.value() == -5 ? "T" : "F") << endl;
    }
    catch (const out_of_range& e)
    {
        cout << "exception" << endl;
    }

    cout << endl << "Array of int test" << endl;
    AWS::ArrayElement arrayElement("array");
    AWS::Integer* integ1 = new AWS::Integer("integ1"); integ1->setValue(1);
    AWS::Integer* integ2 = new AWS::Integer("integ2"); integ2->setValue(2147483647); // long int
    AWS::Integer* integ3 = new AWS::Integer("integ3"); integ3->setValue(4294967295); // -1
    AWS::Integer* integ4 = new AWS::Integer("integ4"); integ4->setValue(92233720368547758074294967295); // -1

    arrayElement.add(integ1);
    arrayElement.add(integ2);
    arrayElement.add(integ3);
    arrayElement.add(integ4);

    std::vector<int> vect;
    arrayElement.fill(&vect, NULL);

    for (std::vector<int>::iterator iter = vect.begin(); iter != vect.end(); ++iter)
        cout << *iter << endl;

    cout << endl << "Array of real test" << endl;
    AWS::ArrayElement realArrayElement("array");
    AWS::Real* real1 = new AWS::Real("real1"); real1->setValue(1.0);
    AWS::Real* real2 = new AWS::Real("real2"); real2->setValue(2147483647.0); // long int
    AWS::Real* real3 = new AWS::Real("real3"); real3->setValue(4294967295); // -1
    AWS::Real* real4 = new AWS::Real("real4"); real4->setValue(2); // -1

    realArrayElement.add(real1);
    realArrayElement.add(real2);
    realArrayElement.add(real3);
    realArrayElement.add(real4);

    std::vector<double> realVect;
    realArrayElement.fill(&realVect, NULL);

    for (std::vector<double>::iterator iter = realVect.begin(); iter != realVect.end(); ++iter)
        cout << *iter << endl;

    cout << endl << "Array of string test" << endl;
    AWS::ArrayElement arrayStringElement("array");
    AWS::String* string1 = new AWS::String("integ1"); string1->setValue("a");
    AWS::String* string2 = new AWS::String("integ2"); string2->setValue("b");
    AWS::String* string3 = new AWS::String("integ3"); string3->setValue("c");
    AWS::String* string4 = new AWS::String("integ4"); string4->setValue("d");

    arrayStringElement.add(string1);
    arrayStringElement.add(string2);
    arrayStringElement.add(string3);
    arrayStringElement.add(string4);

    std::vector<std::string> vectString;
    arrayStringElement.fill(&vectString, NULL);

    for (std::vector<std::string>::iterator iter = vectString.begin(); iter != vectString.end(); ++iter)
        cout << *iter << endl;

    cout << endl << "Class test" << endl;
    AWS::ClassElement classVehicle("vehicle");
    AWS::Boolean* isMotorized  = new AWS::Boolean("isMotorized"); isMotorized->setValue(true);
    AWS::Integer* wheels       = new AWS::Integer("wheels");      wheels->setValue(4);
    AWS::String*  brand        = new AWS::String("brand");        brand->setValue("Renault");
    AWS::String*  david        = new AWS::String("name");         david->setValue("David");
    AWS::ClassElement* people  = new AWS::ClassElement(""); people->add(david);// Class name not necessary because it is in an array.
    AWS::ArrayElement* peoples = new AWS::ArrayElement("people"); peoples->add(people);

    classVehicle.add(isMotorized);
    classVehicle.add(wheels     );
    classVehicle.add(brand      );
    classVehicle.add(peoples    );

    Vehicle vehicle;
    classVehicle.fill(&vehicle, NULL);

    cout << "isMotorized: " << vehicle.isMotorized    << endl;
    cout << "wheels     : " << vehicle.wheels         << endl;
    cout << "brand      : " << vehicle.brand          << endl;
    cout << "people     : " << vehicle.people[0]->name << endl;

    cout << endl << "Element test" << endl;
    AWS::ClassElement* classElement = (AWS::ClassElement*)vehicle.toElement("");
    cout << "isMotorized: " << ((AWS::Boolean*)classElement->get("isMotorized"))->value()    << endl;
    cout << "brand      : " << ((AWS::String*)classElement->get("brand")       )->value()    << endl;
    cout << "wheels     : " << ((AWS::Integer*)classElement->get("wheels")     )->value()    << endl;
    cout << "people     : " << ((AWS::String*)((AWS::ClassElement*)((AWS::ArrayElement*)classElement->get("people"))->m_elements[0])->get("name"))->value()    << endl;

    return 0;
}
Example #25
0
void WorldSession::HandleEjectPassenger(WorldPacket& data)
{
    Vehicle* vehicle = _player->GetVehicleKit();
    if (!vehicle)
    {
        data.rfinish();                                     // prevent warnings spam
        TC_LOG_ERROR("network", "HandleEjectPassenger: Player %u is not in a vehicle!", GetPlayer()->GetGUIDLow());
        return;
    }

    uint64 guid;
    data >> guid;

    if (IS_PLAYER_GUID(guid))
    {
        Player* player = ObjectAccessor::FindPlayer(guid);
        if (!player)
        {
            TC_LOG_ERROR("network", "Player %u tried to eject player %u from vehicle, but the latter was not found in world!", GetPlayer()->GetGUIDLow(), GUID_LOPART(guid));
            return;
        }

        if (!player->IsOnVehicle(vehicle->GetBase()))
        {
            TC_LOG_ERROR("network", "Player %u tried to eject player %u, but they are not in the same vehicle", GetPlayer()->GetGUIDLow(), GUID_LOPART(guid));
            return;
        }

        VehicleSeatEntry const* seat = vehicle->GetSeatForPassenger(player);
        ASSERT(seat);
        if (seat->IsEjectable())
            player->ExitVehicle();
        else
            TC_LOG_ERROR("network", "Player %u attempted to eject player %u from non-ejectable seat.", GetPlayer()->GetGUIDLow(), GUID_LOPART(guid));
    }

    else if (IS_CREATURE_GUID(guid))
    {
        Unit* unit = ObjectAccessor::GetUnit(*_player, guid);
        if (!unit) // creatures can be ejected too from player mounts
        {
            TC_LOG_ERROR("network", "Player %u tried to eject creature guid %u from vehicle, but the latter was not found in world!", GetPlayer()->GetGUIDLow(), GUID_LOPART(guid));
            return;
        }

        if (!unit->IsOnVehicle(vehicle->GetBase()))
        {
            TC_LOG_ERROR("network", "Player %u tried to eject unit %u, but they are not in the same vehicle", GetPlayer()->GetGUIDLow(), GUID_LOPART(guid));
            return;
        }

        VehicleSeatEntry const* seat = vehicle->GetSeatForPassenger(unit);
        ASSERT(seat);
        if (seat->IsEjectable())
        {
            ASSERT(GetPlayer() == vehicle->GetBase());
            unit->ExitVehicle();
        }
        else
            TC_LOG_ERROR("network", "Player %u attempted to eject creature GUID %u from non-ejectable seat.", GetPlayer()->GetGUIDLow(), GUID_LOPART(guid));
    }
    else
        TC_LOG_ERROR("network", "HandleEjectPassenger: Player %u tried to eject invalid GUID " UI64FMTD, GetPlayer()->GetGUIDLow(), guid);
}
Example #26
0
 void Reset()
 {
     ASSERT(vehicle);
     vehicle->Reset();
 }
Example #27
0
void initializeGraphics()
{
	//Build Pop Up Menu
	BuildPopupMenu();
	glutAttachMenu (GLUT_RIGHT_BUTTON);

	//inittextures
	for(int i=0;i<MAXTEXTURES;i++)
		textures[i]=0;
		
	// disable Lighting
    glDisable( GL_LIGHTING );

    glClearColor (0.0f, 0.0f, 0.0f, 0.0f);

    glEnable( GL_DEPTH_TEST );
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    glGetFloatv( GL_MODELVIEW_MATRIX, modelViewMatrix );  // save MY copy in modelViewMatrix

    glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glEnable(GL_TEXTURE_2D);
    glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);

	//Load Textures
	textures[SIRENID] = loadtextures(sirenFile, 52,45);
	textures[VEHICLEID] = loadtextures(vehicleFile, 207,177);
	textures[WALLID] = loadtextures(wallFile, 512,512);
	textures[FLOORID] = loadtextures(floorFile, 512,512);
	textures[CARROTID] = loadtextures(carrotFile, 52,45);
	textures[BUTTONID] = loadtextures(buttonFile, 52,45);
	textures[PARTICLEID]=textures[VEHICLEID];
	textures[PONDID] = loadtextures(marbleFile,225,225);
	textures[WATERID] = loadtextures(waterFile,393,385);
	
	//snow drifts
	snowcave.resetPoints(snowCavePoints);
	snowcave.setBoundingBoxes(driftBuffer);

	snowcave2.resetPoints(snowCavePoints2);
//	snowcave2.setBoundingBox(-50,-27, //min max X
//							-50,-30, //min max Y
//							-50,10); //min max z
	snowcave2.setBoundingBoxes(driftBuffer);
	//snowman
	snowman = Snowman(snowmanOrigin,
		SNOWMANID,
		snowmanSize,
		textures[FLOORID],
		textures[CARROTID], 
		textures[BUTTONID]);


	snowman2 = Snowman(snowmanOrigin2,
		SNOWMANID,
		snowmanSize,
		textures[FLOORID],
		textures[CARROTID], 
		textures[BUTTONID]);

	snowman3 = Snowman(snowmanOrigin3,
		SNOWMANID,
		snowmanSize,
		textures[FLOORID],
		textures[CARROTID], 
		textures[BUTTONID]);

	//Pond 
	pond = Pond(pondOrigin,PONDID,pondRadius,pondHeight);
	pond.setSpaceDimensions(Point(10,10,10));
	pond.setBoundingBox(pondOrigin.x-10,pondOrigin.x+10,-50,pondOrigin.y+5,pondOrigin.z-10,pondOrigin.z+10);

	//Gifts
	gifts[0] = Gift(giftOrigin1,GIFT1ID,giftSize);
	gifts[1] = Gift(giftOrigin2,GIFT2ID,giftSize);
	gifts[2] = Gift(giftOrigin3,GIFT3ID,giftSize);
	gifts[3] = Gift(giftOrigin4,GIFT4ID,giftSize);
	gifts[4] = Gift(giftOrigin5,GIFT5ID,giftSize);

	//enemy 
	npc.setSpeed(npcSpeed);
	npc.setSpaceDimensions(Point(bodyRadius/2,bodyRadius/2,bodyRadius/2));
	npc.setThrowRange(20);
	npc.setInDanger(true);

	//vehicle
	vehicle.setDamage(0);
	vehicle.setMaxDamage(100);
	vehicle.setIsAlive(true);
	vehicle.setStrikeRange(30);


	//init shadow paramteres
   glEnable(GL_COLOR_MATERIAL);
   glColorMaterial( GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE );
   glEnable(GL_DEPTH_TEST);
   glDepthFunc(GL_LEQUAL);    
   glShadeModel (GL_SMOOTH);
   glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);

	//this is defined 
	//bool (*fp_processCollision)(Obstacle);
	fp_processCollision = &processCollision;


	//Map Creation assessment
	currMap.createMap(minCoords, 
					maxCoords, 
					npc, 
					gifts, 
					giftCount, 
					fp_processCollision
					);
	currMap.printState();

	//setup the controller
	controller = PathController(&currMap,&npc,&vehicle);
	controller.setNextTarget(); //set the target
	controller.setMaxPath(100);

	
}
Example #28
0
bool SVGOptionsScreen::Update()
{
    Vehicle *veh = VehicleMgr.GetVehicle();

    if( veh )
    {
        m_LenUnitChoice.Update( veh->m_SVGLenUnit.GetID() );
        m_2DViewType.Update( veh->m_SVGView.GetID() );
        m_4ViewChoice1.Update( veh->m_SVGView1.GetID() );
        m_4ViewChoice2.Update( veh->m_SVGView2.GetID() );
        m_4ViewChoice3.Update( veh->m_SVGView3.GetID() );
        m_4ViewChoice4.Update( veh->m_SVGView4.GetID() );
        m_4RotChoice1.Update( veh->m_SVGView1_rot.GetID() );
        m_4RotChoice2.Update( veh->m_SVGView2_rot.GetID() );
        m_4RotChoice3.Update( veh->m_SVGView3_rot.GetID() );
        m_4RotChoice4.Update( veh->m_SVGView4_rot.GetID() );
        m_ProjectionLineToggle.Update( veh->m_SVGProjectionFlag.GetID() );
        m_TessSlider.Update( veh->m_SVGTessFactor.GetID() );
        m_XSecToggle.Update( veh->m_SVGAllXSecFlag.GetID() );

        if ( veh->m_SVGProjectionFlag() )
        {
            m_TessSlider.Activate();
        }
        else 
        {
            m_TessSlider.Deactivate();
        }

        if ( veh->m_SVGLenUnit() == vsp::LEN_UNITLESS )
        {
            veh->m_Scale.Set( 0 );
        }
        else 
        {
            GetScale( veh->m_SVGSet.Get() );
        }

        if ( veh->m_SVGView() == vsp::VIEW_1 )
        {
            m_4ViewChoice1.Activate();
            m_4ViewChoice2.Deactivate();
            m_4ViewChoice3.Deactivate();
            m_4ViewChoice4.Deactivate();
            m_4RotChoice1.Activate();
            m_4RotChoice2.Deactivate();
            m_4RotChoice3.Deactivate();
            m_4RotChoice4.Deactivate();
        }
        else if ( veh->m_SVGView() == vsp::VIEW_2HOR )
        {
            m_4ViewChoice1.Activate();
            m_4ViewChoice2.Activate();
            m_4ViewChoice3.Deactivate();
            m_4ViewChoice4.Deactivate();
            m_4RotChoice1.Activate();
            m_4RotChoice2.Activate();
            m_4RotChoice3.Deactivate();
            m_4RotChoice4.Deactivate();
        }
        else if ( veh->m_SVGView() == vsp::VIEW_2VER )
        {
            m_4ViewChoice1.Activate();
            m_4ViewChoice2.Deactivate();
            m_4ViewChoice3.Activate();
            m_4ViewChoice4.Deactivate();
            m_4RotChoice1.Activate();
            m_4RotChoice2.Deactivate();
            m_4RotChoice3.Activate();
            m_4RotChoice4.Deactivate();
        }
        else if ( veh->m_SVGView() == vsp::VIEW_4 )
        {
            m_4ViewChoice1.Activate();
            m_4ViewChoice2.Activate();
            m_4ViewChoice3.Activate();
            m_4ViewChoice4.Activate();
            m_4RotChoice1.Activate();
            m_4RotChoice2.Activate();
            m_4RotChoice3.Activate();
            m_4RotChoice4.Activate();
        }
    }

    m_FLTK_Window->redraw();

    return false;
}
Example #29
0
void 
update()
{
	
	Obstacle tmpObj = vehicle;
	tmpObj.moveObstacle();
	//MapNode *location =currMap.getNode(tmpObj.getOrigin());
	//MapNode *currLocation  =currMap.getNode(vehicle.getOrigin());


	if (processCollision(tmpObj)) //process collisions and damage taken
	{
		//make accomodations to ensure that 
 		vehicle.setSpeed(0);
		vehicle.moveObstacle();
	}


	vehicle.moveObstacle();
 	translate(0,0,vehicle.getSpeed());	

	if(activeBeam) //do not respond to events when beam is activated-drop vehicle velocity to zero
	{
        vehicle.setSpeed( -vehicle.getSpeed());
		return; 
	}

	//if (speed>0)
    if ( vehicle.getSpeed()>0 )
		vehicle.setSpeed(vehicle.getSpeed()-0.001f);
    else
		vehicle.setSpeed(0);

	//move the enemy player
	controller.advanceCharacter();

	//if NPC is throwing snowball then handle it
	//create a snowball projectile
	if(npc.getCurrentState()==RELEASE_SNOWBALL)
	{
		Snowball *newSnowball = new Snowball( SNOWBALLID,
											npc.getOrigin(), //startPoint
											vehicle.getOrigin(),// endPoint
											npc.getSnowRadius(),
											snowballSpeed, //speed at which the snowball flies through the air
											minCoords, //the coords that the snowball will crash and dissolve
											maxCoords,
											snowballDamage,
											snowballGravity,
											snowballAirFriction,
											textures[FLOORID]
											); 


		projectiles.push_back(newSnowball);
	}

	//manage snowballs and the damage inflicted on the vehicle
	advanceProjectiles();

	display();
}
Example #30
0
 void MoveInLineOfSight(Unit *who)
 {
     if(who->GetTypeId() == TYPEID_PLAYER && CAST_PLR(who)->isGameMaster()
         && !who->GetVehicle() && vehicle->GetPassenger(SEAT_TURRET))
         who->EnterVehicle(vehicle, SEAT_PLAYER);
 }