コード例 #1
0
ファイル: BugReporter.cs プロジェクト: Athlon007/MOP
        public void BugReport()
        {
            if (Directory.Exists(BugReportPath))
            {
                Directory.Delete(BugReportPath, true);
            }

            Directory.CreateDirectory(BugReportPath);

            // Get output_log.txt
            if (File.Exists($"{ExceptionManager.RootPath}/output_log.txt"))
            {
                File.Copy($"{ExceptionManager.RootPath}/output_log.txt", $"{BugReportPath}/output_log.txt");
            }

            // Now we are getting logs generated today.
            string today = DateTime.Now.ToString("yyyy-MM-dd");

            foreach (string log in Directory.GetFiles(ExceptionManager.LogFolder, $"*{today}*.txt"))
            {
                string pathToFile = log.Replace("\\", "/");
                string nameOfFile = log.Split('\\')[1];
                ModConsole.Log(nameOfFile);
                File.Copy(pathToFile, $"{BugReportPath}/{nameOfFile}");
            }

            // Generate a MOP report.
            using (StreamWriter sw = new StreamWriter($"{BugReportPath}/MOP_REPORT.txt"))
            {
                sw.WriteLine(ExceptionManager.GetGameInfo());
            }

            // Now we are packing up everything.
            string lastZipFilePath = $"{BugReportPath}/MOP Bug Report - {DateTime.Now:yyyy-MM-dd_HH-mm}.zip";

            using (ZipFile zip = new ZipFile())
            {
                foreach (string file in Directory.GetFiles(BugReportPath, "*.txt"))
                {
                    zip.AddFile(file, "");
                }

                zip.Save(lastZipFilePath);
            }

            // Now we are deleting all .txt files.
            foreach (string file in Directory.GetFiles(BugReportPath, "*.txt"))
            {
                File.Delete(file);
            }

            // Create the tutorial.
            using (StreamWriter sw = new StreamWriter($"{BugReportPath}/README.txt"))
            {
                sw.WriteLine("A MOP report archive has been successfully generated.\n");
                sw.WriteLine("Upload .zip file to some file hosting site, such as https://www.mediafire.com/. \n\n" +
                             "Remember to describe how you stumbled uppon the error!");
            }

            // We are asking the user if he wants to add his game save to the zip file.
            if (File.Exists(SaveManager.SavePath))
            {
                ModPrompt.CreateYesNoPrompt("Would you like to your include save file?\n\n" +
                                            "This may greatly improve finding and fixing the bug.", "MOP - Bug Report",
                                            () => {
                    using (ZipFile zip = ZipFile.Read(lastZipFilePath))
                    {
                        // Create folder called Save in the zip and get defaultES2Save.txt and items.txt.
                        zip.AddDirectoryByName("Save");
                        if (File.Exists(SaveManager.SavePath))
                        {
                            zip.AddFile(SaveManager.SavePath, "Save");
                        }

                        if (File.Exists(SaveManager.ItemsPath))
                        {
                            zip.AddFile(SaveManager.ItemsPath, "Save");
                        }

                        zip.Save();
                    }
                },
                                            onPromptClose: () => { Process.Start(BugReportPath); Process.Start($"{BugReportPath}/README.txt"); });
            }
        }
コード例 #2
0
        public static void InstallIronPython()
        {
            _filesDownloaded       = 0;
            _downloadingInProgress = true;
            _downloadButtonText    = "0.0 %";
            _infoText = "<b>Please wait</b>\n";
            if (!Directory.Exists(PythonEnvironment.LibPath))
            {
                Directory.CreateDirectory(PythonEnvironment.LibPath);
            }
            try
            {
                for (var fileIndex = 0; fileIndex < FilesRequired; fileIndex++)
                {
                    using (var client = new WebClient())
                    {
                        var i = fileIndex;

                        // delete existing file
                        if (File.Exists(PythonEnvironment.LibPath + FileNames[i]))
                        {
                            File.Delete(PythonEnvironment.LibPath + FileNames[i]);
                        }

                        // progress handler
                        client.DownloadProgressChanged += (sender, e) =>
                        {
                            ReceivedSize[i] = e.BytesReceived;
                            TotalSize[i]    = e.TotalBytesToReceive;
                            var progress = Convert.ToSingle(ReceivedSize.Sum()) / Convert.ToSingle(TotalSize.Sum()) *
                                           100f;
                            _downloadButtonText = progress.ToString("0.0") + " %";
                        };

                        // completion handler
                        client.DownloadFileCompleted += (sender, e) =>
                        {
                            if (e.Error != null)
                            {
                                // set error messages
                                ModConsole.AddMessage(LogType.Log,
                                                      "[LenchScripterMod]: Error downloading file:" + FileNames[i]);
                                ModConsole.AddMessage(LogType.Error, "\t" + e.Error.Message);
                                _infoText = FileNames[i] + " <color=red>✘</color>" +
                                            "\n\n<b><color=red>Download failed</color></b>\n" + e.Error.Message;

                                _downloadingInProgress = false;
                                _downloadButtonText    = "Retry";

                                // delete failed file
                                if (File.Exists(PythonEnvironment.LibPath + FileNames[i]))
                                {
                                    File.Delete(PythonEnvironment.LibPath + FileNames[i]);
                                }
                            }
                            else
                            {
                                ModConsole.AddMessage(LogType.Log,
                                                      "[LenchScripterMod]: File downloaded: " + FileNames[i]);
                                _infoText += "\n" + FileNames[i] + " <color=green>✓</color>";

                                _filesDownloaded++;
                                if (_filesDownloaded != FilesRequired)
                                {
                                    return;
                                }

                                // finish download and load assemblies
                                _downloadButtonText = "Loading";
                                if (Script.LoadEngine(true))
                                {
                                    Visible = false;
                                }
                                else
                                {
                                    _downloadButtonText = "Retry";
                                    _infoText           =
                                        "<b><color=red>Download failed</color></b>\nFailed to initialize Python engine.";
                                }
                                _downloadingInProgress = false;
                            }
                        };

                        // start download
                        client.DownloadFileAsync(
                            new Uri(BaseUri + PythonEnvironment.Version + "/" + FileNames[i]),
                            PythonEnvironment.LibPath + FileNames[i]);
                    }
                }
            }
            catch (Exception e)
            {
                Debug.Log("[LenchScripterMod]: Error while downloading:");
                Debug.LogException(e);
                _downloadingInProgress = false;
                _downloadButtonText    = "Retry";
                _infoText = "<b><color=red>Download failed</color></b>\n" + e.Message;
            }
        }
コード例 #3
0
        /// <summary>
        /// Reps modapi print-to-console function
        /// </summary>
        public static void print(string format, params object[] args)
        {
            // Written, 09.10.2021

            ModConsole.Log(string.Format("<color=grey>[ModAPI] - " + format + "</color>", args));
        }
コード例 #4
0
        /// <summary>
        /// Initialize class
        /// </summary>
        /// <param name="gameObjectName"></param>
        public Vehicle(string gameObjectName)
        {
            // gameObject the object by name
            gameObject = GameObject.Find(gameObjectName);

            // Use Resources.FindObjectsOfTypeAll method, if the vehicle was not found.
            if (gameObject == null)
            {
                gameObject = Resources.FindObjectsOfTypeAll <GameObject>().FirstOrDefault(g => g.name == gameObjectName);
            }

            if (gameObject == null)
            {
                ModConsole.Error($"[MOP] Could not find {gameObjectName} vehicle.");
                return;
            }

            // Get the object position and rotation
            Position = gameObject.transform.localPosition;
            Rotation = gameObject.transform.localRotation;

            // Creates a new gameobject that is names after the original file + '_TEMP' (ex. "SATSUMA(557kg, 248)_TEMP")
            temporaryParent = new GameObject($"{gameObject.name}_TEMP").transform;

            preventToggleOnObjects = new List <PreventToggleOnObject>();

            // This should fix bug that leads to items inside of vehicles to fall through it.
            PlayMakerFSM lodFSM = gameObject.GetPlayMakerByName("LOD");

            if (lodFSM != null)
            {
                lodFSM.Fsm.RestartOnEnable = false;
                FsmState resetState = lodFSM.FindFsmState("Fix Collider");
                if (resetState != null)
                {
                    resetState.Actions = new FsmStateAction[] { new CustomStopAction() };
                    resetState.SaveActions();
                }

                lodFSM.FindFsmState("Load game").Actions = new FsmStateAction[] { new CustomNullState() };
            }

            if (gameObject.name == "BOAT")
            {
                return;
            }

            // Get the object's child which are responsible for audio
            foreach (Transform audioObject in FindAudioObjects())
            {
                preventToggleOnObjects.Add(new PreventToggleOnObject(audioObject));
            }

            // Fix for fuel level resetting after respawn
            Transform fuelTank = gameObject.transform.Find("FuelTank");

            if (fuelTank != null)
            {
                PlayMakerFSM fuelTankFSM = fuelTank.GetComponent <PlayMakerFSM>();
                if (fuelTankFSM)
                {
                    fuelTankFSM.Fsm.RestartOnEnable = false;
                }
            }

            // If the vehicle is Gifu, find knobs and add them to list of unloadable objects
            if (gameObject.name == "GIFU(750/450psi)")
            {
                Transform knobs = gameObject.transform.Find("Dashboard/Knobs");
                foreach (PlayMakerFSM knobsFSMs in knobs.GetComponentsInChildren <PlayMakerFSM>())
                {
                    knobsFSMs.Fsm.RestartOnEnable = false;
                }

                PlayMakerFSM          shitFsm          = gameObject.transform.Find("ShitTank").gameObject.GetComponent <PlayMakerFSM>();
                FsmState              loadGame         = shitFsm.FindFsmState("Load game");
                List <FsmStateAction> loadArrayActions = new List <FsmStateAction> {
                    new CustomNullState()
                };
                loadArrayActions.Add(new CustomNullState());
                loadGame.Actions = loadArrayActions.ToArray();
                loadGame.SaveActions();
            }

            // Fixed kickstand resetting to the default value.
            if (gameObject.name == "JONNEZ ES(Clone)")
            {
                PlayMakerFSM          kickstandFsm     = gameObject.transform.Find("Kickstand").gameObject.GetComponent <PlayMakerFSM>();
                FsmState              loadGame         = kickstandFsm.FindFsmState("Load game");
                List <FsmStateAction> loadArrayActions = new List <FsmStateAction> {
                    new CustomNullState()
                };
                loadArrayActions.Add(new CustomNullState());
                loadGame.Actions = loadArrayActions.ToArray();
                loadGame.SaveActions();

                // Disable on restart for wheels script.
                Transform wheelsParent = transform.Find("Wheels");
                foreach (Transform wheel in wheelsParent.GetComponentsInChildren <Transform>())
                {
                    if (!wheel.gameObject.name.StartsWith("Moped_wheel"))
                    {
                        continue;
                    }
                    wheel.gameObject.GetComponent <PlayMakerFSM>().Fsm.RestartOnEnable = false;
                }
            }

            carDynamics = gameObject.GetComponent <CarDynamics>();
            axles       = gameObject.GetComponent <Axles>();
            rb          = gameObject.GetComponent <Rigidbody>();

            // Hook HookFront and HookRear
            // Get hooks first
            Transform hookFront = transform.Find("HookFront");
            Transform hookRear  = transform.Find("HookRear");

            // If hooks exists, attach the RopeHookUp and RopeUnhook to appropriate states
            if (hookFront != null)
            {
                fsmHookFront = hookFront.GetComponent <PlayMakerFSM>();
            }

            if (hookRear != null)
            {
                fsmHookRear = hookRear.GetComponent <PlayMakerFSM>();
            }

            // If vehicle is flatbed, hook SwitchToggleMethod to Add scale script
            if (gameObject.name == "FLATBED")
            {
                PlayMakerFSM          logTriggerFsm    = transform.Find("Bed/LogTrigger").gameObject.GetComponent <PlayMakerFSM>();
                FsmState              loadGame         = logTriggerFsm.FindFsmState("Load game");
                List <FsmStateAction> loadArrayActions = new List <FsmStateAction> {
                    new CustomNullState()
                };
                loadGame.Actions = loadArrayActions.ToArray();
                loadGame.SaveActions();

                GameObject trailerLogUnderFloorCheck = new GameObject("MOP_TrailerLogUnderFloorFix");
                trailerLogUnderFloorCheck.transform.parent = gameObject.transform;
                trailerLogUnderFloorCheck.AddComponent <TrailerLogUnderFloor>();
            }

            // Set default toggling method - that is entire vehicle
            Toggle = ToggleActive;

            isHayosiko = gameObject.name == "HAYOSIKO(1500kg, 250)";
            isKekmet   = gameObject.name == "KEKMET(350-400psi)";

            // If the user selected to toggle vehicle's physics only, it overrided any previous set for Toggle method
            if (Rules.instance.SpecialRules.ToggleAllVehiclesPhysicsOnly)
            {
                Toggle = IgnoreToggle;
            }

            // Get all HingeJoints and add HingeManager to them
            // Ignore for Satsuma or cars that use ToggleUnityCar method (and force for Hayosiko - no matter what)
            if (SatsumaScript == null && Toggle != ToggleUnityCar || isHayosiko)
            {
                HingeJoint[] joints = gameObject.transform.GetComponentsInChildren <HingeJoint>();
                foreach (HingeJoint joint in joints)
                {
                    joint.gameObject.AddComponent <HingeManager>();
                }
            }

            // Get one of the wheels.
            wheel      = axles.allWheels[0];
            drivetrain = gameObject.GetComponent <Drivetrain>();

            // Ignore Rules.
            IgnoreRule vehicleRule = Rules.instance.IgnoreRules.Find(v => v.ObjectName == this.gameObject.name);

            if (vehicleRule != null)
            {
                Toggle = IgnoreToggle;

                if (vehicleRule.TotalIgnore)
                {
                    IsActive = false;
                }
            }

            // Prevent Toggle On Object Rule.
            IgnoreRuleAtPlace[] preventToggleOnObjectRule = Rules.instance.IgnoreRulesAtPlaces
                                                            .Where(v => v.Place == this.gameObject.name).ToArray();
            if (preventToggleOnObjectRule.Length > 0)
            {
                foreach (var p in preventToggleOnObjectRule)
                {
                    Transform t = transform.FindRecursive(p.ObjectName);
                    if (t == null)
                    {
                        ModConsole.Error($"[MOP] Couldn't find {p.ObjectName} in {p.Place}.");
                        continue;
                    }

                    preventToggleOnObjects.Add(new PreventToggleOnObject(t));
                }
            }

            eventSounds = gameObject.GetComponent <EventSounds>();

            // Odometers fix.
            switch (gameObject.name)
            {
            case "GIFU(750/450psi)":
                transform.Find("Dashboard/Odometer").gameObject.GetComponent <PlayMakerFSM>().Fsm.RestartOnEnable = false;
                break;

            case "HAYOSIKO(1500kg, 250)":
                transform.Find("Odometer").gameObject.GetComponent <PlayMakerFSM>().Fsm.RestartOnEnable = false;
                break;

            case "KEKMET(350-400psi)":
                transform.Find("Dashboard/HourMeter").gameObject.GetComponent <PlayMakerFSM>().Fsm.RestartOnEnable = false;
                break;

            case "SATSUMA(557kg, 248)":
                GameObject.Find("dashboard meters(Clone)").transform.Find("Gauges/Odometer").gameObject.GetComponent <PlayMakerFSM>().Fsm.RestartOnEnable = false;
                break;
            }
        }
