Ejemplo n.º 1
0
        /// <summary>
        /// Cpp指针转换过程-EngineInformation
        /// </summary>
        /// <param name="Ptr"></param>
        /// <returns></returns>
        protected static EngineInfo Intptr2EngineInformation(IntPtr Ptr)
        {
            EngineInfo Ret = new EngineInfo();

            Ret.Version = "Error";
            try
            {
                EngineInformation_Cpp ret = (EngineInformation_Cpp)Marshal.PtrToStructure(Ptr, typeof(EngineInformation_Cpp));
                if (ret.Name != "")
                {
                    Ret.Author        = ret.Author;
                    Ret.FlagItemCount = ret.FlagItemCount;
                    Ret.Name          = ret.Name;
                    Ret.Usuage        = ret.Usuage;
                    Ret.Version       = ret.Version;
                    Ret.FlagItem      = new EngineFlagItem[ret.FlagItemCount];
                    int basePtr = ret.FlgItem.ToInt32();
                    int PtrSize = Marshal.SizeOf(Ret.FlagItem[0]);
                    for (int i = 0; i < Ret.FlagItemCount; i++)
                    {
                        Ret.FlagItem[i] = (EngineFlagItem)Marshal.PtrToStructure(new IntPtr(basePtr + i * PtrSize), typeof(EngineFlagItem));
                    }
                    //Ret = ret;
                }
            }
            catch {; }
            return(Ret);
        }
Ejemplo n.º 2
0
        static void Main()
        {
            Console.WriteLine("This example will create PGP keys in your default keyring.\n");

            // First step is to create a context
            Context ctx = new Context();

            EngineInfo info = ctx.EngineInfo;

            if (info.Protocol != Protocol.OpenPGP)
            {
                ctx.SetEngineInfo(Protocol.OpenPGP, null, null);
                info = ctx.EngineInfo;
            }

            Console.WriteLine("GnuPG home directory: {0}\n"
                              + "Version: {1}\n"
                              + "Reqversion: {2} \n"
                              + "Program: {3}\n",
                              info.HomeDir,
                              info.Version,
                              info.ReqVersion,
                              info.FileName);

            IKeyGenerator keygen = ctx.KeyStore;

            // Create 3 PGP keys..
            CreatePgpKeyForAlice(keygen);
            CreatePgpKeyForBob(keygen);
            CreatePgpKeyForMallory(keygen);
        }
Ejemplo n.º 3
0
 public void Save(EngineInfo info)
 {
     var client = new RedisClient();
     var key = new EngineKeys ().GetInfoKey (info.Id);
     var json = info.ToJson ();
     client.Set(key, json);
 }
Ejemplo n.º 4
0
        public EngineInfo GetInfo()
        {
            EngineInfo ret = new EngineInfo {
                Version = "Error"
            };

            if (!_isLegalPlugin)
            {
                return(ret);
            }
            if (GetInformationMethod != null)
            {
                object Ret = GetInformationMethod.Invoke(null, new object[0]);
                if (Ret != null)
                {
                    ret.Author        = (string)Ret.GetType().GetField("Author").GetValue(Ret);
                    ret.Name          = (string)Ret.GetType().GetField("Name").GetValue(Ret);
                    ret.Usuage        = (string)Ret.GetType().GetField("Usuage").GetValue(Ret);
                    ret.Version       = (string)Ret.GetType().GetField("Version").GetValue(Ret);
                    ret.Author        = (string)Ret.GetType().GetField("Author").GetValue(Ret);
                    ret.FlagItemCount = (int)Ret.GetType().GetField("FlagItemCount").GetValue(Ret);
                    Array ItemArray = (Ret.GetType().GetField("FlagItem").GetValue(Ret)) as Array;
                    ret.FlagItem = new EngineFlagItem[ret.FlagItemCount];
                    for (int i = 0; i < ret.FlagItemCount; i++)
                    {
                        ret.FlagItem[i] = (EngineFlagItem)CopyObjectToNewType(ItemArray.GetValue(i), typeof(EngineFlagItem));
                    }
                }
            }
            return(ret);
        }
        void GetEngineTypes()
        {
            engineTypes = new List <EngineInfo>();

            foreach (var part in FlightGlobals.ActiveVessel.Parts)
            {
                foreach (PartModule m in part.Modules)
                {
                    EngineInfo engineInfo = new EngineInfo();
                    Log.Info("part: " + part.partInfo.title);
                    GetEngineType(m, ref engineInfo.engineType);


                    if (engineInfo.engineType != "")
                    {
                        Log.Info("engineType: [" + engineInfo + "]");
                        bool found = false;
                        foreach (var et in engineTypes)
                        {
                            Log.Info("et.engineType: " + et.engineType);
                            if (et.engineType == engineInfo.engineType)
                            {
                                found = true;
                                break;
                            }
                        }
                        if (!found)
                        {
                            engineTypes.Add(engineInfo);
                        }
                    }
                }
            }
            engineTypes.Sort((x, y) => string.Compare(x.engineType, y.engineType));
        }
Ejemplo n.º 6
0
 /// <summary>
 /// Cpp指针转换过程-EngineInformation
 /// </summary>
 /// <param name="Ptr"></param>
 /// <returns></returns>
 protected static EngineInfo Intptr2EngineInformation(IntPtr Ptr)
 {
     EngineInfo Ret = new EngineInfo();
     Ret.Version = "Error";
     try
     {
         EngineInformation_Cpp ret = (EngineInformation_Cpp)Marshal.PtrToStructure(Ptr, typeof(EngineInformation_Cpp));
         if (ret.Name != "")
         {
             Ret.Author = ret.Author;
             Ret.FlagItemCount = ret.FlagItemCount;
             Ret.Name = ret.Name;
             Ret.Usuage = ret.Usuage;
             Ret.Version = ret.Version;
             Ret.FlagItem = new EngineFlagItem[ret.FlagItemCount];
             int basePtr = ret.FlgItem.ToInt32();
             int PtrSize = Marshal.SizeOf(Ret.FlagItem[0]);
             for (int i = 0; i < Ret.FlagItemCount; i++)
             {
                 Ret.FlagItem[i] = (EngineFlagItem)Marshal.PtrToStructure(new IntPtr(basePtr + i * PtrSize), typeof(EngineFlagItem));
             }
             //Ret = ret;
         }
     }
     catch { ;}
     return Ret;
 }
Ejemplo n.º 7
0
 public DriverModels.EngineInfo GetInfo()
 {
     DriverModels.EngineInfo ret = new EngineInfo();
     ret.Version = "Error";
     if (!_isLegalPlugin)
     {
         return(ret);
     }
     try
     {
         IntPtr hModule = LoadLibrary(DllPath);
         if (hModule == IntPtr.Zero)
         {
             _isLegalPlugin = false;
         }
         else
         {
             IntPtr m = GetProcAddress(hModule, "GetInformation");
             if (m != IntPtr.Zero)
             {
                 GetInformationDelegate g = (GetInformationDelegate)Marshal.GetDelegateForFunctionPointer(m, typeof(GetInformationDelegate));
                 ret = Intptr2EngineInformation(g());
             }
             FreeLibrary(hModule);
         }
     }
     catch {; }
     return(ret);
 }
Ejemplo n.º 8
0
        public void Save(EngineInfo info)
        {
            var client = new RedisClient();
            var key    = new EngineKeys().GetInfoKey(info.Id);
            var json   = info.ToJson();

            client.Set(key, json);
        }
Ejemplo n.º 9
0
 private void PopulateEngineInfo(string engineInfoStr)
 {
     if (m_engineInfo != null)
     {
         return;
     }
     if (!string.IsNullOrWhiteSpace(engineInfoStr))
     {
         m_engineInfo = new EngineInfo(engineInfoStr);
     }
 }
 public static EngineDetails ToEngineDetails(this EngineInfo engineDetails)
 {
     return(new EngineDetails
     {
         RunningSince = (engineDetails.StartDate != DateTimeOffset.MinValue) ? engineDetails.StartDate.ToString(CultureInfo.InvariantCulture) : null,
         Version = engineDetails.Version,
         Engine = engineDetails.Name,
         State = engineDetails.State,
         InstanceId = engineDetails.InstanceId,
         InstanceName = engineDetails.InstanceName
     });
 }
Ejemplo n.º 11
0
        EngineInfo getEngineInfo()
        {
            var engineInfo = new EngineInfo();

            engineInfo.Indicators      = getIndicators();
            engineInfo.PlayToString    = _playTo.ToString();
            engineInfo.PrettyTickFiles = prettyTickDataFiles();
            engineInfo.ResponseName    = _responseName;
            //engineInfo.TotalNumberTicks = Convert.ToDouble(_historicalSimulator.TicksPresent);
            engineInfo.HistoricalSimulator = _historicalSimulator;

            return(engineInfo);
        }
Ejemplo n.º 12
0
            public void OnConnected_DbgThread_NoLock(EngineInfo engineInfo)
            {
                foreach (var info2 in infos)
                {
                    if (info2.EngineInfo == engineInfo)
                    {
                        OnBreak_DbgThread(engineInfo.Engine);
                        return;
                    }
                }
                var info = new Info(engineInfo);

                infos.Add(info);
                info.EngineInfo.Engine.Break();
                CheckIsDone_NoLock();
            }
Ejemplo n.º 13
0
        public async Task <int> StartAsync(EngineInfo engine)
        {
            if (engine == null)
            {
                throw new ArgumentNullException(nameof(engine));
            }

            var startInfo = new ProcessStartInfo(engine.ExePath)
            {
                WorkingDirectory = engine.InstallDir.FullName,
                UseShellExecute  = false
            };

            SetEnvironmentVariables(startInfo.EnvironmentVariables);

            return(await StartProcessAsync(startInfo));
        }
Ejemplo n.º 14
0
        private void btnSave_Click(object sender, EventArgs e)
        {
            google_api_key = txtGoogle_API_key.Text;
            EngineInfo        info  = new EngineInfo(google_api_key, engines);
            List <EngineInfo> infos = new List <EngineInfo>();

            infos.Add(info);
            if (!google_api_key.Equals(String.Empty) && !engines.Count.Equals(0))
            {
                Config.Instance.GenerateEnginesXML(infos);
                Config.Instance.Apis       = infos;
                Config.Instance.first_time = false;
                btnContinue.Enabled        = true;
            }
            else
            {
                MessageBox.Show(Lang.Eng.first_steps_save_error);
            }
        }
        public EngineResult Calculate(string id, EngineInfo engineInfo)
        {
            if (string.IsNullOrWhiteSpace(id))
            {
                throw new System.ArgumentNullException("id");
            }
            if (engineInfo == null)
            {
                throw new System.ArgumentNullException("engineInfo");
            }

            var result = new EngineResult
            {
                ValueA = "A",
                ValueB = "B"
            };

            return(result);
        }
Ejemplo n.º 16
0
        //mxd
        private void btnNewEngine_Click(object sender, EventArgs e)
        {
            // Set initial directory?
            if (testapplication.Text.Length > 0)
            {
                try { testprogramdialog.InitialDirectory = Path.GetDirectoryName(testapplication.Text); }
                catch (Exception) { }
            }

            // Browse for test program
            if (testprogramdialog.ShowDialog() == DialogResult.OK)
            {
                preventchanges = true;

                // Add new EngineInfo
                EngineInfo newInfo = new EngineInfo();
                newInfo.TestSkill = (int)Math.Ceiling(gameconfig.Skills.Count / 2f);                 // Set Medium skill level
                configinfo.TestEngines.Add(newInfo);
                configinfo.Changed = true;

                // Store current engine name
                if (!String.IsNullOrEmpty(cbEngineSelector.Text))
                {
                    configinfo.TestProgramName = cbEngineSelector.Text;
                }

                // Refresh engines list
                cbEngineSelector.Items.Clear();
                foreach (EngineInfo info in configinfo.TestEngines)
                {
                    cbEngineSelector.Items.Add(info.TestProgramName);
                }

                cbEngineSelector.SelectedIndex = configinfo.TestEngines.Count - 1;
                btnRemoveEngine.Enabled        = true;

                preventchanges = false;

                // Set engine path
                testapplication.Text = testprogramdialog.FileName;
            }
        }
