Ejemplo n.º 1
0
        public PayByPhoneApi()
        {
            _myWebClient = new CookieWebClient();
            _myWebClient.BaseAddress = "https://m.paybyphone.com";
            _myWebClient.CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore);
            _myWebClient.Headers[HttpRequestHeader.UserAgent] = Api.UserAgent;
            _myWebClient.Headers["Origin"] = "https://m.paybyphone.com";

            _myVehicleManager = new VehicleManager(this);
            _myPaymentDetails = new PaymentDetails(this);
            _myEmailSettings = new EmailSettings(this);
            _mySecuritySettings = new SecuritySettings(this);
            _myTermsConditions = new TermsConditions(this);
            _myLocationManager = new LocationManager(this);
        }
Ejemplo n.º 2
0
        public async Task <bool> Save(Client player)
        {
            try
            {
                Customization.SaveCharacter(player);

                Vector3 LPos = (player.IsInVehicle) ? player.Vehicle.Position + new Vector3(0, 0, 0.5) : player.Position;
                string  pos  = JsonConvert.SerializeObject(LPos);
                try
                {
                    if (InsideHouseID != -1)
                    {
                        House house = HouseManager.Houses.FirstOrDefault(h => h.ID == InsideHouseID);
                        if (house != null)
                        {
                            pos = JsonConvert.SerializeObject(house.Position + new Vector3(0, 0, 1.12));
                        }
                    }
                    if (InsideGarageID != -1)
                    {
                        Garage garage = GarageManager.Garages[InsideGarageID];
                        pos = JsonConvert.SerializeObject(garage.Position + new Vector3(0, 0, 1.12));
                    }
                    if (ExteriorPos != new Vector3())
                    {
                        Vector3 position = ExteriorPos;
                        pos = JsonConvert.SerializeObject(position + new Vector3(0, 0, 1.12));
                    }
                    if (InsideHotelID != -1)
                    {
                        Vector3 position = Houses.Hotel.HotelEnters[InsideHotelID];
                        pos = JsonConvert.SerializeObject(position + new Vector3(0, 0, 1.12));
                    }
                    if (TuningShop != -1)
                    {
                        Vector3 position = BusinessManager.BizList[TuningShop].EnterPoint;
                        pos = JsonConvert.SerializeObject(position + new Vector3(0, 0, 1.12));
                    }
                }
                catch (Exception e) { Log.Write("EXCEPTION AT \"UnLoadPos\":\n" + e.ToString()); }

                try
                {
                    if (IsSpawned && !IsAlive)
                    {
                        pos    = JsonConvert.SerializeObject(Fractions.Ems.emsCheckpoints[2]);
                        Health = 20;
                        Armor  = 0;
                    }
                    else
                    {
                        Health = player.Health;
                        Armor  = player.Armor;
                    }
                }
                catch (Exception e) { Log.Write("EXCEPTION AT \"UnLoadHP\":\n" + e.ToString()); }

                try
                {
                    var aItem = nInventory.Find(UUID, ItemType.BodyArmor);
                    if (aItem != null && aItem.IsActive)
                    {
                        aItem.Data = $"{Armor}";
                    }
                }
                catch (Exception e) { Log.Write("EXCEPTION AT \"UnLoadArmorItem\":\n" + e.ToString()); }

                try
                {
                    var all_vehicles = VehicleManager.getAllPlayerVehicles(player.Name);
                    foreach (var number in all_vehicles)
                    {
                        VehicleManager.Save(number);
                    }
                }
                catch (Exception e) { Log.Write("EXCEPTION AT \"UnLoadVehicles\":\n" + e.ToString()); }

                if (!IsSpawned)
                {
                    pos = JsonConvert.SerializeObject(SpawnPos);
                }

                Main.PlayerSlotsInfo[UUID] = new Tuple <int, int, int, long>(LVL, EXP, FractionID, Money);

                await MySQL.QueryAsync($"UPDATE `characters` SET `pos`='{pos}',`gender`={Gender},`health`={Health},`armor`={Armor},`lvl`={LVL},`exp`={EXP}," +
                                       $"`money`={Money},`bank`={Bank},`work`={WorkID},`fraction`={FractionID},`fractionlvl`={FractionLVL},`arrest`={ArrestTime}," +
                                       $"`wanted`='{JsonConvert.SerializeObject(WantedLVL)}',`biz`='{JsonConvert.SerializeObject(BizIDs)}',`adminlvl`={AdminLVL}," +
                                       $"`licenses`='{JsonConvert.SerializeObject(Licenses)}',`unwarn`='{MySQL.ConvertTime(Unwarn)}',`unmute`='{Unmute}'," +
                                       $"`warns`={Warns},`hotel`={HotelID},`hotelleft`={HotelLeft},`lastveh`='{LastVeh}',`onduty`={OnDuty},`lasthour`={LastHourMin}," +
                                       $"`demorgan`={DemorganTime},`contacts`='{JsonConvert.SerializeObject(Contacts)}',`achiev`='{JsonConvert.SerializeObject(Achievements)}',`sim`={Sim},`PetName`='{PetName}' WHERE `uuid`={UUID}");

                MoneySystem.Bank.Save(Bank);
                await Log.DebugAsync($"Player [{FirstName}:{LastName}] was saved.");

                return(true);
            }
            catch (Exception e)
            {
                Log.Write("EXCEPTION AT \"Save\":\n" + e.ToString());
                return(false);
            }
        }
        public static void VehicleStatus(int i, ref Vehicle vehicle)
        {
            if (i < Singleton <VehicleManager> .instance.m_vehicles.m_size)
            {
                uint currentFrameIndex = Singleton <SimulationManager> .instance.m_currentFrameIndex;
                int  num4 = (int)(currentFrameIndex & 4095u);
                if (((num4 >> 8) & 255u) == (i & 255u))
                {
                    GetForFuelCount((ushort)i, ref vehicle);
                    VehicleManager instance = Singleton <VehicleManager> .instance;
                    if (!vehicle.m_flags.IsFlagSet(Vehicle.Flags.Arriving) && (vehicle.m_cargoParent == 0) && vehicle.m_flags.IsFlagSet(Vehicle.Flags.Spawned) && !vehicle.m_flags.IsFlagSet(Vehicle.Flags.GoingBack) && !vehicle.m_flags.IsFlagSet(Vehicle.Flags.Parking))
                    {
                        if (vehicle.Info.m_vehicleAI is CargoTruckAI && (vehicle.m_targetBuilding != 0))
                        {
                            if (!MainDataStore.alreadyAskForFuel[i])
                            {
                                if (GasStationAI.IsGasBuilding(vehicle.m_targetBuilding))
                                {
                                    MainDataStore.alreadyAskForFuel[i] = true;
                                }
                                else
                                {
                                    System.Random rand = new System.Random();
                                    if (vehicle.m_flags.IsFlagSet(Vehicle.Flags.DummyTraffic))
                                    {
                                        if (rand.Next(62) < 2)
                                        {
                                            TransferManager.TransferOffer offer = default(TransferManager.TransferOffer);
                                            offer.Priority = rand.Next(8);
                                            offer.Vehicle  = (ushort)i;
                                            offer.Position = vehicle.GetLastFramePosition();
                                            offer.Amount   = 1;
                                            offer.Active   = true;
                                            Singleton <TransferManager> .instance.AddOutgoingOffer((TransferManager.TransferReason) 113, offer);

                                            MainDataStore.alreadyAskForFuel[i] = true;
                                        }
                                    }
                                    else
                                    {
                                        if (rand.Next(93) < 2)
                                        {
                                            TransferManager.TransferOffer offer = default(TransferManager.TransferOffer);
                                            offer.Priority = rand.Next(8);
                                            offer.Vehicle  = (ushort)i;
                                            offer.Position = vehicle.GetLastFramePosition();
                                            offer.Amount   = 1;
                                            offer.Active   = true;
                                            Singleton <TransferManager> .instance.AddOutgoingOffer((TransferManager.TransferReason) 113, offer);

                                            MainDataStore.alreadyAskForFuel[i] = true;
                                        }
                                    }
                                }
                            }
                        }
                        else if (vehicle.Info.m_vehicleAI is PassengerCarAI && vehicle.Info.m_class.m_subService == ItemClass.SubService.ResidentialLow)
                        {
                            if (!MainDataStore.alreadyAskForFuel[i])
                            {
                                if (GasStationAI.IsGasBuilding(vehicle.m_targetBuilding))
                                {
                                    MainDataStore.alreadyAskForFuel[i] = true;
                                }
                                else
                                {
                                    System.Random rand    = new System.Random();
                                    ushort        citizen = GetDriverInstance((ushort)i, ref vehicle);
                                    if (Singleton <CitizenManager> .instance.m_citizens.m_buffer[Singleton <CitizenManager> .instance.m_instances.m_buffer[citizen].m_citizen].m_flags.IsFlagSet(Citizen.Flags.DummyTraffic))
                                    {
                                        if (rand.Next(62) < 2)
                                        {
                                            TransferManager.TransferOffer offer = default(TransferManager.TransferOffer);
                                            offer.Priority = rand.Next(8);
                                            offer.Vehicle  = (ushort)i;
                                            offer.Position = vehicle.GetLastFramePosition();
                                            offer.Amount   = 1;
                                            offer.Active   = true;
                                            Singleton <TransferManager> .instance.AddOutgoingOffer((TransferManager.TransferReason) 112, offer);

                                            MainDataStore.alreadyAskForFuel[i] = true;
                                        }
                                    }
                                    else
                                    {
                                        if (rand.Next(93) < 2)
                                        {
                                            TransferManager.TransferOffer offer = default(TransferManager.TransferOffer);
                                            offer.Priority = rand.Next(8);
                                            offer.Vehicle  = (ushort)i;
                                            offer.Position = vehicle.GetLastFramePosition();
                                            offer.Amount   = 1;
                                            offer.Active   = true;
                                            Singleton <TransferManager> .instance.AddOutgoingOffer((TransferManager.TransferReason) 112, offer);

                                            MainDataStore.alreadyAskForFuel[i] = true;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            else
            {
                DebugLog.LogToFileOnly("Error: invalid vehicleID = " + i.ToString());
            }
        }
Ejemplo n.º 4
0
    public class CustomTrainAI : TrainAI {     // correct would be to inherit from VehicleAI (in order to keep the correct references to `base`)
        public void TrafficManagerSimulationStep(ushort vehicleId, ref Vehicle vehicleData, Vector3 physicsLodRefPos)
        {
#if USEPATHWAITCOUNTER
            VehicleState state = VehicleStateManager._GetVehicleState(vehicleId);
#endif

            if ((vehicleData.m_flags & Vehicle.Flags.WaitingPath) != 0)
            {
                byte pathFindFlags = Singleton <PathManager> .instance.m_pathUnits.m_buffer[(int)((UIntPtr)vehicleData.m_path)].m_pathFindFlags;
                if ((pathFindFlags & PathUnit.FLAG_READY) != 0)
                {
#if USEPATHWAITCOUNTER
                    state.PathWaitCounter = 0;                     // NON-STOCK CODE
#endif
                    try {
                        this.PathFindReady(vehicleId, ref vehicleData);
                    } catch (Exception e) {
                        Log.Warning($"TrainAI.PathFindReady({vehicleId}) for vehicle {vehicleData.Info?.m_class?.name} threw an exception: {e.ToString()}");
//#if !DEBUG
                        vehicleData.m_flags &= ~Vehicle.Flags.WaitingPath;
                        Singleton <PathManager> .instance.ReleasePath(vehicleData.m_path);

                        vehicleData.m_path = 0u;
                        vehicleData.Unspawn(vehicleId);
//#endif
                        return;
                    }
                    VehicleStateManager.OnPathFindReady(vehicleId, ref vehicleData);                     // NON-STOCK CODE
                }
                else if ((pathFindFlags & PathUnit.FLAG_FAILED) != 0 || vehicleData.m_path == 0
#if USEPATHWAITCOUNTER
                         || ((pathFindFlags & PathUnit.FLAG_CREATED) != 0 && state.PathWaitCounter == ushort.MaxValue)
#endif
                         )
                {
#if USEPATHWAITCOUNTER
                    state.PathWaitCounter = 0;                     // NON-STOCK CODE
#endif
                    vehicleData.m_flags &= ~Vehicle.Flags.WaitingPath;
                    Singleton <PathManager> .instance.ReleasePath(vehicleData.m_path);

                    vehicleData.m_path = 0u;
                    vehicleData.Unspawn(vehicleId);
                    return;
                }
#if USEPATHWAITCOUNTER
                else
                {
                    state.PathWaitCounter = (ushort)Math.Min(ushort.MaxValue, (int)state.PathWaitCounter + 1);                     // NON-STOCK CODE
                }
#endif
            }
            else
            {
#if USEPATHWAITCOUNTER
                state.PathWaitCounter = 0;                 // NON-STOCK CODE
#endif
                if ((vehicleData.m_flags & Vehicle.Flags.WaitingSpace) != 0)
                {
                    this.TrySpawn(vehicleId, ref vehicleData);
                }
            }

            bool   reversed = (vehicleData.m_flags & Vehicle.Flags.Reversed) != 0;
            ushort frontVehicleId;
            if (reversed)
            {
                frontVehicleId = vehicleData.GetLastVehicle(vehicleId);
            }
            else
            {
                frontVehicleId = vehicleId;
            }

            /// NON-STOCK CODE START ///
            try {
                //Log._Debug($"HandleVehicle for trams. vehicleId={vehicleId} frontVehicleId={frontVehicleId}");
                VehicleStateManager.LogTraffic(frontVehicleId, ref Singleton <VehicleManager> .instance.m_vehicles.m_buffer[frontVehicleId], true);
            } catch (Exception e) {
                Log.Error("TrainAI TrafficManagerSimulationStep (1) Error: " + e.ToString());
            }

            try {
                VehicleStateManager.UpdateVehiclePos(frontVehicleId, ref Singleton <VehicleManager> .instance.m_vehicles.m_buffer[frontVehicleId]);
            } catch (Exception e) {
                Log.Error("TrainAI TrafficManagerSimulationStep (2) Error: " + e.ToString());
            }
            /// NON-STOCK CODE END ///

            VehicleManager instance = Singleton <VehicleManager> .instance;
            VehicleInfo    info     = instance.m_vehicles.m_buffer[(int)frontVehicleId].Info;
            info.m_vehicleAI.SimulationStep(frontVehicleId, ref instance.m_vehicles.m_buffer[(int)frontVehicleId], vehicleId, ref vehicleData, 0);
            if ((vehicleData.m_flags & (Vehicle.Flags.Created | Vehicle.Flags.Deleted)) != Vehicle.Flags.Created)
            {
                return;
            }
            bool flag2 = (vehicleData.m_flags & Vehicle.Flags.Reversed) != 0;
            if (flag2 != reversed)
            {
                reversed = flag2;
                if (reversed)
                {
                    frontVehicleId = vehicleData.GetLastVehicle(vehicleId);
                }
                else
                {
                    frontVehicleId = vehicleId;
                }
                info = instance.m_vehicles.m_buffer[(int)frontVehicleId].Info;
                info.m_vehicleAI.SimulationStep(frontVehicleId, ref instance.m_vehicles.m_buffer[(int)frontVehicleId], vehicleId, ref vehicleData, 0);
                if ((vehicleData.m_flags & (Vehicle.Flags.Created | Vehicle.Flags.Deleted)) != Vehicle.Flags.Created)
                {
                    return;
                }
                flag2 = ((vehicleData.m_flags & Vehicle.Flags.Reversed) != 0);
                if (flag2 != reversed)
                {
                    Singleton <VehicleManager> .instance.ReleaseVehicle(vehicleId);

                    return;
                }
            }
            if (reversed)
            {
                frontVehicleId = instance.m_vehicles.m_buffer[(int)frontVehicleId].m_leadingVehicle;
                int num2 = 0;
                while (frontVehicleId != 0)
                {
                    info = instance.m_vehicles.m_buffer[(int)frontVehicleId].Info;
                    info.m_vehicleAI.SimulationStep(frontVehicleId, ref instance.m_vehicles.m_buffer[(int)frontVehicleId], vehicleId, ref vehicleData, 0);
                    if ((vehicleData.m_flags & (Vehicle.Flags.Created | Vehicle.Flags.Deleted)) != Vehicle.Flags.Created)
                    {
                        return;
                    }
                    frontVehicleId = instance.m_vehicles.m_buffer[(int)frontVehicleId].m_leadingVehicle;
                    if (++num2 > 16384)
                    {
                        CODebugBase <LogChannel> .Error(LogChannel.Core, "Invalid list detected!\n" + Environment.StackTrace);

                        break;
                    }
                }
            }
            else
            {
                frontVehicleId = instance.m_vehicles.m_buffer[(int)frontVehicleId].m_trailingVehicle;
                int num3 = 0;
                while (frontVehicleId != 0)
                {
                    info = instance.m_vehicles.m_buffer[(int)frontVehicleId].Info;
                    info.m_vehicleAI.SimulationStep(frontVehicleId, ref instance.m_vehicles.m_buffer[(int)frontVehicleId], vehicleId, ref vehicleData, 0);
                    if ((vehicleData.m_flags & (Vehicle.Flags.Created | Vehicle.Flags.Deleted)) != Vehicle.Flags.Created)
                    {
                        return;
                    }
                    frontVehicleId = instance.m_vehicles.m_buffer[(int)frontVehicleId].m_trailingVehicle;
                    if (++num3 > 16384)
                    {
                        CODebugBase <LogChannel> .Error(LogChannel.Core, "Invalid list detected!\n" + Environment.StackTrace);

                        break;
                    }
                }
            }
            if ((vehicleData.m_flags & (Vehicle.Flags.Spawned | Vehicle.Flags.WaitingPath | Vehicle.Flags.WaitingSpace | Vehicle.Flags.WaitingCargo)) == 0 || (vehicleData.m_blockCounter == 255 && Options.enableDespawning))
            {
                Singleton <VehicleManager> .instance.ReleaseVehicle(vehicleId);
            }
        }
Ejemplo n.º 5
0
        private void LoadPassengers(ushort vehicleID, ref Vehicle data, ushort currentStop, ushort nextStop)
        {
            if ((int)currentStop == 0 || (int)nextStop == 0)
            {
                return;
            }
            CitizenManager instance1 = Singleton <CitizenManager> .instance;
            VehicleManager instance2 = Singleton <VehicleManager> .instance;
            NetManager     instance3 = Singleton <NetManager> .instance;
            Vector3        position1 = instance3.m_nodes.m_buffer[(int)currentStop].m_position;
            Vector3        position2 = instance3.m_nodes.m_buffer[(int)nextStop].m_position;

            instance3.m_nodes.m_buffer[(int)currentStop].m_maxWaitTime = (byte)0;
            int  tempCounter = (int)instance3.m_nodes.m_buffer[(int)currentStop].m_tempCounter;
            bool flag        = false;
            int  num1        = Mathf.Max((int)(((double)position1.x - 64.0) / 8.0 + 1080.0), 0);
            int  num2        = Mathf.Max((int)(((double)position1.z - 64.0) / 8.0 + 1080.0), 0);
            int  num3        = Mathf.Min((int)(((double)position1.x + 64.0) / 8.0 + 1080.0), 2159);
            int  num4        = Mathf.Min((int)(((double)position1.z + 64.0) / 8.0 + 1080.0), 2159);
            //begin mod(+): track passengers in
            int passengersIn = 0;

            //end mod
            for (int index1 = num2; index1 <= num4 && !flag; ++index1)
            {
                for (int index2 = num1; index2 <= num3 && !flag; ++index2)
                {
                    ushort instanceID = instance1.m_citizenGrid[index1 * 2160 + index2];
                    int    num5       = 0;
                    while ((int)instanceID != 0 && !flag)
                    {
                        ushort nextGridInstance = instance1.m_instances.m_buffer[(int)instanceID].m_nextGridInstance;
                        if ((instance1.m_instances.m_buffer[(int)instanceID].m_flags &
                             CitizenInstance.Flags.WaitingTransport) != CitizenInstance.Flags.None)
                        {
                            Vector3 targetPos = (Vector3)instance1.m_instances.m_buffer[(int)instanceID].m_targetPos;
                            if ((double)Vector3.SqrMagnitude(targetPos - position1) < 4096.0)
                            {
                                CitizenInfo info = instance1.m_instances.m_buffer[(int)instanceID].Info;
                                if (info.m_citizenAI.TransportArriveAtSource(instanceID,
                                                                             ref instance1.m_instances.m_buffer[(int)instanceID], position1, position2))
                                {
                                    ushort trailerID;
                                    uint   unitID;
                                    if (Vehicle.GetClosestFreeTrailer(vehicleID, targetPos, out trailerID, out unitID))
                                    {
                                        if (info.m_citizenAI.SetCurrentVehicle(instanceID,
                                                                               ref instance1.m_instances.m_buffer[(int)instanceID], trailerID, unitID,
                                                                               position1))
                                        {
                                            ++tempCounter;
                                            ++instance2.m_vehicles.m_buffer[(int)trailerID].m_transferSize;
                                            //begin mod(+): increment passengers in
                                            ++passengersIn;
                                            //end mod
                                        }
                                        else
                                        {
                                            flag = true;
                                        }
                                    }
                                    else
                                    {
                                        flag = true;
                                    }
                                }
                            }
                        }
                        instanceID = nextGridInstance;
                        if (++num5 > 65536)
                        {
                            CODebugBase <LogChannel> .Error(LogChannel.Core,
                                                            "Invalid list detected!\n" + System.Environment.StackTrace);

                            break;
                        }
                    }
                }
            }
            instance3.m_nodes.m_buffer[(int)currentStop].m_tempCounter =
                (ushort)Mathf.Min(tempCounter, (int)ushort.MaxValue);

            //begin mod (+): calculate statistics after loading passengers
            int ticketPrice = data.Info.m_vehicleAI.GetTicketPrice(vehicleID, ref data);

            VehicleManagerMod.m_cachedVehicleData[(int)vehicleID].Add(passengersIn, ticketPrice);
            NetManagerMod.m_cachedNodeData[(int)currentStop].PassengersIn += passengersIn;
            //end mod
        }
Ejemplo n.º 6
0
        public override void OnUpdate(float realTimeDelta, float simulationTimeDelta)
        {
            if (_terminated)
            {
                return;
            }

            if (!_helper.GameLoaded)
            {
                return;
            }

            try
            {
                if (!_initialized)
                {
                    if (!IsOverwatched())
                    {
                        _helper.NotifyPlayer("Skylines Overwatch not found. Terminating...");
                        _terminated = true;

                        return;
                    }

                    SkylinesOverwatch.Settings.Instance.Enable.VehicleMonitor = true;

                    _initialized = true;

                    _helper.NotifyPlayer("Initialized");
                }
                else
                {
                    if (WorldInfoPanel.AnyWorldInfoPanelOpen())
                    {
                        _selected = WorldInfoPanel.GetCurrentInstanceID();

                        if (_selected.IsEmpty || _selected.Vehicle == 0)
                        {
                            _selected = default(InstanceID);
                        }
                    }
                    else
                    {
                        _selected = default(InstanceID);
                    }

                    VehicleManager         instance   = Singleton <VehicleManager> .instance;
                    InstanceID             instanceID = new InstanceID();
                    SkylinesOverwatch.Data data       = SkylinesOverwatch.Data.Instance;

                    foreach (ushort i in data.VehiclesUpdated)
                    {
                        Vehicle v = instance.m_vehicles.m_buffer[(int)i];

                        bool isBlocked  = !data.IsCar(i) && v.m_blockCounter >= 64; // we will let the game decide when to remove a blocked car
                        bool isConfused = v.Info.m_vehicleAI.GetLocalizedStatus(i, ref v, out instanceID) == _confused;

                        if (!isBlocked && !isConfused)
                        {
                            continue;
                        }

                        RemoveVehicle(i);
                    }

                    foreach (ushort i in _helper.ManualRemovalRequests)
                    {
                        RemoveVehicle(i);
                    }

                    _helper.ManualRemovalRequests.Clear();
                }
            }
            catch (Exception e)
            {
                string error = String.Format("Failed to {0}\r\n", !_initialized ? "initialize" : "update");
                error += String.Format("Error: {0}\r\n", e.Message);
                error += "\r\n";
                error += "==== STACK TRACE ====\r\n";
                error += e.StackTrace;

                _helper.Log(error);

                if (!_initialized)
                {
                    _terminated = true;
                }
            }

            base.OnUpdate(realTimeDelta, simulationTimeDelta);
        }
Ejemplo n.º 7
0
 private static bool isVehicleCreated(VehicleManager vMgr, ushort iVehicleIndex)
 {
     if ((vMgr.m_vehicles.m_buffer[iVehicleIndex].m_flags & Vehicle.Flags.Created) == Vehicle.Flags.Created )
     {
         return true;
     }
     return false;
 }
		private void SimulateTrailingVehicles(ushort leaderId, ref Vehicle leaderData, int lodPhysics,
			ushort trailingVehicleId, ref VehicleManager vehicleManager, int numberOfIterations) {
			if (trailingVehicleId == 0) {
				return;
			}

			var trailingTrailingVehicleId = vehicleManager.m_vehicles.m_buffer[trailingVehicleId].m_trailingVehicle;
			var trailingVehicleInfo = vehicleManager.m_vehicles.m_buffer[trailingVehicleId].Info;

			trailingVehicleInfo.m_vehicleAI.SimulationStep(trailingVehicleId,
				ref vehicleManager.m_vehicles.m_buffer[trailingVehicleId], leaderId,
				ref leaderData, lodPhysics);

			if (++numberOfIterations > 16384) {
				CODebugBase<LogChannel>.Error(LogChannel.Core,
					"Invalid list detected!\n" + Environment.StackTrace);
				return;
			}
			SimulateTrailingVehicles(leaderId, ref leaderData, lodPhysics, trailingTrailingVehicleId, ref vehicleManager, numberOfIterations);
		}
        public void CustomSimulationStep(ushort instanceId,
                                         ref CitizenInstance instanceData,
                                         Vector3 physicsLodRefPos)
        {
#if DEBUG
            bool citizenDebug = (DebugSettings.CitizenInstanceId == 0 ||
                                 DebugSettings.CitizenInstanceId == instanceId) &&
                                (DebugSettings.CitizenId == 0 ||
                                 DebugSettings.CitizenId == instanceData.m_citizen) &&
                                (DebugSettings.SourceBuildingId == 0 ||
                                 DebugSettings.SourceBuildingId == instanceData.m_sourceBuilding) &&
                                (DebugSettings.TargetBuildingId == 0 ||
                                 DebugSettings.TargetBuildingId == instanceData.m_targetBuilding);
            bool logParkingAi = DebugSwitch.BasicParkingAILog.Get() && citizenDebug;
#else
            var logParkingAi = false;
#endif
            CitizenManager citizenManager = Singleton <CitizenManager> .instance;
            uint           citizenId      = instanceData.m_citizen;

            if ((instanceData.m_flags & (CitizenInstance.Flags.Blown
                                         | CitizenInstance.Flags.Floating)) != CitizenInstance.Flags.None &&
                (instanceData.m_flags & CitizenInstance.Flags.Character) == CitizenInstance.Flags.None)
            {
                citizenManager.ReleaseCitizenInstance(instanceId);
                if (citizenId != 0u)
                {
                    citizenManager.ReleaseCitizen(citizenId);
                }

                return;
            }

            Citizen[] citizensBuffer = citizenManager.m_citizens.m_buffer;
            if ((instanceData.m_flags & CitizenInstance.Flags.WaitingPath) != CitizenInstance.Flags.None)
            {
                PathManager pathManager   = Singleton <PathManager> .instance;
                byte        pathFindFlags = pathManager.m_pathUnits.m_buffer[instanceData.m_path].m_pathFindFlags;

                // NON-STOCK CODE START
                ExtPathState mainPathState = ExtPathState.Calculating;
                if ((pathFindFlags & PathUnit.FLAG_FAILED) != 0 || instanceData.m_path == 0)
                {
                    mainPathState = ExtPathState.Failed;
                }
                else if ((pathFindFlags & PathUnit.FLAG_READY) != 0)
                {
                    mainPathState = ExtPathState.Ready;
                }

                if (logParkingAi)
                {
                    Log._Debug(
                        $"CustomHumanAI.CustomSimulationStep({instanceId}): " +
                        $"Path: {instanceData.m_path}, mainPathState={mainPathState}");
                }

                ExtSoftPathState finalPathState;
                using (var bm = Benchmark.MaybeCreateBenchmark(
                           null,
                           "ConvertPathStateToSoftPathState+UpdateCitizenPathState"))
                {
                    finalPathState = ExtCitizenInstance.ConvertPathStateToSoftPathState(mainPathState);

                    if (Options.parkingAI)
                    {
                        finalPathState = AdvancedParkingManager.Instance.UpdateCitizenPathState(
                            instanceId,
                            ref instanceData,
                            ref ExtCitizenInstanceManager
                            .Instance.ExtInstances[
                                instanceId],
                            ref ExtCitizenManager
                            .Instance.ExtCitizens[
                                citizenId],
                            ref citizensBuffer[
                                instanceData.m_citizen],
                            mainPathState);
                        if (logParkingAi)
                        {
                            Log._Debug(
                                $"CustomHumanAI.CustomSimulationStep({instanceId}): " +
                                $"Applied Parking AI logic. Path: {instanceData.m_path}, " +
                                $"mainPathState={mainPathState}, finalPathState={finalPathState}, " +
                                $"extCitizenInstance={ExtCitizenInstanceManager.Instance.ExtInstances[instanceId]}");
                        }
                    } // if Options.parkingAi
                }

                switch (finalPathState)
                {
                case ExtSoftPathState.Ready: {
                    if (logParkingAi)
                    {
                        Log._Debug(
                            $"CustomHumanAI.CustomSimulationStep({instanceId}): Path-finding " +
                            $"succeeded for citizen instance {instanceId} " +
                            $"(finalPathState={finalPathState}). Path: {instanceData.m_path} " +
                            "-- calling HumanAI.PathfindSuccess");
                    }

                    if (citizenId == 0 ||
                        citizensBuffer[instanceData.m_citizen].m_vehicle == 0)
                    {
                        Spawn(instanceId, ref instanceData);
                    }

                    instanceData.m_pathPositionIndex = 255;
                    instanceData.m_flags            &= ~CitizenInstance.Flags.WaitingPath;
                    instanceData.m_flags            &= ~(CitizenInstance.Flags.HangAround
                                                         | CitizenInstance.Flags.Panicking
                                                         | CitizenInstance.Flags.SittingDown
                                                         | CitizenInstance.Flags.Cheering);

                    // NON-STOCK CODE START (transferred from ResidentAI.PathfindSuccess)
                    const Citizen.Flags CTZ_MASK = Citizen.Flags.Tourist
                                                   | Citizen.Flags.MovingIn
                                                   | Citizen.Flags.DummyTraffic;
                    if (citizenId != 0 &&
                        (citizensBuffer[citizenId].m_flags & CTZ_MASK) == Citizen.Flags.MovingIn)
                    {
                        StatisticBase statisticBase = Singleton <StatisticsManager>
                                                      .instance.Acquire <StatisticInt32>(StatisticType.MoveRate);

                        statisticBase.Add(1);
                    }

                    // NON-STOCK CODE END
                    PathfindSuccess(instanceId, ref instanceData);
                    break;
                }

                case ExtSoftPathState.Ignore: {
                    if (logParkingAi)
                    {
                        Log._Debug(
                            $"CustomHumanAI.CustomSimulationStep({instanceId}): " +
                            "Path-finding result shall be ignored for citizen instance " +
                            $"{instanceId} (finalPathState={finalPathState}). " +
                            $"Path: {instanceData.m_path} -- ignoring");
                    }

                    return;
                }

                case ExtSoftPathState.Calculating:
                default: {
                    if (logParkingAi)
                    {
                        Log._Debug(
                            $"CustomHumanAI.CustomSimulationStep({instanceId}): " +
                            $"Path-finding result undetermined for citizen instance {instanceId} " +
                            $"(finalPathState={finalPathState}). " +
                            $"Path: {instanceData.m_path} -- continue");
                    }

                    break;
                }

                case ExtSoftPathState.FailedHard: {
                    if (logParkingAi)
                    {
                        Log._Debug(
                            $"CustomHumanAI.CustomSimulationStep({instanceId}): " +
                            $"HARD path-finding failure for citizen instance {instanceId} " +
                            $"(finalPathState={finalPathState}). Path: {instanceData.m_path} " +
                            "-- calling HumanAI.PathfindFailure");
                    }

                    instanceData.m_flags &= ~CitizenInstance.Flags.WaitingPath;
                    instanceData.m_flags &= ~(CitizenInstance.Flags.HangAround
                                              | CitizenInstance.Flags.Panicking
                                              | CitizenInstance.Flags.SittingDown
                                              | CitizenInstance.Flags.Cheering);
                    Singleton <PathManager> .instance.ReleasePath(instanceData.m_path);

                    instanceData.m_path = 0u;
                    PathfindFailure(instanceId, ref instanceData);
                    return;
                }

                case ExtSoftPathState.FailedSoft: {
                    if (logParkingAi)
                    {
                        Log._Debug(
                            $"CustomHumanAI.CustomSimulationStep({instanceId}): " +
                            $"SOFT path-finding failure for citizen instance {instanceId} " +
                            $"(finalPathState={finalPathState}). Path: {instanceData.m_path} " +
                            "-- calling HumanAI.InvalidPath");
                    }

                    // path mode has been updated, repeat path-finding
                    instanceData.m_flags &= ~CitizenInstance.Flags.WaitingPath;
                    instanceData.m_flags &= ~(CitizenInstance.Flags.HangAround
                                              | CitizenInstance.Flags.Panicking
                                              | CitizenInstance.Flags.SittingDown
                                              | CitizenInstance.Flags.Cheering);
                    InvalidPath(instanceId, ref instanceData);
                    break;
                }
                }

                // NON-STOCK CODE END
            }

            // NON-STOCK CODE START
            using (var bm = Benchmark.MaybeCreateBenchmark(null, "ExtSimulationStep")) {
                if (Options.parkingAI)
                {
                    if (ExtSimulationStep(
                            instanceId,
                            ref instanceData,
                            ref ExtCitizenInstanceManager.Instance.ExtInstances[instanceId],
                            physicsLodRefPos))
                    {
                        return;
                    }
                }
            }

            // NON-STOCK CODE END
            base.SimulationStep(instanceId, ref instanceData, physicsLodRefPos);

            VehicleManager vehicleManager = Singleton <VehicleManager> .instance;
            ushort         vehicleId      = 0;
            if (instanceData.m_citizen != 0u)
            {
                vehicleId = citizensBuffer[instanceData.m_citizen].m_vehicle;
            }

            if (vehicleId != 0)
            {
                Vehicle[]   vehiclesBuffer = vehicleManager.m_vehicles.m_buffer;
                VehicleInfo vehicleInfo    = vehiclesBuffer[vehicleId].Info;

                if (vehicleInfo.m_vehicleType == VehicleInfo.VehicleType.Bicycle)
                {
                    vehicleInfo.m_vehicleAI.SimulationStep(
                        vehicleId,
                        ref vehiclesBuffer[vehicleId],
                        vehicleId,
                        ref vehiclesBuffer[vehicleId],
                        0);
                    vehicleId = 0;
                }
            }

            if (vehicleId != 0 ||
                (instanceData.m_flags & (CitizenInstance.Flags.Character
                                         | CitizenInstance.Flags.WaitingPath
                                         | CitizenInstance.Flags.Blown
                                         | CitizenInstance.Flags.Floating)) !=
                CitizenInstance.Flags.None)
            {
                return;
            }

            instanceData.m_flags &= ~(CitizenInstance.Flags.HangAround
                                      | CitizenInstance.Flags.Panicking
                                      | CitizenInstance.Flags.SittingDown);
            ArriveAtDestination(instanceId, ref instanceData, false);
            citizenManager.ReleaseCitizenInstance(instanceId);
        }
Ejemplo n.º 10
0
 public VehicleAddPacketProcessor(PlayerManager playerManager, VehicleManager vehicleManager)
 {
     this.playerManager  = playerManager;
     this.vehicleManager = vehicleManager;
 }
Ejemplo n.º 11
0
        void Initialize()
        {
            instance = this;

            ModConsole.Log("[MOP] Loading MOP...");

            // Initialize the worldObjectManager list
            worldObjectManager = new WorldObjectManager();

            // Looking for player and yard
            player = GameObject.Find("PLAYER").transform;

            // Add GameFixes MonoBehaviour.
            try
            {
                gameObject.AddComponent <GameFixes>();
            }
            catch (Exception ex)
            {
                ExceptionManager.New(ex, false, $"GAME_FIXES_INITIALIZAITON | {ex}");
            }

            // Loading vehicles
            vehicleManager = new VehicleManager();

            // World Objects
            try
            {
                worldObjectManager.Add("CABIN", DisableOn.Distance | DisableOn.IgnoreInQualityMode);
                worldObjectManager.Add("COTTAGE", DisableOn.Distance, 400);
                worldObjectManager.Add("DANCEHALL", DisableOn.Distance, 500);
                worldObjectManager.Add("PERAJARVI", DisableOn.Distance | DisableOn.IgnoreInQualityMode, 400);
                worldObjectManager.Add("SOCCER", DisableOn.Distance);
                worldObjectManager.Add("WATERFACILITY", DisableOn.Distance, 300);
                worldObjectManager.Add("DRAGRACE", DisableOn.Distance, 1100);
                worldObjectManager.Add("StrawberryField", DisableOn.Distance, 400);
                worldObjectManager.Add("MAP/Buildings/DINGONBIISI", DisableOn.Distance, 400);
                worldObjectManager.Add("RALLY/PartsSalesman", DisableOn.Distance, 400);
                worldObjectManager.Add("LakeSmallBottom1", DisableOn.Distance, 500);
                worldObjectManager.Add("machine", DisableOn.Distance, 200, silent: true);

                ModConsole.Log("[MOP] World objects (1) loaded");
            }
            catch (Exception ex)
            {
                ExceptionManager.New(ex, false, "WORLD_OBJECTS_1_INITIALIZAITON_FAIL");
            }

            // Initialize places.
            placeManager = new PlaceManager();

            // Fixes
            GameFixes.Instance.MainFixes();

            //Things that should be enabled when out of proximity of the house
            try
            {
                worldObjectManager.Add("NPC_CARS", DisableOn.PlayerInHome);
                worldObjectManager.Add("TRAFFIC", DisableOn.PlayerInHome);
                worldObjectManager.Add("TRAIN", DisableOn.PlayerInHome | DisableOn.IgnoreInQualityMode);
                worldObjectManager.Add("Buildings", DisableOn.PlayerInHome);
                worldObjectManager.Add("TrafficSigns", DisableOn.PlayerInHome);
                worldObjectManager.Add("StreetLights", DisableOn.PlayerInHome);
                worldObjectManager.Add("HUMANS", DisableOn.PlayerInHome);
                worldObjectManager.Add("TRACKFIELD", DisableOn.PlayerInHome);
                worldObjectManager.Add("SkijumpHill", DisableOn.PlayerInHome | DisableOn.IgnoreInQualityMode);
                worldObjectManager.Add("Factory", DisableOn.PlayerInHome);
                worldObjectManager.Add("WHEAT", DisableOn.PlayerInHome);
                worldObjectManager.Add("RAILROAD", DisableOn.PlayerInHome);
                worldObjectManager.Add("AIRPORT", DisableOn.PlayerInHome);
                worldObjectManager.Add("RAILROAD_TUNNEL", DisableOn.PlayerInHome);
                worldObjectManager.Add("PierDancehall", DisableOn.PlayerInHome);
                worldObjectManager.Add("PierRiver", DisableOn.PlayerInHome);
                worldObjectManager.Add("PierStore", DisableOn.PlayerInHome);
                worldObjectManager.Add("BRIDGE_dirt", DisableOn.PlayerInHome);
                worldObjectManager.Add("BRIDGE_highway", DisableOn.PlayerInHome);
                worldObjectManager.Add("BirdTower", DisableOn.Distance, 400);
                worldObjectManager.Add("RYKIPOHJA", DisableOn.PlayerInHome);
                worldObjectManager.Add("COMPUTER", DisableOn.PlayerAwayFromHome);

                ModConsole.Log("[MOP] World objects (2) loaded");
            }
            catch (Exception ex)
            {
                ExceptionManager.New(ex, false, "WORLD_OBJECTS_2_INITIALIZAITON_FAIL");
            }

            // Adding area check if Satsuma is in the inspection's area
            try
            {
                SatsumaInArea inspectionArea = GameObject.Find("INSPECTION").AddComponent <SatsumaInArea>();
                inspectionArea.Initialize(new Vector3(20, 20, 20));
            }
            catch (Exception ex)
            {
                ExceptionManager.New(ex, false, "SATSUMA_AREA_CHECK_INSPECTION_FAIL");
            }

            // Check for when Satsuma is on the lifter
            try
            {
                SatsumaInArea lifterArea = GameObject.Find("REPAIRSHOP/Lifter/Platform").AddComponent <SatsumaInArea>();
                lifterArea.Initialize(new Vector3(5, 5, 5));
            }
            catch (Exception ex)
            {
                ExceptionManager.New(ex, false, "SATSUMA_AREA_CHECK_REPAIRSHOP_FAIL");
            }

            // Area for the parc ferme.
            try
            {
                GameObject parcFermeTrigger = new GameObject("MOP_ParcFermeTrigger");
                parcFermeTrigger.transform.parent   = GameObject.Find("RALLY").transform.Find("Scenery");
                parcFermeTrigger.transform.position = new Vector3(-1383f, 3f, 1260f);
                SatsumaInArea parcFerme = parcFermeTrigger.AddComponent <SatsumaInArea>();
                parcFerme.Initialize(new Vector3(41, 12, 35));
            }
            catch (Exception ex)
            {
                ExceptionManager.New(ex, false, "PARC_FERME_TRIGGER_FAIL");
            }

            ModConsole.Log("[MOP] Satsuma triggers loaded");

            // Jokke's furnitures.
            // Only renderers are going to be toggled.
            try
            {
                if (GameObject.Find("tv(Clo01)"))
                {
                    string[] furnitures = { "tv(Clo01)",    "chair(Clo02)", "chair(Clo05)", "bench(Clo01)",
                                            "bench(Clo02)", "table(Clo02)", "table(Clo03)", "table(Clo04)",
                                            "table(Clo05)", "desk(Clo01)",  "arm chair(Clo01)" };

                    foreach (string furniture in furnitures)
                    {
                        GameObject g = GameObject.Find(furniture);
                        if (g)
                        {
                            g.transform.parent = null;
                            worldObjectManager.Add(g, DisableOn.Distance, 100, ToggleModes.Renderer);
                        }
                    }

                    ModConsole.Log("[MOP] Jokke's furnitures found and loaded");
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.New(ex, false, "JOKKE_FURNITURE_ERROR");
            }

            // Haybales.
            // First we null out the prevent it from reloading the position of haybales.
            try
            {
                GameObject haybalesParent = GameObject.Find("JOBS/HayBales");
                if (haybalesParent != null)
                {
                    haybalesParent.GetComponent <PlayMakerFSM>().Fsm.RestartOnEnable = false;
                    // And now we add all child haybale to world objects.
                    foreach (Transform haybale in haybalesParent.transform.GetComponentInChildren <Transform>())
                    {
                        worldObjectManager.Add(haybale.gameObject.name, DisableOn.Distance | DisableOn.IgnoreInQualityMode, 120);
                    }
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.New(ex, false, "HAYBALES_FIX_ERROR");
            }

            // Logwalls
            try
            {
                foreach (GameObject wall in Resources.FindObjectsOfTypeAll <GameObject>().Where(g => g.name == "LogwallLarge"))
                {
                    worldObjectManager.Add(wall, DisableOn.Distance, 300);
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.New(ex, false, "LOGWALL_LOAD_ERROR");
            }

            // Perajarvi Church.
            try
            {
                if (MopSettings.Mode != PerformanceMode.Performance)
                {
                    GameObject church = GameObject.Find("PERAJARVI").transform.Find("CHURCH").gameObject;
                    church.transform.parent = null;
                    GameObject churchLOD = church.transform.Find("LOD").gameObject;
                    church.GetComponent <PlayMakerFSM>().enabled = false;
                    worldObjectManager.Add(churchLOD, DisableOn.Distance, 300);
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.New(ex, false, "CHURCH_LOD_ERROR");
            }

            // Lake houses.
            try
            {
                if (MopSettings.Mode == PerformanceMode.Quality)
                {
                    GameObject.Find("PERAJARVI").transform.Find("TerraceHouse").transform.parent = null;
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.New(ex, false, "LAKE_HOUSE_ERROR");
            }

            // VehiclesHighway renderers.
            try
            {
                Transform vehiclesHighway = GameObject.Find("TRAFFIC").transform.Find("VehiclesHighway");
                foreach (var f in vehiclesHighway.GetComponentsInChildren <Transform>(true).Where(f => f.parent == vehiclesHighway))
                {
                    worldObjectManager.Add(f.gameObject, DisableOn.Distance, 600, ToggleModes.MultipleRenderers);
                }

                // Also we gonna fix the lag on initial traffic load.
                vehiclesHighway.gameObject.SetActive(true);
            }
            catch (Exception ex)
            {
                ExceptionManager.New(ex, false, "TRAFFIC_VEHICLES_ERROR");
            }

            // FITTAN renderers.
            try
            {
                worldObjectManager.Add(GameObject.Find("TRAFFIC").transform.Find("VehiclesDirtRoad/Rally/FITTAN").gameObject, DisableOn.Distance, 600, ToggleModes.MultipleRenderers);
            }
            catch (Exception ex)
            {
                ExceptionManager.New(ex, false, "FITTAN_RENDERERS_ERROR");
            }

            // Initialize Items class
            try
            {
                new ItemsManager();
                ItemsManager.Instance.Initialize();
                ModConsole.Log("[MOP] Items class initialized");
            }
            catch (Exception ex)
            {
                ExceptionManager.New(ex, true, "ITEMS_CLASS_ERROR");
            }

            try
            {
                DateTime now = DateTime.Now;
                if (now.Day == 1 && now.Month == 4)
                {
                    GameObject     fpsObject = GameObject.Find("GUI").transform.Find("HUD/FPS/HUDValue").gameObject;
                    PlayMakerFSM[] fsms      = fpsObject.GetComponents <PlayMakerFSM>();
                    foreach (var fsm in fsms)
                    {
                        fsm.enabled = false;
                    }
                    fpsObject.GetComponent <TextMesh>().text = "99999999 :)";
                    fpsObject.transform.Find("HUDValueShadow").GetComponent <TextMesh>().text = "99999999 :)";
                }
            }
            catch { }

            HookPreSaveGame();

            ModConsole.Log("[MOP] Loading rules...");
            foreach (ToggleRule v in RulesManager.Instance.ToggleRules)
            {
                try
                {
                    switch (v.ToggleMode)
                    {
                    default:
                        ModConsole.LogError($"[MOP] Unrecognized toggle mode for {v.ObjectName}: {v.ToggleMode}.");
                        break;

                    case ToggleModes.Simple:
                        if (GameObject.Find(v.ObjectName) == null)
                        {
                            ModConsole.LogError($"[MOP] Couldn't find world object {v.ObjectName}");
                            continue;
                        }

                        worldObjectManager.Add(v.ObjectName, DisableOn.Distance);
                        break;

                    case ToggleModes.Renderer:
                        if (GameObject.Find(v.ObjectName) == null)
                        {
                            ModConsole.LogError($"[MOP] Couldn't find world object {v.ObjectName}");
                            continue;
                        }

                        worldObjectManager.Add(v.ObjectName, DisableOn.Distance, 200, ToggleModes.Renderer);
                        break;

                    case ToggleModes.Item:
                        GameObject g = GameObject.Find(v.ObjectName);

                        if (g == null)
                        {
                            ModConsole.LogError($"[MOP] Couldn't find item {v.ObjectName}");
                            continue;
                        }

                        if (g.GetComponent <ItemBehaviour>() == null)
                        {
                            g.AddComponent <ItemBehaviour>();
                        }
                        break;

                    case ToggleModes.Vehicle:
                        if (RulesManager.Instance.SpecialRules.IgnoreModVehicles)
                        {
                            continue;
                        }

                        if (GameObject.Find(v.ObjectName) == null)
                        {
                            ModConsole.LogError($"[MOP] Couldn't find vehicle {v.ObjectName}");
                            continue;
                        }

                        vehicleManager.Add(new Vehicle(v.ObjectName));
                        break;

                    case ToggleModes.VehiclePhysics:
                        if (RulesManager.Instance.SpecialRules.IgnoreModVehicles)
                        {
                            continue;
                        }

                        if (GameObject.Find(v.ObjectName) == null)
                        {
                            ModConsole.LogError($"[MOP] Couldn't find vehicle {v.ObjectName}");
                            continue;
                        }
                        vehicleManager.Add(new Vehicle(v.ObjectName));
                        Vehicle veh = vehicleManager[vehicleManager.Count - 1];
                        veh.Toggle = veh.ToggleUnityCar;
                        break;
                    }
                }
                catch (Exception ex)
                {
                    ExceptionManager.New(ex, false, "TOGGLE_RULES_LOAD_ERROR");
                }
            }

            ModConsole.Log("[MOP] Rules loading complete!");

            // Initialzie sector manager
            try
            {
                gameObject.AddComponent <SectorManager>();
            }
            catch (Exception ex)
            {
                ExceptionManager.New(ex, true, "SECTOR_MANAGER_ERROR");
            }

            // Add DynamicDrawDistance component.
            try
            {
                gameObject.AddComponent <DynamicDrawDistance>();
            }
            catch (Exception ex)
            {
                ExceptionManager.New(ex, false, "DYNAMIC_DRAW_DISTANCE_ERROR");
            }

            try
            {
                if (MopSettings.Mode != PerformanceMode.Safe)
                {
                    ToggleAll(false, ToggleAllMode.OnLoad);
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.New(ex, true, "TOGGLE_ALL_ERROR");
            }

            // Initialize the coroutines.
            currentLoop = LoopRoutine();
            StartCoroutine(currentLoop);
            currentControlCoroutine = ControlCoroutine();
            StartCoroutine(currentControlCoroutine);

            ModConsole.Log("<color=green>[MOP] MOD LOADED SUCCESFULLY!</color>");
            Resources.UnloadUnusedAssets();
            GC.Collect();

            // If generate-list command is set to true, generate the list of items that are disabled by MOP.
            if (MopSettings.GenerateToggledItemsListDebug)
            {
                if (System.IO.File.Exists("world.txt"))
                {
                    System.IO.File.Delete("world.txt");
                }
                string world = "";
                foreach (var w in worldObjectManager.GetList())
                {
                    if (world.Contains(w.GetName()))
                    {
                        continue;
                    }
                    world += w.GetName() + ", ";
                }
                System.IO.File.WriteAllText("world.txt", world);
                System.Diagnostics.Process.Start("world.txt");

                if (System.IO.File.Exists("vehicle.txt"))
                {
                    System.IO.File.Delete("vehicle.txt");
                }
                string vehiclez = "";
                foreach (var w in vehicleManager.List())
                {
                    vehiclez += w.gameObject.name + ", ";
                }
                System.IO.File.WriteAllText("vehicle.txt", vehiclez);
                System.Diagnostics.Process.Start("vehicle.txt");

                if (System.IO.File.Exists("items.txt"))
                {
                    System.IO.File.Delete("items.txt");
                }
                string items = "";
                foreach (var w in ItemsManager.Instance.All())
                {
                    if (items.Contains(w.gameObject.name))
                    {
                        continue;
                    }
                    items += w.gameObject.name + ", ";
                }
                System.IO.File.WriteAllText("items.txt", items);
                System.Diagnostics.Process.Start("items.txt");

                if (System.IO.File.Exists("place.txt"))
                {
                    System.IO.File.Delete("place.txt");
                }
                string place = "";
                foreach (var w in placeManager.GetList())
                {
                    place += w.GetName() + ": ";
                    foreach (var f in w.GetDisableableChilds())
                    {
                        if (place.Contains(f.gameObject.name))
                        {
                            continue;
                        }
                        place += f.gameObject.name + ", ";
                    }

                    place += "\n\n";
                }
                System.IO.File.WriteAllText("place.txt", place);
                System.Diagnostics.Process.Start("place.txt");
            }
        }
Ejemplo n.º 12
0
        private void API_onClientEventTrigger(Client sender, string eventName, params object[] arguments)
        {
            if (eventName == "vehicledealer_selectcar")
            {
                Character character = sender.GetCharacter();

                string[] selectedCar = null;

                #region Get Car Info.

                switch ((int)arguments[0])
                {
                case 0:
                    selectedCar = _motorsycles[(int)arguments[1]];
                    break;

                case 1:
                    selectedCar = _copues[(int)arguments[1]];
                    break;

                case 2:
                    selectedCar = _trucksnvans[(int)arguments[1]];
                    break;

                case 3:
                    selectedCar = _offroad[(int)arguments[1]];
                    break;

                case 4:
                    selectedCar = _musclecars[(int)arguments[1]];
                    break;

                case 5:
                    selectedCar = _suv[(int)arguments[1]];
                    break;

                case 6:
                    selectedCar = _supercars[(int)arguments[1]];
                    break;

                case 7:
                    selectedCar = _cycles[(int)arguments[1]];
                    break;

                case 8:
                    selectedCar = _sedans[(int)arguments[1]];
                    break;

                case 9:
                    selectedCar = _sportsCars[(int)arguments[1]];
                    break;

                case 10:
                    selectedCar = _compactCars[(int)arguments[1]];
                    break;
                }

                #endregion

                if (selectedCar == null)
                {
                    return;
                }

                if (Money.GetCharacterMoney(character) >= Convert.ToInt32(selectedCar[2]))
                {
                    //Remove price.
                    InventoryManager.DeleteInventoryItem(character, typeof(Money), Convert.ToInt32(selectedCar[2]));

                    //Spawn positions.
                    Vector3[] spawnPoss =
                    {
                        new Vector3(-42.44885, -1115.865, 25.86397),
                        new Vector3(-45.04674, -1116.336, 25.86318),
                        new Vector3(-47.77579, -1116.404, 25.86377),
                        new Vector3(-50.53339, -1116.758, 25.86334),
                        new Vector3(-53.56507, -1116.645, 25.86412),
                        new Vector3(-56.42249, -1116.668,  25.8641),
                        new Vector3(-59.06798, -1117.206, 25.86339),
                        new Vector3(-61.86055, -1117.122, 25.8629)
                    };
                    var randomPos = new Random().Next(1, spawnPoss.Length) - 1;
                    //Create the vehicle.
                    var theVehicle = VehicleManager.CreateVehicle(
                        (VehicleHash)Convert.ToInt32(selectedCar[1]),
                        spawnPoss[randomPos],
                        new Vector3(0.1917319, 0.1198539, -177.1394),
                        "...",
                        character.Id,
                        vehicle_manager.Vehicle.VehTypePerm
                        );
                    theVehicle.OwnerName = character.CharacterName;

                    //Add it to the players cars.
                    theVehicle.Insert();

                    //Spawn it.
                    if (VehicleManager.spawn_vehicle(theVehicle) != 1)
                    {
                        API.SendChatMessageToPlayer(sender, "An error occured while spawning your vehicle.");
                    }

                    //Notify.
                    API.SendChatMessageToPlayer(sender,
                                                $"You have sucessfully bought the ~g~{selectedCar[0]}~w~ for ${selectedCar[2]}.");
                    API.SendChatMessageToPlayer(sender, "Use /myvehicles to manage it.");

                    //Log it.
                    LogManager.Log(LogManager.LogTypes.Stats, $"[Vehicle Dealership] {sender.GetCharacter().CharacterName}[{sender.GetAccount().AccountName}] has bought a(n) {API.GetVehicleDisplayName(theVehicle.VehModel)} for ${selectedCar[2]}.");

                    //Exit.
                    API.TriggerClientEvent(sender, "dealership_exitdealermenu");
                }
                else
                {
                    API.SendChatMessageToPlayer(sender,
                                                $"You don't have enough money to buy the ~g~{selectedCar[0]}~w~.");
                }
            }
        }
Ejemplo n.º 13
0
        private static bool CreateVehicle(VehicleManager vMgr, out ushort vehicle, ref Randomizer r, VehicleInfo info, Vector3 position, TransferManager.TransferReason type, bool transferToSource, bool transferToTarget)
        {
            bool AttemptFlag = false;
            uint ReserveMax = (vMgr.m_vehicles.m_size - 1) - Mod.RESERVEAMOUNT;  //we subtract 1 cause game doesn't use entry 0 for a real vehicle.
            int CurrentVehicleNum = vMgr.m_vehicleCount; //vMgr.m_vehicles.ItemCount(); //found they were never different ~+\- a nanosecond.
            int m_VecCount = vMgr.m_vehicleCount;  //unly
            Mod.timesCV_CalledTotal++; //stat tracking.
            if (CurrentVehicleNum >= ReserveMax && type != TransferManager.TransferReason.Fire && type != TransferManager.TransferReason.Sick
                && type != TransferManager.TransferReason.Garbage && type != TransferManager.TransferReason.Dead
                && type != TransferManager.TransferReason.Crime && type != TransferManager.TransferReason.Bus
                && type != TransferManager.TransferReason.MetroTrain && type != TransferManager.TransferReason.PassengerTrain
                && type != TransferManager.TransferReason.DeadMove && type != TransferManager.TransferReason.CriminalMove
                && type != TransferManager.TransferReason.Taxi && type != TransferManager.TransferReason.GarbageMove
                && type != TransferManager.TransferReason.Tram && type != TransferManager.TransferReason.RoadMaintenance
                && type != TransferManager.TransferReason.Snow && type != TransferManager.TransferReason.SnowMove
                && type != TransferManager.TransferReason.Fire2 && type != TransferManager.TransferReason.ForestFire
                && type != TransferManager.TransferReason.FloodWater && type !=TransferManager.TransferReason.SickMove
                && type != TransferManager.TransferReason.Sick2 && type !=TransferManager.TransferReason.EvacuateVipA
                && type != TransferManager.TransferReason.EvacuateVipB && type != TransferManager.TransferReason.EvacuateVipC
                && type != TransferManager.TransferReason.EvacuateVipD)

            {
                Mod.timesFailedByReserve++; //stat tracking
                Mod.timesFailedToCreate++;  //stat tracking
                vehicle = 0;
                return false;
            }

            if (CurrentVehicleNum >= ReserveMax)
            {
                AttemptFlag = true;
                Mod.timesReservedAttempted++;  //stat tracking.
                if (CurrentVehicleNum == (vMgr.m_vehicles.m_size -1)) { Mod.timesLimitReached++; } //stattracking
                if (Mod.DEBUG_LOG_ON && Mod.DEBUG_LOG_LEVEL >= 3) { Helper.dbgLog(" Vehicles[" + CurrentVehicleNum.ToString() +
                    "] max reached, attempting to use reserve for a " + type.ToString() + " - " + System.DateTime.Now.ToString() +
                    " : " + DateTime.Now.Millisecond.ToString() + " counter=" + Mod.timesReservedAttempted.ToString() + " reservemax=" +
                    ReserveMax.ToString()); }
            }

            //Original Untouched Below except for attemptflag and Mod.timeFailedToCreate Counters and debug logging.
            ushort num;
            if (!vMgr.m_vehicles.CreateItem(out num, ref r))
            {
                vehicle = 0;
                if (AttemptFlag)
                {
                    Mod.timesReserveAttemptFailed++ ; //stat tracking.
                    if (Mod.DEBUG_LOG_ON && Mod.DEBUG_LOG_LEVEL >= 2) {  Helper.dbgLog(" Vehicles[" + CurrentVehicleNum.ToString() +
                        "] max reached, attempted to use reserve for a " + type.ToString() + " but Failed! " + System.DateTime.Now.ToString() + " : " +
                        DateTime.Now.Millisecond.ToString() + " counter=" + Mod.timesReservedAttempted.ToString()); }
                }

                Mod.timesFailedToCreate++;  //stat tracking
                return false;
            }

            vehicle = num;
            Vehicle.Frame frame = new Vehicle.Frame(position, Quaternion.identity);
            vMgr.m_vehicles.m_buffer[vehicle].m_flags = Vehicle.Flags.Created;
            if (transferToSource)
            {
                vMgr.m_vehicles.m_buffer[vehicle].m_flags = vMgr.m_vehicles.m_buffer[vehicle].m_flags | Vehicle.Flags.TransferToSource;
            }
            if (transferToTarget)
            {
                vMgr.m_vehicles.m_buffer[vehicle].m_flags = vMgr.m_vehicles.m_buffer[vehicle].m_flags | Vehicle.Flags.TransferToTarget;
            }
            vMgr.m_vehicles.m_buffer[vehicle].Info = info;
            vMgr.m_vehicles.m_buffer[vehicle].m_frame0 = frame;
            vMgr.m_vehicles.m_buffer[vehicle].m_frame1 = frame;
            vMgr.m_vehicles.m_buffer[vehicle].m_frame2 = frame;
            vMgr.m_vehicles.m_buffer[vehicle].m_frame3 = frame;
            vMgr.m_vehicles.m_buffer[vehicle].m_targetPos0 = Vector4.zero;
            vMgr.m_vehicles.m_buffer[vehicle].m_targetPos1 = Vector4.zero;
            vMgr.m_vehicles.m_buffer[vehicle].m_targetPos2 = Vector4.zero;
            vMgr.m_vehicles.m_buffer[vehicle].m_targetPos3 = Vector4.zero;
            vMgr.m_vehicles.m_buffer[vehicle].m_sourceBuilding = 0;
            vMgr.m_vehicles.m_buffer[vehicle].m_targetBuilding = 0;
            vMgr.m_vehicles.m_buffer[vehicle].m_transferType = (byte)type;
            vMgr.m_vehicles.m_buffer[vehicle].m_transferSize = 0;
            vMgr.m_vehicles.m_buffer[vehicle].m_waitCounter = 0;
            vMgr.m_vehicles.m_buffer[vehicle].m_blockCounter = 0;
            vMgr.m_vehicles.m_buffer[vehicle].m_nextGridVehicle = 0;
            vMgr.m_vehicles.m_buffer[vehicle].m_nextOwnVehicle = 0;
            vMgr.m_vehicles.m_buffer[vehicle].m_nextGuestVehicle = 0;
            vMgr.m_vehicles.m_buffer[vehicle].m_nextLineVehicle = 0;
            vMgr.m_vehicles.m_buffer[vehicle].m_transportLine = 0;
            vMgr.m_vehicles.m_buffer[vehicle].m_leadingVehicle = 0;
            vMgr.m_vehicles.m_buffer[vehicle].m_trailingVehicle = 0;
            vMgr.m_vehicles.m_buffer[vehicle].m_cargoParent = 0;
            vMgr.m_vehicles.m_buffer[vehicle].m_firstCargo = 0;
            vMgr.m_vehicles.m_buffer[vehicle].m_nextCargo = 0;
            vMgr.m_vehicles.m_buffer[vehicle].m_citizenUnits = 0;
            vMgr.m_vehicles.m_buffer[vehicle].m_path = 0;
            vMgr.m_vehicles.m_buffer[vehicle].m_lastFrame = 0;
            vMgr.m_vehicles.m_buffer[vehicle].m_pathPositionIndex = 0;
            vMgr.m_vehicles.m_buffer[vehicle].m_lastPathOffset = 0;
            vMgr.m_vehicles.m_buffer[vehicle].m_gateIndex = 0;
            vMgr.m_vehicles.m_buffer[vehicle].m_waterSource = 0;
            info.m_vehicleAI.CreateVehicle(vehicle, ref vMgr.m_vehicles.m_buffer[vehicle]);
            info.m_vehicleAI.FrameDataUpdated(vehicle, ref vMgr.m_vehicles.m_buffer[vehicle], ref vMgr.m_vehicles.m_buffer[vehicle].m_frame0);
            vMgr.m_vehicleCount = (int)(vMgr.m_vehicles.ItemCount() - 1);
            return true;
        }
Ejemplo n.º 14
0
 /// <summary>
 ///  Managers used by the Accounting Instance
 /// </summary>
 public Instance(InvoiceManager im, UserManager um, VehicleManager vm)
 {
     _manager.Add("Invoice", im);
     _manager.Add("User", um);
     _manager.Add("Vehicle", vm);
 }
Ejemplo n.º 15
0
        public void CustomSimulationStep(ushort vehicleId,
                                         ref Vehicle vehicleData,
                                         Vector3 physicsLodRefPos)
        {
#if DEBUG
            bool vehDebug = DebugSettings.VehicleId == 0 ||
                            DebugSettings.VehicleId == vehicleId;
            bool logParkingAi = DebugSwitch.BasicParkingAILog.Get() && vehDebug;
#else
            var logParkingAi = false;
#endif

            if ((vehicleData.m_flags & Vehicle.Flags.WaitingPath) != 0)
            {
                PathManager pathManager   = Singleton <PathManager> .instance;
                byte        pathFindFlags = pathManager.m_pathUnits.m_buffer[vehicleData.m_path].m_pathFindFlags;

                // NON-STOCK CODE START
                ExtPathState mainPathState = ExtPathState.Calculating;
                if ((pathFindFlags & PathUnit.FLAG_FAILED) != 0 || vehicleData.m_path == 0)
                {
                    mainPathState = ExtPathState.Failed;
                }
                else if ((pathFindFlags & PathUnit.FLAG_READY) != 0)
                {
                    mainPathState = ExtPathState.Ready;
                }

#if DEBUG
                uint logVehiclePath = vehicleData.m_path;
                Log._DebugIf(
                    logParkingAi,
                    () => $"CustomCarAI.CustomSimulationStep({vehicleId}): " +
                    $"Path: {logVehiclePath}, mainPathState={mainPathState}");
#endif

                IExtVehicleManager extVehicleManager = Constants.ManagerFactory.ExtVehicleManager;
                ExtSoftPathState   finalPathState    = ExtCitizenInstance.ConvertPathStateToSoftPathState(mainPathState);
                if (Options.parkingAI &&
                    extVehicleManager.ExtVehicles[vehicleId].vehicleType == ExtVehicleType.PassengerCar)
                {
                    ushort driverInstanceId = extVehicleManager.GetDriverInstanceId(vehicleId, ref vehicleData);
                    finalPathState = AdvancedParkingManager.Instance.UpdateCarPathState(
                        vehicleId,
                        ref vehicleData,
                        ref Singleton <CitizenManager> .instance.m_instances.m_buffer[driverInstanceId],
                        ref ExtCitizenInstanceManager.Instance.ExtInstances[driverInstanceId],
                        mainPathState);

#if DEBUG
                    if (logParkingAi)
                    {
                        Log._Debug($"CustomCarAI.CustomSimulationStep({vehicleId}): " +
                                   $"Applied Parking AI logic. Path: {vehicleData.m_path}, " +
                                   $"mainPathState={mainPathState}, finalPathState={finalPathState}");
                    }
#endif
                }

                switch (finalPathState)
                {
                case ExtSoftPathState.Ready: {
#if DEBUG
                    if (logParkingAi)
                    {
                        Log._Debug(
                            $"CustomCarAI.CustomSimulationStep({vehicleId}): Path-finding " +
                            $"succeeded for vehicle {vehicleId} (finalPathState={finalPathState}). " +
                            $"Path: {vehicleData.m_path} -- calling CarAI.PathfindSuccess");
                    }
#endif

                    vehicleData.m_pathPositionIndex = 255;
                    vehicleData.m_flags            &= ~Vehicle.Flags.WaitingPath;
                    vehicleData.m_flags            &= ~Vehicle.Flags.Arriving;
                    PathfindSuccess(vehicleId, ref vehicleData);
                    TrySpawn(vehicleId, ref vehicleData);
                    break;
                }

                case ExtSoftPathState.Ignore: {
#if DEBUG
                    if (logParkingAi)
                    {
                        Log._Debug(
                            $"CustomCarAI.CustomSimulationStep({vehicleId}): Path-finding " +
                            $"result shall be ignored for vehicle {vehicleId} " +
                            $"(finalPathState={finalPathState}). Path: {vehicleData.m_path} -- ignoring");
                    }
#endif
                    return;
                }

                case ExtSoftPathState.Calculating:
                default: {
#if DEBUG
                    if (logParkingAi)
                    {
                        Log._Debug(
                            $"CustomCarAI.CustomSimulationStep({vehicleId}): Path-finding " +
                            $"result undetermined for vehicle {vehicleId} (finalPathState={finalPathState}). " +
                            $"Path: {vehicleData.m_path} -- continue");
                    }
#endif
                    break;
                }

                case ExtSoftPathState.FailedHard: {
#if DEBUG
                    if (logParkingAi)
                    {
                        Log._Debug(
                            $"CustomCarAI.CustomSimulationStep({vehicleId}): HARD path-finding " +
                            $"failure for vehicle {vehicleId} (finalPathState={finalPathState}). " +
                            $"Path: {vehicleData.m_path} -- calling CarAI.PathfindFailure");
                    }
#endif
                    vehicleData.m_flags &= ~Vehicle.Flags.WaitingPath;
                    Singleton <PathManager> .instance.ReleasePath(vehicleData.m_path);

                    vehicleData.m_path = 0u;
                    PathfindFailure(vehicleId, ref vehicleData);
                    return;
                }

                case ExtSoftPathState.FailedSoft: {
#if DEBUG
                    if (logParkingAi)
                    {
                        Log._Debug(
                            $"CustomCarAI.CustomSimulationStep({vehicleId}): SOFT path-finding " +
                            $"failure for vehicle {vehicleId} (finalPathState={finalPathState}). " +
                            $"Path: {vehicleData.m_path} -- calling CarAI.InvalidPath");
                    }
#endif

                    // path mode has been updated, repeat path-finding
                    vehicleData.m_flags &= ~Vehicle.Flags.WaitingPath;
                    InvalidPath(vehicleId, ref vehicleData, vehicleId, ref vehicleData);
                    break;
                }
                }

                // NON-STOCK CODE END
            }
            else
            {
                if ((vehicleData.m_flags & Vehicle.Flags.WaitingSpace) != 0)
                {
                    TrySpawn(vehicleId, ref vehicleData);
                }
            }

            // NON-STOCK CODE START
            IExtVehicleManager extVehicleMan = Constants.ManagerFactory.ExtVehicleManager;
            extVehicleMan.UpdateVehiclePosition(vehicleId, ref vehicleData);

            if (Options.advancedAI &&
                (vehicleData.m_flags & Vehicle.Flags.Spawned) != 0)
            {
                extVehicleMan.LogTraffic(vehicleId, ref vehicleData);
            }

            // NON-STOCK CODE END
            Vector3 lastFramePosition = vehicleData.GetLastFramePosition();
            int     lodPhysics;
            if (Vector3.SqrMagnitude(physicsLodRefPos - lastFramePosition) >= 1100f * 1100f)
            {
                lodPhysics = 2;
            }
            else if (Vector3.SqrMagnitude(
                         Singleton <SimulationManager> .instance.m_simulationView.m_position -
                         lastFramePosition) >= 500f * 500f)
            {
                lodPhysics = 1;
            }
            else
            {
                lodPhysics = 0;
            }

            SimulationStep(vehicleId, ref vehicleData, vehicleId, ref vehicleData, lodPhysics);
            if (vehicleData.m_leadingVehicle == 0 && vehicleData.m_trailingVehicle != 0)
            {
                VehicleManager vehManager = Singleton <VehicleManager> .instance;
                ushort         trailerId  = vehicleData.m_trailingVehicle;
                int            numIters   = 0;
                while (trailerId != 0)
                {
                    ushort      trailingVehicle = vehManager.m_vehicles.m_buffer[trailerId].m_trailingVehicle;
                    VehicleInfo info            = vehManager.m_vehicles.m_buffer[trailerId].Info;

                    info.m_vehicleAI.SimulationStep(
                        trailerId,
                        ref vehManager.m_vehicles.m_buffer[trailerId],
                        vehicleId,
                        ref vehicleData,
                        lodPhysics);

                    trailerId = trailingVehicle;
                    if (++numIters > 16384)
                    {
                        CODebugBase <LogChannel> .Error(
                            LogChannel.Core,
                            $"Invalid list detected!\n{Environment.StackTrace}");

                        break;
                    }
                }
            }

            int privateServiceIndex = ItemClass.GetPrivateServiceIndex(m_info.m_class.m_service);
            int maxBlockCounter     = (privateServiceIndex == -1) ? 150 : 100;

            if ((vehicleData.m_flags & (Vehicle.Flags.Spawned
                                        | Vehicle.Flags.WaitingPath
                                        | Vehicle.Flags.WaitingSpace)) == 0 &&
                vehicleData.m_cargoParent == 0)
            {
                Singleton <VehicleManager> .instance.ReleaseVehicle(vehicleId);
            }
            else if (vehicleData.m_blockCounter >= maxBlockCounter)
            {
                // NON-STOCK CODE START
                if (VehicleBehaviorManager.Instance.MayDespawn(ref vehicleData))
                {
                    // NON-STOCK CODE END
                    Singleton <VehicleManager> .instance.ReleaseVehicle(vehicleId);
                } // NON-STOCK CODE
            }
        }
 public static void Prefix(VehicleManager __instance, ushort vehicle)
 {
     Constants.ManagerFactory.ExtVehicleManager.OnReleaseVehicle(
         vehicle,
         ref vehicle.ToVehicle());
 }
Ejemplo n.º 17
0
    class CustomTramBaseAI : TramBaseAI {     // TODO inherit from VehicleAI (in order to keep the correct references to `base`)
        public void CustomSimulationStep(ushort vehicleId, ref Vehicle vehicleData, Vector3 physicsLodRefPos)
        {
            if ((vehicleData.m_flags & Vehicle.Flags.WaitingPath) != 0)
            {
                byte pathFindFlags = Singleton <PathManager> .instance.m_pathUnits.m_buffer[vehicleData.m_path].m_pathFindFlags;

                if ((pathFindFlags & PathUnit.FLAG_READY) != 0)
                {
                    try {
                        this.PathfindSuccess(vehicleId, ref vehicleData);
                        this.PathFindReady(vehicleId, ref vehicleData);
                    } catch (Exception e) {
                        Log.Warning($"TramBaseAI.PathFindSuccess/PathFindReady({vehicleId}) threw an exception: {e.ToString()}");
                        vehicleData.m_flags &= ~Vehicle.Flags.WaitingPath;
                        Singleton <PathManager> .instance.ReleasePath(vehicleData.m_path);

                        vehicleData.m_path = 0u;
                        this.PathfindFailure(vehicleId, ref vehicleData);
                        return;
                    }
                }
                else if ((pathFindFlags & PathUnit.FLAG_FAILED) != 0 || vehicleData.m_path == 0)
                {
                    vehicleData.m_flags &= ~Vehicle.Flags.WaitingPath;
                    Singleton <PathManager> .instance.ReleasePath(vehicleData.m_path);

                    vehicleData.m_path = 0u;
                    this.PathfindFailure(vehicleId, ref vehicleData);
                    return;
                }
            }
            else
            {
                if ((vehicleData.m_flags & Vehicle.Flags.WaitingSpace) != 0)
                {
                    this.TrySpawn(vehicleId, ref vehicleData);
                }
            }

            // NON-STOCK CODE START
#if BENCHMARK
            using (var bm = new Benchmark(null, "UpdateVehiclePosition")) {
#endif
            VehicleStateManager.Instance.UpdateVehiclePosition(vehicleId, ref vehicleData);
#if BENCHMARK
        }
#endif
            if (!Options.isStockLaneChangerUsed())
            {
#if BENCHMARK
                using (var bm = new Benchmark(null, "LogTraffic")) {
#endif
                // Advanced AI traffic measurement
                VehicleStateManager.Instance.LogTraffic(vehicleId);
#if BENCHMARK
            }
#endif
            }
            // NON-STOCK CODE END

            VehicleManager instance = Singleton <VehicleManager> .instance;
            VehicleInfo info        = instance.m_vehicles.m_buffer[(int)vehicleId].Info;
            info.m_vehicleAI.SimulationStep(vehicleId, ref instance.m_vehicles.m_buffer[(int)vehicleId], vehicleId, ref vehicleData, 0);
            if ((vehicleData.m_flags & (Vehicle.Flags.Created | Vehicle.Flags.Deleted)) != Vehicle.Flags.Created)
            {
                return;
            }
            ushort trailingVehicle = instance.m_vehicles.m_buffer[(int)vehicleId].m_trailingVehicle;
            int num = 0;
            while (trailingVehicle != 0)
            {
                info = instance.m_vehicles.m_buffer[(int)trailingVehicle].Info;
                info.m_vehicleAI.SimulationStep(trailingVehicle, ref instance.m_vehicles.m_buffer[(int)trailingVehicle], vehicleId, ref vehicleData, 0);
                if ((vehicleData.m_flags & (Vehicle.Flags.Created | Vehicle.Flags.Deleted)) != Vehicle.Flags.Created)
                {
                    return;
                }
                trailingVehicle = instance.m_vehicles.m_buffer[(int)trailingVehicle].m_trailingVehicle;
                if (++num > 16384)
                {
                    CODebugBase <LogChannel> .Error(LogChannel.Core, "Invalid list detected!\n" + Environment.StackTrace);

                    break;
                }
            }
            if ((vehicleData.m_flags & (Vehicle.Flags.Spawned | Vehicle.Flags.WaitingPath | Vehicle.Flags.WaitingSpace | Vehicle.Flags.WaitingCargo)) == 0)
            {
                Singleton <VehicleManager> .instance.ReleaseVehicle(vehicleId);
            }
            else if (vehicleData.m_blockCounter == 255)
            {
                // NON-STOCK CODE START
                bool mayDespawn = true;
#if BENCHMARK
                using (var bm = new Benchmark(null, "MayDespawn")) {
#endif
                mayDespawn = VehicleBehaviorManager.Instance.MayDespawn(ref vehicleData);
#if BENCHMARK
            }
#endif

                if (mayDespawn)
                {
                    // NON-STOCK CODE END
                    Singleton <VehicleManager> .instance.ReleaseVehicle(vehicleId);
                }                 // NON-STOCK CODE
            }
        }
Ejemplo n.º 18
0
 void Awake()
 {
     cameraController = GetComponent<CameraController>();
     camera = GetComponent<Camera>();
     vManager = VehicleManager.instance;
 }
Ejemplo n.º 19
0
        public void CustomSimulationStep(ushort vehicleID, ref Vehicle vehicleData, ref Vehicle.Frame frameData, ushort leaderID, ref Vehicle leaderData, int lodPhysics)
        {
#if DEBUG
            bool debug = GlobalConfig.Instance.Debug.Switches[16] && GlobalConfig.Instance.Debug.NodeId == vehicleID;
#endif

            ushort leadingVehicle  = vehicleData.m_leadingVehicle;
            uint currentFrameIndex = Singleton <SimulationManager> .instance.m_currentFrameIndex;
            VehicleInfo leaderInfo;
            if (leaderID != vehicleID)
            {
                leaderInfo = leaderData.Info;
            }
            else
            {
                leaderInfo = this.m_info;
            }
            TramBaseAI tramBaseAI = leaderInfo.m_vehicleAI as TramBaseAI;

            if (leadingVehicle != 0)
            {
                frameData.m_position += frameData.m_velocity * 0.4f;
            }
            else
            {
                frameData.m_position += frameData.m_velocity * 0.5f;
            }

            frameData.m_swayPosition += frameData.m_swayVelocity * 0.5f;
            Vector3 wheelBaseRot      = frameData.m_rotation * new Vector3(0f, 0f, this.m_info.m_generatedInfo.m_wheelBase * 0.5f);
            Vector3 posAfterWheelRot  = frameData.m_position + wheelBaseRot;
            Vector3 posBeforeWheelRot = frameData.m_position - wheelBaseRot;

            float acceleration = this.m_info.m_acceleration;
            float braking      = this.m_info.m_braking;
            float curSpeed     = frameData.m_velocity.magnitude;

            Vector3 afterRotToTargetPos1Diff     = (Vector3)vehicleData.m_targetPos1 - posAfterWheelRot;
            float afterRotToTargetPos1DiffSqrMag = afterRotToTargetPos1Diff.sqrMagnitude;

            Quaternion curInvRot = Quaternion.Inverse(frameData.m_rotation);
            Vector3 curveTangent = curInvRot * frameData.m_velocity;

#if DEBUG
            if (debug)
            {
                Log._Debug($"CustomTramBaseAI.SimulationStep({vehicleID}): ================================================");
                Log._Debug($"CustomTramBaseAI.SimulationStep({vehicleID}): leadingVehicle={leadingVehicle} frameData.m_position={frameData.m_position} frameData.m_swayPosition={frameData.m_swayPosition} wheelBaseRot={wheelBaseRot} posAfterWheelRot={posAfterWheelRot} posBeforeWheelRot={posBeforeWheelRot} acceleration={acceleration} braking={braking} curSpeed={curSpeed} afterRotToTargetPos1Diff={afterRotToTargetPos1Diff} afterRotToTargetPos1DiffSqrMag={afterRotToTargetPos1DiffSqrMag} curInvRot={curInvRot} curveTangent={curveTangent} this.m_info.m_generatedInfo.m_wheelBase={this.m_info.m_generatedInfo.m_wheelBase}");
            }
#endif

            Vector3 forward      = Vector3.forward;
            Vector3 targetMotion = Vector3.zero;
            float targetSpeed    = 0f;
            float motionFactor   = 0.5f;
            float turnAngle      = 0f;
            if (leadingVehicle != 0)
            {
                VehicleManager vehMan = Singleton <VehicleManager> .instance;
                Vehicle.Frame leadingVehLastFrameData = vehMan.m_vehicles.m_buffer[(int)leadingVehicle].GetLastFrameData();
                VehicleInfo leadingVehInfo            = vehMan.m_vehicles.m_buffer[(int)leadingVehicle].Info;

                float attachOffset;
                if ((vehicleData.m_flags & Vehicle.Flags.Inverted) != (Vehicle.Flags) 0)
                {
                    attachOffset = this.m_info.m_attachOffsetBack - this.m_info.m_generatedInfo.m_size.z * 0.5f;
                }
                else
                {
                    attachOffset = this.m_info.m_attachOffsetFront - this.m_info.m_generatedInfo.m_size.z * 0.5f;
                }

                float leadingAttachOffset;
                if ((vehMan.m_vehicles.m_buffer[(int)leadingVehicle].m_flags & Vehicle.Flags.Inverted) != (Vehicle.Flags) 0)
                {
                    leadingAttachOffset = leadingVehInfo.m_attachOffsetFront - leadingVehInfo.m_generatedInfo.m_size.z * 0.5f;
                }
                else
                {
                    leadingAttachOffset = leadingVehInfo.m_attachOffsetBack - leadingVehInfo.m_generatedInfo.m_size.z * 0.5f;
                }

                Vector3 curPosMinusRotAttachOffset    = frameData.m_position - frameData.m_rotation * new Vector3(0f, 0f, attachOffset);
                Vector3 leadingPosPlusRotAttachOffset = leadingVehLastFrameData.m_position + leadingVehLastFrameData.m_rotation * new Vector3(0f, 0f, leadingAttachOffset);

                wheelBaseRot = leadingVehLastFrameData.m_rotation * new Vector3(0f, 0f, leadingVehInfo.m_generatedInfo.m_wheelBase * 0.5f);
                Vector3 leadingPosBeforeWheelRot = leadingVehLastFrameData.m_position - wheelBaseRot;

                if (Vector3.Dot(vehicleData.m_targetPos1 - vehicleData.m_targetPos0, (Vector3)vehicleData.m_targetPos0 - posBeforeWheelRot) < 0f && vehicleData.m_path != 0u && (leaderData.m_flags & Vehicle.Flags.WaitingPath) == (Vehicle.Flags) 0)
                {
                    int someIndex = -1;
                    InvokeUpdatePathTargetPositions(tramBaseAI, vehicleID, ref vehicleData, vehicleData.m_targetPos0, posBeforeWheelRot, 0, ref leaderData, ref someIndex, 0, 0, Vector3.SqrMagnitude(posBeforeWheelRot - (Vector3)vehicleData.m_targetPos0) + 1f, 1f);
                    afterRotToTargetPos1DiffSqrMag = 0f;
                }

                float attachRotDist = Mathf.Max(Vector3.Distance(curPosMinusRotAttachOffset, leadingPosPlusRotAttachOffset), 2f);

                float one = 1f;
                float attachRotSqrDist = attachRotDist * attachRotDist;
                float oneSqr           = one * one;
                int i = 0;
                if (afterRotToTargetPos1DiffSqrMag < attachRotSqrDist)
                {
                    if (vehicleData.m_path != 0u && (leaderData.m_flags & Vehicle.Flags.WaitingPath) == (Vehicle.Flags) 0)
                    {
                        InvokeUpdatePathTargetPositions(tramBaseAI, vehicleID, ref vehicleData, posBeforeWheelRot, posAfterWheelRot, 0, ref leaderData, ref i, 1, 2, attachRotSqrDist, oneSqr);
                    }
                    while (i < 4)
                    {
                        vehicleData.SetTargetPos(i, vehicleData.GetTargetPos(i - 1));
                        i++;
                    }
                    afterRotToTargetPos1Diff       = (Vector3)vehicleData.m_targetPos1 - posAfterWheelRot;
                    afterRotToTargetPos1DiffSqrMag = afterRotToTargetPos1Diff.sqrMagnitude;
                }
                afterRotToTargetPos1Diff = curInvRot * afterRotToTargetPos1Diff;

                float negTotalAttachLen = -((this.m_info.m_generatedInfo.m_wheelBase + leadingVehInfo.m_generatedInfo.m_wheelBase) * 0.5f + attachOffset + leadingAttachOffset);
                bool hasPath            = false;
                if (vehicleData.m_path != 0u && (leaderData.m_flags & Vehicle.Flags.WaitingPath) == (Vehicle.Flags) 0)
                {
                    float u1;
                    float u2;
                    if (Line3.Intersect(posAfterWheelRot, vehicleData.m_targetPos1, leadingPosBeforeWheelRot, negTotalAttachLen, out u1, out u2))
                    {
                        targetMotion = afterRotToTargetPos1Diff * Mathf.Clamp(Mathf.Min(u1, u2) / 0.6f, 0f, 2f);
                    }
                    else
                    {
                        Line3.DistanceSqr(posAfterWheelRot, vehicleData.m_targetPos1, leadingPosBeforeWheelRot, out u1);
                        targetMotion = afterRotToTargetPos1Diff * Mathf.Clamp(u1 / 0.6f, 0f, 2f);
                    }
                    hasPath = true;
                }

                if (hasPath)
                {
                    if (Vector3.Dot(leadingPosBeforeWheelRot - posAfterWheelRot, posAfterWheelRot - posBeforeWheelRot) < 0f)
                    {
                        motionFactor = 0f;
                    }
                }
                else
                {
                    float leadingPosBeforeToAfterWheelRotDist = Vector3.Distance(leadingPosBeforeWheelRot, posAfterWheelRot);
                    motionFactor = 0f;
                    targetMotion = curInvRot * ((leadingPosBeforeWheelRot - posAfterWheelRot) * (Mathf.Max(0f, leadingPosBeforeToAfterWheelRotDist - negTotalAttachLen) / Mathf.Max(1f, leadingPosBeforeToAfterWheelRotDist * 0.6f)));
                }
            }
            else
            {
                float estimatedFrameDist = (curSpeed + acceleration) * (0.5f + 0.5f * (curSpeed + acceleration) / braking) + (this.m_info.m_generatedInfo.m_size.z - this.m_info.m_generatedInfo.m_wheelBase) * 0.5f;
                float maxSpeedAdd        = Mathf.Max(curSpeed + acceleration, 2f);
                float meanSpeedAdd       = Mathf.Max((estimatedFrameDist - maxSpeedAdd) / 2f, 2f);
                float maxSpeedAddSqr     = maxSpeedAdd * maxSpeedAdd;
                float meanSpeedAddSqr    = meanSpeedAdd * meanSpeedAdd;
                if (Vector3.Dot(vehicleData.m_targetPos1 - vehicleData.m_targetPos0, (Vector3)vehicleData.m_targetPos0 - posBeforeWheelRot) < 0f && vehicleData.m_path != 0u && (leaderData.m_flags & (Vehicle.Flags.WaitingPath | Vehicle.Flags.Stopped)) == (Vehicle.Flags) 0)
                {
                    int someIndex = -1;
                    InvokeUpdatePathTargetPositions(tramBaseAI, vehicleID, ref vehicleData, vehicleData.m_targetPos0, posBeforeWheelRot, leaderID, ref leaderData, ref someIndex, 0, 0, Vector3.SqrMagnitude(posBeforeWheelRot - (Vector3)vehicleData.m_targetPos0) + 1f, 1f);
                    afterRotToTargetPos1DiffSqrMag = 0f;
#if DEBUG
                    if (debug)
                    {
                        Log._Debug($"CustomTramBaseAI.SimulationStep({vehicleID}): dot < 0");
                    }
#endif
                }

#if DEBUG
                if (debug)
                {
                    Log._Debug($"CustomTramBaseAI.SimulationStep({vehicleID}): Leading vehicle is 0. vehicleData.m_targetPos0={vehicleData.m_targetPos0} vehicleData.m_targetPos1={vehicleData.m_targetPos1} posBeforeWheelRot={posBeforeWheelRot} posBeforeWheelRot={posAfterWheelRot} estimatedFrameDist={estimatedFrameDist} maxSpeedAdd={maxSpeedAdd} meanSpeedAdd={meanSpeedAdd} maxSpeedAddSqr={maxSpeedAddSqr} meanSpeedAddSqr={meanSpeedAddSqr} afterRotToTargetPos1DiffSqrMag={afterRotToTargetPos1DiffSqrMag}");
                }
#endif

                int posIndex = 0;
                bool hasValidPathTargetPos = false;
                if ((afterRotToTargetPos1DiffSqrMag < maxSpeedAddSqr || vehicleData.m_targetPos3.w < 0.01f) && (leaderData.m_flags & (Vehicle.Flags.WaitingPath | Vehicle.Flags.Stopped)) == (Vehicle.Flags) 0)
                {
                    if (vehicleData.m_path != 0u)
                    {
                        InvokeUpdatePathTargetPositions(tramBaseAI, vehicleID, ref vehicleData, posBeforeWheelRot, posAfterWheelRot, leaderID, ref leaderData, ref posIndex, 1, 4, maxSpeedAddSqr, meanSpeedAddSqr);
                    }
                    if (posIndex < 4)
                    {
                        hasValidPathTargetPos = true;
                        while (posIndex < 4)
                        {
                            vehicleData.SetTargetPos(posIndex, vehicleData.GetTargetPos(posIndex - 1));
                            posIndex++;
                        }
                    }
                    afterRotToTargetPos1Diff       = (Vector3)vehicleData.m_targetPos1 - posAfterWheelRot;
                    afterRotToTargetPos1DiffSqrMag = afterRotToTargetPos1Diff.sqrMagnitude;
                }

#if DEBUG
                if (debug)
                {
                    Log._Debug($"CustomTramBaseAI.SimulationStep({vehicleID}): posIndex={posIndex} hasValidPathTargetPos={hasValidPathTargetPos}");
                }
#endif

                if (leaderData.m_path != 0u && (leaderData.m_flags & Vehicle.Flags.WaitingPath) == (Vehicle.Flags) 0)
                {
                    NetManager netMan         = Singleton <NetManager> .instance;
                    byte leaderPathPosIndex   = leaderData.m_pathPositionIndex;
                    byte leaderLastPathOffset = leaderData.m_lastPathOffset;
                    if (leaderPathPosIndex == 255)
                    {
                        leaderPathPosIndex = 0;
                    }
                    int noise;
                    float leaderLen = 1f + leaderData.CalculateTotalLength(leaderID, out noise);

#if DEBUG
                    if (debug)
                    {
                        Log._Debug($"CustomTramBaseAI.SimulationStep({vehicleID}): leaderPathPosIndex={leaderPathPosIndex} leaderLastPathOffset={leaderLastPathOffset} leaderPathPosIndex={leaderPathPosIndex} leaderLen={leaderLen}");
                    }
#endif

                    // reserve space / add traffic
                    PathManager pathMan = Singleton <PathManager> .instance;
                    PathUnit.Position pathPos;
                    if (pathMan.m_pathUnits.m_buffer[leaderData.m_path].GetPosition(leaderPathPosIndex >> 1, out pathPos))
                    {
                        netMan.m_segments.m_buffer[(int)pathPos.m_segment].AddTraffic(Mathf.RoundToInt(leaderLen * 2.5f), noise);
                        bool reservedSpaceOnCurrentLane = false;
                        if ((leaderPathPosIndex & 1) == 0 || leaderLastPathOffset == 0)
                        {
                            uint laneId = PathManager.GetLaneID(pathPos);
                            if (laneId != 0u)
                            {
                                Vector3 curPathOffsetPos              = netMan.m_lanes.m_buffer[laneId].CalculatePosition((float)pathPos.m_offset * 0.003921569f);
                                float speedAdd                        = 0.5f * curSpeed * curSpeed / this.m_info.m_braking;
                                float afterWheelRotCurPathOffsetDist  = Vector3.Distance(posAfterWheelRot, curPathOffsetPos);
                                float beforeWheelRotCurPathOffsetDist = Vector3.Distance(posBeforeWheelRot, curPathOffsetPos);
                                if (Mathf.Min(afterWheelRotCurPathOffsetDist, beforeWheelRotCurPathOffsetDist) >= speedAdd - 1f)
                                {
                                    netMan.m_lanes.m_buffer[laneId].ReserveSpace(leaderLen);
                                    reservedSpaceOnCurrentLane = true;
                                }
                            }
                        }

                        if (!reservedSpaceOnCurrentLane && pathMan.m_pathUnits.m_buffer[leaderData.m_path].GetNextPosition(leaderPathPosIndex >> 1, out pathPos))
                        {
                            uint nextLaneId = PathManager.GetLaneID(pathPos);
                            if (nextLaneId != 0u)
                            {
                                netMan.m_lanes.m_buffer[nextLaneId].ReserveSpace(leaderLen);
                            }
                        }
                    }

                    if ((ulong)(currentFrameIndex >> 4 & 15u) == (ulong)((long)(leaderID & 15)))
                    {
                        // check if vehicle can proceed to next path position

                        bool canProceeed          = false;
                        uint curLeaderPathId      = leaderData.m_path;
                        int curLeaderPathPosIndex = leaderPathPosIndex >> 1;
                        int k = 0;
                        while (k < 5)
                        {
                            bool invalidPos;
                            if (PathUnit.GetNextPosition(ref curLeaderPathId, ref curLeaderPathPosIndex, out pathPos, out invalidPos))
                            {
                                uint laneId = PathManager.GetLaneID(pathPos);
                                if (laneId != 0u && !netMan.m_lanes.m_buffer[laneId].CheckSpace(leaderLen))
                                {
                                    k++;
                                    continue;
                                }
                            }
                            if (invalidPos)
                            {
                                this.InvalidPath(vehicleID, ref vehicleData, leaderID, ref leaderData);
                            }
                            canProceeed = true;
                            break;
                        }
                        if (!canProceeed)
                        {
                            leaderData.m_flags |= Vehicle.Flags.Congestion;
                        }
                    }
                }

                float maxSpeed;
                if ((leaderData.m_flags & Vehicle.Flags.Stopped) != (Vehicle.Flags) 0)
                {
                    maxSpeed = 0f;
#if DEBUG
                    if (debug)
                    {
                        Log._Debug($"CustomTramBaseAI.SimulationStep({vehicleID}): Vehicle is stopped. maxSpeed={maxSpeed}");
                    }
#endif
                }
                else
                {
                    maxSpeed = Mathf.Min(vehicleData.m_targetPos1.w, GetMaxSpeed(leaderID, ref leaderData));
#if DEBUG
                    if (debug)
                    {
                        Log._Debug($"CustomTramBaseAI.SimulationStep({vehicleID}): Vehicle is not stopped. maxSpeed={maxSpeed}");
                    }
#endif
                }

#if DEBUG
                if (debug)
                {
                    Log._Debug($"CustomTramBaseAI.SimulationStep({vehicleID}): Start of second part. curSpeed={curSpeed} curInvRot={curInvRot}");
                }
#endif

                afterRotToTargetPos1Diff = curInvRot * afterRotToTargetPos1Diff;
#if DEBUG
                if (debug)
                {
                    Log._Debug($"CustomTramBaseAI.SimulationStep({vehicleID}): afterRotToTargetPos1Diff={afterRotToTargetPos1Diff} (old afterRotToTargetPos1DiffSqrMag={afterRotToTargetPos1DiffSqrMag})");
                }
#endif
                Vector3 zero     = Vector3.zero;
                bool blocked     = false;
                float forwardLen = 0f;
                if (afterRotToTargetPos1DiffSqrMag > 1f)                   // TODO why is this not recalculated?
                {
                    forward = VectorUtils.NormalizeXZ(afterRotToTargetPos1Diff, out forwardLen);
#if DEBUG
                    if (debug)
                    {
                        Log._Debug($"CustomTramBaseAI.SimulationStep({vehicleID}): afterRotToTargetPos1DiffSqrMag > 1f. forward={forward} forwardLen={forwardLen}");
                    }
#endif
                    if (forwardLen > 1f)
                    {
                        Vector3 fwd = afterRotToTargetPos1Diff;
                        maxSpeedAdd    = Mathf.Max(curSpeed, 2f);
                        maxSpeedAddSqr = maxSpeedAdd * maxSpeedAdd;
#if DEBUG
                        if (debug)
                        {
                            Log._Debug($"CustomTramBaseAI.SimulationStep({vehicleID}): forwardLen > 1f. fwd={fwd} maxSpeedAdd={maxSpeedAdd} maxSpeedAddSqr={maxSpeedAddSqr}");
                        }
#endif
                        if (afterRotToTargetPos1DiffSqrMag > maxSpeedAddSqr)
                        {
                            float fwdLimiter = maxSpeedAdd / Mathf.Sqrt(afterRotToTargetPos1DiffSqrMag);
                            fwd.x *= fwdLimiter;
                            fwd.y *= fwdLimiter;

#if DEBUG
                            if (debug)
                            {
                                Log._Debug($"CustomTramBaseAI.SimulationStep({vehicleID}): afterRotToTargetPos1DiffSqrMag > maxSpeedAddSqr. afterRotToTargetPos1DiffSqrMag={afterRotToTargetPos1DiffSqrMag} maxSpeedAddSqr={maxSpeedAddSqr} fwdLimiter={fwdLimiter} fwd={fwd}");
                            }
#endif
                        }

                        if (fwd.z < -1f)                           // !!!
                        {
#if DEBUG
                            if (debug)
                            {
                                Log._Debug($"CustomTramBaseAI.SimulationStep({vehicleID}): fwd.z < -1f. fwd={fwd}");
                            }
#endif

                            if (vehicleData.m_path != 0u && (leaderData.m_flags & Vehicle.Flags.WaitingPath) == (Vehicle.Flags) 0)
                            {
                                Vector3 targetPos0TargetPos1Diff = vehicleData.m_targetPos1 - vehicleData.m_targetPos0;
                                if ((curInvRot * targetPos0TargetPos1Diff).z < -0.01f)                                   // !!!
                                {
#if DEBUG
                                    if (debug)
                                    {
                                        Log._Debug($"CustomTramBaseAI.SimulationStep({vehicleID}): (curInvRot * targetPos0TargetPos1Diff).z < -0.01f. curInvRot={curInvRot} targetPos0TargetPos1Diff={targetPos0TargetPos1Diff}");
                                    }
#endif
                                    if (afterRotToTargetPos1Diff.z < Mathf.Abs(afterRotToTargetPos1Diff.x) * -10f)                                       // !!!
                                    {
#if DEBUG
                                        if (debug)
                                        {
                                            Log._Debug($"CustomTramBaseAI.SimulationStep({vehicleID}): afterRotToTargetPos1Diff.z < Mathf.Abs(afterRotToTargetPos1Diff.x) * -10f. fwd={fwd} targetPos0TargetPos1Diff={targetPos0TargetPos1Diff} afterRotToTargetPos1Diff={afterRotToTargetPos1Diff}");
                                        }
#endif

                                        /*fwd.z = 0f;
                                         * afterRotToTargetPos1Diff = Vector3.zero;*/
                                        maxSpeed = 0.5f;                                         // NON-STOCK CODE

#if DEBUG
                                        if (debug)
                                        {
                                            Log._Debug($"CustomTramBaseAI.SimulationStep({vehicleID}): (1) set maxSpeed={maxSpeed}");
                                        }
#endif
                                    }
                                    else
                                    {
                                        posAfterWheelRot = posBeforeWheelRot + Vector3.Normalize(vehicleData.m_targetPos1 - vehicleData.m_targetPos0) * this.m_info.m_generatedInfo.m_wheelBase;
                                        posIndex         = -1;
                                        InvokeUpdatePathTargetPositions(tramBaseAI, vehicleID, ref vehicleData, vehicleData.m_targetPos0, vehicleData.m_targetPos1, leaderID, ref leaderData, ref posIndex, 0, 0, Vector3.SqrMagnitude(vehicleData.m_targetPos1 - vehicleData.m_targetPos0) + 1f, 1f);

#if DEBUG
                                        if (debug)
                                        {
                                            Log._Debug($"CustomTramBaseAI.SimulationStep({vehicleID}): afterRotToTargetPos1Diff.z >= Mathf.Abs(afterRotToTargetPos1Diff.x) * -10f. Invoked UpdatePathTargetPositions. posAfterWheelRot={posAfterWheelRot} posBeforeWheelRot={posBeforeWheelRot} this.m_info.m_generatedInfo.m_wheelBase={this.m_info.m_generatedInfo.m_wheelBase}");
                                        }
#endif
                                    }
                                }
                                else
                                {
                                    posIndex = -1;
                                    InvokeUpdatePathTargetPositions(tramBaseAI, vehicleID, ref vehicleData, vehicleData.m_targetPos0, posBeforeWheelRot, leaderID, ref leaderData, ref posIndex, 0, 0, Vector3.SqrMagnitude(posBeforeWheelRot - (Vector3)vehicleData.m_targetPos0) + 1f, 1f);
                                    vehicleData.m_targetPos1 = posAfterWheelRot;
                                    fwd.z = 0f;
                                    afterRotToTargetPos1Diff = Vector3.zero;
                                    maxSpeed = 0f;

#if DEBUG
                                    if (debug)
                                    {
                                        Log._Debug($"CustomTramBaseAI.SimulationStep({vehicleID}): Vehicle is waiting for a path. posIndex={posIndex} vehicleData.m_targetPos1={vehicleData.m_targetPos1} fwd={fwd} afterRotToTargetPos1Diff={afterRotToTargetPos1Diff} maxSpeed={maxSpeed}");
                                    }
#endif
                                }
                            }
                            motionFactor = 0f;
#if DEBUG
                            if (debug)
                            {
                                Log._Debug($"CustomTramBaseAI.SimulationStep({vehicleID}): Reset motion factor. motionFactor={motionFactor}");
                            }
#endif
                        }

                        forward = VectorUtils.NormalizeXZ(fwd, out forwardLen);
                        float curve = Mathf.PI / 2f /* 1.57079637f*/ * (1f - forward.z);                       // <- constant: a bit inaccurate PI/2
                        if (forwardLen > 1f)
                        {
                            curve /= forwardLen;
                        }
                        float targetDist = forwardLen;
#if DEBUG
                        if (debug)
                        {
                            Log._Debug($"CustomTramBaseAI.SimulationStep({vehicleID}): targetDist={targetDist} fwd={fwd} curve={curve} maxSpeed={maxSpeed}");
                        }
#endif

                        if (vehicleData.m_targetPos1.w < 0.1f)
                        {
                            maxSpeed = this.CalculateTargetSpeed(vehicleID, ref vehicleData, 1000f, curve);
                            maxSpeed = Mathf.Min(maxSpeed, CalculateMaxSpeed(targetDist, vehicleData.m_targetPos1.w, braking * 0.9f));
                        }
                        else
                        {
                            maxSpeed = Mathf.Min(maxSpeed, this.CalculateTargetSpeed(vehicleID, ref vehicleData, 1000f, curve));
                        }
#if DEBUG
                        if (debug)
                        {
                            Log._Debug($"CustomTramBaseAI.SimulationStep({vehicleID}): [1] maxSpeed={maxSpeed}");
                        }
#endif
                        maxSpeed = Mathf.Min(maxSpeed, CalculateMaxSpeed(targetDist, vehicleData.m_targetPos2.w, braking * 0.9f));
#if DEBUG
                        if (debug)
                        {
                            Log._Debug($"CustomTramBaseAI.SimulationStep({vehicleID}): [2] maxSpeed={maxSpeed}");
                        }
#endif
                        targetDist += VectorUtils.LengthXZ(vehicleData.m_targetPos2 - vehicleData.m_targetPos1);
                        maxSpeed    = Mathf.Min(maxSpeed, CalculateMaxSpeed(targetDist, vehicleData.m_targetPos3.w, braking * 0.9f));
#if DEBUG
                        if (debug)
                        {
                            Log._Debug($"CustomTramBaseAI.SimulationStep({vehicleID}): [3] maxSpeed={maxSpeed}");
                        }
#endif
                        targetDist += VectorUtils.LengthXZ(vehicleData.m_targetPos3 - vehicleData.m_targetPos2);
                        if (vehicleData.m_targetPos3.w < 0.01f)
                        {
                            targetDist = Mathf.Max(0f, targetDist + (this.m_info.m_generatedInfo.m_wheelBase - this.m_info.m_generatedInfo.m_size.z) * 0.5f);
                        }
                        maxSpeed = Mathf.Min(maxSpeed, CalculateMaxSpeed(targetDist, 0f, braking * 0.9f));
#if DEBUG
                        if (debug)
                        {
                            Log._Debug($"CustomTramBaseAI.SimulationStep({vehicleID}): [4] maxSpeed={maxSpeed}");
                        }
#endif
                        CarAI.CheckOtherVehicles(vehicleID, ref vehicleData, ref frameData, ref maxSpeed, ref blocked, ref zero, estimatedFrameDist, braking * 0.9f, lodPhysics);
#if DEBUG
                        if (debug)
                        {
                            Log._Debug($"CustomTramBaseAI.SimulationStep({vehicleID}): CheckOtherVehicles finished. blocked={blocked}");
                        }
#endif
                        if (maxSpeed < curSpeed)
                        {
                            float brake = Mathf.Max(acceleration, Mathf.Min(braking, curSpeed));
                            targetSpeed = Mathf.Max(maxSpeed, curSpeed - brake);
#if DEBUG
                            if (debug)
                            {
                                Log._Debug($"CustomTramBaseAI.SimulationStep({vehicleID}): maxSpeed < curSpeed. maxSpeed={maxSpeed} curSpeed={curSpeed} brake={brake} targetSpeed={targetSpeed}");
                            }
#endif
                        }
                        else
                        {
                            float accel = Mathf.Max(acceleration, Mathf.Min(braking, -curSpeed));
                            targetSpeed = Mathf.Min(maxSpeed, curSpeed + accel);
#if DEBUG
                            if (debug)
                            {
                                Log._Debug($"CustomTramBaseAI.SimulationStep({vehicleID}): maxSpeed >= curSpeed. maxSpeed={maxSpeed} curSpeed={curSpeed} accel={accel} targetSpeed={targetSpeed}");
                            }
#endif
                        }
                    }
                }
                else if (curSpeed < 0.1f && hasValidPathTargetPos && leaderInfo.m_vehicleAI.ArriveAtDestination(leaderID, ref leaderData))
                {
                    leaderData.Unspawn(leaderID);
                    return;
                }
                if ((leaderData.m_flags & Vehicle.Flags.Stopped) == (Vehicle.Flags) 0 && maxSpeed < 0.1f)
                {
#if DEBUG
                    if (debug)
                    {
                        Log._Debug($"CustomTramBaseAI.SimulationStep({vehicleID}): Vehicle is not stopped but maxSpeed < 0.1. maxSpeed={maxSpeed}");
                    }
#endif
                    blocked = true;
                }
                if (blocked)
                {
                    leaderData.m_blockCounter = (byte)Mathf.Min((int)(leaderData.m_blockCounter + 1), 255);
                }
                else
                {
                    leaderData.m_blockCounter = 0;
                }
                if (forwardLen > 1f)
                {
                    turnAngle    = Mathf.Asin(forward.x) * Mathf.Sign(targetSpeed);
                    targetMotion = forward * targetSpeed;
                }
                else
                {
                    Vector3 vel = Vector3.ClampMagnitude(afterRotToTargetPos1Diff * 0.5f - curveTangent, braking);
                    targetMotion = curveTangent + vel;
                }
            }
            bool mayBlink   = (currentFrameIndex + (uint)leaderID & 16u) != 0u;
            Vector3 springs = targetMotion - curveTangent;
            Vector3 targetAfterWheelRotMotion  = frameData.m_rotation * targetMotion;
            Vector3 targetBeforeWheelRotMotion = Vector3.Normalize((Vector3)vehicleData.m_targetPos0 - posBeforeWheelRot) * (targetMotion.magnitude * motionFactor);
            targetBeforeWheelRotMotion -= targetAfterWheelRotMotion * (Vector3.Dot(targetAfterWheelRotMotion, targetBeforeWheelRotMotion) / Mathf.Max(1f, targetAfterWheelRotMotion.sqrMagnitude));
            posAfterWheelRot           += targetAfterWheelRotMotion;
            posBeforeWheelRot          += targetBeforeWheelRotMotion;
            frameData.m_rotation        = Quaternion.LookRotation(posAfterWheelRot - posBeforeWheelRot);
            Vector3 targetPos = posAfterWheelRot - frameData.m_rotation * new Vector3(0f, 0f, this.m_info.m_generatedInfo.m_wheelBase * 0.5f);
            frameData.m_velocity = targetPos - frameData.m_position;
            if (leadingVehicle != 0)
            {
                frameData.m_position += frameData.m_velocity * 0.6f;
            }
            else
            {
                frameData.m_position += frameData.m_velocity * 0.5f;
            }
            frameData.m_swayVelocity    = frameData.m_swayVelocity * (1f - this.m_info.m_dampers) - springs * (1f - this.m_info.m_springs) - frameData.m_swayPosition * this.m_info.m_springs;
            frameData.m_swayPosition   += frameData.m_swayVelocity * 0.5f;
            frameData.m_steerAngle      = 0f;
            frameData.m_travelDistance += targetMotion.z;
            if (leadingVehicle != 0)
            {
                frameData.m_lightIntensity = Singleton <VehicleManager> .instance.m_vehicles.m_buffer[(int)leaderID].GetLastFrameData().m_lightIntensity;
            }
            else
            {
                frameData.m_lightIntensity.x = 5f;
                frameData.m_lightIntensity.y = ((springs.z >= -0.1f) ? 0.5f : 5f);
                frameData.m_lightIntensity.z = ((turnAngle >= -0.1f || !mayBlink) ? 0f : 5f);
                frameData.m_lightIntensity.w = ((turnAngle <= 0.1f || !mayBlink) ? 0f : 5f);
            }
            frameData.m_underground = ((vehicleData.m_flags & Vehicle.Flags.Underground) != (Vehicle.Flags) 0);
            frameData.m_transition  = ((vehicleData.m_flags & Vehicle.Flags.Transition) != (Vehicle.Flags) 0);
            //base.SimulationStep(vehicleID, ref vehicleData, ref frameData, leaderID, ref leaderData, lodPhysics);
        }
Ejemplo n.º 20
0
        private void RemoveVehicle(ushort vehicle)
        {
            if (!_selected.IsEmpty && _selected.Vehicle == vehicle)
            {
                WorldInfoPanel.HideAllWorldInfoPanels();

                if (!InstanceManager.IsValid(_dummy) || _dummy.Vehicle == vehicle)
                {
                    _dummy      = default(InstanceID);
                    _dummy.Type = InstanceType.Vehicle;

                    foreach (ushort i in SkylinesOverwatch.Data.Instance.Vehicles)
                    {
                        if (i == vehicle)
                        {
                            continue;
                        }

                        _dummy.Vehicle = i;
                        break;
                    }
                }

                Singleton <InstanceManager> .instance.SelectInstance(_dummy);

                Singleton <InstanceManager> .instance.FollowInstance(_dummy);
            }

            VehicleManager instance = Singleton <VehicleManager> .instance;

            HashSet <ushort> removals = new HashSet <ushort>();
            ushort           current  = vehicle;

            while (current != 0)
            {
                removals.Add(current);

                current = instance.m_vehicles.m_buffer[(int)current].m_trailingVehicle;
            }

            current = instance.m_vehicles.m_buffer[(int)vehicle].m_firstCargo;

            while (current != 0)
            {
                removals.Add(current);

                current = instance.m_vehicles.m_buffer[(int)current].m_nextCargo;
            }

            foreach (ushort i in removals)
            {
                try
                {
                    instance.ReleaseVehicle(i);
                }
                catch (Exception e)
                {
                    string error = String.Format("Failed to release {0}\r\n", i);
                    error += String.Format("Error: {0}\r\n", e.Message);
                    error += "\r\n";
                    error += "==== STACK TRACE ====\r\n";
                    error += e.StackTrace;

                    _helper.Log(error);
                }
            }

            SkylinesOverwatch.Helper.Instance.RequestVehicleRemoval(vehicle);
        }
 public CyclopsChangeSilentRunningProcessor(VehicleManager vehicleManager, PlayerManager playerManager)
 {
     this.vehicleManager = vehicleManager;
     this.playerManager  = playerManager;
 }
Ejemplo n.º 22
0
        private void UnloadPassengers(ushort vehicleID, ref Vehicle data, ushort currentStop, ushort nextStop)
        {
            if ((int)currentStop == 0)
            {
                return;
            }
            VehicleManager   instance1 = Singleton <VehicleManager> .instance;
            NetManager       instance2 = Singleton <NetManager> .instance;
            TransportManager instance3 = Singleton <TransportManager> .instance;
            Vector3          position  = instance2.m_nodes.m_buffer[(int)currentStop].m_position;
            Vector3          targetPos = Vector3.zero;

            if ((int)nextStop != 0)
            {
                targetPos = instance2.m_nodes.m_buffer[(int)nextStop].m_position;
            }
            int serviceCounter = 0;
            int num            = 0;

            //begin mod (+): calculate passenger count before unloading passengers
            ushort vehicleID1 = vehicleID;

            GetBufferStatus(vehicleID1, ref instance1.m_vehicles.m_buffer[(int)vehicleID1], out string localeKey,
                            out int bufferStatusBefore, out int max);
            //end mod

            while ((int)vehicleID != 0)
            {
                if ((int)data.m_transportLine != 0)
                {
                    BusAI.TransportArriveAtTarget(vehicleID, ref instance1.m_vehicles.m_buffer[(int)vehicleID],
                                                  position, targetPos, ref serviceCounter,
                                                  ref instance3.m_lines.m_buffer[(int)data.m_transportLine].m_passengers, (int)nextStop == 0);
                }
                else
                {
                    BusAI.TransportArriveAtTarget(vehicleID, ref instance1.m_vehicles.m_buffer[(int)vehicleID],
                                                  position, targetPos, ref serviceCounter,
                                                  ref instance3.m_passengers[(int)this.m_transportInfo.m_transportType], (int)nextStop == 0);
                }
                vehicleID = instance1.m_vehicles.m_buffer[(int)vehicleID].m_trailingVehicle;
                if (++num > 16384)
                {
                    CODebugBase <LogChannel> .Error(LogChannel.Core,
                                                    "Invalid list detected!\n" + System.Environment.StackTrace);

                    break;
                }
            }
            Singleton <StatisticsManager> .instance.Acquire <StatisticArray>(StatisticType.PassengerCount)
            .Acquire <StatisticInt32>((int)this.m_transportInfo.m_transportType, 10)
            .Add(serviceCounter);

            serviceCounter += (int)instance2.m_nodes.m_buffer[(int)currentStop].m_tempCounter;
            instance2.m_nodes.m_buffer[(int)currentStop].m_tempCounter =
                (ushort)Mathf.Min(serviceCounter, (int)ushort.MaxValue);

            //begin mod (+): calculate passenger count after unloading passengers
            GetBufferStatus(vehicleID1, ref instance1.m_vehicles.m_buffer[(int)vehicleID1], out localeKey,
                            out int bufferStatusAfter, out max);
            int diff = bufferStatusBefore - bufferStatusAfter;

            VehicleManagerMod.m_cachedVehicleData[(int)vehicleID1].LastStopGonePassengers = diff;
            VehicleManagerMod.m_cachedVehicleData[(int)vehicleID1].CurrentStop            = currentStop;
            NetManagerMod.m_cachedNodeData[(int)currentStop].PassengersOut += diff;
            //end mod
        }
Ejemplo n.º 23
0
        public static Courier <List <Manufacturer> > GetAllMakes()
        {
            VehicleManager mgr = new VehicleManager();

            return(mgr.GetAllMakes());
        }
        // Run before the original method. Skip the original one if the vehicle is a cable car
        public static bool Prefix(RenderManager.CameraInfo cameraInfo, VehicleInfo info, Vector3 position, ref Quaternion rotation, Vector3 swayPosition, Vector4 lightState, Vector4 tyrePosition, Vector3 velocity, float acceleration, Color color, Vehicle.Flags flags, int variationMask, InstanceID id, bool underground, bool overground)
        {
            // if the vehicle is not a cable car, skip and use the original method
            if ((int)info.m_vehicleType != 0x1000)
            {
                return(true);
            }

            // limit rotation along the x and z axes for all meshes except submesh1
            // submesh1 would rotate in the original way(along with the cable)
            Quaternion originalRotation = rotation;

            rotation.x = 0.0f;
            rotation.z = 0.0f;

            // change how cable cars sway
            // so they don't move up and down on the cables as if they're ships moving in sea waves
            swayPosition.y = 0.0f;


            if ((cameraInfo.m_layerMask & (1 << info.m_prefabDataLayer)) == 0)
            {
                // return false to skip the original method
                return(false);
            }
            Vector3 scale = Vector3.one;

            if ((flags & Vehicle.Flags.Inverted) != 0)
            {
                scale = new Vector3(-1f, 1f, -1f);
                Vector4 vector = lightState;
                lightState.x = vector.y;
                lightState.y = vector.x;
                lightState.z = vector.w;
                lightState.w = vector.z;
            }

            info.m_vehicleAI.RenderExtraStuff(id.Vehicle, ref Singleton <VehicleManager> .instance.m_vehicles.m_buffer[id.Vehicle], cameraInfo, id, position, rotation, tyrePosition, lightState, scale, swayPosition, underground, overground);

            if (cameraInfo.CheckRenderDistance(position, info.m_lodRenderDistance))
            {
                VehicleManager instance      = Singleton <VehicleManager> .instance;
                Matrix4x4      bodyMatrix    = info.m_vehicleAI.CalculateBodyMatrix(flags, ref position, ref rotation, ref scale, ref swayPosition);
                Matrix4x4      topBodyMatrix = info.m_vehicleAI.CalculateBodyMatrix(flags, ref position, ref originalRotation, ref scale, ref Mod.TopSwayPosition);
                Matrix4x4      value         = info.m_vehicleAI.CalculateTyreMatrix(flags, ref position, ref rotation, ref scale, ref bodyMatrix);
                if (Singleton <InfoManager> .instance.CurrentMode == InfoManager.InfoMode.None)
                {
                    RenderGroup.MeshData effectMeshData = info.m_vehicleAI.GetEffectMeshData();
                    EffectInfo.SpawnArea area           = new EffectInfo.SpawnArea(bodyMatrix, effectMeshData, info.m_generatedInfo.m_tyres, info.m_lightPositions);
                    if (info.m_effects != null)
                    {
                        for (int i = 0; i < info.m_effects.Length; i++)
                        {
                            VehicleInfo.Effect effect = info.m_effects[i];
                            if (((effect.m_vehicleFlagsRequired | effect.m_vehicleFlagsForbidden) & flags) == effect.m_vehicleFlagsRequired && effect.m_parkedFlagsRequired == VehicleParked.Flags.None)
                            {
                                effect.m_effect.RenderEffect(id, area, velocity, acceleration, 1f, -1f, Singleton <SimulationManager> .instance.m_simulationTimeDelta, cameraInfo);
                            }
                        }
                    }
                }
                if ((flags & Vehicle.Flags.Inverted) != 0)
                {
                    tyrePosition.x = 0f - tyrePosition.x;
                    tyrePosition.y = 0f - tyrePosition.y;
                }
                MaterialPropertyBlock materialBlock = instance.m_materialBlock;
                materialBlock.Clear();
                materialBlock.SetMatrix(instance.ID_TyreMatrix, value);
                materialBlock.SetVector(instance.ID_TyrePosition, tyrePosition);
                materialBlock.SetVector(instance.ID_LightState, lightState);
                bool flag = Singleton <ToolManager> .instance.m_properties.m_mode == ItemClass.Availability.AssetEditor;
                if (!flag)
                {
                    materialBlock.SetColor(instance.ID_Color, color);
                }
                bool flag2 = true;
                if (flag)
                {
                    flag2 = BuildingDecoration.IsMainMeshRendered();
                }
                if (info.m_subMeshes != null)
                {
                    for (int j = 0; j < info.m_subMeshes.Length; j++)
                    {
                        VehicleInfo.MeshInfo meshInfo = info.m_subMeshes[j];
                        VehicleInfoBase      subInfo  = meshInfo.m_subInfo;
                        if ((!flag && ((meshInfo.m_vehicleFlagsRequired | meshInfo.m_vehicleFlagsForbidden) & flags) == meshInfo.m_vehicleFlagsRequired && (meshInfo.m_variationMask & variationMask) == 0 && meshInfo.m_parkedFlagsRequired == VehicleParked.Flags.None) || (flag && BuildingDecoration.IsSubMeshRendered(subInfo)))
                        {
                            if (!(subInfo != null))
                            {
                                continue;
                            }
                            instance.m_drawCallData.m_defaultCalls++;
                            if (underground)
                            {
                                if (subInfo.m_undergroundMaterial == null && subInfo.m_material != null)
                                {
                                    VehicleProperties properties = instance.m_properties;
                                    if (properties != null)
                                    {
                                        subInfo.m_undergroundMaterial = new Material(properties.m_undergroundShader);
                                        subInfo.m_undergroundMaterial.CopyPropertiesFromMaterial(subInfo.m_material);
                                    }
                                }
                                subInfo.m_undergroundMaterial.SetVectorArray(instance.ID_TyreLocation, subInfo.m_generatedInfo.m_tyres);
                                if (j == 1)
                                {
                                    Graphics.DrawMesh(subInfo.m_mesh, topBodyMatrix, subInfo.m_undergroundMaterial, instance.m_undergroundLayer, null, 0, materialBlock);
                                }
                                else
                                {
                                    Graphics.DrawMesh(subInfo.m_mesh, bodyMatrix, subInfo.m_undergroundMaterial, instance.m_undergroundLayer, null, 0, materialBlock);
                                }
                            }
                            if (overground)
                            {
                                subInfo.m_material.SetVectorArray(instance.ID_TyreLocation, subInfo.m_generatedInfo.m_tyres);
                                if (j == 1)
                                {
                                    Graphics.DrawMesh(subInfo.m_mesh, topBodyMatrix, subInfo.m_material, info.m_prefabDataLayer, null, 0, materialBlock);
                                }
                                else
                                {
                                    Graphics.DrawMesh(subInfo.m_mesh, bodyMatrix, subInfo.m_material, info.m_prefabDataLayer, null, 0, materialBlock);
                                }
                            }
                        }
                        else if (subInfo == null)
                        {
                            flag2 = false;
                        }
                    }
                }
                if (!flag2)
                {
                    // return false to skip the original method
                    return(false);
                }
                instance.m_drawCallData.m_defaultCalls++;
                if (underground)
                {
                    if (info.m_undergroundMaterial == null && info.m_material != null)
                    {
                        VehicleProperties properties2 = instance.m_properties;
                        if (properties2 != null)
                        {
                            info.m_undergroundMaterial = new Material(properties2.m_undergroundShader);
                            info.m_undergroundMaterial.CopyPropertiesFromMaterial(info.m_material);
                        }
                    }
                    info.m_undergroundMaterial.SetVectorArray(instance.ID_TyreLocation, info.m_generatedInfo.m_tyres);
                    Graphics.DrawMesh(info.m_mesh, bodyMatrix, info.m_undergroundMaterial, instance.m_undergroundLayer, null, 0, materialBlock);
                }
                if (overground)
                {
                    info.m_material.SetVectorArray(instance.ID_TyreLocation, info.m_generatedInfo.m_tyres);
                    Graphics.DrawMesh(info.m_mesh, bodyMatrix, info.m_material, info.m_prefabDataLayer, null, 0, materialBlock);
                }
                // return false to skip the original method
                return(false);
            }
            Matrix4x4 bodyMatrix2    = info.m_vehicleAI.CalculateBodyMatrix(flags, ref position, ref rotation, ref scale, ref swayPosition);
            Matrix4x4 topBodyMatrix2 = info.m_vehicleAI.CalculateBodyMatrix(flags, ref position, ref originalRotation, ref scale, ref Mod.TopSwayPosition);

            if (Singleton <ToolManager> .instance.m_properties.m_mode == ItemClass.Availability.AssetEditor)
            {
                Matrix4x4             value2         = info.m_vehicleAI.CalculateTyreMatrix(flags, ref position, ref rotation, ref scale, ref bodyMatrix2);
                VehicleManager        instance2      = Singleton <VehicleManager> .instance;
                MaterialPropertyBlock materialBlock2 = instance2.m_materialBlock;
                materialBlock2.Clear();
                materialBlock2.SetMatrix(instance2.ID_TyreMatrix, value2);
                materialBlock2.SetVector(instance2.ID_TyrePosition, tyrePosition);
                materialBlock2.SetVector(instance2.ID_LightState, lightState);
                Mesh     mesh     = null;
                Material material = null;
                if (info.m_lodObject != null)
                {
                    MeshFilter component = info.m_lodObject.GetComponent <MeshFilter>();
                    if (component != null)
                    {
                        mesh = component.sharedMesh;
                    }
                    Renderer component2 = info.m_lodObject.GetComponent <Renderer>();
                    if (component2 != null)
                    {
                        material = component2.sharedMaterial;
                    }
                }
                if (mesh != null && material != null)
                {
                    materialBlock2.SetVectorArray(instance2.ID_TyreLocation, info.m_generatedInfo.m_tyres);
                    Graphics.DrawMesh(mesh, bodyMatrix2, material, info.m_prefabDataLayer, null, 0, materialBlock2);
                }
            }
            else if (Singleton <InfoManager> .instance.CurrentMode == InfoManager.InfoMode.None)
            {
                RenderGroup.MeshData effectMeshData2 = info.m_vehicleAI.GetEffectMeshData();
                EffectInfo.SpawnArea area2           = new EffectInfo.SpawnArea(bodyMatrix2, effectMeshData2, info.m_generatedInfo.m_tyres, info.m_lightPositions);
                if (info.m_effects != null)
                {
                    for (int k = 0; k < info.m_effects.Length; k++)
                    {
                        VehicleInfo.Effect effect2 = info.m_effects[k];
                        if (((effect2.m_vehicleFlagsRequired | effect2.m_vehicleFlagsForbidden) & flags) == effect2.m_vehicleFlagsRequired && effect2.m_parkedFlagsRequired == VehicleParked.Flags.None)
                        {
                            effect2.m_effect.RenderEffect(id, area2, velocity, acceleration, 1f, -1f, Singleton <SimulationManager> .instance.m_simulationTimeDelta, cameraInfo);
                        }
                    }
                }
            }
            bool flag3 = true;

            if (info.m_subMeshes != null)
            {
                for (int l = 0; l < info.m_subMeshes.Length; l++)
                {
                    VehicleInfo.MeshInfo meshInfo2 = info.m_subMeshes[l];
                    VehicleInfoBase      subInfo2  = meshInfo2.m_subInfo;
                    if (((meshInfo2.m_vehicleFlagsRequired | meshInfo2.m_vehicleFlagsForbidden) & flags) == meshInfo2.m_vehicleFlagsRequired && (meshInfo2.m_variationMask & variationMask) == 0 && meshInfo2.m_parkedFlagsRequired == VehicleParked.Flags.None)
                    {
                        if (!(subInfo2 != null))
                        {
                            continue;
                        }
                        if (underground)
                        {
                            if (l == 1)
                            {
                                subInfo2.m_undergroundLodTransforms[subInfo2.m_undergroundLodCount] = topBodyMatrix2;
                            }
                            else
                            {
                                subInfo2.m_undergroundLodTransforms[subInfo2.m_undergroundLodCount] = bodyMatrix2;
                            }

                            subInfo2.m_undergroundLodLightStates[subInfo2.m_undergroundLodCount] = lightState;
                            subInfo2.m_undergroundLodColors[subInfo2.m_undergroundLodCount]      = color.linear;
                            subInfo2.m_undergroundLodMin = Vector3.Min(subInfo2.m_undergroundLodMin, position);
                            subInfo2.m_undergroundLodMax = Vector3.Max(subInfo2.m_undergroundLodMax, position);
                            if (++subInfo2.m_undergroundLodCount == subInfo2.m_undergroundLodTransforms.Length)
                            {
                                Vehicle.RenderUndergroundLod(cameraInfo, subInfo2);
                            }
                        }
                        if (overground)
                        {
                            if (l == 1)
                            {
                                subInfo2.m_lodTransforms[subInfo2.m_lodCount] = topBodyMatrix2;
                            }
                            else
                            {
                                subInfo2.m_lodTransforms[subInfo2.m_lodCount] = bodyMatrix2;
                            }
                            subInfo2.m_lodLightStates[subInfo2.m_lodCount] = lightState;
                            subInfo2.m_lodColors[subInfo2.m_lodCount]      = color.linear;
                            subInfo2.m_lodMin = Vector3.Min(subInfo2.m_lodMin, position);
                            subInfo2.m_lodMax = Vector3.Max(subInfo2.m_lodMax, position);
                            if (++subInfo2.m_lodCount == subInfo2.m_lodTransforms.Length)
                            {
                                Vehicle.RenderLod(cameraInfo, subInfo2);
                            }
                        }
                    }
                    else if (subInfo2 == null)
                    {
                        flag3 = false;
                    }
                }
            }
            if (!flag3)
            {
                return(false);
            }
            if (underground)
            {
                info.m_undergroundLodTransforms[info.m_undergroundLodCount]  = bodyMatrix2;
                info.m_undergroundLodLightStates[info.m_undergroundLodCount] = lightState;
                info.m_undergroundLodColors[info.m_undergroundLodCount]      = color.linear;
                info.m_undergroundLodMin = Vector3.Min(info.m_undergroundLodMin, position);
                info.m_undergroundLodMax = Vector3.Max(info.m_undergroundLodMax, position);
                if (++info.m_undergroundLodCount == info.m_undergroundLodTransforms.Length)
                {
                    Vehicle.RenderUndergroundLod(cameraInfo, info);
                }
            }
            if (overground)
            {
                info.m_lodTransforms[info.m_lodCount]  = bodyMatrix2;
                info.m_lodLightStates[info.m_lodCount] = lightState;
                info.m_lodColors[info.m_lodCount]      = color.linear;
                info.m_lodMin = Vector3.Min(info.m_lodMin, position);
                info.m_lodMax = Vector3.Max(info.m_lodMax, position);
                if (++info.m_lodCount == info.m_lodTransforms.Length)
                {
                    Vehicle.RenderLod(cameraInfo, info);
                }
            }
            // return false to skip the original method
            return(false);
        }
Ejemplo n.º 25
0
        public static Courier <Manufacturer> CreateNewMake(string newMakeName, string username)
        {
            VehicleManager mgr = new VehicleManager();

            return(mgr.CreateNewMake(newMakeName, username));
        }
Ejemplo n.º 26
0
        /// <summary>
        ///  Checks fields entered are valid then adds vehicle to database.
        /// </summary>
        protected void VehicleAddBtn_Click(object sender, EventArgs e)
        {
            try
            {
                string manufacturer, model, SIPPCodeStr, imageLoc;
                double mpg    = 0;
                int    userID = 0;

                //If any conditions fail then do not add vehicle
                bool insertVehicle = true;

                imageLoc = null;

                SIPPCodeStr  = SIPPCodeTxt.Text.ToUpper();
                manufacturer = manufacturerTxt.Text;
                model        = modelTxt.Text;

                #region checkValidity
                insertVehicle = PictureUpload();

                //Upload selected image (check further down if upload failed)
                if (noImageChk.Checked == false)
                {
                    //If no image is selected save null location in database
                    if (imgViewFile.ImageUrl != "")
                    {
                        imageLoc = imgViewFile.ImageUrl;
                    }
                    else
                    {
                        imageLoc = null;
                    }
                }
                //If no file is being uploaded then set there to be no file to look at
                else if (noImageChk.Checked == true)
                {
                    imageLoc = null;
                }

                if (Variables.CheckDecimal(MPGTxt.Text) == false)
                {
                    MPGFailLbl.Text = "MPG - Please enter either a number or decimal number";
                    insertVehicle   = false;
                }
                else
                {
                    mpg = Convert.ToDouble(MPGTxt.Text);
                }
                if (SIPPCode.CheckSIPPCode(SIPPCodeStr) == false)
                {
                    SIPPCodeFailLbl.Text = "Please enter a valid 4 digit SIPP code";
                    insertVehicle        = false;
                }
                if (model == "")
                {
                    modelFailLbl.Text = "Please enter a model";
                    insertVehicle     = false;
                }
                if (manufacturer == "")
                {
                    manufacturerFailLbl.Text = "Please enter a manufacturer";
                    insertVehicle            = false;
                }

                userID = Variables.GetUser(Session["UserID"].ToString());
                if (userID == 0)
                {
                    insertVehicle        = false;
                    generalErrorLbl.Text = "Not logged in. Please login to continue";
                }
                #endregion

                if (insertVehicle == true)
                {
                    VehicleManager.InsertNewVehicle(manufacturer, model, SIPPCodeStr, mpg, imageLoc, userID, (int)UserAccess.UserType.company);

                    addCompleteLbl.Text = "Car Added Successfully";

                    //Send user to the list of all vehicles.
                    HtmlMeta meta = new HtmlMeta();
                    meta.HttpEquiv = "Refresh";
                    meta.Content   = "2;url=" + Variables.URL + "Vehicles";
                    this.Page.Controls.Add(meta);
                }
            }
            catch (Exception ex)
            {
                generalErrorLbl.Text = "An error has occured saying: " + ex.Message + " Please contact your system administrator.";
            }
        }
Ejemplo n.º 27
0
        private void BaseSimulationStep(ushort vehicleId, ref Vehicle data, Vector3 physicsLodRefPos)
        {
            if ((data.m_flags & Vehicle.Flags.WaitingPath) != Vehicle.Flags.None)
            {
                PathManager instance      = Singleton <PathManager> .instance;
                byte        pathFindFlags = instance.m_pathUnits.m_buffer[(int)((UIntPtr)data.m_path)].m_pathFindFlags;
                if ((pathFindFlags & 4) != 0)
                {
                    data.m_pathPositionIndex = 255;
                    data.m_flags            &= ~Vehicle.Flags.WaitingPath;
                    data.m_flags            &= ~Vehicle.Flags.Arriving;
                    PathfindSuccess(vehicleId, ref data);
                    TrySpawn(vehicleId, ref data);
                }
                else if ((pathFindFlags & 8) != 0)
                {
                    data.m_flags &= ~Vehicle.Flags.WaitingPath;
                    Singleton <PathManager> .instance.ReleasePath(data.m_path);

                    data.m_path = 0u;
                    PathfindFailure(vehicleId, ref data);
                    return;
                }
            }
            else if ((data.m_flags & Vehicle.Flags.WaitingSpace) != Vehicle.Flags.None)
            {
                TrySpawn(vehicleId, ref data);
            }
            Vector3 lastFramePosition = data.GetLastFramePosition();
            int     lodPhysics;

            if (Vector3.SqrMagnitude(physicsLodRefPos - lastFramePosition) >= 1210000f)
            {
                lodPhysics = 2;
            }
            else if (
                Vector3.SqrMagnitude(Singleton <SimulationManager> .instance.m_simulationView.m_position -
                                     lastFramePosition) >= 250000f)
            {
                lodPhysics = 1;
            }
            else
            {
                lodPhysics = 0;
            }
            SimulationStep(vehicleId, ref data, vehicleId, ref data, lodPhysics);
            if (data.m_leadingVehicle == 0 && data.m_trailingVehicle != 0)
            {
                VehicleManager instance2 = Singleton <VehicleManager> .instance;
                ushort         num       = data.m_trailingVehicle;
                int            num2      = 0;
                while (num != 0)
                {
                    ushort      trailingVehicle = instance2.m_vehicles.m_buffer[num].m_trailingVehicle;
                    VehicleInfo info            = instance2.m_vehicles.m_buffer[num].Info;
                    info.m_vehicleAI.SimulationStep(num, ref instance2.m_vehicles.m_buffer[num], vehicleId,
                                                    ref data, lodPhysics);
                    num = trailingVehicle;
                    if (++num2 > 16384)
                    {
                        CODebugBase <LogChannel> .Error(LogChannel.Core,
                                                        "Invalid list detected!\n" + Environment.StackTrace);

                        break;
                    }
                }
            }
            int num3 = (m_info.m_class.m_service > ItemClass.Service.Office) ? 150 : 100;

            if ((data.m_flags & (Vehicle.Flags.Spawned | Vehicle.Flags.WaitingPath | Vehicle.Flags.WaitingSpace)) ==
                Vehicle.Flags.None && data.m_cargoParent == 0)
            {
                Singleton <VehicleManager> .instance.ReleaseVehicle(vehicleId);
            }
            else if (data.m_blockCounter >= num3 && LoadingExtension.Instance.DespawnEnabled)
            {
                Singleton <VehicleManager> .instance.ReleaseVehicle(vehicleId);
            }
        }
Ejemplo n.º 28
0
        private void API_onClientEventTrigger(Client sender, string eventName, params object[] arguments)
        {
            if (eventName == "chopperdealer_selectcar")
            {
                Character character = sender.GetCharacter();

                string[] selectedCar = null;

                #region Get Car Info.

                switch ((int)arguments[0])
                {
                case 0:
                    selectedCar = _helicopters[(int)arguments[1]];
                    break;
                }

                #endregion

                if (selectedCar == null)
                {
                    return;
                }

                if (Money.GetCharacterMoney(character) >= Convert.ToInt32(selectedCar[2]))
                {
                    //Remove price.
                    InventoryManager.DeleteInventoryItem(character, typeof(Money), Convert.ToInt32(selectedCar[2]));

                    //Spawn positions.
                    Vector3[] spawnPoss =
                    {
                        new Vector3(-1112.07,  -2883.274, 13.94603),
                        new Vector3(-1145.618, -2864.848, 13.94607),
                        new Vector3(-1177.989, -2845.755, 13.94576),
                    };
                    var randomPos = new Random().Next(1, spawnPoss.Length) - 1;

                    //Create the vehicle.
                    var theVehicle = VehicleManager.CreateVehicle(
                        (VehicleHash)Convert.ToInt32(selectedCar[1]),
                        spawnPoss[randomPos],
                        new Vector3(0.1917319, 0.1198539, -177.1394),
                        "Unregistered",
                        character.Id,
                        vehicle_manager.Vehicle.VehTypePerm
                        );
                    //theVehicle.IsVip = true;
                    theVehicle.OwnerName = character.CharacterName;
                    //Add it to the players cars.
                    theVehicle.Insert();

                    //Spawn it.
                    if (VehicleManager.spawn_vehicle(theVehicle) != 1)
                    {
                        API.SendChatMessageToPlayer(sender, "An error occured while spawning your vehicle.");
                    }

                    //Notify.
                    API.SendChatMessageToPlayer(sender,
                                                $"You have sucessfully bought the ~g~{selectedCar[0]}~w~ for ${selectedCar[2]}.");
                    API.SendChatMessageToPlayer(sender, "Use /myvehicles to manage it.");

                    //Log it.
                    LogManager.Log(LogManager.LogTypes.Stats, $"[Chopper Dealership] {sender.GetCharacter().CharacterName}[{sender.GetAccount().AccountName}] has bought a(n) {API.GetVehicleDisplayName(theVehicle.VehModel)} for ${selectedCar[2]}.");

                    //Exit.
                    API.TriggerClientEvent(sender, "chopperdealership_exitdealermenu");
                }
                else
                {
                    API.SendChatMessageToPlayer(sender,
                                                $"You don't have enough money to buy the ~g~{selectedCar[0]}~w~.");
                }
            }
        }
Ejemplo n.º 29
0
        public static bool EndRenderingImplPrefix(VehicleManager __instance, RenderManager.CameraInfo cameraInfo, ulong[] ___m_renderBuffer, ulong[] ___m_renderBuffer2)
        {
            float   levelOfDetailFactor = RenderManager.LevelOfDetailFactor;
            float   near    = cameraInfo.m_near;
            float   d       = Mathf.Min(levelOfDetailFactor * 5000f, Mathf.Min(levelOfDetailFactor * 2000f + cameraInfo.m_height * 0.6f, cameraInfo.m_far));
            Vector3 lhs     = cameraInfo.m_position + cameraInfo.m_directionA * near;
            Vector3 rhs     = cameraInfo.m_position + cameraInfo.m_directionB * near;
            Vector3 lhs2    = cameraInfo.m_position + cameraInfo.m_directionC * near;
            Vector3 rhs2    = cameraInfo.m_position + cameraInfo.m_directionD * near;
            Vector3 lhs3    = cameraInfo.m_position + cameraInfo.m_directionA * d;
            Vector3 rhs3    = cameraInfo.m_position + cameraInfo.m_directionB * d;
            Vector3 lhs4    = cameraInfo.m_position + cameraInfo.m_directionC * d;
            Vector3 rhs4    = cameraInfo.m_position + cameraInfo.m_directionD * d;
            Vector3 vector  = Vector3.Min(Vector3.Min(Vector3.Min(lhs, rhs), Vector3.Min(lhs2, rhs2)), Vector3.Min(Vector3.Min(lhs3, rhs3), Vector3.Min(lhs4, rhs4)));
            Vector3 vector2 = Vector3.Max(Vector3.Max(Vector3.Max(lhs, rhs), Vector3.Max(lhs2, rhs2)), Vector3.Max(Vector3.Max(lhs3, rhs3), Vector3.Max(lhs4, rhs4)));
            int     num     = Mathf.Max((int)((vector.x - 10f) / 32f + 270f), 0);
            int     num2    = Mathf.Max((int)((vector.z - 10f) / 32f + 270f), 0);
            int     num3    = Mathf.Min((int)((vector2.x + 10f) / 32f + 270f), 539);
            int     num4    = Mathf.Min((int)((vector2.z + 10f) / 32f + 270f), 539);

            for (int i = num2; i <= num4; i++)
            {
                for (int j = num; j <= num3; j++)
                {
                    ushort num5 = __instance.m_vehicleGrid[i * 540 + j];
                    if (num5 != 0)
                    {
                        ___m_renderBuffer[num5 >> 6] |= (ulong)(1L << (int)num5);
                    }
                }
            }
            float   near2   = cameraInfo.m_near;
            float   d2      = Mathf.Min(2000f, cameraInfo.m_far);
            Vector3 lhs5    = cameraInfo.m_position + cameraInfo.m_directionA * near2;
            Vector3 rhs5    = cameraInfo.m_position + cameraInfo.m_directionB * near2;
            Vector3 lhs6    = cameraInfo.m_position + cameraInfo.m_directionC * near2;
            Vector3 rhs6    = cameraInfo.m_position + cameraInfo.m_directionD * near2;
            Vector3 lhs7    = cameraInfo.m_position + cameraInfo.m_directionA * d2;
            Vector3 rhs7    = cameraInfo.m_position + cameraInfo.m_directionB * d2;
            Vector3 lhs8    = cameraInfo.m_position + cameraInfo.m_directionC * d2;
            Vector3 rhs8    = cameraInfo.m_position + cameraInfo.m_directionD * d2;
            Vector3 vector3 = Vector3.Min(Vector3.Min(Vector3.Min(lhs5, rhs5), Vector3.Min(lhs6, rhs6)), Vector3.Min(Vector3.Min(lhs7, rhs7), Vector3.Min(lhs8, rhs8)));
            Vector3 vector4 = Vector3.Max(Vector3.Max(Vector3.Max(lhs5, rhs5), Vector3.Max(lhs6, rhs6)), Vector3.Max(Vector3.Max(lhs7, rhs7), Vector3.Max(lhs8, rhs8)));
            int     num6    = Mathf.Max((int)((vector3.x - 10f) / 32f + 270f), 0);
            int     num7    = Mathf.Max((int)((vector3.z - 10f) / 32f + 270f), 0);
            int     num8    = Mathf.Min((int)((vector4.x + 10f) / 32f + 270f), 539);
            int     num9    = Mathf.Min((int)((vector4.z + 10f) / 32f + 270f), 539);

            for (int k = num7; k <= num9; k++)
            {
                for (int l = num6; l <= num8; l++)
                {
                    ushort num10 = __instance.m_parkedGrid[k * 540 + l];
                    if (num10 != 0)
                    {
                        ___m_renderBuffer2[num10 >> 6] |= (ulong)(1L << (int)num10);
                    }
                }
            }
            float   near3   = cameraInfo.m_near;
            float   num11   = Mathf.Min(10000f, cameraInfo.m_far);
            Vector3 lhs9    = cameraInfo.m_position + cameraInfo.m_directionA * near3;
            Vector3 rhs9    = cameraInfo.m_position + cameraInfo.m_directionB * near3;
            Vector3 lhs10   = cameraInfo.m_position + cameraInfo.m_directionC * near3;
            Vector3 rhs10   = cameraInfo.m_position + cameraInfo.m_directionD * near3;
            Vector3 lhs11   = cameraInfo.m_position + cameraInfo.m_directionA * num11;
            Vector3 rhs11   = cameraInfo.m_position + cameraInfo.m_directionB * num11;
            Vector3 lhs12   = cameraInfo.m_position + cameraInfo.m_directionC * num11;
            Vector3 rhs12   = cameraInfo.m_position + cameraInfo.m_directionD * num11;
            Vector3 vector5 = Vector3.Min(Vector3.Min(Vector3.Min(lhs9, rhs9), Vector3.Min(lhs10, rhs10)), Vector3.Min(Vector3.Min(lhs11, rhs11), Vector3.Min(lhs12, rhs12)));
            Vector3 vector6 = Vector3.Max(Vector3.Max(Vector3.Max(lhs9, rhs9), Vector3.Max(lhs10, rhs10)), Vector3.Max(Vector3.Max(lhs11, rhs11), Vector3.Max(lhs12, rhs12)));

            if (cameraInfo.m_shadowOffset.x < 0f)
            {
                vector6.x = Mathf.Min(cameraInfo.m_position.x + num11, vector6.x - cameraInfo.m_shadowOffset.x);
            }
            else
            {
                vector5.x = Mathf.Max(cameraInfo.m_position.x - num11, vector5.x - cameraInfo.m_shadowOffset.x);
            }
            if (cameraInfo.m_shadowOffset.z < 0f)
            {
                vector6.z = Mathf.Min(cameraInfo.m_position.z + num11, vector6.z - cameraInfo.m_shadowOffset.z);
            }
            else
            {
                vector5.z = Mathf.Max(cameraInfo.m_position.z - num11, vector5.z - cameraInfo.m_shadowOffset.z);
            }
            int num12 = Mathf.Max((int)((vector5.x - 50f) / 320f + 27f), 0);
            int num13 = Mathf.Max((int)((vector5.z - 50f) / 320f + 27f), 0);
            int num14 = Mathf.Min((int)((vector6.x + 50f) / 320f + 27f), 53);
            int num15 = Mathf.Min((int)((vector6.z + 50f) / 320f + 27f), 53);

            for (int m = num13; m <= num15; m++)
            {
                for (int n = num12; n <= num14; n++)
                {
                    ushort num16 = __instance.m_vehicleGrid2[m * 54 + n];
                    if (num16 != 0)
                    {
                        ___m_renderBuffer[num16 >> 6] |= (ulong)(1L << (int)num16);
                    }
                }
            }
            int num17 = ___m_renderBuffer.Length;

            for (int num18 = 0; num18 < num17; num18++)
            {
                ulong num19 = ___m_renderBuffer[num18];
                if (num19 == 0)
                {
                    continue;
                }
                for (int num20 = 0; num20 < 64; num20++)
                {
                    ulong num21 = (ulong)(1L << num20);
                    if ((num19 & num21) == 0)
                    {
                        continue;
                    }
                    ushort num22 = (ushort)((num18 << 6) | num20);
                    if (!__instance.m_vehicles.m_buffer[num22].RenderInstance(cameraInfo, num22))
                    {
                        num19 &= ~num21;
                    }
                    ushort nextGridVehicle = __instance.m_vehicles.m_buffer[num22].m_nextGridVehicle;
                    int    num23           = 0;
                    while (nextGridVehicle != 0)
                    {
                        int num24 = nextGridVehicle >> 6;
                        num21 = (ulong)(1L << (int)nextGridVehicle);
                        if (num24 == num18)
                        {
                            if ((num19 & num21) != 0)
                            {
                                break;
                            }
                            num19 |= num21;
                        }
                        else
                        {
                            ulong num25 = ___m_renderBuffer[num24];
                            if ((num25 & num21) != 0)
                            {
                                break;
                            }
                            ___m_renderBuffer[num24] = (num25 | num21);
                        }
                        if (nextGridVehicle > num22)
                        {
                            break;
                        }
                        nextGridVehicle = __instance.m_vehicles.m_buffer[nextGridVehicle].m_nextGridVehicle;
                        if (++num23 > 16384)
                        {
                            CODebugBase <LogChannel> .Error(LogChannel.Core, "Invalid list detected!\n" + Environment.StackTrace);

                            break;
                        }
                    }
                }
                ___m_renderBuffer[num18] = num19;
            }

            var action = new Action(() =>
            {
                int num26 = ___m_renderBuffer2.Length;
                for (int num27 = 0; num27 < num26; num27++)
                {
                    ulong num28 = ___m_renderBuffer2[num27];
                    if (num28 == 0)
                    {
                        continue;
                    }
                    for (int num29 = 0; num29 < 64; num29++)
                    {
                        ulong num30 = (ulong)(1L << num29);
                        if ((num28 & num30) == 0)
                        {
                            continue;
                        }
                        ushort num31 = (ushort)((num27 << 6) | num29);
                        if (!__instance.m_parkedVehicles.m_buffer[num31].RenderInstance(cameraInfo, num31))
                        {
                            num28 &= ~num30;
                        }
                        ushort nextGridParked = __instance.m_parkedVehicles.m_buffer[num31].m_nextGridParked;
                        int num32             = 0;
                        while (nextGridParked != 0)
                        {
                            int num33 = nextGridParked >> 6;
                            num30     = (ulong)(1L << (int)nextGridParked);
                            if (num33 == num27)
                            {
                                if ((num28 & num30) != 0)
                                {
                                    break;
                                }
                                num28 |= num30;
                            }
                            else
                            {
                                ulong num34 = ___m_renderBuffer2[num33];
                                if ((num34 & num30) != 0)
                                {
                                    break;
                                }
                                ___m_renderBuffer2[num33] = (num34 | num30);
                            }
                            if (nextGridParked > num31)
                            {
                                break;
                            }
                            nextGridParked = __instance.m_parkedVehicles.m_buffer[nextGridParked].m_nextGridParked;
                            if (++num32 > 32768)
                            {
                                CODebugBase <LogChannel> .Error(LogChannel.Core, "Invalid list detected!\n" + Environment.StackTrace);
                                break;
                            }
                        }
                    }
                    ___m_renderBuffer2[num27] = num28;
                }


                int num35 = PrefabCollection <VehicleInfo> .PrefabCount();
                for (int num36 = 0; num36 < num35; num36++)
                {
                    VehicleInfo prefab = PrefabCollection <VehicleInfo> .GetPrefab((uint)num36);
                    if ((object)prefab == null)
                    {
                        continue;
                    }
                    if (prefab.m_lodCount != 0)
                    {
                        Vehicle.RenderLod(cameraInfo, prefab);
                    }
                    if (prefab.m_undergroundLodCount != 0)
                    {
                        Vehicle.RenderUndergroundLod(cameraInfo, prefab);
                    }
                    if (prefab.m_subMeshes == null)
                    {
                        continue;
                    }
                    for (int num37 = 0; num37 < prefab.m_subMeshes.Length; num37++)
                    {
                        VehicleInfoBase subInfo = prefab.m_subMeshes[num37].m_subInfo;
                        if (subInfo != null)
                        {
                            if (subInfo.m_lodCount != 0)
                            {
                                Vehicle.RenderLod(cameraInfo, subInfo);
                            }
                            if (subInfo.m_undergroundLodCount != 0)
                            {
                                Vehicle.RenderUndergroundLod(cameraInfo, subInfo);
                            }
                        }
                    }
                }
            });

#if UseTask
            Patcher.Dispatcher.Add(action);
#else
            action.Invoke();
#endif
            return(false);
        }
Ejemplo n.º 30
0
        public static async Task changeName(string oldName)
        {
            try
            {
                if (!toChange.ContainsKey(oldName))
                {
                    return;
                }

                string newName = toChange[oldName];

                //int UUID = Main.PlayerNames.FirstOrDefault(u => u.Value == oldName).Key;
                int Uuid = Main.PlayerUUIDs.GetValueOrDefault(oldName);
                if (Uuid <= 0)
                {
                    await Log.WriteAsync($"Cant'find UUID of player [{oldName}]", nLog.Type.Warn);

                    return;
                }

                string[] split = newName.Split("_");

                Main.PlayerNames[Uuid] = newName;
                Main.PlayerUUIDs.Remove(oldName);
                Main.PlayerUUIDs.Add(newName, Uuid);
                try {
                    if (Main.PlayerBankAccs.ContainsKey(oldName))
                    {
                        int bank = Main.PlayerBankAccs[oldName];
                        Main.PlayerBankAccs.Add(newName, bank);
                        Main.PlayerBankAccs.Remove(oldName);
                    }
                } catch { }

                MySqlCommand cmd = nameCommand;
                cmd.Parameters.AddWithValue("@fn", split[0]);
                cmd.Parameters.AddWithValue("@ln", split[1]);
                cmd.Parameters.AddWithValue("@uuid", Uuid);
                await MySQL.QueryAsync(cmd);

                NAPI.Task.Run(() =>
                {
                    try
                    {
                        VehicleManager.changeOwner(oldName, newName);
                        BusinessManager.changeOwner(oldName, newName);
                        MoneySystem.Bank.changeHolder(oldName, newName);
                        Houses.HouseManager.ChangeOwner(oldName, newName);
                    }
                    catch { }
                });

                await Log.DebugAsync("Nickname has been changed!", nLog.Type.Success);

                toChange.Remove(oldName);
                MoneySystem.Donations.Rename(oldName, newName);
                GameLog.Name(Uuid, oldName, newName);
            }
            catch (Exception e)
            {
                Log.Write("EXCEPTION AT \"CHANGENAME\":\n" + e.ToString(), nLog.Type.Error);
            }
        }
Ejemplo n.º 31
0
 public CyclopsToggleInternalLightingProcessor(VehicleManager vehicleManager, PlayerManager playerManager)
 {
     this.vehicleManager = vehicleManager;
     this.playerManager  = playerManager;
 }
Ejemplo n.º 32
0
 /// <summary>
 /// Managers used by the Lot Instance
 /// </summary>
 public Instance(VehicleManager vm, BayManager bm)
 {
     _manager.Add("Vehicle", vm);
     _manager.Add("Bay", bm);
 }
 public CyclopsToggleEngineStateProcessor(VehicleManager vehicleManager, PlayerManager playerManager)
 {
     this.vehicleManager = vehicleManager;
     this.playerManager  = playerManager;
 }
Ejemplo n.º 34
0
 void Awake()
 {
     vm = GameObject.FindGameObjectWithTag("_VM").GetComponent<VehicleManager>();
 }
Ejemplo n.º 35
0
        public ApiResp Execute(System.Collections.Hashtable params_ht)
        {
            ApiResp resp = new ApiResp();

            resp.code = "-1";

            string client_id = params_ht["client_id"].ToString();
            long   timestamp = long.Parse(params_ht["timestamp"].ToString());
            string sign      = params_ht["sign"].ToString();
            string order_no  = params_ht["order_no"].ToString();

            BaoJiaManager mgr      = new BaoJiaManager();
            Hashtable     order_ht = mgr.GetOrderInfo(order_no);

            if (order_ht != null && order_ht.Keys.Count > 0)
            {
                ServiceAreaManager areaManager = new ServiceAreaManager();

                string vehicleid = SiteHelper.GetHashTableValueByKey(order_ht, "VehicleID");
                string orderid   = SiteHelper.GetHashTableValueByKey(order_ht, "ID");

                GetOrderTracks_Data data = new GetOrderTracks_Data();

                string returnLocType = SiteHelper.GetHashTableValueByKey(order_ht, "ReturnLocType");
                if (returnLocType == "01")
                {
                    data.return_location_address_type = "3";
                    data.return_location_address_msg  = "网点还车";

                    string toParking = SiteHelper.GetHashTableValueByKey(order_ht, "ToParking");
                    if (!string.IsNullOrEmpty(toParking))
                    {
                        Hashtable parking_ht = areaManager.GetInfoByID(toParking);
                        if (parking_ht != null && parking_ht.Keys.Count > 0)
                        {
                            data.return_station_points = SiteHelper.GetHashTableValueByKey(parking_ht, "Coordinates").Replace(";", "|");
                            data.return_station_center = SiteHelper.GetHashTableValueByKey(parking_ht, "Longitude") + "," + SiteHelper.GetHashTableValueByKey(parking_ht, "Latitude");
                        }
                    }
                }
                else if (returnLocType == "02" || returnLocType == "03")
                {
                    data.return_location_address_type = "1";
                    data.return_location_address_msg  = "行驶区域内网点外还车";
                }
                else if (returnLocType == "04")
                {
                    data.return_location_address_type = "2";
                    data.return_location_address_msg  = "行驶区域外还车";

                    Hashtable area_ht = areaManager.GetServiceAreaByVehicleID(vehicleid);
                    if (area_ht != null && area_ht.Keys.Count > 0)
                    {
                        data.return_xianzhi_points = SiteHelper.GetHashTableValueByKey(area_ht, "Coordinates").Replace(";", "|");
                    }
                }

                VehicleManager vm = new VehicleManager();
                DataTable      dt = vm.GetVehicleTrace(vehicleid, orderid, null, null);
                if (dt != null)
                {
                    GetOrderTracks_Data Data = new GetOrderTracks_Data();

                    data.return_location_address_msg = "";
                    data.line_points = "";
                    List <LatLng> pts = new List <LatLng>();
                    foreach (DataRow dr in dt.Rows)
                    {
                        double lng = double.Parse(dr["AMAP_longitude"].ToString());
                        double lat = double.Parse(dr["AMAP_latitude"].ToString());
                        pts.Add(new LatLng(lat, lng));

                        if (data.line_points.Length > 0 && !data.line_points.EndsWith("|"))
                        {
                            data.line_points += "|";
                        }
                        data.line_points += lng + "," + lat;
                    }
                    if (pts.Count > 0)
                    {
                        data.start_lng = pts[0].longitude;
                        data.star_lat  = pts[0].latitude;

                        data.end_lng = pts[pts.Count - 1].longitude;
                        data.end_lat = pts[pts.Count - 1].latitude;
                    }
                    else
                    {
                        LatLng latlng = new LatLng(double.Parse(SiteHelper.GetHashTableValueByKey(order_ht, "EndLatitude")), double.Parse(SiteHelper.GetHashTableValueByKey(order_ht, "EndLongitude")));
                        latlng         = SiteHelper.TransformFromWGSToGCJ(latlng);
                        data.start_lng = latlng.longitude;
                        data.star_lat  = latlng.latitude;
                        data.end_lng   = data.start_lng;
                        data.end_lat   = data.star_lat;
                    }

                    resp.code = "0";
                    resp.msg  = "成功";
                    resp.data = data;
                }
                else
                {
                    resp.code = "-1";
                    resp.msg  = "未找到停车网点";
                }
            }
            else
            {
                resp.code = "-1";
                resp.msg  = "未找到相关订单";
            }

            return(resp);
        }
Ejemplo n.º 36
0
        /*
         * Handles creation and removal of vehicles
         *
         * Note: Just because a vehicle has been removed visually, it does not mean
         * it is removed as far as the game is concerned. The vehicle is only truly removed
         * when the frame covers the vehicle's id, and that's when we will remove the
         * vehicle from our records.
         */
        public override void OnUpdate(float realTimeDelta, float simulationTimeDelta)
        {
            if (_terminated) return;

            if (!_helper.VehicleMonitorSpinnable) return;

            if (!_settings.Enable._VehicleMonitor) return;

            try
            {
                if (!_initialized)
                {
                    _data = Data.Instance;

                    _mapping = new VehiclePrefabMapping();

                    _paused = false;

                    _instance = Singleton<VehicleManager>.instance;
                    _capacity = _instance.m_vehicles.m_buffer.Length;

                    _id = (ushort)_capacity;

                    _initialized = true;
                    _helper.VehicleMonitorSpun = true;
                    _helper.VehicleMonitor = this;

                    _helper.NotifyPlayer("Vehicle monitor initialized");
                }
                else if (!SimulationManager.instance.SimulationPaused)
                {
                    _data._VehiclesUpdated.Clear();
                    _data._VehiclesRemoved.Clear();

                    int end = GetFrame();

                    while (_lastProcessedFrame != end)
                    {
                        _lastProcessedFrame = GetFrame(_lastProcessedFrame + 1);

                        int[] boundaries = GetFrameBoundaries();
                        ushort id;

                        for (int i = boundaries[0]; i <= boundaries[1]; i++)
                        {
                            id = (ushort)i;

                            if (UpdateVehicle(id))
                                _data._VehiclesUpdated.Add(id);
                            else if (_data._Vehicles.Contains(id))
                            {
                                _data._VehiclesRemoved.Add(id);
                                RemoveVehicle(id);
                            }
                        }
                    }
                }

                OutputDebugLog();
            }
            catch (Exception e)
            {
                string error = "Vehicle monitor failed to initialize\r\n";
                error += String.Format("Error: {0}\r\n", e.Message);
                error += "\r\n";
                error += "==== STACK TRACE ====\r\n";
                error += e.StackTrace;

                _helper.Log(error);

                _terminated = true;
            }

            base.OnUpdate(realTimeDelta, simulationTimeDelta);
        }
Ejemplo n.º 37
0
        public void Execute(IRocketPlayer caller,params string[] command)
        {
            bool hasPerm = false;
            UnturnedPlayer player = (UnturnedPlayer)caller;
            if (command.Length == 0)
            {
                UnturnedChat.Say(caller, LIGHT.Instance.Translate("car_help_1"));
                return;
            }
            if (command.Length > 0)
            {

                if (player.HasPermission("car") || player.HasPermission("car.*") || player.HasPermission("*"))
                {
                    hasPerm = true;
                }
                if (!hasPerm && !(caller.IsAdmin))
                {
                    UnturnedChat.Say(caller, LIGHT.Instance.Translate("lpx_no_perm"));
                    return;
                }
                else
                {
                    InteractableVehicle veh = player.Player.movement.getVehicle();                    
                    switch (command[0].ToLower())
                    {
                        case "refuel":
                            if (player.HasPermission("car.refuel") || player.HasPermission("car.*") || player.HasPermission("*"))
                                hasPerm = true;
                            if (!hasPerm && !(caller.IsAdmin))
                            {
                                UnturnedChat.Say(caller, LIGHT.Instance.Translate("lpx_no_perm"));
                                return;
                            }
                            if(command.Length < 2)
                            {
                                UnturnedChat.Say(caller, LIGHT.Instance.Translate("car_refuel_help_1"));
                                return;
                            }
                            else
                            {
                                
                                if (veh != null)
                                {
                                    VehicleAsset vehi = veh.asset;
                                    ushort fuel = vehi.fuel;
                                    ushort maxfuel = vehi.fuel;
                                    double percent = 0;
                                    double truefuel = 0;
                                    if (command[1] == "full" || command[1] == "all" || command[1] == "100")
                                    {
                                        truefuel = (double)fuel - (double)veh.fuel;
                                        percent = double.Parse(fuel.ToString()) / (double)maxfuel * 100.00;
                                        percent = Math.Round(percent, 2);
                                    }
                                    else
                                    {
                                        fuel = 0;                                        
                                        if (ushort.TryParse(command[1], out fuel))
                                        {

                                            if ((((double)veh.fuel / (double)maxfuel * 100.00) + (double)fuel) > 100.00)
                                            {
                                                truefuel = (double)maxfuel - (double)veh.fuel;
                                            }
                                            else
                                            {
                                                truefuel = (double)fuel / 100.00 * (double)maxfuel;
                                            }
                                            truefuel = Math.Round(truefuel, 0);
                                            percent = Math.Round(((double)truefuel / (double)maxfuel) * 100.00, 2);

                                        }
                                        else
                                        {
                                            UnturnedChat.Say(caller, LIGHT.Instance.Translate("car_refuel_error2"));
                                            return;
                                        }

                                    }
                                    decimal price = decimal.Parse("1.3");
                                    decimal.TryParse(LIGHT.Instance.Configuration.Instance.FuelPrice.ToString(), out price);
                                    if (price != 0.00m)
                                    {
                                        decimal balance = Uconomy.Instance.Database.GetBalance(player.Id);
                                        decimal totalprice = Math.Round(price * (decimal)truefuel / (decimal)10, 2);
                                        if (balance < totalprice)
                                        {
                                            UnturnedChat.Say(caller, LIGHT.Instance.Translate("car_not_enough_currency", Uconomy.Instance.Configuration.Instance.MoneyName));
                                            return;
                                        }
                                        decimal bal = Uconomy.Instance.Database.IncreaseBalance(player.CSteamID.ToString(), (totalprice * -1));
                                        UnturnedChat.Say(caller, LIGHT.Instance.Translate("car_refuel_paid", totalprice, Uconomy.Instance.Configuration.Instance.MoneyName, veh.instanceID.ToString(), percent.ToString()));
                                        if (bal >= 0.0m) UnturnedChat.Say(player.CSteamID, LIGHT.Instance.Translate("new_balance_msg", new object[] { bal, Uconomy.Instance.Configuration.Instance.MoneyName }));
                                    }
                                    else
                                        UnturnedChat.Say(caller, LIGHT.Instance.Translate("car_refuelled_1", percent.ToString()));
                                    veh.askFill((ushort)truefuel);                                                                           
                                }
                                else
                                {
                                    UnturnedChat.Say(caller, LIGHT.Instance.Translate("car_error_1"));
                                    return;
                                }
                            }
                            break;
                        case "lock":
                            if (veh != null)
                            {
                                if (command.Length == 1)
                                {
                                    if (LIGHT.Instance.DatabaseCar.CheckOwner(veh.instanceID.ToString()) == player.Id)
                                    {
                                        LIGHT.Instance.DatabaseCar.AddLockedStatus(veh.instanceID.ToString(), true);
                                        UnturnedChat.Say(caller, LIGHT.Instance.Translate("car_Locked", veh.instanceID.ToString()));
                                    }
                                    else
                                    {
                                        string[] PlayersWithKey = LIGHT.Instance.DatabaseCar.GetGivenKeys(veh.instanceID.ToString());
                                        for(int x = 0; x < PlayersWithKey.Length; x++)
                                        {
                                            if(PlayersWithKey[x].Trim() == player.Id)
                                            {
                                                LIGHT.Instance.DatabaseCar.AddLockedStatus(veh.instanceID.ToString(), true);
                                                UnturnedChat.Say(caller, LIGHT.Instance.Translate("car_Locked", veh.instanceID.ToString()));
                                                break;
                                            }
                                            
                                        }
                                        UnturnedChat.Say(caller, LIGHT.Instance.Translate("car_commmand_notowner"));
                                        return;
                                    }
                                    
                                }
                            }
                            else
                            {
                                UnturnedChat.Say(caller, LIGHT.Instance.Translate("car_error_1"));
                                return;
                            }
                            break;
                        case "unlock":
                            if (veh != null)
                            {
                                if (command.Length == 1)
                                {
                                    if (LIGHT.Instance.DatabaseCar.CheckOwner(veh.instanceID.ToString()) == player.Id)
                                    {
                                        LIGHT.Instance.DatabaseCar.AddLockedStatus(veh.instanceID.ToString(), false);
                                        UnturnedChat.Say(caller, LIGHT.Instance.Translate("car_Unlocked", veh.instanceID.ToString()));
                                    }
                                    else
                                    {
                                        UnturnedChat.Say(caller, LIGHT.Instance.Translate("car_commmand_notowner"));
                                        return;
                                    }
                                }
                            }
                            else
                            {
                                UnturnedChat.Say(caller, LIGHT.Instance.Translate("car_error_1"));
                                return;
                            }
                            break;
                        case "key":
                            if(command.Length == 1)
                            {
                                UnturnedChat.Say(caller, LIGHT.Instance.Translate("car_commmand_keyhelp"));
                                return;
                            }
                            if(command.Length == 2)
                            {
                                UnturnedChat.Say(caller, LIGHT.Instance.Translate("car_commmand_keyhelp2"));
                                return;
                            }
                            if(command.Length > 2)
                            {
                                if (LIGHT.Instance.DatabaseCar.CheckCarExistInDB(command[1]))
                                {
                                    if (LIGHT.Instance.DatabaseCar.CheckOwner(command[1]) == player.Id)
                                    {
                                        UnturnedPlayer PlayerKey = UnturnedPlayer.FromName(command[2]);
                                        if (PlayerKey != null)
                                        {
                                            LIGHT.Instance.DatabaseCar.AddGivenKeys(command[1], PlayerKey.Id);
                                            UnturnedChat.Say(caller, LIGHT.Instance.Translate("car_key_given",command[1], PlayerKey.CharacterName));
                                        }
                                        else
                                        {
                                            UnturnedChat.Say(caller, LIGHT.Instance.Translate("lpx_playernotfound"));
                                            return;
                                        }
                                    }
                                    else
                                    {
                                        UnturnedChat.Say(caller, LIGHT.Instance.Translate("car_commmand_notowner"));
                                        return;
                                    }
                                }
                                else
                                {
                                    UnturnedChat.Say(caller, LIGHT.Instance.Translate("car_not_found"));
                                    return;
                                }
                            }
                            break;
                        case "repair":
                            if (player.HasPermission("car.repair") || player.HasPermission("car.*") || player.HasPermission("*"))
                                hasPerm = true;
                            if (!hasPerm && !(caller.IsAdmin))
                            {
                                UnturnedChat.Say(caller, LIGHT.Instance.Translate("lpx_no_perm"));
                                return;
                            }
                            if (command.Length == 1)
                            {
                                if (veh != null)
                                {
                                    VehicleAsset vehi = veh.asset;
                                    int repair = 0;
                                    double percent = 0.00;
                                    repair = vehi.health - veh.health;
                                    if(repair > 0)
                                    {
                                        
                                        percent = Math.Round(((double)repair / (double)vehi.health) * 100.00, 2);
                                        if(LIGHT.Instance.Configuration.Instance.RepairPrice == 0)
                                            UnturnedChat.Say(caller, LIGHT.Instance.Translate("car_repaired", veh.instanceID.ToString(), percent));
                                        else
                                        {
                                            decimal price = decimal.Parse("2");
                                            decimal.TryParse(LIGHT.Instance.Configuration.Instance.RepairPrice.ToString(), out price);
                                            decimal balance = Uconomy.Instance.Database.GetBalance(player.Id);
                                            decimal totalprice = Math.Round(price * (decimal)repair / (decimal)6, 2);
                                            if (balance < totalprice)
                                            {
                                                UnturnedChat.Say(caller, LIGHT.Instance.Translate("car_not_enough_currency", Uconomy.Instance.Configuration.Instance.MoneyName));
                                                return;
                                            }
                                            decimal bal = Uconomy.Instance.Database.IncreaseBalance(player.CSteamID.ToString(), (totalprice * -1));
                                            if (bal >= 0.0m) UnturnedChat.Say(player.CSteamID, LIGHT.Instance.Translate("new_balance_msg", new object[] { bal, Uconomy.Instance.Configuration.Instance.MoneyName }));
                                            UnturnedChat.Say(caller, LIGHT.Instance.Translate("car_repaired_price", veh.instanceID.ToString(), percent, totalprice, Uconomy.Instance.Configuration.Instance.MoneyName));
                                        }
                                        veh.askRepair((ushort)repair);
                                        
                                    }
                                    else
                                    {
                                        UnturnedChat.Say(caller, LIGHT.Instance.Translate("car_repair_notneeded", veh.instanceID.ToString()));
                                        return;
                                    }
                                }
                                else
                                {
                                    UnturnedChat.Say(caller, LIGHT.Instance.Translate("car_error_1"));
                                    return;
                                }
                            }
                            break;
                        case "locate":
                            if (command.Length == 1)
                            {
                                UnturnedChat.Say(caller, LIGHT.Instance.Translate("car_locate_help"));
                                return;
                            }
                            if(command.Length == 2)
                            {
                                if (LIGHT.Instance.DatabaseCar.CheckCarExistInDB(command[1]))
                                {
                                    if (LIGHT.Instance.DatabaseCar.CheckOwner(command[1]) == player.Id)
                                    {
                                        Vector3 point;
                                        byte angle;
                                        ushort index;
                                        string Status = "";
                                        if (ushort.TryParse(command[1], out index))
                                        {
                                            InteractableVehicle vehicle = VehicleManager.getVehicle(index);
                                            vehicle.getExit(0, out point, out angle);
                                            if (vehicle.isEmpty)
                                                Status += "It is Empty. ";
                                            if (vehicle.isDrowned)
                                                Status += "It is Drowned. ";
                                            if (vehicle.isDriven)
                                                Status += "It is Being Drove. ";
                                            UnturnedChat.Say(caller, LIGHT.Instance.Translate("car_located",index,Math.Round(point.x,0),Math.Round(point.y,0),Math.Round(point.z,0), Status));
                                        }
                                        else
                                        {
                                            UnturnedChat.Say(caller, LIGHT.Instance.Translate("lpx_invalid_input"));
                                            return;
                                        }

                                    }
                                    else
                                    {
                                        UnturnedChat.Say(caller, LIGHT.Instance.Translate("car_commmand_notowner"));
                                        return;
                                    }
                                }
                                else
                                {
                                    UnturnedChat.Say(caller, LIGHT.Instance.Translate("car_not_found"));
                                    return;
                                }
                            }
                            break;
                        case "rkey":
                            if (command.Length == 1)
                            {
                                UnturnedChat.Say(caller, LIGHT.Instance.Translate("car_rkey_help"));
                                return;
                            }
                            if (command.Length == 2)
                            {
                                UnturnedChat.Say(caller, LIGHT.Instance.Translate("car_rkey_help2"));
                                return;                                                             
                            }
                            if(command.Length > 2)
                            {
                                if (LIGHT.Instance.DatabaseCar.CheckCarExistInDB(command[1]))
                                {
                                    UnturnedPlayer target;
                                    if (LIGHT.Instance.DatabaseCar.CheckOwner(command[1]) == player.Id)
                                    {
                                        target = UnturnedPlayer.FromName(command[2]);
                                        if (target == null)
                                        {
                                            if(LIGHT.Instance.DatabaseCar.RemoveGiveKeysCar(command[1], command[2]))
                                            {
                                                UnturnedChat.Say(caller, LIGHT.Instance.Translate("car_rkey_success", command[2], command[1]));
                                            }
                                            else
                                            {
                                                UnturnedChat.Say(caller, LIGHT.Instance.Translate("car_rkey_keynotfound", command[1]));
                                                return;     
                                            }
                                        }
                                        else
                                        {
                                            if (LIGHT.Instance.DatabaseCar.RemoveGiveKeysCar(command[1], target.Id))
                                            {
                                                UnturnedChat.Say(caller, LIGHT.Instance.Translate("car_rkey_success", target.CharacterName, command[1]));
                                            }
                                            else
                                            {
                                                UnturnedChat.Say(caller, LIGHT.Instance.Translate("car_rkey_keynotfound", command[1]));
                                                return;
                                            }
                                        }
                                    }
                                    else
                                    {
                                        UnturnedChat.Say(caller, LIGHT.Instance.Translate("car_commmand_notowner"));
                                        return;
                                    }
                                }
                                else
                                {
                                    UnturnedChat.Say(caller, LIGHT.Instance.Translate("car_not_found"));
                                    return;
                                }
                            }
                            break;
                        case "list":
                            string cars = LIGHT.Instance.DatabaseCar.GetAllOwnedCars(player.Id);
                            if(cars == "" || cars == " ")
                            {
                                UnturnedChat.Say(caller, LIGHT.Instance.Translate("car_zero_owned"));
                            }
                            else
                            {
                                UnturnedChat.Say(caller, LIGHT.Instance.Translate("car_list_all"));
                            }
                            break;
                        default:
                            break;
                    }
                }
            }
        }
Ejemplo n.º 38
0
    // Use this for initialization
    public void Awake()
    {
        _VM = GameObject.FindGameObjectWithTag("_VM").GetComponent<VehicleManager>();
        defaultWheel = new GameObject("defaultWheel").transform;
        defaultWheel.transform.parent = this.transform.parent;

        defaultWheel.localPosition = transform.localPosition + Vector3.zero;
        _prevPosition = defaultWheel.localPosition;

        _collider = GetComponent<SphereCollider>();
        //_collider.center = new Vector3(0, radius, 0);
        //_collider.radius = 0.0f;
        rb = GetComponent<Rigidbody>();


    }
Ejemplo n.º 39
0
 private void btnGetVehicleCode_Click(object sender, EventArgs e)
 {
     //string vehicleCode = GPSDataHelper.GetVehicleCodeByGPSCode("00092042100264");
     //MessageBox.Show(vehicleCode);
     IVehicleManager db = new VehicleManager();
     Dictionary<Guid, string> dict = new Dictionary<Guid, string>();
     dict = db.GetVehicleCodeAndLicensePlate("2010031000001");
 }