コード例 #5
0
 public override void Run(string[] args)
 {
     ModConsole.Print("<color=green><b>Available commands:</b></color>");
     cc.help(args);
 }
コード例 #6
0
ファイル: GodMode.cs プロジェクト: tommyyeet/MSC_Playground
        void GodModeWindow(int id)
        {
            // STYLING
            GUIStyle godLabelStyle = new GUIStyle();

            godLabelStyle.alignment        = TextAnchor.UpperCenter;
            godLabelStyle.fontSize         = 14;
            godLabelStyle.fontStyle        = FontStyle.Bold;
            godLabelStyle.normal.textColor = Color.white;

            //BUTTON TO LOCK SATSUMA PARTS
            GUI.Label(
                new Rect(50, 50, 300, 30),
                "This will make it harder for parts to fall off. \n " + "WARNING! Save before you do this!",
                godLabelStyle);
            //BUTTON TO UNLOCK SATSUMA PARTS



            if (GUI.Button(new Rect(100, 90, 200, 30), "Lock Satsuma Parts"))
            {
                foreach (var VARIABLE in Resources.FindObjectsOfTypeAll <FixedJoint>())
                {
                    if (VARIABLE.transform.root.name == "SATSUMA(557kg)")
                    {
                        Object.Destroy(VARIABLE.gameObject.GetComponent <Rigidbody>());
                        ModConsole.Print(VARIABLE.transform.name);
                    }
                }

/*                bool done = false;
 *              StreamWriter writer = new StreamWriter("PlaymakerExperimentalFSM.txt");
 *              foreach (var VARIABLE in Resources.FindObjectsOfTypeAll<PlayMakerFSM>())
 *              {
 *                writer.WriteLine(VARIABLE.Fsm.GameObject.transform.root.name + " | " + VARIABLE.FsmName + " | " + VARIABLE.Active + " | Enabled: " + VARIABLE.enabled + " | " + VARIABLE.Fsm.GameObject.name + " | " + VARIABLE.Fsm.GameObject.activeInHierarchy);
 *                  if (VARIABLE.Fsm.GameObject.name == "fender right(Clone)")
 *                  {
 *                      foreach (var varia in VARIABLE.FsmVariables.BoolVariables)
 *                      {
 *                          ModConsole.Print(varia.Name);
 *                          varia.UseVariable = false;
 *                      }
 *                  }
 * //                    if (VARIABLE.FsmName == "CarDebug")
 * //                    {
 * //                        VARIABLE.enabled = true;
 * //                    }
 *              }*/
                //writer.Close();
            }
            if (GUI.Button(new Rect(100, 120, 200, 30), "Unlock Satsuma Parts"))
            {
                foreach (var VARIABLE in Resources.FindObjectsOfTypeAll <PlayMakerFSM>())
                {
                    ModConsole.Print(VARIABLE.Fsm.EventTarget.target);
                }
            }

            //SHOW LABEL THAT PARTS ARE LOCKED
            if (this._partsLocked)
            {
                GUI.Label(new Rect(50, 140, 300, 30), "PARTS LOCKED", godLabelStyle);
            }

            //Close Window
            if (GUI.Button(new Rect(125, 195, 150, 30), "Close"))
            {
                this._guiShow = false;
            }
        }
コード例 #7
0
        private bool _checkBattery(bool connect)
        {
            // Skip the whole shebang if battery usage is disabled
            if (!(bool)UseBattery.GetValue())
            {
                return(true);
            }

            // Disconnect the battery if needed
            if (!connect)
            {
                _battery       = null;
                _batteryCharge = null;
                return(false);
            }

            // Try to find a battery
            if (_battery == null)
            {
                foreach (GameObject o in GameObject.FindObjectsOfType <GameObject>().Where(e => e.name == "battery(Clone)"))
                {
                    if ((o.transform.position - _base.transform.position).sqrMagnitude < 1.0f)
                    {
                        if (_batteryIsInstalled(o))
                        {
                            continue;
                        }
                        _battery = o;
                        ModConsole.Print($"[Floodlight] Battery found, {o.GetComponents<PlayMakerFSM>().Single(c => c.FsmName == "Use").FsmVariables.FindFsmFloat("Charge").Value.ToString("0.00")} charge");
                    }
                }
                if (_battery == null)
                {
                    ModConsole.Print("[Floodlight] Battery not found");
                }
            }

            // Check if the battery is still connected
            if (_battery != null)
            {
                // Check if the battery is in range and not installed in the car
                if ((_battery.transform.position - _base.transform.position).sqrMagnitude < 1.0f && !_batteryIsInstalled(_battery))
                {
                    // Check the charge level
                    if (_batteryCharge == null)
                    {
                        _batteryCharge = _battery.GetComponents <PlayMakerFSM>().Single(c => c.FsmName == "Use").FsmVariables.FindFsmFloat("Charge");
                    }
                    if (_batteryCharge != null && _batteryCharge.Value >= _turnOffCharge)
                    {
                        // If the charge level is above minimum, drain energy
                        if (_on)
                        {
                            _batteryCharge.Value -= _dischargeRate * Time.deltaTime;
                            if (_batteryCharge.Value > _turnOffCharge)
                            {
                                //_intensity = (_batteryCharge.Value < _dimStartCharge ? (_batteryCharge.Value - _turnOffCharge) / (_dimStartCharge - _turnOffCharge) : 1.0f);
                                _intensityMult = _batteryCharge.Value < _dimStartCharge
                                                                        ? (_batteryCharge.Value - _turnOffCharge) / (_dimStartCharge - _turnOffCharge) / 2.0f + 0.5f
                                                                        : 1.0f;
                                if ((bool)Flicker.GetValue())
                                {
                                    _flicker(_flickerTimer);
                                }
                            }
                            _light.intensity = _baseIntensity * _intensityMult * _flickerMult;
                        }

                        return(true);
                    }
                    else
                    {
                        // If not, disconnect
                        ModConsole.Print("[Floodlight] Battery depleted");
                        _battery       = null;
                        _batteryCharge = null;
                        return(false);
                    }
                }
                else
                {
                    // If not, disconnect and play the disconnect sound clip
                    ModConsole.Print("[Floodlight] Battery disconnected");
                    _batteryCharge = null;
                    _battery       = null;
                    _disconnect.Play();
                    return(false);
                }
            }
            else
            {
                return(false);
            }
        }