Ejemplo n.º 17
0
        /**
         * Get the road types the given company can build.
         * @param company the company to get the roadtypes for.
         * @return the road types.
         */
        public static RoadTypes GetCompanyRoadtypes(CompanyID company)
        {
            RoadTypes rt = RoadTypes.ROADTYPES_NONE;

            Engine e;

            FOR_ALL_ENGINES_OF_TYPE(e, VEH_ROAD)
            {
                EngineInfo ei = e.info;

                if (BitMath.HasBit(ei.climates, _settings_game.game_creation.landscape) &&
                    (BitMath.HasBit(e.company_avail, company) ||
                     DateConstants._date >= e.intro_date + DateConstants.DAYS_IN_YEAR))
                {
                    BitMath.SetBit(rt, BitMath.HasBit(ei.misc_flags, EF_ROAD_TRAM) ? ROADTYPE_TRAM : ROADTYPE_ROAD);
                }
            }

            return(rt);
        }
Ejemplo n.º 18
0
        void Step_DbgThread(DbgStepperImpl stepper, object stepperTag, DbgEngineStepKind step, bool singleProcess)
        {
            Dispatcher.VerifyAccess();

            var        infos             = new List <EngineInfo>();
            EngineInfo stepperEngineInfo = null;

            lock (lockObj) {
                var process = stepper.Process;
                var runtime = stepper.Runtime;
                foreach (var info in engines)
                {
                    if (info.Runtime == runtime)
                    {
                        stepperEngineInfo = info;
                    }
                    if (info.Process == process || !singleProcess)
                    {
                        infos.Add(info);
                    }
                }
            }

            if (stepperEngineInfo?.Process?.State != DbgProcessState.Paused)
            {
                RaiseStepperError_DbgThread(stepper, dnSpy_Debugger_Resources.ProcessIsNotPaused);
                return;
            }

            Debug.Assert(infos.Contains(stepperEngineInfo));
            RunEngines_DbgThread(infos.ToArray(), info => {
                if (info == stepperEngineInfo)
                {
                    stepper.EngineStepper.Step(stepperTag, step);
                }
                else
                {
                    info.Engine.Run();
                }
            });
        }
Ejemplo n.º 19
0
        public EngineContext(EngineSettings settings, DataManager data)
        {
            Data = data;

            Settings = settings;

            Console = new ConsoleHelper(Settings);

            Clock = new EngineClock(Settings, Console);

            Info = new EngineInfo(Clock.StartTime, Settings);

            Log = new LogWriter(Settings.EngineId, data.Client);

            World = new GameEnvironment(this);

            if (Settings.IsVerbose)
            {
                Console.WriteDebugLine("Constructing engine context");
            }
        }
Ejemplo n.º 20
0
        private void PopulateEngineInfo(string engineInfoStr)
        {
            if (m_engineInfo != null)
            {
                return;
            }
            if (!string.IsNullOrWhiteSpace(engineInfoStr))
            {
                m_engineInfo = new EngineInfo(engineInfoStr);
            }

            //if (m_engineInfo != null)
            //{
            //    Console.WriteLine("Print EngineInfo:");
            //    foreach (var res in m_engineInfo.SupportedResources)
            //    {
            //        Console.Write("\t {0}  {1} ", res.Type, res.Description);
            //        foreach (string ext in res.FileExts)
            //            Console.Write(ext + "  ");
            //        Console.WriteLine();
            //    }
            //}
        }