コード例 #8
0
        public override void OnLoad()
        {
            satsuma     = GameObject.Find("SATSUMA(557kg, 248)");
            raccarb     = GameObject.Find("racing carburators(Clone)");
            carb2       = GameObject.Find("twin carburators(Clone)");
            powerMP     = FsmVariables.GlobalVariables.FindFsmFloat("EnginePowerMultiplier");
            pullmesh    = GameObject.Find("crankshaft_pulley_mesh");
            inVencle    = FsmVariables.GlobalVariables.FindFsmString("PlayerCurrentVehicle");
            engine_head = GameObject.Find("cylinder head(Clone)");
            Mixture     = satsuma.transform.GetChild(14).GetChild(1).GetChild(3).gameObject.GetComponents <PlayMakerFSM>()[1].FsmVariables.FloatVariables[16];
            math1       = satsuma.transform.GetChild(14).GetChild(1).GetChild(7).gameObject.GetComponent <PlayMakerFSM>().FsmVariables.FloatVariables[1];
            n2o         = satsuma.transform.GetChild(14).GetChild(1).GetChild(7).gameObject.GetComponent <PlayMakerFSM>().FsmStates[4];
            n2oPSI      = satsuma.transform.GetChild(14).GetChild(1).GetChild(7).gameObject.GetComponent <PlayMakerFSM>().FsmVariables.FloatVariables[4];
            drivetrain  = satsuma.GetComponent <Drivetrain>();
            sparkRetard = satsuma.transform.GetChild(14).GetChild(1).GetChild(7).gameObject.GetComponent <PlayMakerFSM>().FsmVariables.FloatVariables[7];
            noN2O       = satsuma.transform.GetChild(14).GetChild(1).GetChild(7).gameObject.GetComponent <PlayMakerFSM>().FsmStates[5];
            heat        = FsmVariables.GlobalVariables.FindFsmFloat("EngineTemp");

            AssetBundle ab = LoadAssets.LoadBundle(this, "turbo.unity3d");

            turbine       = ab.LoadAsset("Turbine.prefab") as GameObject;
            turbine.name  = "Turbine";
            turbine.tag   = "PART";
            turbine.layer = LayerMask.NameToLayer("Parts");

            pulley       = ab.LoadAsset("Pulley.prefab") as GameObject;
            pulley.name  = "Pulley";
            pulley.tag   = "PART";
            pulley.layer = LayerMask.NameToLayer("Parts");

            pipe       = ab.LoadAsset("Pipe.prefab") as GameObject;
            pipe.name  = "Pipe";
            pipe.tag   = "PART";
            pipe.layer = LayerMask.NameToLayer("Parts");

            pipe_rac_carb       = ab.LoadAsset("Pipe rac_carb.prefab") as GameObject;
            pipe_rac_carb.name  = "racing carburators pipe";
            pipe_rac_carb.tag   = "PART";
            pipe_rac_carb.layer = LayerMask.NameToLayer("Parts");

            belt       = ab.LoadAsset("Belt.prefab") as GameObject;
            belt.name  = "Turbine belt";
            belt.tag   = "PART";
            belt.layer = LayerMask.NameToLayer("Parts");

            turbinegauge       = ab.LoadAsset("Датчик.prefab") as GameObject;
            turbinegauge.name  = "Turbine gauge";
            turbinegauge.tag   = "PART";
            turbinegauge.layer = LayerMask.NameToLayer("Parts");

            pipe_2_carb       = ab.LoadAsset("Pipe 2_carb.prefab") as GameObject;
            pipe_2_carb.name  = "Twin carburators pipe";
            pipe_2_carb.tag   = "PART";
            pipe_2_carb.layer = LayerMask.NameToLayer("Parts");

            switch_button       = ab.LoadAsset("Switch.prefab") as GameObject;
            switch_button.name  = "Switch button";
            switch_button.tag   = "PART";
            switch_button.layer = LayerMask.NameToLayer("Parts");

            headgasket       = ab.LoadAsset("Head_gasket.prefab") as GameObject;
            headgasket.name  = "Additional Head Gasket";
            headgasket.tag   = "PART";
            headgasket.layer = LayerMask.NameToLayer("Parts");

            filter       = ab.LoadAsset("filter.prefab") as GameObject;
            filter.name  = "filter";
            filter.tag   = "PART";
            filter.layer = LayerMask.NameToLayer("Parts");

            PartSaveInfo pulleySaveInfo = null, turbineSaveInfo = null, pipeSaveInfo = null, pipe_rac_carbSaveInfo = null, beltSaveInfo = null, turbinegaugeSaveInfo = null, pipe_2_carbSaveInfo = null, switch_buttonSaveInfo = null, filterSaveInfo = null, headgasketSaveInfo = null;

            pulleySaveInfo        = LoadSaveData("pulleySaveInfo");
            turbineSaveInfo       = LoadSaveData("turbineSaveInfo");
            pipeSaveInfo          = LoadSaveData("pipeSaveInfo");
            pipe_rac_carbSaveInfo = LoadSaveData("pipe_rac_carbSaveInfo");
            beltSaveInfo          = LoadSaveData("beltSaveInfo");
            turbinegaugeSaveInfo  = LoadSaveData("turbinegaugeSaveInfo");
            pipe_2_carbSaveInfo   = LoadSaveData("pipe_2_carbSaveInfo");
            switch_buttonSaveInfo = LoadSaveData("switch_buttonSaveInfo");
            filterSaveInfo        = LoadSaveData("filterSaveInfo");
            headgasketSaveInfo    = LoadSaveData("headgasketSaveInfo");
            try
            {
                buysafeinfo = SaveLoad.DeserializeSaveFile <Safeinfo>(this, "Safeinfo");
            }
            catch
            {
            }
            if (buysafeinfo == null)
            {
                buysafeinfo = new Safeinfo()
                {
                    Buybelt          = false,
                    Buypipe          = false,
                    Buypipe_2_carb   = false,
                    Buypipe_rac_carb = false,
                    Buypulley        = false,
                    Buyturbine       = false,
                    Buyturbinegauge  = false,
                    Buyswitch_button = false,
                    Buyfilter        = false,
                    Buyheadgasket    = false,
                    Beltwear         = 100,
                    Filterwear       = 100,
                    Turbinewear      = 100,
                    BoostOn          = true
                };
            }
            if (!buysafeinfo.Buyturbine)
            {
                turbineSaveInfo = null;
            }
            if (!buysafeinfo.Buybelt)
            {
                beltSaveInfo = null;
            }
            if (!buysafeinfo.Buypulley)
            {
                pulleySaveInfo = null;
            }
            if (!buysafeinfo.Buypipe)
            {
                pipeSaveInfo = null;
            }
            if (!buysafeinfo.Buypipe_rac_carb)
            {
                pipe_rac_carbSaveInfo = null;
            }
            if (!buysafeinfo.Buypipe_2_carb)
            {
                pipe_2_carbSaveInfo = null;
            }
            if (!buysafeinfo.Buyturbinegauge)
            {
                turbinegaugeSaveInfo = null;
            }
            if (!buysafeinfo.Buyswitch_button)
            {
                switch_buttonSaveInfo = null;
            }
            if (!buysafeinfo.Buyfilter)
            {
                filterSaveInfo = null;
            }
            if (!buysafeinfo.Buyheadgasket)
            {
                headgasketSaveInfo = null;
            }

            GameObject pulleyparent  = GameObject.Find("crankshaft_pulley_mesh");
            Trigger    pulleytrigger = new Trigger("pulleyTrigger", pulleyparent, new Vector3(0.027f, 0.0f, 0.0f), Quaternion.Euler(0, 0, 0), new Vector3(0.1f, 0.1f, 0.1f), false);

            pulleyPart = new Pulley(pulleySaveInfo, pulleytrigger, new Vector3(0.027f, 0.0f, 0.0f), new Quaternion(0, 0, 0, 0), pulley, pulleyparent);

            GameObject turbineparent  = GameObject.Find("block(Clone)");
            Trigger    turbinetrigger = new Trigger("turbineTrigger", turbineparent, new Vector3(0.234f, 0.14f, 0.0817f), Quaternion.Euler(0, 0, 0), new Vector3(0.1f, 0.1f, 0.1f), false);

            turbinePart = new Turbine(turbineSaveInfo, turbinetrigger, new Vector3(0.234f, 0.14f, 0.0817f), Quaternion.Euler(90, 0, 0), turbine, turbineparent);

            GameObject pipeparent  = turbinePart.rigidPart;
            Trigger    pipetrigger = new Trigger("pipeTrigger", pipeparent, new Vector3(-0.12f, 0.085f, -0.04f), Quaternion.Euler(0, 0, 0), new Vector3(0.1f, 0.1f, 0.1f), false);

            pipePart = new Pipe(pipeSaveInfo, pipetrigger, new Vector3(-0.12f, 0.085f, -0.04f), new Quaternion(0, 0, 0, 0), pipe, pipeparent);

            GameObject pipe_rac_carbparent = GameObject.Find("cylinder head(Clone)");

            pipe_rac_carbtrigger = new Trigger("pipe_rac_carbTrigger", pipe_rac_carbparent, new Vector3(0.013f, -0.139f, 0.12f), Quaternion.Euler(90, 0, 0), new Vector3(0.3f, 0.3f, 0.3f), false);
            pipe_rac_carbPart    = new Pipe_rac_carb(pipe_rac_carbSaveInfo, pipe_rac_carbtrigger, new Vector3(0.013f, -0.139f, 0.12f), Quaternion.Euler(90, 0, 0), pipe_rac_carb, pipe_rac_carbparent);

            GameObject beltparent = turbinePart.rigidPart;

            belttrigger = new Trigger("beltTrigger", beltparent, new Vector3(0.035f, -0.091f, 0.08f), Quaternion.Euler(0, 0, 0), new Vector3(0.1f, 0.1f, 0.1f), false);
            beltPart    = new Belt(beltSaveInfo, belttrigger, new Vector3(0.035f, -0.091f, 0.08f), new Quaternion(0, 0, 0, 0), belt, beltparent);

            GameObject turbinegaugeParent  = GameObject.Find("dashboard(Clone)");
            Trigger    turbinegaugeTrigger = new Trigger("turbinegaugeTriger", turbinegaugeParent, new Vector3(0.48f, -0.04f, 0.135f), Quaternion.Euler(0, 0, 0), new Vector3(0.1f, 0.1f, 0.1f), false);

            turbinegaugePart = new Turbinegauge(turbinegaugeSaveInfo, turbinegaugeTrigger, new Vector3(0.48f, -0.04f, 0.135f), Quaternion.Euler(0, 0, 345), turbinegauge, turbinegaugeParent);

            GameObject pipe_2_carbparent = GameObject.Find("cylinder head(Clone)");

            pipe_2_carbtrigger = new Trigger("pipe_2_carbTrigger", pipe_rac_carbparent, new Vector3(0.06f, -0.147f, 0.04f), Quaternion.Euler(0, 0, 0), new Vector3(0.3f, 0.3f, 0.3f), false);
            pipe_2_carbPart    = new Pipe_2_carb(pipe_2_carbSaveInfo, pipe_2_carbtrigger, new Vector3(0.06f, -0.147f, 0.04f), Quaternion.Euler(90, 0, 0), pipe_2_carb, pipe_2_carbparent);

            GameObject switchbuttonparent  = GameObject.Find("dashboard(Clone)");
            Trigger    switchbuttontrigger = new Trigger("switchbuttonTrigger", switchbuttonparent, new Vector3(0.54f, -0.062f, -0.065f), Quaternion.Euler(0, 0, 0), new Vector3(0.1f, 0.1f, 0.1f), false);

            switch_buttonPart = new Switchbutton(switch_buttonSaveInfo, switchbuttontrigger, new Vector3(0.54f, -0.062f, -0.065f), Quaternion.Euler(12, 0, 0), switch_button, switchbuttonparent);

            GameObject filterparent  = pipePart.rigidPart;
            Trigger    filtertrigger = new Trigger("filterTrigger", filterparent, new Vector3(-0.14f, 0.075f, -0.035f), Quaternion.Euler(0, 0, 0), new Vector3(0.1f, 0.1f, 0.1f), false);

            filterPart = new Filter(filterSaveInfo, filtertrigger, new Vector3(-0.14f, 0.075f, -0.035f), Quaternion.Euler(0, 0, 0), filter, filterparent);

            GameObject headgasketparent = GameObject.Find("head gasket(Clone)");

            headgaskettrigger = new Trigger("headgasketTrigger", headgasketparent, new Vector3(0f, 0f, 0.003f), Quaternion.Euler(0, 0, 0), new Vector3(0.1f, 0.1f, 0.1f), false);
            headgasketPart    = new HeadGasket(headgasketSaveInfo, headgaskettrigger, new Vector3(0f, 0f, 0.003f), Quaternion.Euler(0, 0, 0), headgasket, headgasketparent);

            shop         = GameObject.Find("Shop for mods").GetComponent <ShopItem>();
            shop_turbine = new ProductDetails()
            {
                productName       = "Centrifugal supercharger",
                multiplePurchases = false,
                productCategory   = "Details",
                productIcon       = ab.LoadAsset <Sprite>("Turbine_ico.png"),
                productPrice      = 3499
            };
            if (!buysafeinfo.Buyturbine)
            {
                shop.Add(this, shop_turbine, ShopType.Fleetari, Buy_turbine, turbinePart.activePart);
                turbinePart.activePart.SetActive(false);
            }


            shopbelt = new ProductDetails()
            {
                productName       = "Belt",
                multiplePurchases = false,
                productCategory   = "Details",
                productIcon       = ab.LoadAsset <Sprite>("Belt.png"),
                productPrice      = 299
            };
            if (!buysafeinfo.Buybelt)
            {
                shop.Add(this, shopbelt, ShopType.Fleetari, Buy_belt, beltPart.activePart);
                beltPart.activePart.SetActive(false);
            }


            if (!buysafeinfo.Buypulley)
            {
                ProductDetails shop_pulley = new ProductDetails()
                {
                    productName       = "Pulley",
                    multiplePurchases = false,
                    productCategory   = "Details",
                    productIcon       = ab.LoadAsset <Sprite>("pulley.png"),
                    productPrice      = 399
                };
                shop.Add(this, shop_pulley, ShopType.Fleetari, Buy_pulley, pulleyPart.activePart);
                pulleyPart.activePart.SetActive(false);
            }


            if (!buysafeinfo.Buypipe)
            {
                ProductDetails shop_pipe = new ProductDetails()
                {
                    productName       = "Pipe",
                    multiplePurchases = false,
                    productCategory   = "Details",
                    productIcon       = ab.LoadAsset <Sprite>("pipe.png"),
                    productPrice      = 749
                };
                shop.Add(this, shop_pipe, ShopType.Fleetari, Buy_pipe, pipePart.activePart);
                pipePart.activePart.SetActive(false);
            }


            if (!buysafeinfo.Buypipe_rac_carb)
            {
                ProductDetails shop_pipe_rac_carb = new ProductDetails()
                {
                    productName       = "Racing carburators pipe",
                    multiplePurchases = false,
                    productCategory   = "Details",
                    productIcon       = ab.LoadAsset <Sprite>("pipe2.png"),
                    productPrice      = 749
                };
                shop.Add(this, shop_pipe_rac_carb, ShopType.Fleetari, Buy_pipe_rac_carb, pipe_rac_carbPart.activePart);
                pipe_rac_carbPart.activePart.SetActive(false);
            }


            if (!buysafeinfo.Buypipe_2_carb)
            {
                ProductDetails shop_pipe_2_carb = new ProductDetails()
                {
                    productName       = "Twin carburators pipe",
                    multiplePurchases = false,
                    productCategory   = "Details",
                    productIcon       = ab.LoadAsset <Sprite>("pipe3.png"),
                    productPrice      = 749
                };
                shop.Add(this, shop_pipe_2_carb, ShopType.Fleetari, Buy_pipe_2_carb, pipe_2_carbPart.activePart);
                pipe_2_carbPart.activePart.SetActive(false);
            }


            if (!buysafeinfo.Buyturbinegauge)
            {
                ProductDetails shop_turbinegauge = new ProductDetails()
                {
                    productName       = "Turbine gauge",
                    multiplePurchases = false,
                    productCategory   = "Details",
                    productIcon       = ab.LoadAsset <Sprite>("Гаджет.png"),
                    productPrice      = 499
                };
                shop.Add(this, shop_turbinegauge, ShopType.Fleetari, Buy_turbinegauge, turbinegaugePart.activePart);
                turbinegaugePart.activePart.SetActive(false);
            }


            if (!buysafeinfo.Buyswitch_button)
            {
                ProductDetails shop_switch_button = new ProductDetails()
                {
                    productName       = "Switch button",
                    multiplePurchases = false,
                    productCategory   = "Details",
                    productIcon       = ab.LoadAsset <Sprite>("switch 1.png"),
                    productPrice      = 249
                };
                shop.Add(this, shop_switch_button, ShopType.Fleetari, Buy_switch_button, switch_buttonPart.activePart);
                switch_buttonPart.activePart.SetActive(false);
            }

            shop_filter = new ProductDetails()
            {
                productName       = "Filter",
                multiplePurchases = false,
                productCategory   = "Details",
                productIcon       = ab.LoadAsset <Sprite>("filter.png"),
                productPrice      = 99
            };
            if (!buysafeinfo.Buyfilter)
            {
                shop.Add(this, shop_filter, ShopType.Fleetari, Buy_filter, filterPart.activePart);
                filterPart.activePart.SetActive(false);
            }

            if (!buysafeinfo.Buyheadgasket)
            {
                ProductDetails shop_headgasket = new ProductDetails()
                {
                    productName       = "Additional Head Gasket",
                    multiplePurchases = false,
                    productCategory   = "Details",
                    productIcon       = ab.LoadAsset <Sprite>("headgasket.png"),
                    productPrice      = 329
                };
                shop.Add(this, shop_headgasket, ShopType.Fleetari, Buy_headgasket, headgasketPart.activePart);
                headgasketPart.activePart.SetActive(false);
            }


            ab.Unload(false);

            UnityEngine.Object.Destroy(turbine);
            UnityEngine.Object.Destroy(pulley);
            UnityEngine.Object.Destroy(pipe);
            UnityEngine.Object.Destroy(pipe_rac_carb);
            UnityEngine.Object.Destroy(belt);
            UnityEngine.Object.Destroy(turbinegauge);
            UnityEngine.Object.Destroy(ab);
            UnityEngine.Object.Destroy(pipe_2_carb);
            UnityEngine.Object.Destroy(switch_button);
            turbinePart.rigidPart.GetComponent <AudioSource>().volume = 0;

            racingcarb_inst = false;
            carb2_inst      = false;

            fullreset = false;

            if (buysafeinfo.BoostOn)
            {
                switch_buttonPart.rigidPart.transform.GetChild(0).transform.localRotation = Quaternion.Euler(50, 0, 0);
            }
            else
            {
                switch_buttonPart.rigidPart.transform.GetChild(0).transform.localRotation = Quaternion.Euler(-50, 0, 0);
            }

            ModConsole.Print("Supercharger for Satsuma was loaded.");
        }
コード例 #9
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");
            }
        }
コード例 #10
0
            public override void Run(string[] args)
            {
                // Check if the command can run in the first place
                if (Application.loadedLevelName != "GAME")
                {
                    ModConsole.Print("Cannot execute command outside of game");
                    return;
                }

                // If the argument is missing, not a number, or out of range, display the help text.
                if (args.Length < 1 || !int.TryParse(args[0], out int num) || num < 0 || num >= vehicles.Length)
                {
                    ModConsole.Print(_helpString);
                    return;
                }

                // Otherwise, try to find the vehicle.
                GameObject selected = GameObject.Find(vehicles[num]);

                if (selected == null)
                {
                    ModConsole.Print($"Could not find {vehicles[num]}");
                    return;
                }
                float yaw = selected.transform.localEulerAngles.y;

                // If it is found, check if the user has defined a second argument.
                if (args.Length > 1)
                {
                    // Try parsing it as an angle in degrees
                    if (!float.TryParse(args[1], out yaw))
                    {
                        // ...or as a cardinal direction.
                        if (args[1] == "north" || args[1] == "n")
                        {
                            yaw = 0.0f;
                        }
                        else if (args[1] == "west" || args[1] == "w")
                        {
                            yaw = 270.0f;
                        }
                        else if (args[1] == "south" || args[1] == "s")
                        {
                            yaw = 180.0f;
                        }
                        else if (args[1] == "east" || args[1] == "e")
                        {
                            yaw = 90.0f;
                        }
                        else
                        {
                            ModConsole.Print("Incorrect angle: " + args[1]);
                            return;
                        }
                    }
                }

                // Then apply the transformations.
                selected.transform.position         = selected.transform.position + new Vector3(0, 1, 0);
                selected.transform.localEulerAngles = new Vector3(0, yaw, 0);
            }
コード例 #11
0
            public override void Run(string[] args)
            {
                // Make sure the command is executed with arguments.
                if (args.Length < 1)
                {
                    ModConsole.Error("Incorrect number of arguments. See 'gps help' for details.");
                    return;
                }

                // Print the help text
                if (Array.Exists(args, e => e.ToLowerInvariant() == "help" || e == "-?"))
                {
                    ModConsole.Print(_helpString);
                    return;
                }

                // When starting or restarting, try to find -p and try to validate the following argument as a port number
                if (Array.Exists(args, e => e.ToLowerInvariant() == "start" || e.ToLowerInvariant() == "restart"))
                {
                    int p;
                    if ((p = Array.IndexOf(args, "-p")) >= 0 || (p = Array.IndexOf(args, "--port")) >= 0)
                    {
                        if (args.Length >= p + 1 && int.TryParse(args[p + 1], out int portNumber) && portNumber <= 65535 && portNumber >= 1)
                        {
                            _mod._port = portNumber;
                        }
                        else
                        {
                            ModConsole.Print(_helpString);
                        }
                    }
                }

                // Restart
                if (Array.Exists(args, e => e.ToLowerInvariant() == "restart"))
                {
                    _mod.StopServer();
                    _mod.StartServer();
                    return;
                }

                // Start
                if (Array.Exists(args, e => e.ToLowerInvariant() == "start"))
                {
                    _mod.StartServer();
                    return;
                }

                // Stop
                if (Array.Exists(args, e => e.ToLowerInvariant() == "stop"))
                {
                    _mod.StopServer();
                    return;
                }

                // Write to file
                if (Array.Exists(args, e => e.ToLowerInvariant() == "write"))
                {
                    if (Array.Exists(args, e => e.ToLowerInvariant() == "json"))
                    {
                        using (StreamWriter writer = new StreamWriter(Path.Combine(ModLoader.GetModConfigFolder(_mod), "out.json")))
                        {
                            writer.Write(_mod.GetJsonContent());
                        }
                    }
                    else if (Array.Exists(args, e => e.ToLowerInvariant() == "xml"))
                    {
                        using (StreamWriter writer = new StreamWriter(Path.Combine(ModLoader.GetModConfigFolder(_mod), "out.xml")))
                        {
                            writer.Write(_mod.GetXmlContent());
                        }
                    }
                    else
                    {
                        using (StreamWriter writer = new StreamWriter(Path.Combine(ModLoader.GetModConfigFolder(_mod), "out.json")))
                        {
                            writer.Write(_mod.GetJsonContent());
                        }
                        using (StreamWriter writer = new StreamWriter(Path.Combine(ModLoader.GetModConfigFolder(_mod), "out.xml")))
                        {
                            writer.Write(_mod.GetXmlContent());
                        }
                    }
                    ModConsole.Print("Completed writing - check the mod's config folder.");
                    return;
                }

                // If this point is reached, there were no valid commands to execute.
                ModConsole.Error("Invalid arguments. See 'gps help' for details.");
            }
コード例 #12
0
 // The function that's called when the command is ran
 public override void Run(string[] args)
 {
     ModConsole.Print(args);
     ModConsole.Print("NoclipMod by haverdaden (DD) | Check RacingDeparment for help");
 }
コード例 #13
0
ファイル: ItemList.cs プロジェクト: Wampa842/MySummerMods
        // Test if the GameObject can be picked up
        public bool CanPickUp(GameObject o)
        {
            // List is full
            if (_list.Count >= _list.Capacity)
            {
                if (MySettings.Settings.LogAll)
                {
                    ModConsole.Print($"List is full");
                }
                return(false);
            }

            // Object is not a part or item
            if (!(o.layer == 16 || o.layer == 19))
            {
                if (MySettings.Settings.LogAll)
                {
                    ModConsole.Print($"{o.name} is on layer {o.layer}");
                }
                return(false);
            }

            // Item doesn't have a rigid body
            if (o.GetComponent <Rigidbody>() == null)
            {
                if (MySettings.Settings.LogAll)
                {
                    ModConsole.Print($"{o.name} doesn't have a rigid body");
                }
                return(false);
            }

            // Item is in the blacklist
            if (Array.Exists(Blacklist, e => e == o.name))
            {
                if (MySettings.Settings.LogAll)
                {
                    ModConsole.Print($"{o.name} is blacklisted");
                }
                return(false);
            }

            // Item is installed on or bolted to the car
            // Loop through all PlayMakerFSM components
            foreach (PlayMakerFSM c in o.GetComponents <PlayMakerFSM>())
            {
                // Part is installed if component is "Data" or "Use" and "Installed" is true
                if (c.FsmName == "Data" || c.FsmName == "Use")
                {
                    FsmBool v = c.FsmVariables.FindFsmBool("Installed");
                    if (v != null && v.Value)
                    {
                        return(false);
                    }
                }

                // Part is bolted if component is "BoltCheck" and "Tightness" is greater than 0
                if (c.FsmName == "BoltCheck")
                {
                    FsmFloat v = c.FsmVariables.FindFsmFloat("Tightness");
                    if (v != null && v.Value > 0.0f)
                    {
                        return(false);
                    }
                }
            }

            // Otherwise, the item can be picked up
            return(true);
        }
コード例 #14
0
 public override void Run(string[] args)
 {
     ModConsole.Clear();
 }
コード例 #15
0
 private void _initAudioAsync()
 {
     if (_audio.SwitchOn == null)
     {
         if (_load == null)
         {
             _load = new WWW("file:///" + Path.Combine(ModLoader.GetModAssetsFolder(this), _audio.SwitchOnFile));
         }
         if (!_load.isDone)
         {
             return;
         }
         _audio.SwitchOn                  = _lamp.AddComponent <AudioSource>();
         _audio.SwitchOn.clip             = _load.GetAudioClip(true);
         _audio.SwitchOn.transform.parent = _lamp.transform;
         _audio.SwitchOn.spatialBlend     = 1.0f;
         _audio.SwitchOn.maxDistance      = 5.0f;
         _load = null;
         ModConsole.Print("Loaded SwitchOn");
     }
     if (_audio.SwitchOff == null)
     {
         if (_load == null)
         {
             _load = new WWW("file:///" + Path.Combine(ModLoader.GetModAssetsFolder(this), _audio.SwitchOffFile));
         }
         if (!_load.isDone)
         {
             return;
         }
         _audio.SwitchOff                  = _lamp.AddComponent <AudioSource>();
         _audio.SwitchOff.clip             = _load.GetAudioClip(true);
         _audio.SwitchOff.transform.parent = _lamp.transform;
         _audio.SwitchOff.spatialBlend     = 1.0f;
         _audio.SwitchOff.maxDistance      = 5.0f;
         _load = null;
         ModConsole.Print("Loaded SwitchOff");
     }
     if (_audio.HumLoop == null)
     {
         if (_load == null)
         {
             _load = new WWW("file:///" + Path.Combine(ModLoader.GetModAssetsFolder(this), _audio.HumLoopFile));
         }
         if (!_load.isDone)
         {
             return;
         }
         _audio.HumLoop                  = _lamp.AddComponent <AudioSource>();
         _audio.HumLoop.clip             = _load.GetAudioClip(true);
         _audio.HumLoop.loop             = true;
         _audio.HumLoop.volume           = 0.3f;
         _audio.HumLoop.transform.parent = _lamp.transform;
         _audio.HumLoop.spatialBlend     = 1.0f;
         _audio.HumLoop.maxDistance      = 5.0f;
         _load = null;
         ModConsole.Print("Loaded Hum");
     }
     if (_audio.Disconnect == null)
     {
         if (_load == null)
         {
             _load = new WWW("file:///" + Path.Combine(ModLoader.GetModAssetsFolder(this), _audio.DisconnectFile));
         }
         if (!_load.isDone)
         {
             return;
         }
         _audio.Disconnect                  = _lamp.AddComponent <AudioSource>();
         _audio.Disconnect.clip             = _load.GetAudioClip(true);
         _audio.Disconnect.transform.parent = _lamp.transform;
         _audio.Disconnect.spatialBlend     = 1.0f;
         _audio.Disconnect.maxDistance      = 10.0f;
         _load = null;
         ModConsole.Print("Loaded Disconnect");
     }
     if (_audio.Break == null)
     {
         if (_load == null)
         {
             _load = new WWW("file:///" + Path.Combine(ModLoader.GetModAssetsFolder(this), _audio.BreakFile));
         }
         if (!_load.isDone)
         {
             return;
         }
         _audio.Break                  = _lamp.AddComponent <AudioSource>();
         _audio.Break.clip             = _load.GetAudioClip(true);
         _audio.Break.transform.parent = _lamp.transform;
         _audio.Break.spatialBlend     = 1.0f;
         _audio.Break.maxDistance      = 30.0f;
         _load = null;
         ModConsole.Print("Loaded Break");
     }
     _audio.HasLoaded = true;
 }
コード例 #16
0
        /// <summary>
        /// Looks for gamobject named SAVEGAME, and hooks PreSaveGame into them.
        /// </summary>
        void HookPreSaveGame()
        {
            try
            {
                GameObject[] saveGames = Resources.FindObjectsOfTypeAll <GameObject>()
                                         .Where(obj => obj.name.Contains("SAVEGAME")).ToArray();

                int i = 0;
                for (; i < saveGames.Length; i++)
                {
                    bool useInnactiveFix = false;
                    bool isJail          = false;

                    if (!saveGames[i].activeSelf)
                    {
                        useInnactiveFix = true;
                        saveGames[i].SetActive(true);
                    }

                    if (saveGames[i].transform.parent != null && saveGames[i].transform.parent.name == "JAIL" && saveGames[i].transform.parent.gameObject.activeSelf == false)
                    {
                        useInnactiveFix = true;
                        isJail          = true;
                        saveGames[i].transform.parent.gameObject.SetActive(true);
                    }

                    FsmHook.FsmInject(saveGames[i], "Mute audio", PreSaveGame);

                    if (useInnactiveFix)
                    {
                        if (isJail)
                        {
                            saveGames[i].transform.parent.gameObject.SetActive(false);
                            continue;
                        }

                        saveGames[i].SetActive(false);
                    }
                }

                // Hooking up on death save.
                GameObject onDeathSaveObject = new GameObject("MOP_OnDeathSave");
                onDeathSaveObject.transform.parent = GameObject.Find("Systems").transform.Find("Death/GameOverScreen");
                OnDeathBehaviour behaviour = onDeathSaveObject.AddComponent <OnDeathBehaviour>();
                behaviour.Initialize(PreSaveGame);
                i++;

                // Adding custom action to state that will trigger PreSaveGame, if the player picks up the phone with large Suski.
                PlayMakerFSM          useHandleFSM     = GameObject.Find("Telephone").transform.Find("Logic/UseHandle").GetComponent <PlayMakerFSM>();
                FsmState              phoneFlip        = useHandleFSM.GetState("Pick phone");
                List <FsmStateAction> phoneFlipActions = phoneFlip.Actions.ToList();
                phoneFlipActions.Insert(0, new CustomSuskiLargeFlip());
                phoneFlip.Actions = phoneFlipActions.ToArray();
                i++;

                ModConsole.Log($"[MOP] Hooked {i} save points!");
            }
            catch (Exception ex)
            {
                ExceptionManager.New(ex, true, "SAVE_HOOK_ERROR");
            }
        }