Ejemplo n.º 21
0
        public void Update(Vessel vessel)
        {
            if (vessel.rigidbody == null)
            {
                return;                           //if we try to update before rigidbodies exist we spam the console with NullPointerExceptions.
            }
            //if (vessel.packed) return;

            // To investigate some strange error
            if ((vessel.mainBody == null || (object)(vessel.mainBody) == null) && counter == 0)
            {
                if ((object)(vessel.mainBody) == null)
                {
                    MechJebCore.print("vessel.mainBody is proper null");
                }
                else
                {
                    MechJebCore.print("vessel.mainBody is Unity null");
                }

                counter = counter++ % 100;
            }


            time   = Planetarium.GetUniversalTime();
            deltaT = TimeWarp.fixedDeltaTime;

            CoM = vessel.findWorldCenterOfMass();
            up  = (CoM - vessel.mainBody.position).normalized;

            Rigidbody rigidBody = vessel.rootPart.rigidbody;

            if (rigidBody != null)
            {
                rootPartPos = rigidBody.position;
            }

            north                 = Vector3d.Exclude(up, (vessel.mainBody.position + vessel.mainBody.transform.up * (float)vessel.mainBody.Radius) - CoM).normalized;
            east                  = vessel.mainBody.getRFrmVel(CoM).normalized;
            forward               = vessel.GetTransform().up;
            rotationSurface       = Quaternion.LookRotation(north, up);
            rotationVesselSurface = Quaternion.Inverse(Quaternion.Euler(90, 0, 0) * Quaternion.Inverse(vessel.GetTransform().rotation) * rotationSurface);

//            velocityVesselOrbit = vessel.orbit.GetVel();
//            velocityVesselOrbitUnit = velocityVesselOrbit.normalized;
//            velocityVesselSurface = velocityVesselOrbit - vessel.mainBody.getRFrmVel(CoM);
//            velocityVesselSurfaceUnit = velocityVesselSurface.normalized;
            velocityMainBodySurface = rotationSurface * vessel.srf_velocity;

            horizontalOrbit   = Vector3d.Exclude(up, vessel.obt_velocity).normalized;
            horizontalSurface = Vector3d.Exclude(up, vessel.srf_velocity).normalized;

            angularVelocity = Quaternion.Inverse(vessel.GetTransform().rotation) * vessel.rigidbody.angularVelocity;

            radialPlusSurface = Vector3d.Exclude(vessel.srf_velocity, up).normalized;
            radialPlus        = Vector3d.Exclude(vessel.obt_velocity, up).normalized;
            normalPlusSurface = -Vector3d.Cross(radialPlusSurface, vessel.srf_velocity.normalized);
            normalPlus        = -Vector3d.Cross(radialPlus, vessel.obt_velocity.normalized);

            gravityForce = FlightGlobals.getGeeForceAtPosition(CoM);
            localg       = gravityForce.magnitude;

            speedOrbital.value           = vessel.obt_velocity.magnitude;
            speedSurface.value           = vessel.srf_velocity.magnitude;
            speedVertical.value          = Vector3d.Dot(vessel.srf_velocity, up);
            speedSurfaceHorizontal.value = Vector3d.Exclude(up, vessel.srf_velocity).magnitude; //(velocityVesselSurface - (speedVertical * up)).magnitude;
            speedOrbitHorizontal         = (vessel.obt_velocity - (speedVertical * up)).magnitude;

            vesselHeading.value = rotationVesselSurface.eulerAngles.y;
            vesselPitch.value   = (rotationVesselSurface.eulerAngles.x > 180) ? (360.0 - rotationVesselSurface.eulerAngles.x) : -rotationVesselSurface.eulerAngles.x;
            vesselRoll.value    = (rotationVesselSurface.eulerAngles.z > 180) ? (rotationVesselSurface.eulerAngles.z - 360.0) : rotationVesselSurface.eulerAngles.z;

            altitudeASL.value = vessel.mainBody.GetAltitude(CoM);
            //RaycastHit sfc;
            //if (Physics.Raycast(CoM, -up, out sfc, (float)altitudeASL + 10000.0F, 1 << 15))
            //{
            //    altitudeTrue.value = sfc.distance;
            //}
            //else if (vessel.mainBody.pqsController != null)
            //{
            //    // from here: http://kerbalspaceprogram.com/forum/index.php?topic=10324.msg161923#msg161923
            //    altitudeTrue.value = vessel.mainBody.GetAltitude(CoM) - (vessel.mainBody.pqsController.GetSurfaceHeight(QuaternionD.AngleAxis(vessel.mainBody.GetLongitude(CoM), Vector3d.down) * QuaternionD.AngleAxis(vessel.mainBody.GetLatitude(CoM), Vector3d.forward) * Vector3d.right) - vessel.mainBody.pqsController.radius);
            //}
            //else
            //{
            //    altitudeTrue.value = vessel.mainBody.GetAltitude(CoM);
            //}

            //double surfaceAltitudeASL = altitudeASL - altitudeTrue;

            double surfaceAltitudeASL = vessel.mainBody.pqsController != null ? vessel.pqsAltitude : 0d;

            altitudeTrue.value = altitudeASL - surfaceAltitudeASL;

            altitudeBottom = altitudeTrue;
            foreach (Part p in vessel.parts)
            {
                if (p.collider != null)
                {
                    Vector3d bottomPoint   = p.collider.ClosestPointOnBounds(vessel.mainBody.position);
                    double   partBottomAlt = vessel.mainBody.GetAltitude(bottomPoint) - surfaceAltitudeASL;
                    altitudeBottom = Math.Max(0, Math.Min(altitudeBottom, partBottomAlt));
                }
            }

            double atmosphericPressure = FlightGlobals.getStaticPressure(altitudeASL, vessel.mainBody);

            if (atmosphericPressure < vessel.mainBody.atmosphereMultiplier * 1e-6)
            {
                atmosphericPressure = 0;
            }
            atmosphericDensity      = FlightGlobals.getAtmDensity(atmosphericPressure);
            atmosphericDensityGrams = atmosphericDensity * 1000;

            orbitApA.value      = vessel.orbit.ApA;
            orbitPeA.value      = vessel.orbit.PeA;
            orbitPeriod.value   = vessel.orbit.period;
            orbitTimeToAp.value = vessel.orbit.timeToAp;
            if (vessel.orbit.eccentricity < 1)
            {
                orbitTimeToPe.value = vessel.orbit.timeToPe;
            }
            else
            {
                orbitTimeToPe.value = -vessel.orbit.meanAnomaly / (2 * Math.PI / vessel.orbit.period);
            }
            orbitLAN.value = vessel.orbit.LAN;
            orbitArgumentOfPeriapsis.value = vessel.orbit.argumentOfPeriapsis;
            orbitInclination.value         = vessel.orbit.inclination;
            orbitEccentricity.value        = vessel.orbit.eccentricity;
            orbitSemiMajorAxis.value       = vessel.orbit.semiMajorAxis;
            latitude.value  = vessel.mainBody.GetLatitude(CoM);
            longitude.value = MuUtils.ClampDegrees180(vessel.mainBody.GetLongitude(CoM));

            if (vessel.mainBody != Planetarium.fetch.Sun)
            {
                Vector3d delta = vessel.mainBody.getPositionAtUT(Planetarium.GetUniversalTime() + 1) - vessel.mainBody.getPositionAtUT(Planetarium.GetUniversalTime() - 1);
                Vector3d plUp  = Vector3d.Cross(vessel.mainBody.getPositionAtUT(Planetarium.GetUniversalTime()) - vessel.mainBody.referenceBody.getPositionAtUT(Planetarium.GetUniversalTime()), vessel.mainBody.getPositionAtUT(Planetarium.GetUniversalTime() + vessel.mainBody.orbit.period / 4) - vessel.mainBody.referenceBody.getPositionAtUT(Planetarium.GetUniversalTime() + vessel.mainBody.orbit.period / 4)).normalized;
                angleToPrograde = MuUtils.ClampDegrees360((((vessel.orbit.inclination > 90) || (vessel.orbit.inclination < -90)) ? 1 : -1) * ((Vector3)up).AngleInPlane(plUp, delta));
            }
            else
            {
                angleToPrograde = 0;
            }

            mainBody = vessel.mainBody;

            radius = (CoM - vessel.mainBody.position).magnitude;

            mass = massDrag = torqueThrustPYAvailable = 0;
            thrustVectorLastFrame   = new Vector3d();
            thrustVectorMaxThrottle = new Vector3d();
            thrustVectorMinThrottle = new Vector3d();
            torqueAvailable         = new Vector3d();
            rcsThrustAvailable      = new Vector6();
            rcsTorqueAvailable      = new Vector6();
            ctrlTorqueAvailable     = new Vector6();

            EngineInfo einfo = new EngineInfo(CoM);
            IntakeInfo iinfo = new IntakeInfo();

            parachutes = new List <ModuleParachute>();

            var rcsbal = vessel.GetMasterMechJeb().rcsbal;

            if (vessel.ActionGroups[KSPActionGroup.RCS] && rcsbal.enabled)
            {
                Vector3d rot = Vector3d.zero;
                foreach (Vector6.Direction dir6 in Enum.GetValues(typeof(Vector6.Direction)))
                {
                    Vector3d dir = Vector6.directions[dir6];
                    double[] throttles;
                    List <RCSSolver.Thruster> thrusters;
                    rcsbal.GetThrottles(dir, out throttles, out thrusters);
                    if (throttles != null)
                    {
                        for (int i = 0; i < throttles.Length; i++)
                        {
                            if (throttles[i] > 0)
                            {
                                Vector3d force = thrusters[i].GetThrust(dir, rot);
                                rcsThrustAvailable.Add(vessel.GetTransform().InverseTransformDirection(dir * Vector3d.Dot(force * throttles[i], dir)));
                            }
                        }
                    }
                }
            }

            hasMFE = false;

            foreach (Part p in vessel.parts)
            {
                if (p.IsPhysicallySignificant())
                {
                    double partMass = p.TotalMass();
                    mass     += partMass;
                    massDrag += partMass * p.maximum_drag;
                }

                if (vessel.ActionGroups[KSPActionGroup.RCS] && !rcsbal.enabled)
                {
                    foreach (ModuleRCS pm in p.Modules.OfType <ModuleRCS>())
                    {
                        double   maxT         = pm.thrusterPower;
                        Vector3d partPosition = p.Rigidbody.worldCenterOfMass - CoM;

                        if ((pm.isEnabled) && (!pm.isJustForShow))
                        {
                            foreach (Transform t in pm.thrusterTransforms)
                            {
                                Vector3d thrusterThrust = vessel.GetTransform().InverseTransformDirection(-t.up.normalized) * pm.thrusterPower;
                                rcsThrustAvailable.Add(thrusterThrust);
                                Vector3d thrusterTorque = Vector3.Cross(vessel.GetTransform().InverseTransformDirection(partPosition), thrusterThrust);
                                rcsTorqueAvailable.Add(thrusterTorque);
                            }
                        }
                    }
                }

                if (p is ControlSurface)
                {
                    Vector3d       partPosition = p.Rigidbody.worldCenterOfMass - CoM;
                    ControlSurface cs           = (p as ControlSurface);
                    Vector3d       airSpeed     = vessel.srf_velocity + Vector3.Cross(cs.Rigidbody.angularVelocity, cs.transform.position - cs.Rigidbody.position);
                    // Air Speed is velocityVesselSurface
                    // AddForceAtPosition seems to need the airspeed vector rotated with the flap rotation x its surface
                    Quaternion airSpeedRot   = Quaternion.AngleAxis(cs.ctrlSurfaceRange * cs.ctrlSurfaceArea, cs.transform.rotation * cs.pivotAxis);
                    Vector3    ctrlTroquePos = vessel.GetTransform().InverseTransformDirection(Vector3.Cross(partPosition, cs.getLiftVector(airSpeedRot * airSpeed)));
                    Vector3    ctrlTroqueNeg = vessel.GetTransform().InverseTransformDirection(Vector3.Cross(partPosition, cs.getLiftVector(Quaternion.Inverse(airSpeedRot) * airSpeed)));
                    ctrlTorqueAvailable.Add(ctrlTroquePos);
                    ctrlTorqueAvailable.Add(ctrlTroqueNeg);
                }

                if (p is CommandPod)
                {
                    torqueAvailable += Vector3d.one * Math.Abs(((CommandPod)p).rotPower);
                }

                foreach (VesselStatePartExtension vspe in vesselStatePartExtensions)
                {
                    vspe(p);
                }

                foreach (PartModule pm in p.Modules)
                {
                    if (!pm.isEnabled)
                    {
                        continue;
                    }

                    if (pm is ModuleReactionWheel)
                    {
                        ModuleReactionWheel rw = (ModuleReactionWheel)pm;
                        // I had to remove the test for active in .23 since the new ressource system reply to the RW that
                        // there is no energy available when the RW do tiny adjustement.
                        // I replaceed it with a test that check if there is electricity anywhere on the ship.
                        // Let's hope we don't get reaction wheel that use something else
                        //if (rw.wheelState == ModuleReactionWheel.WheelState.Active && !rw.stateString.Contains("Not enough"))
                        if (rw.wheelState == ModuleReactionWheel.WheelState.Active && vessel.HasElectricCharge())
                        {
                            torqueAvailable += new Vector3d(rw.PitchTorque, rw.RollTorque, rw.YawTorque);
                        }
                    }
                    else if (pm is ModuleEngines)
                    {
                        einfo.AddNewEngine(pm as ModuleEngines);
                    }
                    else if (pm is ModuleEnginesFX)
                    {
                        einfo.AddNewEngine(pm as ModuleEnginesFX);
                    }
                    else if (pm is ModuleResourceIntake)
                    {
                        iinfo.addIntake(pm as ModuleResourceIntake);
                    }
                    else if (pm is ModuleParachute)
                    {
                        parachutes.Add(pm as ModuleParachute);
                    }
                    else if (pm is ModuleControlSurface)
                    {
                        // TODO : Tweakable for ignorePitch / ignoreYaw  / ignoreRoll
                        ModuleControlSurface cs           = (pm as ModuleControlSurface);
                        Vector3d             partPosition = p.Rigidbody.worldCenterOfMass - CoM;

                        Vector3d airSpeed = vessel.srf_velocity + Vector3.Cross(cs.part.Rigidbody.angularVelocity, cs.transform.position - cs.part.Rigidbody.position);

                        Quaternion airSpeedRot = Quaternion.AngleAxis(cs.ctrlSurfaceRange * cs.ctrlSurfaceArea, cs.transform.rotation * Vector3.right);

                        Vector3 ctrlTroquePos = vessel.GetTransform().InverseTransformDirection(Vector3.Cross(partPosition, cs.getLiftVector(airSpeedRot * airSpeed)));
                        Vector3 ctrlTroqueNeg = vessel.GetTransform().InverseTransformDirection(Vector3.Cross(partPosition, cs.getLiftVector(Quaternion.Inverse(airSpeedRot) * airSpeed)));
                        ctrlTorqueAvailable.Add(ctrlTroquePos);
                        ctrlTorqueAvailable.Add(ctrlTroqueNeg);
                    }

                    if (pm.ClassName == "ModuleEngineConfigs" || pm.ClassName == "ModuleHybridEngine" || pm.ClassName == "ModuleHybridEngines")
                    {
                        hasMFE = true;
                    }

                    foreach (VesselStatePartModuleExtension vspme in vesselStatePartModuleExtensions)
                    {
                        vspme(pm);
                    }
                }
            }

            // Consider all the parachutes
            {
                bool tempParachuteDeployed = false;
                foreach (ModuleParachute p in parachutes)
                {
                    if (p.deploymentState == ModuleParachute.deploymentStates.DEPLOYED || p.deploymentState == ModuleParachute.deploymentStates.SEMIDEPLOYED)
                    {
                        tempParachuteDeployed = true;
                        break;
                    }
                }
                this.parachuteDeployed = tempParachuteDeployed;
            }

            torqueAvailable += Vector3d.Max(rcsTorqueAvailable.positive, rcsTorqueAvailable.negative);   // Should we use Max or Min ?
            torqueAvailable += Vector3d.Max(ctrlTorqueAvailable.positive, ctrlTorqueAvailable.negative); // Should we use Max or Min ?

            thrustVectorMaxThrottle += einfo.thrustMax;
            thrustVectorMinThrottle += einfo.thrustMin;
            thrustVectorLastFrame   += einfo.thrustCurrent;
            torqueThrustPYAvailable += einfo.torqueThrustPYAvailable;

            if (thrustVectorMaxThrottle.magnitude == 0 && vessel.ActionGroups[KSPActionGroup.RCS])
            {
                rcsThrust = true;
                thrustVectorMaxThrottle += (Vector3d)(vessel.transform.up) * rcsThrustAvailable.down;
            }
            else
            {
                rcsThrust = false;
            }

            // Convert the resource information from the einfo and iinfo format
            // to the more useful ResourceInfo format.
            resources = new Dictionary <int, ResourceInfo>();
            foreach (var info in einfo.resourceRequired)
            {
                int id  = info.Key;
                var req = info.Value;
                resources[id] = new ResourceInfo(
                    PartResourceLibrary.Instance.GetDefinition(id),
                    req.requiredLastFrame,
                    req.requiredAtMaxThrottle,
                    iinfo.getIntakes(id));
            }

            int intakeAirId = PartResourceLibrary.Instance.GetDefinition("IntakeAir").id;

            intakeAir           = 0;
            intakeAirNeeded     = 0;
            intakeAirAtMax      = 0;
            intakeAirAllIntakes = 0;
            if (resources.ContainsKey(intakeAirId))
            {
                intakeAir           = resources[intakeAirId].intakeProvided;
                intakeAirAllIntakes = resources[intakeAirId].intakeAvailable;
                intakeAirNeeded     = resources[intakeAirId].required;
                intakeAirAtMax      = resources[intakeAirId].requiredAtMaxThrottle;
            }

            angularMomentum = new Vector3d(angularVelocity.x * MoI.x, angularVelocity.y * MoI.y, angularVelocity.z * MoI.z);

            inertiaTensor = new Matrix3x3();
            foreach (Part p in vessel.parts)
            {
                if (p.Rigidbody == null)
                {
                    continue;
                }

                //Compute the contributions to the vessel inertia tensor due to the part inertia tensor
                Vector3d   principalMoments = p.Rigidbody.inertiaTensor;
                Quaternion princAxesRot     = Quaternion.Inverse(vessel.GetTransform().rotation) * p.transform.rotation * p.Rigidbody.inertiaTensorRotation;
                Quaternion invPrincAxesRot  = Quaternion.Inverse(princAxesRot);

                for (int i = 0; i < 3; i++)
                {
                    Vector3d iHat = Vector3d.zero;
                    iHat[i] = 1;
                    for (int j = 0; j < 3; j++)
                    {
                        Vector3d jHat = Vector3d.zero;
                        jHat[j]              = 1;
                        inertiaTensor[i, j] += Vector3d.Dot(iHat, princAxesRot * Vector3d.Scale(principalMoments, invPrincAxesRot * jHat));
                    }
                }

                //Compute the contributions to the vessel inertia tensor due to the part mass and position
                double  partMass     = p.TotalMass();
                Vector3 partPosition = vessel.GetTransform().InverseTransformDirection(p.Rigidbody.worldCenterOfMass - CoM);

                for (int i = 0; i < 3; i++)
                {
                    inertiaTensor[i, i] += partMass * partPosition.sqrMagnitude;

                    for (int j = 0; j < 3; j++)
                    {
                        inertiaTensor[i, j] += -partMass * partPosition[i] * partPosition[j];
                    }
                }
            }

            MoI             = new Vector3d(inertiaTensor[0, 0], inertiaTensor[1, 1], inertiaTensor[2, 2]);
            angularMomentum = inertiaTensor * angularVelocity;
        }