コード例 #17
0
        public override void Update()
        {
            //// Load audio
            //if (!_audio.HasLoaded)
            //{
            //	try
            //	{
            //		_initAudioAsync();
            //	}
            //	catch (Exception ex)
            //	{
            //		ModConsole.Error(ex.ToString());
            //	}
            //}

            // Get inputs
            float scroll = Input.GetAxis("Mouse ScrollWheel");
            bool  use    = cInput.GetButtonDown("Use");

            // Raycast
            RaycastHit[] hits = Physics.RaycastAll(Camera.main.ScreenPointToRay(Input.mousePosition), 1.0f);
            for (int i = 0; i < hits.Length; ++i)
            {
                if (hits[i].collider == _lampCollider)
                {
                    PlayMakerGlobals.Instance.Variables.FindFsmBool("GUIuse").Value           = true;
                    PlayMakerGlobals.Instance.Variables.FindFsmString("GUIinteraction").Value = _on ? "light on" : "light off";
                    if (use)
                    {
                        // Toggle the light
                        _switchLight(!_on);
                        if (_on)
                        {
                            FloodlightAudio.Play(_audio.SwitchOn);
                        }
                        else
                        {
                            FloodlightAudio.Play(_audio.SwitchOff);
                            _battery       = null;
                            _batteryCharge = null;
                        }
                    }

                    if (scroll > 0)
                    {
                        // Pitch up
                        _pitch -= 5.0f;
                        if (_pitch < -60.0f)
                        {
                            _pitch = -60.0f;
                        }
                        _lamp.transform.localEulerAngles = new Vector3(_pitch, 0.0f, 0.0f);
                    }
                    if (scroll < 0)
                    {
                        // Pitch down
                        _pitch += 5.0f;
                        if (_pitch > 10.0f)
                        {
                            _pitch = 10.0f;
                        }
                        _lamp.transform.localEulerAngles = new Vector3(_pitch, 0.0f, 0.0f);
                    }

                    break;
                }
                else if (hits[i].collider == _boxColliderTeimo || hits[i].collider == _boxColliderFleetari)
                {
                    PlayMakerGlobals.Instance.Variables.FindFsmBool("GUIbuy").Value           = true;
                    PlayMakerGlobals.Instance.Variables.FindFsmString("GUIinteraction").Value = _bulbText;
                    if (Input.GetKeyDown(KeyCode.Mouse0))
                    {
                        if (_bulbHealth <= 0)
                        {
                            FsmFloat wealth = PlayMakerGlobals.Instance.Variables.FindFsmFloat("PlayerMoney");
                            if (wealth.Value >= _bulbCost)
                            {
                                wealth.Value -= _bulbCost;
                                hits[i].collider.transform.gameObject.GetComponent <AudioSource>().Play();
                                _bulbHealth = UnityEngine.Random.Range(60, 100);
                                ModConsole.Print($"Floodlight: lightbulb replaced, {_bulbHealth} health");
                            }
                            else
                            {
                                ModConsole.Print($"Floodlight: not enough money ({wealth.Value.ToString("0")} wealth, {_bulbCost.ToString("0")} cost)");
                            }
                        }
                        else
                        {
                            ModConsole.Print($"Floodlight: lightbulb is not broken ({_bulbHealth} health)");
                        }
                    }

                    break;
                }
            }

            // Conditions to switch off
            if (_on)
            {
                if (!_checkBattery(true))
                {
                    _switchLight(false);
                }
                if (_bulbHealth <= 0)
                {
                    if (_bulbHealth == 0)
                    {
                        FloodlightAudio.Play(_audio.Break);
                    }
                    --_bulbHealth;
                    _switchLight(false);
                }
            }
        }
コード例 #18
0
        IEnumerator LoopRoutine()
        {
            MopSettings.IsModActive = true;

            FramerateRecorder rec = gameObject.AddComponent <FramerateRecorder>();

            rec.Initialize();

            while (MopSettings.IsModActive)
            {
                // Ticks make sure that MOP is still up and running.
                // If the ticks didn't update, that means this routine stopped.
                ++ticks;

                if (!itemInitializationDelayDone)
                {
                    // We are slightly delaying the initialization, so all items have chance to set in place, because f**k MSC and its physics.
                    waitTime++;
                    if (waitTime >= WaitDone)
                    {
                        FinishLoading();
                    }
                }

                isPlayerAtYard = MOP.ActiveDistance.Value == 0 ? Vector3.Distance(player.position, placeManager[0].transform.position) < 100
                    : Vector3.Distance(player.position, placeManager[0].transform.position) < 100 * MopSettings.ActiveDistanceMultiplicationValue;

                // When player is in any of the sectors, MOP will act like the player is at yard.
                if (SectorManager.Instance.IsPlayerInSector())
                {
                    inSectorMode   = true;
                    isPlayerAtYard = true;
                }
                else
                {
                    inSectorMode = false;
                }

                yield return(null);

                int  i;
                long half = worldObjectManager.Count >> 1;
                // World Objects.
                for (i = 0; i < worldObjectManager.Count; ++i)
                {
                    if (i == half)
                    {
                        yield return(null);
                    }

                    try
                    {
                        GenericObject worldObject = worldObjectManager[i];

                        // Check if object was destroyed (mostly intended for AI pedastrians).
                        if (worldObject.GameObject == null)
                        {
                            worldObjectManager.Remove(worldObject);
                            continue;
                        }

                        if (SectorManager.Instance.IsPlayerInSector() && SectorManager.Instance.SectorRulesContains(worldObject.GameObject.name))
                        {
                            worldObject.GameObject.SetActive(true);
                            continue;
                        }

                        // Should the object be disabled when the player leaves the house?
                        if (worldObject.DisableOn.HasFlag(DisableOn.PlayerAwayFromHome) || worldObject.DisableOn.HasFlag(DisableOn.PlayerInHome))
                        {
                            if (worldObject.GameObject.name == "NPC_CARS" && inSectorMode)
                            {
                                continue;
                            }

                            if (worldObject.GameObject.name == "COMPUTER" && worldObject.GameObject.transform.Find("SYSTEM").gameObject.activeSelf)
                            {
                                continue;
                            }

                            worldObject.Toggle(worldObject.DisableOn.HasFlag(DisableOn.PlayerAwayFromHome) ? isPlayerAtYard : !isPlayerAtYard);
                        }
                        else if (worldObject.DisableOn.HasFlag(DisableOn.Distance))
                        {
                            // The object will be disabled, if the player is in the range of that object.
                            worldObject.Toggle(IsEnabled(worldObject.transform, worldObject.Distance));
                        }
                    }
                    catch (Exception ex)
                    {
                        ExceptionManager.New(ex, false, "WORLD_OBJECT_TOGGLE_ERROR");
                    }
                }

                // Safe mode prevents toggling elemenets that MAY case some issues (vehicles, items, etc.)
                if (MopSettings.Mode == PerformanceMode.Safe)
                {
                    yield return(new WaitForSeconds(.7f));

                    continue;
                }

                // So we create two separate lists - one is meant to enable, and second is ment to disable them,
                // Why?
                // If we enable items before enabling vehicle inside of which these items are supposed to be, they'll fall through to ground.
                // And the opposite happens if we disable vehicles before disabling items.
                // So if we are disabling items, we need to do that BEFORE we disable vehicles.
                // And we need to enable items AFTER we enable vehicles.
                itemsToEnable.Clear();
                itemsToDisable.Clear();
                half = ItemsManager.Instance.Count >> 1;
                for (i = 0; i < ItemsManager.Instance.Count; ++i)
                {
                    if (i == half)
                    {
                        yield return(null);
                    }

                    // Safe check if somehow the i gets bigger than array length.
                    if (i >= ItemsManager.Instance.Count)
                    {
                        break;
                    }

                    try
                    {
                        ItemBehaviour item = ItemsManager.Instance[i];

                        if (item == null || item.gameObject == null)
                        {
                            itemsToRemove.Add(item);
                            continue;
                        }

                        // Check the mode in what MOP is supposed to run and adjust to it.
                        bool toEnable = true;
                        if (MopSettings.Mode == 0)
                        {
                            toEnable = IsEnabled(item.transform, FsmManager.IsPlayerInCar() && !isPlayerAtYard ? 20 : 150);
                        }
                        else
                        {
                            toEnable = IsEnabled(item.transform, 150);
                        }

                        if (toEnable)
                        {
                            item.ToggleChangeFix();
                            if (item.ActiveSelf)
                            {
                                continue;
                            }
                            itemsToEnable.Add(item);
                        }
                        else
                        {
                            if (!item.ActiveSelf)
                            {
                                continue;
                            }
                            itemsToDisable.Add(item);
                        }

                        if (item.rb != null && item.rb.IsSleeping())
                        {
                            if (item.IsPartMagnetAttached())
                            {
                                continue;
                            }
                            if (CompatibilityManager.IsInBackpack(item))
                            {
                                continue;
                            }
                            item.rb.isKinematic = true;
                        }
                    }
                    catch (Exception ex)
                    {
                        ExceptionManager.New(ex, false, "ITEM_TOGGLE_GATHER_ERROR");
                    }
                }

                // Items To Disable
                int full = itemsToDisable.Count;
                if (full > 0)
                {
                    half = itemsToDisable.Count >> 1;
                    for (i = 0; i < full; ++i)
                    {
                        if (half != 0 && i == half)
                        {
                            yield return(null);
                        }

                        try
                        {
                            itemsToDisable[i].Toggle(false);
                        }
                        catch (Exception ex)
                        {
                            ExceptionManager.New(ex, false, "ITEM_TOGGLE_DISABLE_ERROR - " + itemsToDisable[i] != null ? itemsToDisable[i].gameObject.name : "null");
                        }
                    }
                }

                // Vehicles (new)
                half = vehicleManager.Count >> 1;
                for (i = 0; i < vehicleManager.Count; ++i)
                {
                    if (half != 0 && i == half)
                    {
                        yield return(null);
                    }

                    try
                    {
                        if (vehicleManager[i] == null)
                        {
                            vehicleManager.RemoveAt(i);
                            continue;
                        }

                        float distance       = Vector3.Distance(player.transform.position, vehicleManager[i].transform.position);
                        float toggleDistance = MOP.ActiveDistance.Value == 0
                            ? MopSettings.UnityCarActiveDistance : MopSettings.UnityCarActiveDistance * MopSettings.ActiveDistanceMultiplicationValue;

                        switch (vehicleManager[i].VehicleType)
                        {
                        case VehiclesTypes.Satsuma:
                            Satsuma.Instance.ToggleElements(distance);
                            vehicleManager[i].ToggleEventSounds(distance < 3);
                            break;

                        case VehiclesTypes.Jonnez:
                            vehicleManager[i].ToggleEventSounds(distance < 2);
                            break;
                        }

                        vehicleManager[i].ToggleUnityCar(IsVehiclePhysicsEnabled(distance, toggleDistance));
                        vehicleManager[i].Toggle(IsVehicleEnabled(distance));
                    }
                    catch (Exception ex)
                    {
                        ExceptionManager.New(ex, false, $"VEHICLE_TOGGLE_ERROR_{i}");
                    }
                }

                // Items To Enable
                full = itemsToEnable.Count;
                if (full > 0)
                {
                    half = full >> 1;
                    for (i = 0; i < full; ++i)
                    {
                        if (half != 0 && i == half)
                        {
                            yield return(null);
                        }

                        try
                        {
                            itemsToEnable[i].Toggle(true);
                        }
                        catch (Exception ex)
                        {
                            ExceptionManager.New(ex, false, "ITEM_TOGGLE_ENABLE_ERROR - " + itemsToEnable[i] != null ? itemsToDisable[i].gameObject.name : "null");
                        }
                    }
                }

                // Places (New)
                full = placeManager.Count;
                half = full >> 1;
                for (i = 0; i < full; ++i)
                {
                    if (i == half)
                    {
                        yield return(null);
                    }

                    try
                    {
                        if (SectorManager.Instance.IsPlayerInSector() && SectorManager.Instance.SectorRulesContains(placeManager[i].GetName()))
                        {
                            continue;
                        }

                        placeManager[i].ToggleActive(IsPlaceEnabled(placeManager[i].transform, placeManager[i].GetToggleDistance()));
                    }
                    catch (Exception ex)
                    {
                        ExceptionManager.New(ex, false, $"PLACE_TOGGLE_ERROR_{i}");
                    }
                }

                // Remove items that don't exist anymore.
                if (itemsToRemove.Count > 0)
                {
                    for (i = itemsToRemove.Count - 1; i >= 0; --i)
                    {
                        ItemsManager.Instance.RemoveAt(i);
                    }

                    itemsToRemove.Clear();
                }

                yield return(new WaitForSeconds(.7f));

                if (retries > 0 && !restartSucceedMessaged)
                {
                    restartSucceedMessaged = true;
                    ModConsole.Log("<color=green>[MOP] Restart succeeded!</color>");
                }
            }
        }
コード例 #19
0
        private static void InstallIronPython()
        {
            downloading_in_progress = true;
            download_button_text    = "0.0 %";
            info_text = "<b>Please wait</b>\n";
            if (!Directory.Exists(Application.dataPath + "/Mods/Resources/LenchScripter/lib/"))
            {
                Directory.CreateDirectory(Application.dataPath + "/Mods/Resources/LenchScripter/lib/");
            }
            try
            {
                for (int file_index = 0; file_index < files_required; file_index++)
                {
                    using (var client = new WebClient())
                    {
                        var i = file_index;

                        // delete existing file
                        if (File.Exists(Application.dataPath + file_paths[i]))
                        {
                            File.Delete(Application.dataPath + file_paths[i]);
                        }

                        // progress handler
                        client.DownloadProgressChanged += (object sender, DownloadProgressChangedEventArgs e) =>
                        {
                            received_size[i] = e.BytesReceived;
                            float progress = (Convert.ToSingle(received_size.Sum()) / Convert.ToSingle(total_size.Sum()) * 100f);
                            download_button_text = progress.ToString("0.0") + " %";
                        };

                        // completion handler
                        client.DownloadFileCompleted += (object sender, AsyncCompletedEventArgs e) =>
                        {
                            if (e.Error != null)
                            {
                                // set error messages
                                ModConsole.AddMessage(LogType.Log, "[LenchScripterMod]: Error downloading file:" + file_paths[i].Split('/').Last());
                                ModConsole.AddMessage(LogType.Error, "\t" + e.Error.Message);
                                info_text = file_paths[i].Split('/').Last() + " <color=red>✘</color>" +
                                            "\n\n<b><color=red>Download failed</color></b>\n" + e.Error.Message;

                                downloading_in_progress = false;
                                download_button_text    = "Retry";

                                // delete failed file
                                if (File.Exists(Application.dataPath + file_paths[i]))
                                {
                                    File.Delete(Application.dataPath + file_paths[i]);
                                }
                            }
                            else
                            {
                                ModConsole.AddMessage(LogType.Log, "[LenchScripterMod]: File downloaded: " + file_paths[i].Split('/').Last());
                                info_text += "\n" + file_paths[i].Split('/').Last() + " <color=green>✓</color>";

                                files_downloaded++;
                                if (files_downloaded == files_required)
                                {
                                    // finish download and load assemblies
                                    if (PythonEnvironment.LoadPythonAssembly())
                                    {
                                        download_button_text = "Complete";
                                        ScripterMod.LoadScripter();
                                        Instance.Visible = false;
                                        Destroy(Instance);
                                    }
                                    else
                                    {
                                        download_button_text = "Retry";
                                        info_text            = "<b><color=red>Download failed</color></b>\nFailed to initialize Python engine.";
                                    }
                                    downloading_in_progress = false;
                                }
                            }
                        };

                        // start download
                        client.DownloadFileAsync(
                            file_uris[i],
                            Application.dataPath + file_paths[i]);
                    }
                }
            }
            catch (Exception e)
            {
                Debug.Log("[LenchScripterMod]: Error while downloading:");
                Debug.LogException(e);
                downloading_in_progress = false;
                download_button_text    = "Retry";
                info_text = "<b><color=red>Download failed</color></b>\n" + e.Message;
            }
        }
コード例 #20
0
ファイル: RuleFilesLoader.cs プロジェクト: MSCOTeam/MOP
        IEnumerator DownloadAndUpdateRoutine()
        {
            string lastModList = File.Exists(lastModListPath) ? File.ReadAllText(lastModListPath) : "";

            Mod[]  mods          = ModLoader.LoadedMods.Where(m => !m.ID.ContainsAny("MSCLoader_", "MOP")).ToArray();
            string modListString = "";

            ModConsole.Print("[MOP] Checking for new mods...");

            bool isUpdateTime = !File.Exists(lastDateFilePath) || IsUpdateTime();

            if (isUpdateTime)
            {
                ModConsole.Print("[MOP] Looking for updates...");
            }

            foreach (Mod mod in mods)
            {
                string modId = mod.ID;
                modListString += $"{modId}\n";

                string ruleUrl  = $"{RemoteServer}{modId}.mopconfig";
                string filePath = $"{MOP.ModConfigPath}/{modId}.mopconfig";

                // Prevent downloading, if file is on the server.
                if (lastModList.Contains(mod.ID) && !isUpdateTime)
                {
                    continue;
                }

                // Check if rule file for mod is on the server.
                // If not, continue.
                if (!IsFileOnServer(modId))
                {
                    continue;
                }

                // Check if the newer file is available on the server.
                if (!overrideUpdateCheck)
                {
                    if (serverContent == null)
                    {
                        GetServerContent();
                    }

                    DateTime          lastLocalFileWrite = GetFileWriteTime(filePath);
                    ServerContentData data = serverContent.First(t => t.ID == modId);
                    DateTime          lastRemoteFileWrite = data.UpdateTime;
                    if (lastRemoteFileWrite <= lastLocalFileWrite)
                    {
                        ModConsole.Print($"<color=orange>[MOP] Skipping {modId}, because local file and remote file are the same.</color>");
                        continue;
                    }
                }

                // Check if file actually exists on remote server.
                if (!RemoteFileExists(ruleUrl))
                {
                    ModConsole.Error($"[MOP] Rule file for mod doesn't exist!\nID: {modId}\nURL: {ruleUrl}");
                    continue;
                }

                fileDownloadCompleted = false;
                using (WebClient web = new WebClient())
                {
                    ModConsole.Print($"<color=yellow>[MOP] Downloading new rule file for {mod.Name}...</color>");
                    NewMessage($"MOP: Downloading new rule file for {mod.Name}...");
#if DEBUG
                    web.Headers.Add("user-agent", $"MOP/{MOP.ModVersion}_DEBUG {ExceptionManager.GetSystemInfo()}");
#else
                    web.Headers.Add("user-agent", $"MOP/{MOP.ModVersion} {ExceptionManager.GetSystemInfo()}");
#endif
                    if (File.Exists(filePath))
                    {
                        File.Delete(filePath);
                    }

                    web.DownloadFileCompleted += DownloadFileCompleted;
                    web.DownloadFileAsync(new Uri(ruleUrl), filePath);

                    int waitTime = 0;
                    while (!fileDownloadCompleted)
                    {
                        yield return(new WaitForSeconds(.5f));

                        waitTime++;

                        // If wait time is longer than 30 seconds, abandon downloading.
                        if (waitTime > 60)
                        {
                            ModConsole.Error("[MOP] Downloading failed. Skipping downloading.");
                            NewMessage("MOP: Downloading failed. Skipping downloading.");
                            GetAndReadRules();
                            yield break;
                        }
                    }

                    web.Dispose();
                }

                ModConsole.Print("<color=green>[MOP] Downloading completed!</color>");
            }

            File.WriteAllText(lastModListPath, modListString);
            if (isUpdateTime)
            {
                File.WriteAllText(lastDateFilePath, DateTime.Now.ToString());
            }

            // File downloading and updating completed!
            // Start reading those files.
            GetAndReadRules();
        }
コード例 #21
0
 // Access methods for the console command
 public void SetHealth(int health)
 {
     _health = health;
     ModConsole.Print($"[Floodlight] Health: {_health}");
 }
コード例 #22
0
ファイル: RuleFilesLoader.cs プロジェクト: MSCOTeam/MOP
        /// <summary>
        /// Seeks for rule files (.mopconfig) in MOP config folder.
        /// </summary>
        void GetAndReadRules()
        {
            overrideUpdateCheck = false;

            try
            {
                // Find and .mopconfig files.
                DirectoryInfo   dir   = new DirectoryInfo(MOP.ModConfigPath);
                List <FileInfo> files = dir.GetFiles().Where(d => d.Name.EndsWith(".mopconfig")).ToList();
                // Load custom rule file.
                if (File.Exists($"{dir}/Custom.txt"))
                {
                    files.Add(new FileInfo($"{dir}/Custom.txt"));
                    ModConsole.Print("[MOP] User custom rule file found!");
                }

                if (files.Count == 0)
                {
                    ModConsole.Print($"[MOP] No rule files found.");
                    NewMessage("");
                    return;
                }

                string message = $"[MOP] Found {files.Count} rule file{(files.Count > 1 ? "s" : "")}!";
                if (files.Count == 69)
                {
                    message = message.Rainbowmize();
                }

                ModConsole.Print(message);

                int removed = 0;

                // Read rule files.
                foreach (FileInfo file in files)
                {
                    // Delete rules for mods that don't exist.
                    if (ModLoader.LoadedMods.Find(m => m.ID == Path.GetFileNameWithoutExtension(file.Name)) == null && file.Name != "Custom.txt")
                    {
                        if ((bool)MOP.NoDeleteRuleFiles.GetValue())
                        {
                            ModConsole.Print($"<color=yellow>[MOP] Skipped {file.Name} rule, " +
                                             $"because the corresponding mod is not present.</color>");
                            continue;
                        }
                        File.Delete(file.FullName);
                        ModConsole.Print($"<color=yellow>[MOP] Rule file {file.Name} has been deleted, " +
                                         $"because corresponding mod is not present.</color>");
                        removed++;
                        continue;
                    }

                    // Verify if the servercontent has that rule file.
                    // Some mod makers may include poorly configured rule files,
                    // that's why they have to be only provided by the server.
                    if (serverContent != null && (bool)MOP.VerifyRuleFiles.GetValue() && file.Name != "Custom.txt")
                    {
                        if (serverContent.Find(m => m.ID == Path.GetFileNameWithoutExtension(file.Name)) == null)
                        {
                            File.Delete(file.FullName);
                            ModConsole.Warning($"[MOP] Rule file {file.Name} has been deleted, because it couldn't be verified.");
                            removed++;
                            continue;
                        }
                    }

                    Rules.instance.RuleFileNames.Add(file.Name);
                    ReadRulesFromFile(file.FullName);
                }

                ModConsole.Print("<color=green>[MOP] Loading rule files done!</color>");
                NewMessage($"MOP: Loading {files.Count - removed} rule file{(files.Count - removed > 1 ? "s" : "")} done!");
            }
            catch (Exception ex)
            {
                ExceptionManager.New(ex, "RULE_FILES_READ_ERROR");
            }
        }
コード例 #23
0
 public void LogMessage(string message)
 {
     ModConsole.Log(message);
 }