Ejemplo n.º 22
0
        public void Update(Vessel vessel)
        {
            if (vessel.rigidbody == null)
            {
                return;                           //if we try to update before rigidbodies exist we spam the console with NullPointerExceptions.
            }
            //if (vessel.packed) return;

            time   = Planetarium.GetUniversalTime();
            deltaT = TimeWarp.fixedDeltaTime;

            CoM = vessel.findWorldCenterOfMass();
            up  = (CoM - vessel.mainBody.position).normalized;

            Rigidbody rigidBody = vessel.rootPart.rigidbody;

            if (rigidBody != null)
            {
                rootPartPos = rigidBody.position;
            }

            north                 = Vector3d.Exclude(up, (vessel.mainBody.position + vessel.mainBody.transform.up * (float)vessel.mainBody.Radius) - CoM).normalized;
            east                  = vessel.mainBody.getRFrmVel(CoM).normalized;
            forward               = vessel.GetTransform().up;
            rotationSurface       = Quaternion.LookRotation(north, up);
            rotationVesselSurface = Quaternion.Inverse(Quaternion.Euler(90, 0, 0) * Quaternion.Inverse(vessel.GetTransform().rotation) * rotationSurface);

            velocityVesselOrbit       = vessel.orbit.GetVel();
            velocityVesselOrbitUnit   = velocityVesselOrbit.normalized;
            velocityVesselSurface     = velocityVesselOrbit - vessel.mainBody.getRFrmVel(CoM);
            velocityVesselSurfaceUnit = velocityVesselSurface.normalized;
            velocityMainBodySurface   = rotationSurface * velocityVesselSurface;

            horizontalOrbit   = Vector3d.Exclude(up, velocityVesselOrbit).normalized;
            horizontalSurface = Vector3d.Exclude(up, velocityVesselSurface).normalized;

            angularVelocity = Quaternion.Inverse(vessel.GetTransform().rotation) * vessel.rigidbody.angularVelocity;

            radialPlusSurface = Vector3d.Exclude(velocityVesselSurface, up).normalized;
            radialPlus        = Vector3d.Exclude(velocityVesselOrbit, up).normalized;
            normalPlusSurface = -Vector3d.Cross(radialPlusSurface, velocityVesselSurfaceUnit);
            normalPlus        = -Vector3d.Cross(radialPlus, velocityVesselOrbitUnit);

            gravityForce = FlightGlobals.getGeeForceAtPosition(CoM);
            localg       = gravityForce.magnitude;

            speedOrbital.value           = velocityVesselOrbit.magnitude;
            speedSurface.value           = velocityVesselSurface.magnitude;
            speedVertical.value          = Vector3d.Dot(velocityVesselSurface, up);
            speedSurfaceHorizontal.value = (velocityVesselSurface - (speedVertical * up)).magnitude;
            speedOrbitHorizontal         = (velocityVesselOrbit - (speedVertical * up)).magnitude;

            vesselHeading.value = rotationVesselSurface.eulerAngles.y;
            vesselPitch.value   = (rotationVesselSurface.eulerAngles.x > 180) ? (360.0 - rotationVesselSurface.eulerAngles.x) : -rotationVesselSurface.eulerAngles.x;
            vesselRoll.value    = (rotationVesselSurface.eulerAngles.z > 180) ? (rotationVesselSurface.eulerAngles.z - 360.0) : rotationVesselSurface.eulerAngles.z;

            altitudeASL.value = vessel.mainBody.GetAltitude(CoM);
            RaycastHit sfc;

            if (Physics.Raycast(CoM, -up, out sfc, (float)altitudeASL + 10000.0F, 1 << 15))
            {
                altitudeTrue.value = sfc.distance;
            }
            else if (vessel.mainBody.pqsController != null)
            {
                // from here: http://kerbalspaceprogram.com/forum/index.php?topic=10324.msg161923#msg161923
                altitudeTrue.value = vessel.mainBody.GetAltitude(CoM) - (vessel.mainBody.pqsController.GetSurfaceHeight(QuaternionD.AngleAxis(vessel.mainBody.GetLongitude(CoM), Vector3d.down) * QuaternionD.AngleAxis(vessel.mainBody.GetLatitude(CoM), Vector3d.forward) * Vector3d.right) - vessel.mainBody.pqsController.radius);
            }
            else
            {
                altitudeTrue.value = vessel.mainBody.GetAltitude(CoM);
            }

            double surfaceAltitudeASL = altitudeASL - altitudeTrue;

            altitudeBottom = altitudeTrue;
            foreach (Part p in vessel.parts)
            {
                if (p.collider != null)
                {
                    Vector3d bottomPoint   = p.collider.ClosestPointOnBounds(vessel.mainBody.position);
                    double   partBottomAlt = vessel.mainBody.GetAltitude(bottomPoint) - surfaceAltitudeASL;
                    altitudeBottom = Math.Max(0, Math.Min(altitudeBottom, partBottomAlt));
                }
            }

            double atmosphericPressure = FlightGlobals.getStaticPressure(altitudeASL, vessel.mainBody);

            if (atmosphericPressure < vessel.mainBody.atmosphereMultiplier * 1e-6)
            {
                atmosphericPressure = 0;
            }
            atmosphericDensity      = FlightGlobals.getAtmDensity(atmosphericPressure);
            atmosphericDensityGrams = atmosphericDensity * 1000;

            orbitApA.value      = vessel.orbit.ApA;
            orbitPeA.value      = vessel.orbit.PeA;
            orbitPeriod.value   = vessel.orbit.period;
            orbitTimeToAp.value = vessel.orbit.timeToAp;
            if (vessel.orbit.eccentricity < 1)
            {
                orbitTimeToPe.value = vessel.orbit.timeToPe;
            }
            else
            {
                orbitTimeToPe.value = -vessel.orbit.meanAnomaly / (2 * Math.PI / vessel.orbit.period);
            }
            orbitLAN.value = vessel.orbit.LAN;
            orbitArgumentOfPeriapsis.value = vessel.orbit.argumentOfPeriapsis;
            orbitInclination.value         = vessel.orbit.inclination;
            orbitEccentricity.value        = vessel.orbit.eccentricity;
            orbitSemiMajorAxis.value       = vessel.orbit.semiMajorAxis;
            latitude.value  = vessel.mainBody.GetLatitude(CoM);
            longitude.value = MuUtils.ClampDegrees180(vessel.mainBody.GetLongitude(CoM));

            if (vessel.mainBody != Planetarium.fetch.Sun)
            {
                Vector3d delta = vessel.mainBody.getPositionAtUT(Planetarium.GetUniversalTime() + 1) - vessel.mainBody.getPositionAtUT(Planetarium.GetUniversalTime() - 1);
                Vector3d plUp  = Vector3d.Cross(vessel.mainBody.getPositionAtUT(Planetarium.GetUniversalTime()) - vessel.mainBody.referenceBody.getPositionAtUT(Planetarium.GetUniversalTime()), vessel.mainBody.getPositionAtUT(Planetarium.GetUniversalTime() + vessel.mainBody.orbit.period / 4) - vessel.mainBody.referenceBody.getPositionAtUT(Planetarium.GetUniversalTime() + vessel.mainBody.orbit.period / 4)).normalized;
                angleToPrograde = MuUtils.ClampDegrees360((((vessel.orbit.inclination > 90) || (vessel.orbit.inclination < -90)) ? 1 : -1) * ((Vector3)up).AngleInPlane(plUp, delta));
            }
            else
            {
                angleToPrograde = 0;
            }

            mainBody = vessel.mainBody;

            radius = (CoM - vessel.mainBody.position).magnitude;

            mass = thrustAvailable = thrustMinimum = massDrag = torqueRAvailable = torquePYAvailable = torqueThrustPYAvailable = 0;
            rcsThrustAvailable = new Vector6();
            rcsTorqueAvailable = new Vector6();

            EngineInfo einfo = new EngineInfo(forward, CoM);
            IntakeInfo iinfo = new IntakeInfo();

            var rcsbal = vessel.GetMasterMechJeb().rcsbal;

            if (vessel.ActionGroups[KSPActionGroup.RCS] && rcsbal.enabled)
            {
                Vector3d rot = Vector3d.zero;
                foreach (Vector6.Direction dir6 in Enum.GetValues(typeof(Vector6.Direction)))
                {
                    Vector3d dir = Vector6.directions[dir6];
                    double[] throttles;
                    List <RCSSolver.Thruster> thrusters;
                    rcsbal.GetThrottles(dir, out throttles, out thrusters);
                    if (throttles != null)
                    {
                        for (int i = 0; i < throttles.Length; i++)
                        {
                            if (throttles[i] > 0)
                            {
                                Vector3d force = thrusters[i].GetThrust(dir, rot);
                                rcsThrustAvailable.Add(dir * Vector3d.Dot(force * throttles[i], dir));
                            }
                        }
                    }
                }
            }

            foreach (Part p in vessel.parts)
            {
                if (p.physicalSignificance != Part.PhysicalSignificance.NONE)
                {
                    double partMass = p.TotalMass();
                    mass     += partMass;
                    massDrag += partMass * p.maximum_drag;
                }

                if (vessel.ActionGroups[KSPActionGroup.RCS] && !rcsbal.enabled)
                {
                    foreach (ModuleRCS pm in p.Modules.OfType <ModuleRCS>())
                    {
                        double maxT = pm.thrusterPower;

                        if ((pm.isEnabled) && (!pm.isJustForShow))
                        {
                            torqueRAvailable += maxT;
                            if (p.Rigidbody != null)
                            {
                                torquePYAvailable += maxT * (p.Rigidbody.worldCenterOfMass - CoM).magnitude;
                            }

                            foreach (Transform t in pm.thrusterTransforms)
                            {
                                rcsThrustAvailable.Add(-t.up * pm.thrusterPower);
                            }
                        }
                    }
                }
                if (p is CommandPod)
                {
                    torqueRAvailable  += Math.Abs(((CommandPod)p).rotPower);
                    torquePYAvailable += Math.Abs(((CommandPod)p).rotPower);
                }

                foreach (PartModule pm in p.Modules)
                {
                    if (!pm.isEnabled)
                    {
                        continue;
                    }

                    if (pm is ModuleEngines)
                    {
                        einfo.AddNewEngine(pm as ModuleEngines);
                    }
                    else if (pm is ModuleResourceIntake)
                    {
                        iinfo.addIntake(pm as ModuleResourceIntake);
                    }
                }
            }

            thrustAvailable         += einfo.thrustAvailable;
            thrustMinimum           += einfo.thrustMinimum;
            torqueThrustPYAvailable += einfo.torqueThrustPYAvailable;

            // Convert the resource information from the einfo and iinfo format
            // to the more useful ResourceInfo format.
            resources = new Dictionary <int, ResourceInfo>();
            foreach (var info in einfo.resourceRequired)
            {
                int id  = info.Key;
                var req = info.Value;
                resources[id] = new ResourceInfo(
                    PartResourceLibrary.Instance.GetDefinition(id),
                    req.requiredLastFrame,
                    req.requiredAtMaxThrottle,
                    iinfo.getIntakes(id));
            }

            int intakeAirId = PartResourceLibrary.Instance.GetDefinition("IntakeAir").id;

            intakeAir       = 0;
            intakeAirNeeded = 0;
            intakeAirAtMax  = 0;
            if (resources.ContainsKey(intakeAirId))
            {
                intakeAir       = resources[intakeAirId].intakeProvided;
                intakeAirNeeded = resources[intakeAirId].required;
                intakeAirAtMax  = resources[intakeAirId].requiredAtMaxThrottle;
            }

            angularMomentum = new Vector3d(angularVelocity.x * MoI.x, angularVelocity.y * MoI.y, angularVelocity.z * MoI.z);

            maxThrustAccel = thrustAvailable / mass;
            minThrustAccel = thrustMinimum / mass;

            inertiaTensor = new Matrix3x3();
            foreach (Part p in vessel.parts)
            {
                if (p.Rigidbody == null)
                {
                    continue;
                }

                //Compute the contributions to the vessel inertia tensor due to the part inertia tensor
                Vector3d   principalMoments = p.Rigidbody.inertiaTensor;
                Quaternion princAxesRot     = Quaternion.Inverse(vessel.GetTransform().rotation) * p.transform.rotation * p.Rigidbody.inertiaTensorRotation;
                Quaternion invPrincAxesRot  = Quaternion.Inverse(princAxesRot);

                for (int i = 0; i < 3; i++)
                {
                    Vector3d iHat = Vector3d.zero;
                    iHat[i] = 1;
                    for (int j = 0; j < 3; j++)
                    {
                        Vector3d jHat = Vector3d.zero;
                        jHat[j]              = 1;
                        inertiaTensor[i, j] += Vector3d.Dot(iHat, princAxesRot * Vector3d.Scale(principalMoments, invPrincAxesRot * jHat));
                    }
                }

                //Compute the contributions to the vessel inertia tensor due to the part mass and position
                double  partMass     = p.TotalMass();
                Vector3 partPosition = vessel.transform.InverseTransformDirection(p.Rigidbody.worldCenterOfMass - CoM);

                for (int i = 0; i < 3; i++)
                {
                    inertiaTensor[i, i] += partMass * partPosition.sqrMagnitude;

                    for (int j = 0; j < 3; j++)
                    {
                        inertiaTensor[i, j] += -partMass * partPosition[i] * partPosition[j];
                    }
                }
            }

            MoI             = new Vector3d(inertiaTensor[0, 0], inertiaTensor[1, 1], inertiaTensor[2, 2]);
            angularMomentum = inertiaTensor * angularVelocity;
        }
Ejemplo n.º 23
0
 public void RegisterControl(EngineInfo info)
 {
     controls.Add (info);
 }
Ejemplo n.º 24
0
        private void CreateControl(string engine)
        {
            if (engine == null)
                engine = App.Session.Engine;

            string id, args;
            GetIDFromEngine (engine, out id, out args);
            string msg = null;
            try
            {
                foreach (EngineInfo info in controls)
                {
                    if (info.ID.Equals (id))
                      {
                          control =
                              info.
                              CreateInstance ();
                          chosenEngine = info;
                          break;
                      }
                }

                if (control == null)
                    msg = Catalog.
                        GetString
                        ("<b>Unknown engine</b>\n\nPlease check gconf keys of csboard");
            }
            catch (Exception e)
            {
                msg = String.Format (Catalog.
                             GetString
                             ("<b>Unable to load engine '{0}'</b>"),
                             engine);
                Console.WriteLine (e.StackTrace);

            }
            if (control == null)
              {
                  MessageDialog md =
                      new MessageDialog (csboardWindow,
                                 DialogFlags.
                                 DestroyWithParent,
                                 MessageType.
                                 Error,
                                 ButtonsType.
                                 Close,
                                 msg);

                  md.Run ();
                  md.Hide ();
                  md.Dispose ();
                  control = new NullControl ();
              }

            control.WaitEvent +=
                new ControlWaitHandler (on_control_wait);
            control.BusyEvent +=
                new ControlBusyHandler (on_control_busy);
            control.PositionChangedEvent +=
                new
                ControlPositionChangedHandler
                (on_position_changed);
            control.GameOverEvent +=
                new
                ControlGameOverHandler (on_control_game_over);
            control.SwitchSideEvent +=
                new
                ControlSwitchSideHandler (on_control_side);
            control.HintEvent +=
                new ControlHintHandler (on_control_hint);
        }
Ejemplo n.º 25
0
 public Info(EngineInfo engineInfo)
 {
     EngineInfo = engineInfo;
     Done       = engineInfo.EngineState == EngineState.Paused;
 }
Ejemplo n.º 26
0
 public DriverModels.EngineInfo GetInfo()
 {
     DriverModels.EngineInfo ret = new EngineInfo();
     ret.Version = "Error";
     if (!_isLegalPlugin) return ret;
     try
     {
         IntPtr hModule = LoadLibrary(DllPath);
         if (hModule == IntPtr.Zero) _isLegalPlugin = false;
         else
         {
             IntPtr m = GetProcAddress(hModule, "GetInformation");
             if (m != IntPtr.Zero)
             {
                 GetInformationDelegate g = (GetInformationDelegate)Marshal.GetDelegateForFunctionPointer(m, typeof(GetInformationDelegate));
                 ret = Intptr2EngineInformation(g());
             }
             FreeLibrary(hModule);
         }
     }
     catch { ;}
     return ret;
 }
Ejemplo n.º 27
0
        /*
         * 付:外挂ini配置文件格式:
         * [Information]
         * Name=Resampler
         * Author=Unknown
         * Version=1.0
         *
         * [Usuage]
         * This is all the Usuage Text,A Mono Text
         *
         * [FlagsSetting]
         * ItemCount=2
         *
         * [Flag1]
         * Flag=B
         * ThreeLetterName=BRI
         * Min=-100
         * Max=100
         * Default=1
         *
         * [Flag2]
         * Flag=b
         * ThreeLetterName=bre
         * Min=-100
         * Max=100
         * Default=10
         */

        public DriverModels.EngineInfo GetInfo()
        {
            DriverModels.EngineInfo ret = new EngineInfo
            {
                Version = "Error"
            };
            if (!_isLegalPlugin)
            {
                return(ret);
            }
            ret.Author        = "Unknown";
            ret.Name          = System.IO.Path.GetFileName(ExePath);
            ret.Version       = "Unknown";
            ret.Usuage        = $"Traditional Resample Engine in {ExePath}";
            ret.FlagItem      = new EngineFlagItem[0];
            ret.FlagItemCount = 0;
            try
            {
                if (ExePath.EndsWith(".exe", StringComparison.CurrentCultureIgnoreCase))
                {
                    string RealFile = ExePath.Substring(0, ExePath.Length - 3) + "ini";
                    if (System.IO.File.Exists(RealFile))
                    {
                        IniFileClass IniFile = new IniFileClass(RealFile);
                        string       Name    = IniFile.getKeyValue("Information", "Name");
                        if (Name != string.Empty)
                        {
                            ret.Name = Name;
                        }
                        string Author = IniFile.getKeyValue("Information", "Author");
                        if (Author != string.Empty)
                        {
                            ret.Author = Author;
                        }
                        string Version = IniFile.getKeyValue("Information", "Version");
                        if (Version != string.Empty)
                        {
                            ret.Version = Version;
                        }
                        StringBuilder Usuage = new StringBuilder();
                        Usuage.Append(IniFile.SectionValues("Usuage"));
                        if (Usuage.Length > 10)
                        {
                            ret.Usuage = Usuage.ToString();
                        }
                        string FlagItemCount = IniFile.getKeyValue("FlagsSetting", "ItemCount");
                        int.TryParse(FlagItemCount, out ret.FlagItemCount);
                        List <EngineFlagItem> Items = new List <EngineFlagItem>();
                        for (int i = 1; i <= ret.FlagItemCount; i++)
                        {
                            try
                            {
                                EngineFlagItem I = new EngineFlagItem
                                {
                                    Default         = double.Parse(IniFile.getKeyValue($"Flag{i}", "Default")),
                                    flagStr         = IniFile.getKeyValue($"Flag{i}", "Flag"),
                                    Max             = double.Parse(IniFile.getKeyValue($"Flag{i}", "Max")),
                                    Min             = double.Parse(IniFile.getKeyValue($"Flag{i}", "Min")),
                                    ThreeLetterName = IniFile.getKeyValue($"Flag{i}", "ThreeLetterName")
                                };
                                Items.Add(I);
                            }
                            catch {; }
                        }
                        ret.FlagItemCount = Items.Count;
                        ret.FlagItem      = Items.ToArray();
                    }
                }
            }
            catch {; }
            return(ret);
        }
Ejemplo n.º 28
0
        /*
         付:外挂ini配置文件格式:
         [Information]
         Name=Resampler
         Author=Unknown
         Version=1.0
         
         [Usuage]
         This is all the Usuage Text,A Mono Text
          
         [FlagsSetting]
         ItemCount=2
          
         [Flag1]
         Flag=B
         ThreeLetterName=BRI
         Min=-100
         Max=100
         Default=1
         
         [Flag2]
         Flag=b
         ThreeLetterName=bre
         Min=-100
         Max=100
         Default=10
         */

        public DriverModels.EngineInfo GetInfo()
        {
            DriverModels.EngineInfo ret = new EngineInfo();
            ret.Version = "Error";
            if (!_isLegalPlugin) return ret;
            ret.Author = "Unknown";
            ret.Name = System.IO.Path.GetFileName(ExePath);
            ret.Version = "Unknown";
            ret.Usuage = "Traditional Resample Engine in "+ExePath;
            ret.FlagItem = new EngineFlagItem[0];
            ret.FlagItemCount = 0;
            try
            {
                if(ExePath.ToLower().EndsWith(".exe"))
                {
                    string RealFile=ExePath.Substring(0,ExePath.Length-3)+"ini";
                    if (System.IO.File.Exists(RealFile))
                    {
                        IniFileClass IniFile = new IniFileClass(RealFile);
                        string Name=IniFile.getKeyValue("Information", "Name");
                        if (Name != "") ret.Name = Name;
                        string Author = IniFile.getKeyValue("Information", "Author");
                        if (Author != "") ret.Author = Author;
                        string Version = IniFile.getKeyValue("Information", "Version");
                        if (Version != "") ret.Version = Version;
                        StringBuilder Usuage = new StringBuilder();
                        Usuage.Append(IniFile.SectionValues("Usuage"));
                        if (Usuage.Length > 10) ret.Usuage = Usuage.ToString();
                        string FlagItemCount = IniFile.getKeyValue("FlagsSetting", "ItemCount");
                        int.TryParse(FlagItemCount, out ret.FlagItemCount);
                        List<EngineFlagItem> Items = new List<EngineFlagItem>();
                        for (int i = 1; i <= ret.FlagItemCount; i++)
                        {
                            try
                            {
                                EngineFlagItem I = new EngineFlagItem();
                                I.Default = double.Parse(IniFile.getKeyValue("Flag" + i.ToString(), "Default"));
                                I.flagStr = IniFile.getKeyValue("Flag" + i.ToString(), "Flag");
                                I.Max = double.Parse(IniFile.getKeyValue("Flag" + i.ToString(), "Max"));
                                I.Min = double.Parse(IniFile.getKeyValue("Flag" + i.ToString(), "Min"));
                                I.ThreeLetterName = IniFile.getKeyValue("Flag" + i.ToString(), "ThreeLetterName");
                                Items.Add(I);
                            }
                            catch { ;}
                        }
                        ret.FlagItemCount = Items.Count;
                        ret.FlagItem = Items.ToArray();
                    }
                }
            }
            catch { ;}
            return ret;
        }
Ejemplo n.º 29
0
        static void Main(string[] args)
        {
            Console.WriteLine("This example will create PGP keys in your default keyring.\n");

            // First step is to create a context
            Context ctx = new Context();

            EngineInfo info = ctx.EngineInfo;

            if (info.Protocol != Protocol.OpenPGP)
            {
                ctx.SetEngineInfo(Protocol.OpenPGP, null, null);
                info = ctx.EngineInfo;
            }

            Console.WriteLine("GnuPG home directory: {0}\n"
                              + "Version: {1}\n"
                              + "Reqversion: {2} \n"
                              + "Program: {3}\n",
                              info.HomeDir,
                              info.Version,
                              info.ReqVersion,
                              info.FileName);

            IKeyGenerator keygen = ctx.KeyStore;

            KeyParameters aliceparam, bobparam, malloryparam;

            aliceparam                = new KeyParameters();
            aliceparam.RealName       = "Alice";
            aliceparam.Comment        = "my comment";
            aliceparam.Email          = "*****@*****.**";
            aliceparam.ExpirationDate = DateTime.Now.AddYears(3);

            // primary key parameters
            aliceparam.KeyLength       = KeyParameters.KEY_LENGTH_2048;
            aliceparam.PubkeyAlgorithm = KeyAlgorithm.RSA;
            // the primary key algorithm MUST have the "Sign" capability
            aliceparam.PubkeyUsage =
                AlgorithmCapability.CanSign
                | AlgorithmCapability.CanAuth
                | AlgorithmCapability.CanCert;

            // subkey parameters (optional)
            aliceparam.SubkeyLength    = KeyParameters.KEY_LENGTH_4096;
            aliceparam.SubkeyAlgorithm = KeyAlgorithm.RSA;
            aliceparam.SubkeyUsage     = AlgorithmCapability.CanEncrypt;

            aliceparam.Passphrase = "topsecret";

            // Generate Alice key
            Console.WriteLine(
                "Create a new PGP key for Alice.\n"
                + "Name: {0}\n"
                + "Comment: {1} \n"
                + "Email: {2} \n"
                + "Secret passphrase: {3} \n"
                + "Expire date: {4} \n"
                + "Primary key algorithm = {5} ({6} bit)\n"
                + "Sub key algorithm = {7} ({8} bit)",
                aliceparam.RealName,
                aliceparam.Comment,
                aliceparam.Email,
                aliceparam.Passphrase,
                aliceparam.ExpirationDate.ToString(),
                Gpgme.GetPubkeyAlgoName(aliceparam.PubkeyAlgorithm),
                aliceparam.PubkeyLength,
                Gpgme.GetPubkeyAlgoName(aliceparam.SubkeyAlgorithm),
                aliceparam.SubkeyLength
                );

            Console.Write("Start key generation.. ");
            GenkeyResult result = keygen.GenerateKey(
                Protocol.OpenPGP,
                aliceparam);

            Console.WriteLine("done.\nFingerprint: {0}\n",
                              result.Fingerprint);

            // okay, create two more keys

            Console.Write("Create PGP key for Bob.. ");
            bobparam                = new KeyParameters();
            bobparam.RealName       = "Bob";
            bobparam.Email          = "*****@*****.**";
            bobparam.ExpirationDate = DateTime.Now.AddYears(2);
            bobparam.Passphrase     = "topsecret";

            result = keygen.GenerateKey(
                Protocol.OpenPGP,
                bobparam);
            Console.WriteLine("done.\nFingerprint: {0}\n",
                              result.Fingerprint);

            Console.Write("Create PGP key for Mallory.. ");
            malloryparam          = new KeyParameters();
            malloryparam.RealName = "Mallory";
            malloryparam.Email    = "*****@*****.**";
            malloryparam.MakeInfinitely(); // PGP key does not expire
            malloryparam.Passphrase = "topsecret";

            result = keygen.GenerateKey(
                Protocol.OpenPGP,
                malloryparam);
            Console.WriteLine("done.\nFingerprint: {0}",
                              result.Fingerprint);

            return;
        }