コード例 #24
0
ファイル: RuleFilesLoader.cs プロジェクト: MSCOTeam/MOP
        // You know the rules and so do I
        // A full commitment's what I'm thinking of
        // You wouldn't get this from any other guy
        // I just wanna tell you how I'm feeling
        // Gotta make you understand
        // Never gonna give you up
        // Never gonna let you down
        // Never gonna run around and desert you
        // Never gonna make you cry
        // Never gonna say goodbye
        // Never gonna tell a lie and hurt you

        void ReadRulesFromFile(string rulePath)
        {
            try
            {
                string[] content     = File.ReadAllLines(rulePath).Where(s => s.Length > 0 && !s.StartsWith("##")).ToArray();
                string   fileName    = Path.GetFileName(rulePath);
                int      lines       = File.ReadAllLines(rulePath).Where(s => s.StartsWith("##")).ToArray().Length;
                int      currentLine = 0;
                foreach (string s in content)
                {
                    lines++;
                    currentLine++;
                    string[] splitted = s.Split(':');

                    // Read flag and rules.
                    string   flag    = splitted[0];
                    string[] objects = new string[0];
                    if (splitted.Length > 1)
                    {
                        objects = splitted[1].Trim().Split(' ');
                        for (int i = 0; i < objects.Length; i++)
                        {
                            objects[i] = objects[i].Replace("%20", " ");
                        }
                    }

                    if (objects.Length > 0 && objects.ContainsAny(illegalValues))
                    {
                        ModConsole.Error($"[MOP] Illegal object: {objects[0]} in rule file {fileName}.");
                        continue;
                    }

                    // Apply these rules
                    switch (flag)
                    {
                    default:
                        ModConsole.Error($"[MOP] Unrecognized flag '{flag}' in {fileName} ({lines}).");
                        break;

                    case "ignore":
                        // Ignore at place
                        if (objects.Length > 1)
                        {
                            Rules.instance.IgnoreRulesAtPlaces.Add(new IgnoreRuleAtPlace(objects[0], objects[1]));
                            break;
                        }

                        Rules.instance.IgnoreRules.Add(new IgnoreRule(objects[0], false));
                        break;

                    case "ignore_full":
                        Rules.instance.IgnoreRules.Add(new IgnoreRule(objects[0], true));
                        break;

                    case "toggle":
                        ToggleModes mode = ToggleModes.Normal;
                        if (objects.Length > 1)
                        {
                            switch (objects[1])
                            {
                            default:
                                ModConsole.Error($"[MOP] Unrecognized method '{objects[1]}' in {fileName} ({lines}).");
                                break;

                            case "renderer":
                                mode = ToggleModes.Renderer;
                                break;

                            case "item":
                                mode = ToggleModes.Item;
                                break;

                            case "vehicle":
                                mode = ToggleModes.Vehicle;
                                break;

                            case "vehicle_physics":
                                mode = ToggleModes.VehiclePhysics;
                                break;
                            }
                        }

                        Rules.instance.ToggleRules.Add(new ToggleRule(objects[0], mode));
                        break;

                    case "satsuma_ignore_renderer":
                        Rules.instance.SpecialRules.SatsumaIgnoreRenderers = true;
                        break;

                    case "dont_destroy_empty_beer_bottles":
                        Rules.instance.SpecialRules.DontDestroyEmptyBeerBottles = true;
                        break;

                    case "sector":
                        Vector3  pos       = ParseToVector3(objects[0]);
                        Vector3  scale     = ParseToVector3(objects[1]);
                        Vector3  rot       = ParseToVector3(objects[2]);
                        string[] whitelist = GetWhitelist(objects);
                        Rules.instance.NewSectors.Add(new NewSector(pos, scale, rot, whitelist));
                        break;

                    case "min_ver":
                        if (fileName == "Custom.txt")
                        {
                            break;
                        }

                        if (currentLine != 1)
                        {
                            ModConsole.Print($"\n=================================" +
                                             $"\n\n<color=cyan>[MOP] Flag '{flag}' must be first in the order!\n\n" +
                                             $"File: {fileName}\n" +
                                             $"Line: {lines}\n" +
                                             $"You can ignore that message.</color>");
                        }

                        int      major, minor, revision = 0;
                        string[] verSplitted = objects[0].Split('.');
                        major = int.Parse(verSplitted[0]);
                        minor = int.Parse(verSplitted[1]);
                        if (verSplitted.Length == 3)
                        {
                            revision = int.Parse(verSplitted[2]);
                        }

                        int      modMajor, modMinor, modRevision = 0;
                        string[] modVersionSpliited = MOP.ModVersion.Split('.');
                        modMajor = int.Parse(modVersionSpliited[0]);
                        modMinor = int.Parse(modVersionSpliited[1]);
                        if (modVersionSpliited.Length == 3)
                        {
                            modRevision = int.Parse(modVersionSpliited[2]);
                        }

                        bool isOutdated = false;
                        if (major > modMajor)
                        {
                            isOutdated = true;
                        }
                        else
                        {
                            if (minor > modMinor && major == modMajor)
                            {
                                isOutdated = true;
                            }
                            else
                            {
                                if (revision > modRevision && minor == modMinor && major == modMajor)
                                {
                                    isOutdated = true;
                                }
                            }
                        }

                        if (isOutdated)
                        {
                            ModConsole.Error($"[MOP] Rule file {fileName} is for the newer version of MOP. Please update MOP right now!\n\n" +
                                             $"Your MOP version: {modMajor}.{modMinor}.{modRevision}\n" +
                                             $"Required version: {major}.{minor}.{revision}");

                            return;
                        }

                        break;

                    // Custom.txt exclusives.
                    case "ignore_mod_vehicles":
                        if (fileName != "Custom.txt")
                        {
                            ModConsole.Error($"[MOP] Flag: {flag} is only allowed to be used in custom rule file.");
                            continue;
                        }
                        Rules.instance.SpecialRules.IgnoreModVehicles = true;
                        break;

                    case "toggle_all_vehicles_physics_only":
                        if (fileName != "Custom.txt")
                        {
                            ModConsole.Error($"[MOP] Flag: {flag} is only allowed to be used in custom rule file.");
                            continue;
                        }
                        Rules.instance.SpecialRules.ToggleAllVehiclesPhysicsOnly = true;
                        break;

                    case "experimental_driveway_sector":
                        if (fileName != "Custom.txt")
                        {
                            ModConsole.Error($"[MOP] Flag: {flag} is only allowed to be used in custom rule file.");
                            continue;
                        }
                        Rules.instance.SpecialRules.DrivewaySector = true;
                        break;

                    case "experimental_satsuma_trunk":
                        if (fileName != "Custom.txt")
                        {
                            ModConsole.Error($"[MOP] Flag: {flag} is only allowed to be used in custom rule file.");
                            continue;
                        }
                        Rules.instance.SpecialRules.ExperimentalSatsumaTrunk = true;
                        break;

                    case "experimental_optimization":
                        if (fileName != "Custom.txt")
                        {
                            ModConsole.Error($"[MOP] Flag: {flag} is only allowed to be used in custom rule file.");
                            continue;
                        }
                        Rules.instance.SpecialRules.ExperimentalOptimization = true;
                        break;

                    case "experimental_save_optimization":
                        if (fileName != "Custom.txt")
                        {
                            ModConsole.Error($"[MOP] Flag: {flag} is only allowed to be used in custom rule file.");
                            continue;
                        }
                        Rules.instance.SpecialRules.ExperimentalSaveOptimization = true;
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                ModConsole.Error($"[MOP] Error loading rule {Path.GetFileName(rulePath)}: {ex}.");
                NewMessage($"<color=red>MOP: Error loading rule :(");
            }
        }
コード例 #25
0
ファイル: ConsoleCommands.cs プロジェクト: MSCOTeam/MOP
        public override void Run(string[] args)
        {
            if (args.Length == 0)
            {
                ModConsole.Print("See \"mop help\" for command list.");
                return;
            }

            switch (args[0])
            {
            default:
                ModConsole.Print("Invalid command. Type \"mop help\" for command list.");
                break;

            case "help":
                ModConsole.Print("<color=yellow>help</color> - Show this list\n" +
                                 "<color=yellow>version</color> - Prints MOP version\n" +
                                 "<color=yellow>rules</color> - Show the list of active rules and loaded rule files\n" +
                                 "<color=yellow>wiki</color> - Open wiki page of rule files\n" +
                                 "<color=yellow>reload</color> - Forces MOP to reload rule files\n" +
                                 "<color=yellow>new [ModID]</color> - Create custom rule file (if no ModID is provided, will create Custom.txt)\n" +
                                 "<color=yellow>open [ModID]</color> - Opens the .modconfig for mod\n" +
                                 "<color=yellow>open-folder</color> - Opens MOP config folder\n" +
                                 "<color=yellow>delete [ModID]</color> - Delete rule file\n" +
                                 "<color=yellow>sector-debug [true/false]</color> - Shows the renderers of sectors\n" +
                                 "<color=yellow>cat [File Name]</color> - Print the content of a rule file\n" +
                                 "<color=yellow>generate-list [true/false]</color> - Generates text files which contain the list of items that are toggled by MOP\n" +
                                 "<color=yellow>restore-save</color> - If you use experimental save optimiztion, allows you to restore your last save file.");
                break;

            case "rules":
                if (args.Length > 1 && args[1] == "roll")
                {
                    ModConsole.Print("\n<color=yellow>You know the rules and so do I\n" +
                                     "A full commitment's what I'm thinking of\n" +
                                     "You wouldn't get this from any other guy\n" +
                                     "I just wanna tell you how I'm feeling\n" +
                                     "Gotta make you understand\n" +
                                     "Never gonna give you up\n" +
                                     "Never gonna let you down\n" +
                                     "Never gonna run around and desert you\n" +
                                     "Never gonna make you cry\n" +
                                     "Never gonna say goodbye\n" +
                                     "Never gonna tell a lie and hurt you</color>\n\n");
                    return;
                }

                if (Rules.instance.IgnoreRules.Count > 0)
                {
                    ModConsole.Print("<color=yellow><b>Ignore Rules</b></color>");
                    foreach (IgnoreRule r in Rules.instance.IgnoreRules)
                    {
                        ModConsole.Print($"<b>Object:</b> {r.ObjectName}");
                    }
                }

                if (Rules.instance.IgnoreRulesAtPlaces.Count > 0)
                {
                    ModConsole.Print("\n<color=yellow><b>Ignore Rules At Place</b></color>");
                    foreach (IgnoreRuleAtPlace r in Rules.instance.IgnoreRulesAtPlaces)
                    {
                        ModConsole.Print($"<b>Place:</b> {r.Place} <b>Object:</b> {r.ObjectName}");
                    }
                }

                if (Rules.instance.ToggleRules.Count > 0)
                {
                    ModConsole.Print("\n<color=yellow><b>Toggle Rules</b></color>");
                    foreach (ToggleRule r in Rules.instance.ToggleRules)
                    {
                        ModConsole.Print($"<b>Object:</b> {r.ObjectName} <b>Toggle Mode:</b> {r.ToggleMode}");
                    }
                }

                if (Rules.instance.NewSectors.Count > 0)
                {
                    ModConsole.Print("\n<color=yellow><b>New Sectors</b></color>");
                    foreach (NewSector r in Rules.instance.NewSectors)
                    {
                        ModConsole.Print($"<b>Pos:</b> {r.Position} <b>Scale:</b> {r.Scale} <b>Rot:</b> {r.Rotation} <b>Ignore:</b> {string.Join(", ", r.Whitelist)}");
                    }
                }

                ModConsole.Print("\n<color=yellow><b>Special Rules</b></color>");
                // Obtain all fields
                FieldInfo[] fields = typeof(SpecialRules).GetFields();
                // Loop through fields
                foreach (var field in fields)
                {
                    ModConsole.Print($"<b>{field.Name}</b>: {field.GetValue(Rules.instance.SpecialRules)}");
                }

                // List rule files.
                string output = "\n<color=yellow><b>Rule Files</b></color>\n";
                foreach (string ruleFile in Rules.instance.RuleFileNames)
                {
                    output += $"{ruleFile}\n";
                }

                ModConsole.Print(output);
                break;

            case "wiki":
                Process.Start("https://github.com/Athlon007/MOP/wiki/Rule-Files-Documentation");
                break;

            case "reload":
                if (ModLoader.GetCurrentScene() != CurrentScene.MainMenu)
                {
                    ModConsole.Print("You can only reload rule files in the main menu");
                    return;
                }

                Rules.instance.WipeAll(false);
                break;

            case "new":
                string path = $"{MOP.ModConfigPath}/Custom.txt";

                if (args.Length > 1)
                {
                    path = $"{MOP.ModConfigPath}/{args[1]}.mopconfig";
                }

                if (File.Exists(path))
                {
                    ModConsole.Print("Custom file already exists. Use \"mop open\" to edit it now.");
                    return;
                }

                File.WriteAllText(path, "## Every line which starts with ## will be ignored.\n" +
                                  "## All new flags MUST be written in a new line.\n" +
                                  "## Visit https://github.com/Athlon007/MOP/wiki/Rule-Files-Documentation for documentation.\n" +
                                  "## WARNING: Using custom rule files may cause issues. Use only at your own risk!");

                Process.Start(path);
                if (path.EndsWith("Custom.txt"))
                {
                    ModConsole.Print("A custom rule file has been created. You can find it as Custom.txt.\n" +
                                     "<color=red>Careless use of rule files may cause bugs and glitchess. Use only at yout own risk!</color>");
                }
                else
                {
                    ModConsole.Print($"A rule file for {args[1]} mod has been created.");
                }
                break;

            case "version":
                ModConsole.Print(MOP.ModVersion);
                break;

            case "cowsay":
                string say = string.Join(" ", args, 1, args.Length - 1);

                switch (say.ToLower())
                {
                case "tell me your secrets":
                    say = "all pls fix and no appreciation makes Athlon an angry boy";
                    break;

                case "tell me your wisdoms":
                    say = "people saying that MOP is just improved KruFPS are straight up wrong";
                    break;

                case "wieski":
                    say = "it really do be like dat doe sometimes";
                    break;

                case "embu":
                    say = "pee vee good";
                    break;

                case "owo":
                    say = "UwU";
                    break;

                case "uwu":
                    say = "OwO";
                    break;

                case "mop sucks":
                    say = "no u";
                    Process.Start("https://www.youtube.com/watch?v=dQw4w9WgXcQ");
                    break;
                }

                ModConsole.Print($"< {say} >\n" +
                                 "        \\   ^__^\n" +
                                 "         \\  (oo)\\____\n" +
                                 "            (__)\\          )\\/\\\n" +
                                 "                ||  ----w  |\n" +
                                 "                ||           || ");
                break;

            case "sector-debug":
                if (args.Length == 1)
                {
                    ModConsole.Print($"Sector debug mode is set to {MopSettings.SectorDebugMode}");
                    return;
                }
                MopSettings.SectorDebugMode = args[1].ToLower() == "true";
                ModConsole.Print($"Sector debug mode is {(MopSettings.SectorDebugMode ? "on" : "off")}!");
                break;

            case "open-folder":
                Process.Start(MOP.ModConfigPath);
                break;

            case "open":
                if (args.Length == 1)
                {
                    ModConsole.Print($"Missing argument.");
                    return;
                }

                if (args[1].StartsWith("Custom") || args[1].StartsWith("custom"))
                {
                    if (!args[1].EndsWith(".txt"))
                    {
                        args[1] += ".txt";
                    }
                }
                else
                {
                    if (!args[1].EndsWith(".mopconfig"))
                    {
                        args[1] += ".mopconfig";
                    }
                }

                if (!File.Exists($"{MOP.ModConfigPath}/{args[1]}"))
                {
                    ModConsole.Print($"File {args[1]} doesn't exist.");
                    return;
                }

                Process.Start($"{MOP.ModConfigPath}/{args[1]}");
                break;

            case "delete":
                if (args.Length == 1)
                {
                    ModConsole.Print($"Missing argument.");
                    return;
                }

                if (args[1].StartsWith("Custom") && !args[1].EndsWith(".txt"))
                {
                    args[1] += ".txt";
                }
                else
                {
                    if (!args[1].EndsWith(".mopconfig"))
                    {
                        args[1] += ".mopconfig";
                    }
                }

                if (!File.Exists($"{MOP.ModConfigPath}/{args[1]}"))
                {
                    ModConsole.Print($"File {args[1]} doesn't exist.");
                    return;
                }

                File.Delete($"{MOP.ModConfigPath}/{args[1]}");
                break;

            case "cat":
                if (args.Length == 1)
                {
                    ModConsole.Print($"Missing argument.");
                    return;
                }

                if (args[1].StartsWith("Custom") && !args[1].EndsWith(".txt"))
                {
                    args[1] += ".txt";
                }
                else
                {
                    if (!args[1].EndsWith(".mopconfig"))
                    {
                        args[1] += ".mopconfig";
                    }
                }

                if (!File.Exists($"{MOP.ModConfigPath}/{args[1]}"))
                {
                    ModConsole.Print($"File {args[1]} doesn't exist.");
                    return;
                }

                ModConsole.Print(File.ReadAllText($"{MOP.ModConfigPath}/{args[1]}"));
                break;

            case "restore-save":
                if (ModLoader.GetCurrentScene() != CurrentScene.MainMenu)
                {
                    ModConsole.Print("You can only restore game save in the main menu.");
                    break;
                }

                bool defaultBackupMissing = false;
                bool itemsBackupMissing   = false;
                if (!File.Exists(SaveManager.GetDefaultES2SavePosition() + ".mopbackup"))
                {
                    defaultBackupMissing = true;
                    ModConsole.Print("defaultES2Save.txt.mopbackup file is missing.");
                }

                if (!File.Exists(SaveManager.GetItemsPosition() + ".mopbackup"))
                {
                    itemsBackupMissing = true;
                    ModConsole.Print("items.txt.mopbackup file is missing.");
                }

                if (defaultBackupMissing && itemsBackupMissing)
                {
                    ModConsole.Print("Save backups don't exists. Do you use the save optimization?");
                    break;
                }

                if (!defaultBackupMissing)
                {
                    File.Delete(SaveManager.GetDefaultES2SavePosition());
                    File.Move(SaveManager.GetDefaultES2SavePosition() + ".mopbackup", SaveManager.GetDefaultES2SavePosition());
                }

                if (!itemsBackupMissing)
                {
                    File.Delete(SaveManager.GetItemsPosition());
                    File.Move(SaveManager.GetItemsPosition() + ".mopbackup", SaveManager.GetItemsPosition());
                }

                ModConsole.Print("Save backup succesfully restored!");
                break;

            case "generate-list":
                if (args.Length == 1)
                {
                    ModConsole.Print($"Generating toggled elements list is set to {MopSettings.GenerateToggledItemsListDebug}");
                    return;
                }

                if (Rules.instance.IgnoreRules.Count > 0 || Rules.instance.IgnoreRulesAtPlaces.Count > 0 ||
                    Rules.instance.NewSectors.Count > 0 || Rules.instance.ToggleRules.Count > 0)
                {
                    ModConsole.Print("<color=red>WARNING:</color> For accurate results, disable all rule files!");
                }

                MopSettings.GenerateToggledItemsListDebug = args[1].ToLower() == "true";
                ModConsole.Print($"Generating toggled elements list is {(MopSettings.GenerateToggledItemsListDebug ? "on" : "off")}!");
                break;
            }
        }
コード例 #26
0
        private void Update()
        {
            UpdateWhellsRotation();
            if (Input.GetMouseButtonDown(0) && m_isCaught && Joint != null && !m_isConnect)
            {
                Support.localScale = new Vector3(1f, 1f, 1f);
                Destroy(Joint);
                m_isCaught = false;
            }

            Ray        ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit raycastHit;

            if (Physics.Raycast(ray, out raycastHit))
            {
                if (raycastHit.collider.name == "ConnectTrigger")
                {
                    //ModConsole.Print(m_connectColision + " - " + m_connectColisionV);
                    if (m_connectColision || m_connectColisionV)
                    {
                        // ModConsole.Print("m_connectColision");
                        PlayMakerGlobals.Instance.Variables.FindFsmBool("GUIuse").Value           = true;
                        PlayMakerGlobals.Instance.Variables.FindFsmString("GUIinteraction").Value = this.m_isConnect ? "Disconnect" : "Connect";
                        if (cInput.GetButtonDown("Use"))
                        {
                            //ModConsole.Print("Use Comand " + m_isConnect);
                            if (!m_isConnect)
                            {
                                //ModConsole.Print("Conneting");
                                try
                                {
                                    if (Joint != null)
                                    {
                                        Destroy(Joint);
                                    }
                                    Joint = base.gameObject.AddComponent <HingeJoint>();

                                    //ModConsole.Print("ridgbody localizado");
                                    if (m_connectColisionV && HitchV != null)
                                    {
                                        //ModConsole.Print("HiutchV localizado");
                                        CreateJoint(new Vector3(0f, 0f, 0f), HitchV.GetComponent <Rigidbody>(), false);
                                    }
                                    else
                                    if (Hitch != null)
                                    {
                                        //ModConsole.Print("Hitch localizado");
                                        CreateJoint(new Vector3(0f, 0f, 0f), Hitch.GetComponent <Rigidbody>(), false);
                                    }
                                }
                                catch (Exception e)
                                {
                                    ModConsole.Error("Connect Erro: " + e.ToString());
                                }
                            }
                            else
                            {
                                ModConsole.Print("Desconnecting");
                                if (Joint != null)
                                {
                                    Destroy(Joint);
                                    Support.localScale = new Vector3(1f, 1f, 1f);
                                }
                            }
                            this.m_isConnect = !this.m_isConnect;


                            return;
                        }
                        else
                        {
                            CreateJointToPlayer();
                        }
                    }
                    else
                    {
                        CreateJointToPlayer();
                    }
                }
            }
        }
コード例 #27
0
        public override void OnLoad()
        {
            gameObjects = new List <GameObject>();

            //Player Vehicles
            // For each vehicle in the game, a new instance of Vehicle class is initialized.
            SATSUMA      = new Vehicle("SATSUMA(557kg, 248)");
            SATSUMA_2    = GameObject.Find("SATSUMA(557kg, 248)");
            FLATBED      = new Vehicle("FLATBED");
            GIFU         = new Gifu("GIFU(750/450psi)");
            HAYOSIKO     = new Vehicle("HAYOSIKO(1500kg, 250)");
            JONNEZ       = new Vehicle("JONNEZ ES(Clone)");
            KEKMET       = new Vehicle("KEKMET(350-400psi)");
            RUSKO        = new Vehicle("RCO_RUSCKO12(270)");
            FERNDALE     = new Vehicle("FERNDALE(1630kg)");
            CABIN        = GameObject.Find("CABIN");
            AXLES        = SATSUMA_2.GetComponent <Axles>();
            CAR_DYNAMICS = SATSUMA_2.GetComponent <CarDynamics>();
            ModConsole.Print("Cars Done");

            //Locations and objects that can be enabled and disabled easily on proximity
            gameObjects.Add(GameObject.Find("BOAT")); //Boat is not a Car, oddly enough.
            //gameObjects.Add(GameObject.Find("CABIN"));
            gameObjects.Add(GameObject.Find("COTTAGE"));
            gameObjects.Add(GameObject.Find("DANCEHALL"));
            //gameObjects.Add(GameObject.Find("DRAGRACE")); //Is broken when disabled, so leave enabled
            gameObjects.Add(GameObject.Find("INSPECTION"));
            gameObjects.Add(GameObject.Find("LANDFILL"));
            gameObjects.Add(GameObject.Find("PERAJARVI"));
            //gameObjects.Add(GameObject.Find("REPAIRSHOP")); //Has to be loaded for repairs and such - Maybe fixable
            gameObjects.Add(GameObject.Find("RYKIPOHJA"));
            gameObjects.Add(GameObject.Find("SOCCER"));
            gameObjects.Add(GameObject.Find("WATERFACILITY"));
            gameObjects.Add(GameObject.Find("KILJUGUY"));
            gameObjects.Add(GameObject.Find("CHURCHWALL"));
            gameObjects.Add(GameObject.Find("TREES1_COLL"));
            gameObjects.Add(GameObject.Find("TREES2_COLL"));
            gameObjects.Add(GameObject.Find("TREES3_COLL"));

            // Initialize Store class
            STORE      = new Store();
            REPAIRSHOP = new RepairShop();

            // Find house of Teimo and detach it from Perajarvi, so it can be loaded and unloaded separately
            // It shouldn't cause any issues, but that needs testing.
            GameObject perajarvi   = GameObject.Find("PERAJARVI");
            GameObject TEIMO_HOUSE = perajarvi.transform.Find("HouseRintama4").gameObject;

            TEIMO_HOUSE.transform.parent = null;
            // Same for chicken house
            GameObject CHICKEN_HOUSE = perajarvi.transform.Find("ChickenHouse").gameObject;

            CHICKEN_HOUSE.transform.parent = null;

            // Now that Teimo's house and chicken house is separated from Perajarvi, we can manage them separately. We're throwing them to gameObjects.
            // Fixes the bug with both dissapearing when leaving Perajarvi, even tho logically they should still load when approached.
            gameObjects.Add(TEIMO_HOUSE);
            gameObjects.Add(CHICKEN_HOUSE);

            // Fix for disappearing grain processing plant
            // https://my-summer-car.fandom.com/wiki/Grain_processing_plant
            //
            // It also puts them to farGameObjects - objects that are larger and need to be rendered from further distance
            foreach (Transform trans in perajarvi.GetComponentsInChildren <Transform>())
            {
                if (trans.gameObject.name.Contains("silo"))
                {
                    trans.parent = null;
                    farGameObjects.Add(trans.gameObject);
                }
            }

            // Chicken house (barn) close to player's house
            Transform playerChickenHouse = GameObject.Find("Buildings").transform.Find("ChickenHouse");

            playerChickenHouse.parent = null;
            gameObjects.Add(playerChickenHouse.gameObject);

            ModConsole.Print("GameObjects Done");

            //Things that should be enabled when out of proximity of the house
            awayFromHouse = new List <GameObject>();
            awayFromHouse.Add(GameObject.Find("NPC_CARS"));
            awayFromHouse.Add(GameObject.Find("RALLY"));
            awayFromHouse.Add(GameObject.Find("TRAFFIC"));
            awayFromHouse.Add(GameObject.Find("TRAIN"));
            awayFromHouse.Add(GameObject.Find("Buildings"));
            awayFromHouse.Add(GameObject.Find("TrafficSigns"));
            awayFromHouse.Add(GameObject.Find("ELEC_POLES"));

            //TODO: Solve Bugs from Unloading/Reloading Satsuma
            // Bugs:
            // Can't open doors
            // May randomly fall through floor

            //TODO:
            // Figure out how to make repairs works at Fleetari's without loading it
            // (*1) Figure out how to trigger a restock at Tiemos on Thursdays without loading it.

            //NOTES:
            // (*1) Partially addressed the Teimo's issue, by unloading part of the shop

            //Camera.main.farClipPlane = (int)RenderDistance.Value; //Helps with lower end GPU's. This specific value. Any others are wrong.
            PLAYER    = GameObject.Find("PLAYER");
            YARD      = GameObject.Find("YARD");                //Used to find out how far the player is from the Object
            KINEMATIC = SATSUMA.Object.GetComponent <Rigidbody>();

            // Get all minor objects from the game world (like beer cases, sausages)
            // Only items that are in the listOfMinorObjects list, and also contain "(itemx)" in their name will be loaded
            // UPDATED: added support for (Clone) items
            GameObject[] allObjects = Object.FindObjectsOfType <GameObject>();
            foreach (GameObject gameObject in allObjects)
            {
                foreach (string itemName in listOfMinorObjects)
                {
                    if (gameObject.name.Contains(itemName) && gameObject.name.ContainsAny("(itemx)", "(Clone)"))
                    {
                        minorObjects.Add(gameObject);
                    }
                }
            }

            ModConsole.Print("[KruFPS] Found all objects");
            DrawDistance = float.Parse(RenderDistance.GetValue().ToString()); //Update saved draw distance variable
            HookAllSavePoints();                                              //Hook all save points (it's before first pass of Update)
        }
コード例 #28
0
 // The function that's called when the command is ran
 public override void Run(string[] args)
 {
     ModConsole.Print(args);
 }
コード例 #29
0
 // The function that's called when executing command
 public override void Run(string[] args)
 {
     ModConsole.Print(string.Format("<color=orange>Log All errors is set to <b>{0}</b></color>", !ModLoader.LogAllErrors));
     ModLoader.LogAllErrors = !ModLoader.LogAllErrors;
 }
コード例 #30
0
        private Keybind create_Object_Dump = new Keybind("objectDump", "Create dump of all objects in scene.", KeyCode.F5); // Create a keybind..

        //Called when mod is loading
        public override void OnLoad()
        {
            //Print out  console message.
            ModConsole.Print("SceneObjects: Loaded");
        }