Ejemplo n.º 30
0
        public void Update(Vessel vessel)
        {
            if (vessel.rigidbody == null) return; //if we try to update before rigidbodies exist we spam the console with NullPointerExceptions.
            //if (vessel.packed) return;

            time = Planetarium.GetUniversalTime();
            deltaT = TimeWarp.fixedDeltaTime;

            CoM = vessel.findWorldCenterOfMass();
            up = (CoM - vessel.mainBody.position).normalized;

            Rigidbody rigidBody = vessel.rootPart.rigidbody;
            if (rigidBody != null) rootPartPos = rigidBody.position;

            north = Vector3d.Exclude(up, (vessel.mainBody.position + vessel.mainBody.transform.up * (float)vessel.mainBody.Radius) - CoM).normalized;
            east = vessel.mainBody.getRFrmVel(CoM).normalized;
            forward = vessel.GetTransform().up;
            rotationSurface = Quaternion.LookRotation(north, up);
            rotationVesselSurface = Quaternion.Inverse(Quaternion.Euler(90, 0, 0) * Quaternion.Inverse(vessel.GetTransform().rotation) * rotationSurface);

            velocityVesselOrbit = vessel.orbit.GetVel();
            velocityVesselOrbitUnit = velocityVesselOrbit.normalized;
            velocityVesselSurface = velocityVesselOrbit - vessel.mainBody.getRFrmVel(CoM);
            velocityVesselSurfaceUnit = velocityVesselSurface.normalized;
            velocityMainBodySurface = rotationSurface * velocityVesselSurface;

            horizontalOrbit = Vector3d.Exclude(up, velocityVesselOrbit).normalized;
            horizontalSurface = Vector3d.Exclude(up, velocityVesselSurface).normalized;

            angularVelocity = Quaternion.Inverse(vessel.GetTransform().rotation) * vessel.rigidbody.angularVelocity;

            radialPlusSurface = Vector3d.Exclude(velocityVesselSurface, up).normalized;
            radialPlus = Vector3d.Exclude(velocityVesselOrbit, up).normalized;
            normalPlusSurface = -Vector3d.Cross(radialPlusSurface, velocityVesselSurfaceUnit);
            normalPlus = -Vector3d.Cross(radialPlus, velocityVesselOrbitUnit);

            gravityForce = FlightGlobals.getGeeForceAtPosition(CoM);
            localg = gravityForce.magnitude;

            speedOrbital.value = velocityVesselOrbit.magnitude;
            speedSurface.value = velocityVesselSurface.magnitude;
            speedVertical.value = Vector3d.Dot(velocityVesselSurface, up);
            speedSurfaceHorizontal.value = (velocityVesselSurface - (speedVertical * up)).magnitude;
            speedOrbitHorizontal = (velocityVesselOrbit - (speedVertical * up)).magnitude;

            vesselHeading.value = rotationVesselSurface.eulerAngles.y;
            vesselPitch.value = (rotationVesselSurface.eulerAngles.x > 180) ? (360.0 - rotationVesselSurface.eulerAngles.x) : -rotationVesselSurface.eulerAngles.x;
            vesselRoll.value = (rotationVesselSurface.eulerAngles.z > 180) ? (rotationVesselSurface.eulerAngles.z - 360.0) : rotationVesselSurface.eulerAngles.z;

            altitudeASL.value = vessel.mainBody.GetAltitude(CoM);
            RaycastHit sfc;
            if (Physics.Raycast(CoM, -up, out sfc, (float)altitudeASL + 10000.0F, 1 << 15))
            {
                altitudeTrue.value = sfc.distance;
            }
            else if (vessel.mainBody.pqsController != null)
            {
                // from here: http://kerbalspaceprogram.com/forum/index.php?topic=10324.msg161923#msg161923
                altitudeTrue.value = vessel.mainBody.GetAltitude(CoM) - (vessel.mainBody.pqsController.GetSurfaceHeight(QuaternionD.AngleAxis(vessel.mainBody.GetLongitude(CoM), Vector3d.down) * QuaternionD.AngleAxis(vessel.mainBody.GetLatitude(CoM), Vector3d.forward) * Vector3d.right) - vessel.mainBody.pqsController.radius);
            }
            else
            {
                altitudeTrue.value = vessel.mainBody.GetAltitude(CoM);
            }

            double surfaceAltitudeASL = altitudeASL - altitudeTrue;
            altitudeBottom = altitudeTrue;
            foreach (Part p in vessel.parts)
            {
                if (p.collider != null)
                {
                    Vector3d bottomPoint = p.collider.ClosestPointOnBounds(vessel.mainBody.position);
                    double partBottomAlt = vessel.mainBody.GetAltitude(bottomPoint) - surfaceAltitudeASL;
                    altitudeBottom = Math.Max(0, Math.Min(altitudeBottom, partBottomAlt));
                }
            }

            double atmosphericPressure = FlightGlobals.getStaticPressure(altitudeASL, vessel.mainBody);
            if (atmosphericPressure < vessel.mainBody.atmosphereMultiplier * 1e-6) atmosphericPressure = 0;
            atmosphericDensity = FlightGlobals.getAtmDensity(atmosphericPressure);
            atmosphericDensityGrams = atmosphericDensity * 1000;

            orbitApA.value = vessel.orbit.ApA;
            orbitPeA.value = vessel.orbit.PeA;
            orbitPeriod.value = vessel.orbit.period;
            orbitTimeToAp.value = vessel.orbit.timeToAp;
            if (vessel.orbit.eccentricity < 1) orbitTimeToPe.value = vessel.orbit.timeToPe;
            else orbitTimeToPe.value = -vessel.orbit.meanAnomaly / (2 * Math.PI / vessel.orbit.period);
            orbitLAN.value = vessel.orbit.LAN;
            orbitArgumentOfPeriapsis.value = vessel.orbit.argumentOfPeriapsis;
            orbitInclination.value = vessel.orbit.inclination;
            orbitEccentricity.value = vessel.orbit.eccentricity;
            orbitSemiMajorAxis.value = vessel.orbit.semiMajorAxis;
            latitude.value = vessel.mainBody.GetLatitude(CoM);
            longitude.value = MuUtils.ClampDegrees180(vessel.mainBody.GetLongitude(CoM));

            if (vessel.mainBody != Planetarium.fetch.Sun)
            {
                Vector3d delta = vessel.mainBody.getPositionAtUT(Planetarium.GetUniversalTime() + 1) - vessel.mainBody.getPositionAtUT(Planetarium.GetUniversalTime() - 1);
                Vector3d plUp = Vector3d.Cross(vessel.mainBody.getPositionAtUT(Planetarium.GetUniversalTime()) - vessel.mainBody.referenceBody.getPositionAtUT(Planetarium.GetUniversalTime()), vessel.mainBody.getPositionAtUT(Planetarium.GetUniversalTime() + vessel.mainBody.orbit.period / 4) - vessel.mainBody.referenceBody.getPositionAtUT(Planetarium.GetUniversalTime() + vessel.mainBody.orbit.period / 4)).normalized;
                angleToPrograde = MuUtils.ClampDegrees360((((vessel.orbit.inclination > 90) || (vessel.orbit.inclination < -90)) ? 1 : -1) * ((Vector3)up).AngleInPlane(plUp, delta));
            }
            else
            {
                angleToPrograde = 0;
            }

            mainBody = vessel.mainBody;

            radius = (CoM - vessel.mainBody.position).magnitude;

            mass = massDrag = torqueThrustPYAvailable = 0;
            thrustVectorLastFrame = new Vector3d();
            thrustVectorMaxThrottle = new Vector3d();
            thrustVectorMinThrottle = new Vector3d();
            torqueAvailable = new Vector3d();
            rcsThrustAvailable = new Vector6();
            rcsTorqueAvailable = new Vector6();
            ctrlTorqueAvailable = new Vector6();

            EngineInfo einfo = new EngineInfo(CoM);
            IntakeInfo iinfo = new IntakeInfo();

            parachutes = new  List<ModuleParachute>();

            var rcsbal = vessel.GetMasterMechJeb().rcsbal;
            if (vessel.ActionGroups[KSPActionGroup.RCS] && rcsbal.enabled)
            {
                Vector3d rot = Vector3d.zero;
                foreach (Vector6.Direction dir6 in Enum.GetValues(typeof(Vector6.Direction)))
                {
                    Vector3d dir = Vector6.directions[dir6];
                    double[] throttles;
                    List<RCSSolver.Thruster> thrusters;
                    rcsbal.GetThrottles(dir, out throttles, out thrusters);
                    if (throttles != null)
                    {
                        for (int i = 0; i < throttles.Length; i++)
                        {
                            if (throttles[i] > 0)
                            {
                                Vector3d force = thrusters[i].GetThrust(dir, rot);
                                rcsThrustAvailable.Add(dir * Vector3d.Dot(force * throttles[i], dir));
                            }
                        }
                    }
                }
            }

            foreach (Part p in vessel.parts)
            {
                if (p.physicalSignificance != Part.PhysicalSignificance.NONE)
                {
                    double partMass = p.TotalMass();
                    mass += partMass;
                    massDrag += partMass * p.maximum_drag;
                }

                if (vessel.ActionGroups[KSPActionGroup.RCS] && !rcsbal.enabled)
                {
                    foreach (ModuleRCS pm in p.Modules.OfType<ModuleRCS>())
                    {
                        double maxT = pm.thrusterPower;
                        Vector3d partPosition = p.Rigidbody.worldCenterOfMass - CoM;

                        if ((pm.isEnabled) && (!pm.isJustForShow))
                        {
                            foreach (Transform t in pm.thrusterTransforms)
                            {
                                Vector3d thrusterThrust = -t.up * pm.thrusterPower;
                                rcsThrustAvailable.Add(thrusterThrust);
                                Vector3d thrusterTorque = vessel.GetTransform().InverseTransformDirection(Vector3.Cross(partPosition, thrusterThrust));
                                rcsTorqueAvailable.Add(thrusterTorque);
                            }
                        }
                    }
                }

                if (p is ControlSurface)
                {
                    Vector3d partPosition = p.Rigidbody.worldCenterOfMass - CoM;
                    ControlSurface cs = (p as ControlSurface);
                    // Air Speed is velocityVesselSurface
                    // AddForceAtPosition seems to need the airspeed vector rotated with the flap rotation x its surface
                    Quaternion airSpeedRot = Quaternion.AngleAxis(cs.ctrlSurfaceRange * cs.ctrlSurfaceArea, cs.transform.rotation * cs.pivotAxis);
                    Vector3 ctrlTroquePos =  vessel.GetTransform().InverseTransformDirection(Vector3.Cross(partPosition, cs.getLiftVector( airSpeedRot * velocityVesselSurface )));
                    Vector3 ctrlTroqueNeg =  vessel.GetTransform().InverseTransformDirection(Vector3.Cross(partPosition, cs.getLiftVector( Quaternion.Inverse(airSpeedRot) * velocityVesselSurface )));
                    ctrlTorqueAvailable.Add(ctrlTroquePos);
                    ctrlTorqueAvailable.Add(ctrlTroqueNeg);
                }

                if (p is CommandPod)
                {
                    torqueAvailable += Vector3d.one * Math.Abs(((CommandPod)p).rotPower);
                }

                foreach (VesselStatePartExtension vspe in vesselStatePartExtensions)
                {
                    vspe(p);
                }

                foreach (PartModule pm in p.Modules)
                {
                    if (!pm.isEnabled) continue;

                    if (pm is ModuleReactionWheel)
                    {
                        ModuleReactionWheel rw = (ModuleReactionWheel)pm;
                        // I had to remove the test for active in .23 since the new ressource system reply to the RW that
                        // there is no energy available when the RW do tiny adjustement.
                        // I replaceed it with a test that check if there is electricity anywhere on the ship.
                        // Let's hope we don't get reaction wheel that use something else
                        //if (rw.wheelState == ModuleReactionWheel.WheelState.Active && !rw.stateString.Contains("Not enough"))
                        if (rw.wheelState == ModuleReactionWheel.WheelState.Active && vessel.HasElectricCharge())
                            torqueAvailable += new Vector3d(rw.PitchTorque, rw.RollTorque, rw.YawTorque);
                    }
                    else if (pm is ModuleEngines)
                    {
                        einfo.AddNewEngine(pm as ModuleEngines);
                    }
                    else if (pm is ModuleEnginesFX)
                    {
                        einfo.AddNewEngine(pm as ModuleEnginesFX);
                    }
                    else if (pm is ModuleResourceIntake)
                    {
                        iinfo.addIntake(pm as ModuleResourceIntake);
                    }
                    else if (pm is ModuleParachute)
                    {
                        parachutes.Add(pm as ModuleParachute);
                    }

                    foreach (VesselStatePartModuleExtension vspme in vesselStatePartModuleExtensions)
                    {
                        vspme(pm);
                    }
                }
            }

            torqueAvailable += Vector3d.Max(rcsTorqueAvailable.positive, rcsTorqueAvailable.negative); // Should we use Max or Min ?
            torqueAvailable += Vector3d.Max(ctrlTorqueAvailable.positive, ctrlTorqueAvailable.negative); // Should we use Max or Min ?

            thrustVectorMaxThrottle += einfo.thrustMax;
            thrustVectorMinThrottle += einfo.thrustMin;
            thrustVectorLastFrame += einfo.thrustCurrent;
            torqueThrustPYAvailable += einfo.torqueThrustPYAvailable;

            // Convert the resource information from the einfo and iinfo format
            // to the more useful ResourceInfo format.
            resources = new Dictionary<int, ResourceInfo>();
            foreach (var info in einfo.resourceRequired)
            {
                int id = info.Key;
                var req = info.Value;
                resources[id] = new ResourceInfo(
                        PartResourceLibrary.Instance.GetDefinition(id),
                        req.requiredLastFrame,
                        req.requiredAtMaxThrottle,
                        iinfo.getIntakes(id));
            }

            int intakeAirId = PartResourceLibrary.Instance.GetDefinition("IntakeAir").id;
            intakeAir = 0;
            intakeAirNeeded = 0;
            intakeAirAtMax = 0;
            intakeAirAllIntakes = 0;
            if (resources.ContainsKey(intakeAirId))
            {
                intakeAir = resources[intakeAirId].intakeProvided;
                intakeAirAllIntakes = resources[intakeAirId].intakeAvailable;
                intakeAirNeeded = resources[intakeAirId].required;
                intakeAirAtMax = resources[intakeAirId].requiredAtMaxThrottle;
            }

            angularMomentum = new Vector3d(angularVelocity.x * MoI.x, angularVelocity.y * MoI.y, angularVelocity.z * MoI.z);

            inertiaTensor = new Matrix3x3();
            foreach (Part p in vessel.parts)
            {
                if (p.Rigidbody == null) continue;

                //Compute the contributions to the vessel inertia tensor due to the part inertia tensor
                Vector3d principalMoments = p.Rigidbody.inertiaTensor;
                Quaternion princAxesRot = Quaternion.Inverse(vessel.GetTransform().rotation) * p.transform.rotation * p.Rigidbody.inertiaTensorRotation;
                Quaternion invPrincAxesRot = Quaternion.Inverse(princAxesRot);

                for (int i = 0; i < 3; i++)
                {
                    Vector3d iHat = Vector3d.zero;
                    iHat[i] = 1;
                    for (int j = 0; j < 3; j++)
                    {
                        Vector3d jHat = Vector3d.zero;
                        jHat[j] = 1;
                        inertiaTensor[i, j] += Vector3d.Dot(iHat, princAxesRot * Vector3d.Scale(principalMoments, invPrincAxesRot * jHat));
                    }
                }

                //Compute the contributions to the vessel inertia tensor due to the part mass and position
                double partMass = p.TotalMass();
                Vector3 partPosition = vessel.GetTransform().InverseTransformDirection(p.Rigidbody.worldCenterOfMass - CoM);

                for (int i = 0; i < 3; i++)
                {
                    inertiaTensor[i, i] += partMass * partPosition.sqrMagnitude;

                    for (int j = 0; j < 3; j++)
                    {
                        inertiaTensor[i, j] += -partMass * partPosition[i] * partPosition[j];
                    }
                }
            }

            MoI = new Vector3d(inertiaTensor[0, 0], inertiaTensor[1, 1], inertiaTensor[2, 2]);
            angularMomentum = inertiaTensor * angularVelocity;
        }
Ejemplo n.º 31
0
 public DriverModels.EngineInfo GetInfo()
 {
     EngineInfo ret = new EngineInfo();
     ret.Version = "Error";
     if (!_isLegalPlugin) return ret;
     if (GetInformationMethod != null)
     {
         object Ret = GetInformationMethod.Invoke(null, new object[0]);
         if (Ret != null)
         {
             ret.Author = (string)Ret.GetType().GetField("Author").GetValue(Ret);
             ret.Name = (string)Ret.GetType().GetField("Name").GetValue(Ret);
             ret.Usuage = (string)Ret.GetType().GetField("Usuage").GetValue(Ret);
             ret.Version = (string)Ret.GetType().GetField("Version").GetValue(Ret);
             ret.Author = (string)Ret.GetType().GetField("Author").GetValue(Ret);
             ret.FlagItemCount = (int)Ret.GetType().GetField("FlagItemCount").GetValue(Ret);
             Array ItemArray = (Ret.GetType().GetField("FlagItem").GetValue(Ret)) as Array;
             ret.FlagItem = new EngineFlagItem[ret.FlagItemCount];
             for (int i = 0; i < ret.FlagItemCount; i++)
             {
                 ret.FlagItem[i] = (EngineFlagItem)CopyObjectToNewType(ItemArray.GetValue(i), typeof(EngineFlagItem));
             }
         }
     }
     return ret;
 }
Ejemplo n.º 32
0
        public void Update(Vessel vessel)
        {
            if (vessel.rigidbody == null) return; //if we try to update before rigidbodies exist we spam the console with NullPointerExceptions.
            //if (vessel.packed) return;

            time = Planetarium.GetUniversalTime();
            deltaT = TimeWarp.fixedDeltaTime;

            CoM = vessel.findWorldCenterOfMass();
            MoI = vessel.findLocalMOI(CoM);
            up = (CoM - vessel.mainBody.position).normalized;

            Rigidbody rigidBody = vessel.rootPart.rigidbody;
            if (rigidBody != null) rootPartPos = rigidBody.position;

            north = Vector3d.Exclude(up, (vessel.mainBody.position + vessel.mainBody.transform.up * (float)vessel.mainBody.Radius) - CoM).normalized;
            east = vessel.mainBody.getRFrmVel(CoM).normalized;
            forward = vessel.GetTransform().up;
            rotationSurface = Quaternion.LookRotation(north, up);
            rotationVesselSurface = Quaternion.Inverse(Quaternion.Euler(90, 0, 0) * Quaternion.Inverse(vessel.GetTransform().rotation) * rotationSurface);

            velocityVesselOrbit = vessel.orbit.GetVel();
            velocityVesselOrbitUnit = velocityVesselOrbit.normalized;
            velocityVesselSurface = velocityVesselOrbit - vessel.mainBody.getRFrmVel(CoM);
            velocityVesselSurfaceUnit = velocityVesselSurface.normalized;
            velocityMainBodySurface = rotationSurface * velocityVesselSurface;

            horizontalOrbit = Vector3d.Exclude(up, velocityVesselOrbit).normalized;
            horizontalSurface = Vector3d.Exclude(up, velocityVesselSurface).normalized;

            angularVelocity = Quaternion.Inverse(vessel.GetTransform().rotation) * vessel.rigidbody.angularVelocity;

            radialPlusSurface = Vector3d.Exclude(velocityVesselSurface, up).normalized;
            radialPlus = Vector3d.Exclude(velocityVesselOrbit, up).normalized;
            normalPlusSurface = -Vector3d.Cross(radialPlusSurface, velocityVesselSurfaceUnit);
            normalPlus = -Vector3d.Cross(radialPlus, velocityVesselOrbitUnit);

            gravityForce = FlightGlobals.getGeeForceAtPosition(CoM);
            localg = gravityForce.magnitude;

            speedOrbital.value = velocityVesselOrbit.magnitude;
            speedSurface.value = velocityVesselSurface.magnitude;
            speedVertical.value = Vector3d.Dot(velocityVesselSurface, up);
            speedSurfaceHorizontal.value = (velocityVesselSurface - (speedVertical * up)).magnitude;
            speedOrbitHorizontal = (velocityVesselOrbit - (speedVertical * up)).magnitude;

            vesselHeading.value = rotationVesselSurface.eulerAngles.y;
            vesselPitch.value = (rotationVesselSurface.eulerAngles.x > 180) ? (360.0 - rotationVesselSurface.eulerAngles.x) : -rotationVesselSurface.eulerAngles.x;
            vesselRoll.value = (rotationVesselSurface.eulerAngles.z > 180) ? (rotationVesselSurface.eulerAngles.z - 360.0) : rotationVesselSurface.eulerAngles.z;

            altitudeASL.value = vessel.mainBody.GetAltitude(CoM);
            RaycastHit sfc;
            if (Physics.Raycast(CoM, -up, out sfc, (float)altitudeASL + 10000.0F, 1 << 15))
            {
                altitudeTrue.value = sfc.distance;
            }
            else if (vessel.mainBody.pqsController != null)
            {
                // from here: http://kerbalspaceprogram.com/forum/index.php?topic=10324.msg161923#msg161923
                altitudeTrue.value = vessel.mainBody.GetAltitude(CoM) - (vessel.mainBody.pqsController.GetSurfaceHeight(QuaternionD.AngleAxis(vessel.mainBody.GetLongitude(CoM), Vector3d.down) * QuaternionD.AngleAxis(vessel.mainBody.GetLatitude(CoM), Vector3d.forward) * Vector3d.right) - vessel.mainBody.pqsController.radius);
            }
            else
            {
                altitudeTrue.value = vessel.mainBody.GetAltitude(CoM);
            }

            double surfaceAltitudeASL = altitudeASL - altitudeTrue;
            altitudeBottom = altitudeTrue;
            foreach (Part p in vessel.parts)
            {
                if (p.collider != null)
                {
                    Vector3d bottomPoint = p.collider.ClosestPointOnBounds(vessel.mainBody.position);
                    double partBottomAlt = vessel.mainBody.GetAltitude(bottomPoint) - surfaceAltitudeASL;
                    altitudeBottom = Math.Max(0, Math.Min(altitudeBottom, partBottomAlt));
                }
            }

            double atmosphericPressure = FlightGlobals.getStaticPressure(altitudeASL, vessel.mainBody);
            if (atmosphericPressure < vessel.mainBody.atmosphereMultiplier * 1e-6) atmosphericPressure = 0;
            atmosphericDensity = FlightGlobals.getAtmDensity(atmosphericPressure);
            atmosphericDensityGrams = atmosphericDensity * 1000;

            orbitApA.value = vessel.orbit.ApA;
            orbitPeA.value = vessel.orbit.PeA;
            orbitPeriod.value = vessel.orbit.period;
            orbitTimeToAp.value = vessel.orbit.timeToAp;
            if (vessel.orbit.eccentricity < 1) orbitTimeToPe.value = vessel.orbit.timeToPe;
            else orbitTimeToPe.value = -vessel.orbit.meanAnomaly / (2 * Math.PI / vessel.orbit.period);
            orbitLAN.value = vessel.orbit.LAN;
            orbitArgumentOfPeriapsis.value = vessel.orbit.argumentOfPeriapsis;
            orbitInclination.value = vessel.orbit.inclination;
            orbitEccentricity.value = vessel.orbit.eccentricity;
            orbitSemiMajorAxis.value = vessel.orbit.semiMajorAxis;
            latitude.value = vessel.mainBody.GetLatitude(CoM);
            longitude.value = MuUtils.ClampDegrees180(vessel.mainBody.GetLongitude(CoM));

            if (vessel.mainBody != Planetarium.fetch.Sun)
            {
                Vector3d delta = vessel.mainBody.getPositionAtUT(Planetarium.GetUniversalTime() + 1) - vessel.mainBody.getPositionAtUT(Planetarium.GetUniversalTime() - 1);
                Vector3d plUp = Vector3d.Cross(vessel.mainBody.getPositionAtUT(Planetarium.GetUniversalTime()) - vessel.mainBody.referenceBody.getPositionAtUT(Planetarium.GetUniversalTime()), vessel.mainBody.getPositionAtUT(Planetarium.GetUniversalTime() + vessel.mainBody.orbit.period / 4) - vessel.mainBody.referenceBody.getPositionAtUT(Planetarium.GetUniversalTime() + vessel.mainBody.orbit.period / 4)).normalized;
                angleToPrograde = MuUtils.ClampDegrees360((((vessel.orbit.inclination > 90) || (vessel.orbit.inclination < -90)) ? 1 : -1) * ((Vector3)up).AngleInPlane(plUp, delta));
            }
            else
            {
                angleToPrograde = 0;
            }

            mainBody = vessel.mainBody;

            radius = (CoM - vessel.mainBody.position).magnitude;

            mass = thrustAvailable = thrustMinimum = massDrag = torqueRAvailable = torquePYAvailable = torqueThrustPYAvailable = 0;
            rcsThrustAvailable = new Vector6();
            rcsTorqueAvailable = new Vector6();

            EngineInfo einfo = new EngineInfo(forward, CoM);
            IntakeInfo iinfo = new IntakeInfo();

            var rcsbal = vessel.GetMasterMechJeb().rcsbal;
            if (vessel.ActionGroups[KSPActionGroup.RCS] && rcsbal.enabled)
            {
                Vector3d rot = Vector3d.zero;
                foreach (Vector6.Direction dir6 in Enum.GetValues(typeof(Vector6.Direction)))
                {
                    Vector3d dir = Vector6.directions[dir6];
                    double[] throttles;
                    List<RCSSolver.Thruster> thrusters;
                    rcsbal.GetThrottles(dir, out throttles, out thrusters);
                    if (throttles != null)
                    {
                        for (int i = 0; i < throttles.Length; i++)
                        {
                            if (throttles[i] > 0)
                            {
                                Vector3d force = thrusters[i].GetThrust(dir, rot);
                                rcsThrustAvailable.Add(dir * Vector3d.Dot(force * throttles[i], dir));
                            }
                        }
                    }
                }
            }

            foreach (Part p in vessel.parts)
            {
                if (p.physicalSignificance != Part.PhysicalSignificance.NONE)
                {
                    double partMass = p.TotalMass();
                    mass += partMass;
                    massDrag += partMass * p.maximum_drag;
                }

                if (p.Rigidbody != null) MoI += p.Rigidbody.inertiaTensor;

                if (vessel.ActionGroups[KSPActionGroup.RCS] && !rcsbal.enabled)
                {
                    foreach (ModuleRCS pm in p.Modules.OfType<ModuleRCS>())
                    {
                        double maxT = pm.thrustForces.Max();

                        if ((pm.isEnabled) && (!pm.isJustForShow))
                        {
                            torqueRAvailable += maxT;
                            if (p.Rigidbody != null) torquePYAvailable += maxT * (p.Rigidbody.worldCenterOfMass - CoM).magnitude;

                            foreach (Transform t in pm.thrusterTransforms)
                            {
                                rcsThrustAvailable.Add(-t.up * pm.thrusterPower);
                            }
                        }
                    }
                }
                if (p is CommandPod)
                {
                    torqueRAvailable += Math.Abs(((CommandPod)p).rotPower);
                    torquePYAvailable += Math.Abs(((CommandPod)p).rotPower);
                }

                foreach (PartModule pm in p.Modules)
                {
                    if (!pm.isEnabled) continue;

                    if (pm is ModuleEngines)
                    {
                        einfo.AddNewEngine(pm as ModuleEngines);
                    }
                    else if (pm is ModuleResourceIntake)
                    {
                        iinfo.addIntake(pm as ModuleResourceIntake);
                    }
                }
            }

            thrustAvailable += einfo.thrustAvailable;
            thrustMinimum += einfo.thrustMinimum;
            torqueThrustPYAvailable += einfo.torqueThrustPYAvailable;

            // Convert the resource information from the einfo and iinfo format
            // to the more useful ResourceInfo format.
            resources = new Dictionary<int, ResourceInfo>();
            foreach (var info in einfo.resourceRequired)
            {
                int id = info.Key;
                var req = info.Value;
                resources[id] = new ResourceInfo(
                        PartResourceLibrary.Instance.GetDefinition(id),
                        req.requiredLastFrame,
                        req.requiredAtMaxThrottle,
                        iinfo.getIntakes(id));
            }

            int intakeAirId = PartResourceLibrary.Instance.GetDefinition("IntakeAir").id;
            intakeAir = 0;
            intakeAirNeeded = 0;
            intakeAirAtMax = 0;
            if (resources.ContainsKey(intakeAirId))
            {
                intakeAir = resources[intakeAirId].intakeProvided;
                intakeAirNeeded = resources[intakeAirId].required;
                intakeAirAtMax = resources[intakeAirId].requiredAtMaxThrottle;
            }

            angularMomentum = new Vector3d(angularVelocity.x * MoI.x, angularVelocity.y * MoI.y, angularVelocity.z * MoI.z);

            maxThrustAccel = thrustAvailable / mass;
            minThrustAccel = thrustMinimum / mass;
        }
Ejemplo n.º 33
0
        // Constructor
        internal ConfigurationInfo(Configuration cfg, string filename)
        {
            // Initialize
            this.filename    = filename;
            this.config      = cfg;        //mxd
            this.settingskey = Path.GetFileNameWithoutExtension(filename).ToLower();

            // Load settings from game configuration
            this.name            = config.ReadSetting("game", "<unnamed game>");
            this.defaultlumpname = config.ReadSetting("defaultlumpname", "");

            // Load settings from program configuration
            this.nodebuildersave       = General.Settings.ReadSetting("configurations." + settingskey + ".nodebuildersave", MISSING_NODEBUILDER);
            this.nodebuildertest       = General.Settings.ReadSetting("configurations." + settingskey + ".nodebuildertest", MISSING_NODEBUILDER);
            this.formatinterface       = config.ReadSetting("formatinterface", "").ToLowerInvariant(); //mxd
            this.defaultscriptcompiler = cfg.ReadSetting("defaultscriptcompiler", "");                 //mxd
            this.resources             = new DataLocationList(General.Settings.Config, "configurations." + settingskey + ".resources");
            this.startmode             = General.Settings.ReadSetting("configurations." + settingskey + ".startmode", "VerticesMode");
            this.enabled = General.Settings.ReadSetting("configurations." + settingskey + ".enabled", config.ReadSetting("enabledbydefault", false));             //mxd

            //mxd. Read test engines
            testEngines = new List <EngineInfo>();
            IDictionary list = General.Settings.ReadSetting("configurations." + settingskey + ".engines", new ListDictionary());

            currentEngineIndex = Math.Max(0, General.Settings.ReadSetting("configurations." + settingskey + ".currentengineindex", 0));

            // No engine list found? Use old engine properties
            if (list.Count == 0)
            {
                EngineInfo info = new EngineInfo();
                info.TestProgram      = General.Settings.ReadSetting("configurations." + settingskey + ".testprogram", "");
                info.TestProgramName  = General.Settings.ReadSetting("configurations." + settingskey + ".testprogramname", EngineInfo.DEFAULT_ENGINE_NAME);
                info.TestParameters   = General.Settings.ReadSetting("configurations." + settingskey + ".testparameters", "");
                info.TestShortPaths   = General.Settings.ReadSetting("configurations." + settingskey + ".testshortpaths", false);
                info.CustomParameters = General.Settings.ReadSetting("configurations." + settingskey + ".customparameters", false);
                info.TestSkill        = General.Settings.ReadSetting("configurations." + settingskey + ".testskill", 3);
                testEngines.Add(info);
                currentEngineIndex = 0;
            }
            else
            {
                //read engines settings from config
                foreach (DictionaryEntry de in list)
                {
                    string     path = "configurations." + settingskey + ".engines." + de.Key;
                    EngineInfo info = new EngineInfo();
                    info.TestProgram      = General.Settings.ReadSetting(path + ".testprogram", "");
                    info.TestProgramName  = General.Settings.ReadSetting(path + ".testprogramname", EngineInfo.DEFAULT_ENGINE_NAME);
                    info.TestParameters   = General.Settings.ReadSetting(path + ".testparameters", "");
                    info.TestShortPaths   = General.Settings.ReadSetting(path + ".testshortpaths", false);
                    info.CustomParameters = General.Settings.ReadSetting(path + ".customparameters", false);
                    info.TestSkill        = General.Settings.ReadSetting(path + ".testskill", 3);
                    testEngines.Add(info);
                }

                if (currentEngineIndex >= testEngines.Count)
                {
                    currentEngineIndex = 0;
                }
            }

            //mxd. read custom linedef colors
            List <LinedefColorPreset> colorPresets = new List <LinedefColorPreset>();

            list = General.Settings.ReadSetting("configurations." + settingskey + ".linedefcolorpresets", new ListDictionary());

            //no presets? add "classic" ones then.
            if (list.Count == 0)
            {
                colorPresets.Add(new LinedefColorPreset("Any action", PixelColor.FromColor(System.Drawing.Color.PaleGreen), -1, 0, new List <string>(), new List <string>(), true));
            }
            else
            {
                //read custom linedef colors from config
                foreach (DictionaryEntry de in list)
                {
                    string        path          = "configurations." + settingskey + ".linedefcolorpresets." + de.Key;
                    string        presetname    = General.Settings.ReadSetting(path + ".name", "Unnamed");
                    bool          presetenabled = General.Settings.ReadSetting(path + ".enabled", true);
                    PixelColor    color         = PixelColor.FromInt(General.Settings.ReadSetting(path + ".color", -1));
                    int           action        = General.Settings.ReadSetting(path + ".action", 0);
                    int           activation    = General.Settings.ReadSetting(path + ".activation", 0);
                    List <string> flags         = new List <string>();
                    flags.AddRange(General.Settings.ReadSetting(path + ".flags", "").Split(LINEDEF_COLOR_PRESET_FLAGS_SEPARATOR, StringSplitOptions.RemoveEmptyEntries));
                    List <string> restrictedFlags = new List <string>();
                    restrictedFlags.AddRange(General.Settings.ReadSetting(path + ".restrictedflags", "").Split(LINEDEF_COLOR_PRESET_FLAGS_SEPARATOR, StringSplitOptions.RemoveEmptyEntries));
                    LinedefColorPreset preset = new LinedefColorPreset(presetname, color, action, activation, flags, restrictedFlags, presetenabled);
                    colorPresets.Add(preset);
                }
            }
            linedefColorPresets = colorPresets.ToArray();

            // Make list of things filters
            thingsfilters = new List <ThingsFilter>();
            IDictionary cfgfilters = General.Settings.ReadSetting("configurations." + settingskey + ".thingsfilters", new Hashtable());

            foreach (DictionaryEntry de in cfgfilters)
            {
                thingsfilters.Add(new ThingsFilter(General.Settings.Config, "configurations." + settingskey + ".thingsfilters." + de.Key));
            }

            // Make list of texture sets
            texturesets = new List <DefinedTextureSet>();
            IDictionary sets = General.Settings.ReadSetting("configurations." + settingskey + ".texturesets", new Hashtable());

            foreach (DictionaryEntry de in sets)
            {
                texturesets.Add(new DefinedTextureSet(General.Settings.Config, "configurations." + settingskey + ".texturesets." + de.Key));
            }

            // Make list of edit modes
            this.editmodes = new Dictionary <string, bool>(StringComparer.Ordinal);
            IDictionary modes = General.Settings.ReadSetting("configurations." + settingskey + ".editmodes", new Hashtable());

            foreach (DictionaryEntry de in modes)
            {
                if (de.Key.ToString().StartsWith(MODE_ENABLED_KEY))
                {
                    editmodes.Add(de.Value.ToString(), true);
                }
                else if (de.Key.ToString().StartsWith(MODE_DISABLED_KEY))
                {
                    editmodes.Add(de.Value.ToString(), false);
                }
            }
        }