Inheritance: MonoBehaviour
示例#1
0
    public static void Remove(PersistentKSPShurikenEmitter pkpe)
    {
        FloatingOrigin.UnregisterParticleSystem(pkpe.pe);
        persistentEmittersShuriken.Remove(pkpe);

        Log.dbg("Removed 1 PersistentKSPParticleEmitter. Count = {0}", persistentEmittersShuriken.Count);
    }
示例#2
0
        public void FixedUpdate()
        {
            frameSkip++;
            if (frameSkip < 25)
            {
                return;
            }
            frameSkip = 0;

            if (!checkRunway())
            {
                if (rwy)
                {
                    printDebug(
                        $"rwy=false; threshold={FloatingOrigin.fetch.threshold}, original threshold={originalThreshold}");
                    rwy = false;
                }

                return;
            }

            FloatingOrigin.fetch.threshold    = holdThreshold;
            FloatingOrigin.fetch.thresholdSqr = holdThresholdSqr;

            if (!rwy)
            {
                printDebug($"rwy=true; threshold={FloatingOrigin.fetch.threshold}, original threshold={originalThreshold}");
                rwy = true;
            }

            FloatingOrigin.SetSafeToEngage(false);
        }
    public static void Remove(PersistentKSPShurikenEmitter pkpe)
    {
        FloatingOrigin.UnregisterParticleSystem(pkpe.pe);
        persistentEmittersShuriken.Remove(pkpe);

        //print("[SmokeScreen PersistentEmitterManager]: Removed 1 PersistentKSPParticleEmitter. Count = " + persistentEmitters.Count);
    }
示例#4
0
        private void travelAtWarp()
        {
            if (throttleLevel <= 0f)
            {
                return;
            }

            // Calculate offset position
            warpDistance = kLightSpeed * maxWarpSpeed * throttleLevel * TimeWarp.fixedDeltaTime;
            Transform refTransform   = this.part.vessel.transform;
            Vector3   warpVector     = refTransform.up * warpDistance;
            Vector3d  offsetPosition = refTransform.position + warpVector;

            // Make sure that we won't run into a celestial body.
            if (previousBody != this.part.orbit.referenceBody)
            {
                previousBody = this.part.orbit.referenceBody;
                bodyBounds   = previousBody.getBounds();
            }
            if (bodyBounds.Contains(offsetPosition))
            {
                ScreenMessages.PostScreenMessage(kTerrainWarning, 3.0f, ScreenMessageStyle.UPPER_CENTER);
                FlightInputHandler.state.mainThrottle = 0;
                return;
            }

            // Apply translation.
            FloatingOrigin.SetOutOfFrameOffset(offsetPosition);
        }
示例#5
0
        public static void SetOrbit(this Vessel vessel, Orbit newOrbit)
        {
            //var originalUp = FlightGlobals.getUpAxis ();
            //Log.Info ("originalUp: " + originalUp.ToString ());

            var destinationMagnitude = newOrbit.getRelativePositionAtUT(Planetarium.GetUniversalTime()).magnitude;

            if (destinationMagnitude > newOrbit.referenceBody.sphereOfInfluence)
            {
                Extensions.ErrorPopup("Destination position was above the sphere of influence");
                return;
            }
            if (destinationMagnitude < newOrbit.referenceBody.Radius)
            {
                Extensions.ErrorPopup("Destination position was below the surface");
                return;
            }

            FlightGlobals.fetch.SetShipOrbit(newOrbit.referenceBody.flightGlobalsIndex, newOrbit.eccentricity, newOrbit.semiMajorAxis, newOrbit.inclination, newOrbit.LAN, newOrbit.meanAnomalyAtEpoch, newOrbit.argumentOfPeriapsis, newOrbit.ObT);
            FloatingOrigin.ResetTerrainShaderOffset();

            try
            {
                OrbitPhysicsManager.HoldVesselUnpack(60);
            }
            catch (NullReferenceException)
            {
                Log.Info("OrbitPhysicsManager.HoldVesselUnpack threw NullReferenceException");
            }
        }
    protected void Start()
    {
        origin                = FindObjectOfType <FloatingOrigin>();
        settings              = GetComponent <ProceduralWorldSettings>();
        origin.OnOriginShift += PostShiftGeneration;

        this.transform.position = new Vector3(origin.clearChildAfter, 0, 0);
        GenerateNewNodes();
    }
 private void OnTriggerEnter(Collider other)
 {
     if (other.TryGetComponent(out IPlayer player))
     {
         FloatingOrigin.Rebase(transform.position);
         // Should the Rebase Sphere Destroy itself?
         GameObject.Destroy(this.gameObject);
     }
 }
示例#8
0
        // If using FloatingOrigin on player, we must sometimes reinitialize so it does not get out of sync
        private void InitFloatingOrigin(Transform playerTransform)
        {
            FloatingOrigin fo = playerTransform.GetComponent <FloatingOrigin>();

            if (fo)
            {
                fo.Initialize();
            }
        }
示例#9
0
        public static bool SetSiteAndResetCamera(ConfigNode KSC, bool force = false)
        {
            bool b = SetSite(KSC);

            if (b && (force || (KSC.HasValue("name") && KSC.GetValue("name") != LastFloatingOriginKSC)))
            {
                FloatingOrigin.SetOffset(PSystemSetup.Instance.SCTransform.position);
                LastFloatingOriginKSC = KSC.GetValue("name");
                Debug.Log("KSCSwitcher set floating point origin offset");
            }

            return(b);
        }
示例#10
0
    private void OnSceneChange(GameScenes scene)
    {
        for (int i = 0; i < persistentEmittersShuriken.Count; i++)
        {
            FloatingOrigin.UnregisterParticleSystem(persistentEmittersShuriken[i].pe);

            if (persistentEmittersShuriken[i].go != null && persistentEmittersShuriken[i].go.transform.parent != null)
            {
                Destroy(persistentEmittersShuriken[i].go);
            }
        }
        persistentEmittersShuriken.Clear();
    }
        public WaterfallSmokeEmitter(string prefabName, Transform parentTransform)
        {
            prefab = prefabName;
            parent = parentTransform;
            GameObject go = GameObject.Instantiate(WaterfallParticleLoader.GetParticles(prefabName), Vector3.zero, Quaternion.identity) as GameObject;

            emitter  = go.GetComponent <ParticleSystem>();
            renderer = go.GetComponent <ParticleSystemRenderer>();
            go.transform.SetParent(parentTransform);
            go.transform.localPosition = Vector3.zero;
            go.transform.localScale    = Vector3.one;
            go.transform.localRotation = Quaternion.identity;

            FloatingOrigin.RegisterParticleSystem(emitter);
        }
示例#12
0
            private void MakeOrbit(OrbitDriver driver, CelestialBody reference)
            {
                Debug.Log("Jumping to " + partnerBody);

                CelestialBody oldBody = driver.referenceBody;

                FlightGlobals.overrideOrbit = true;
                FlightGlobals.fetch.Invoke("disableOverride", 2f);
                driver.vessel.Landed   = false;
                driver.vessel.Splashed = false;
                driver.vessel.SetLandedAt("");
                driver.vessel.KillPermanentGroundContact();
                driver.vessel.ResetGroundContact();
                FlightGlobals.currentMainBody = reference;
                OrbitPhysicsManager.SetDominantBody(reference);

                // Pack vessels
                foreach (Vessel vessel in FlightGlobals.Vessels)
                {
                    if (!vessel.packed)
                    {
                        vessel.GoOnRails();
                    }
                }

                // Disable inverse rotation
                foreach (CelestialBody body in PSystemManager.Instance.localBodies)
                {
                    body.inverseRotation = false;
                }

                driver.orbit.referenceBody = reference;
                driver.updateFromParameters();

                // Finalize Vessel Movement
                CollisionEnhancer.bypass = true;
                FloatingOrigin.SetOffset(driver.vessel.transform.position);
                OrbitPhysicsManager.CheckReferenceFrame();
                OrbitPhysicsManager.HoldVesselUnpack(10);
                if (reference != oldBody)
                {
                    GameEvents.onVesselSOIChanged.Fire(
                        new GameEvents.HostedFromToAction <Vessel, CelestialBody>(driver.vessel, oldBody,
                                                                                  reference));
                }

                driver.vessel.IgnoreGForces(20);
            }
示例#13
0
        /// <summary>
        /// Attaches the LaunchPadFX module and
        /// </summary>
        /// <param name="emitterTransformNames"></param>
        /// <param name="baseObject"></param>
        public void Setup(List <string> emitterTransformNames, GameObject baseObject, string smokeName)
        {
            InitializePSystems();
            List <ParticleSystem>     unityEmitters = new List <ParticleSystem>();
            List <KSPParticleEmitter> kspEmitters   = new List <KSPParticleEmitter>();

            totalFXField = typeof(LaunchPadFX).GetField("totalFX", BindingFlags.NonPublic | BindingFlags.Instance);

            foreach (string emName in emitterTransformNames)
            {
                foreach (Transform emTransform in baseObject.transform.FindAllRecursive(emName))
                {
                    if (particleSystems.ContainsKey(smokeName))
                    {
                        if (particleSystems[smokeName].pSystems != null)
                        {
                            foreach (ParticleSystem pSystem in particleSystems[smokeName].pSystems)
                            {
                                //Log.Normal("adding PSystem: " + pSystem.name);
                                ParticleSystem emPsystem = Instantiate(pSystem, emTransform.position, emTransform.rotation, emTransform);
                                emPsystem.gameObject.SetActive(true);
                                unityEmitters.Add(emPsystem);
                                FloatingOrigin.RegisterParticleSystem(emPsystem);
                            }
                        }
                        if (particleSystems[smokeName].kspEmitters != null)
                        {
                            foreach (KSPParticleEmitter pSystem in particleSystems[smokeName].kspEmitters)
                            {
                                //Log.Normal("adding PSystem: " + pSystem.name);
                                KSPParticleEmitter emPsystem = Instantiate(pSystem, emTransform.position, emTransform.rotation, emTransform);
                                emPsystem.gameObject.SetActive(true);
                                kspEmitters.Add(emPsystem);
                            }
                        }
                    }
                    else
                    {
                        Log.UserError("Cannot find a LaunchPad Smoke with name: " + smokeName);
                    }
                }
            }
            // assign the emitters to the underlying component
            ps    = unityEmitters.ToArray();
            kspPS = kspEmitters.ToArray();
        }
示例#14
0
        private void FloatingOriginSection()
        {
            _displayFloatingOrigin = GUILayout.Toggle(_displayFloatingOrigin, "Floating Origin", ButtonStyle);
            if (_displayFloatingOrigin)
            {
                if (GUILayout.Button("Reset floating origin", ButtonStyle))
                {
                    FloatingOrigin.fetch.ResetOffset();
                }

                if (GUILayout.Button("Set random floating origin", ButtonStyle))
                {
                    FloatingOrigin.SetOffset(new Vector3d(Random.Range(0, FloatingOrigin.fetch.threshold),
                                                          Random.Range(0, FloatingOrigin.fetch.threshold),
                                                          Random.Range(0, FloatingOrigin.fetch.threshold)));
                }
            }
        }
示例#15
0
    private void Generate()
    {
        while (count < maxInterest)
        {
            Quaternion randRotation = Quaternion.Euler(Random.Range(0.0f, 360.0f), Random.Range(0.0f, 360.0f), Random.Range(0.0f, 360.0f));
            int        zoneNum      = GetEmptyZone();
            GameObject g            = GameObject.Instantiate(pieces[random.GetNextRand()], player.transform.position + zonePositions[zoneNum] * initialRange, randRotation);

            if (g.TryGetComponent(out PointOfInterest poi))
            {
                poi.index     = zoneNum;
                poi.generator = this;
            }

            count++;
        }
        FloatingOrigin.Rebase(player.transform.position); // just in case rebase on the players current position. They may be going rogue.
    }
示例#16
0
        public void Setup(List <string> emitterTransformNames, GameObject baseObject)
        {
            GetSquadPsystem();

            List <ParticleSystem> emitters = new List <ParticleSystem>();

            foreach (string emName in emitterTransformNames)
            {
                foreach (Transform emTransform in baseObject.transform.FindAllRecursive(emName))
                {
                    //ParticleSystem emPsystem  = emTransform.gameObject.AddComponent<ParticleSystem>();
                    //ParticleSystemRenderer emPsystemRenderer = emTransform.gameObject.AddComponent<ParticleSystemRenderer>();
                    ParticleSystem         emPsystem         = Instantiate(pSystem, emTransform.position, emTransform.rotation, emTransform);
                    ParticleSystemRenderer emPsystemRenderer = Instantiate(pSystemRenderer, emTransform.position, emTransform.rotation, emTransform);

                    emitters.Add(emPsystem);
                    FloatingOrigin.RegisterParticleSystem(emPsystem);
                }
            }

            ps = emitters.ToArray();
        }
示例#17
0
        /// <summary>
        /// Advance the orbit epoch to the specified time sent as parameter
        /// </summary>
        public static void AdvanceShipPosition(this Vessel vessel, double time)
        {
            //If we advance the orbit when flying, we risk going inside the terrain as the orbit goes deep down the planet!
            if (vessel.situation <= Vessel.Situations.FLYING)
            {
                return;
            }

            var obtPos = vessel.orbit.getRelativePositionAtUT(time);
            var obtVel = vessel.orbit.getOrbitalVelocityAtUT(time);

            if (!vessel.packed)
            {
                vessel.GoOnRails();
            }

            vessel.orbit.UpdateFromStateVectors(obtPos, obtVel, vessel.mainBody, time);
            vessel.orbitDriver.updateFromParameters();

            FloatingOrigin.SetOffset(vessel.transform.position);
            OrbitPhysicsManager.CheckReferenceFrame();
            OrbitPhysicsManager.HoldVesselUnpack(10);
            vessel.IgnoreGForces(20);
        }
        public void FixedUpdate()
        {
            try
            {
                if (!HighLogic.LoadedSceneIsFlight)
                {
                    return;
                }

                if (eModule == null)
                {
                    SetupDrive();
                }

                if (IsDeployed != eModule.getIgnitionState)
                {
                    IsDeployed = eModule.getIgnitionState;
                    CheckBubbleDeployment(3);
                    SetPartState(eModule.getIgnitionState);
                }

                if (IsDeployed)
                {
                    //Failsafe
                    if (!CheckAltitude())
                    {
                        eModule.Shutdown();
                        return;
                    }

                    //Snip parts
                    DecoupleBubbleParts();

                    //OH NO FLAMEOUT!
                    if (eModule.flameout)
                    {
                        print("Flameout");
                        BubbleCollapse(eModule.currentThrottle);
                        FlightInputHandler.state.mainThrottle = 0;
                        IsDeployed = false;
                        return;
                    }

                    PlayWarpAnimation(eModule.currentThrottle);
                    GravityBrake();
                    //Start by adding in our subluminal speed which is exponential
                    double lowerThrottle = (Math.Min(eModule.currentThrottle, SUBLIGHT_THROTTLE) * SUBLIGHT_MULT);
                    double distance      = Math.Pow(lowerThrottle, SUBLIGHT_POWER);

                    //Then if throttle is over our threshold, go linear
                    if (eModule.currentThrottle > SUBLIGHT_THROTTLE)
                    {
                        //How much headroom do we have
                        double maxSpeed = ((LIGHTSPEED * WarpFactor) - distance);
                        //How much of this can we use?
                        var upperThrottle = eModule.currentThrottle - SUBLIGHT_THROTTLE;
                        //How much of this headroom have we used?
                        var throttlePercent = upperThrottle / (1 - SUBLIGHT_THROTTLE);
                        //Add it to our current throttle calculation
                        var additionalDistance = maxSpeed * throttlePercent;
                        distance += additionalDistance;
                    }


                    //Take into acount safe accelleration/decelleration
                    //if (distance > CurrentSpeed + Math.Pow(10,MaxAccelleration))
                    //	distance = CurrentSpeed + Math.Pow(10, MaxAccelleration);
                    //if (distance < CurrentSpeed - Math.Pow(10, MaxAccelleration))
                    //	distance = CurrentSpeed - Math.Pow(10, MaxAccelleration);
                    //CurrentSpeed = distance;

                    //if (distance > 1000)
                    //{
                    //Let's see if we can get rid of precision issues with distance.
                    //	Int32 precision = Math.Round(distance, 0).ToString().Length - 1;
                    //	if (precision > MaxAccelleration) precision = MaxAccelleration;
                    //	var magnitude = Math.Round((distance / Math.Pow(10, precision)),0);
                    //	var jumpDistance = Math.Pow(10,precision) * magnitude;
                    //	distance = jumpDistance;
                    //}

                    double maxspeeddisp = Math.Pow(LIGHTSPEED * WarpFactor, GravityBrakes) / LIGHTSPEED;
                    double ts           = WarpFactor * (TurboPoint / 100d);
                    if (maxspeeddisp >= ts)
                    {
                        distance     = distance / (Math.Log(1 / GravityBrakes) + (1 / (TurboFactor * TurboMult)));
                        maxspeeddisp = maxspeeddisp / (Math.Log(1 / GravityBrakes) + (1 / (TurboFactor * TurboMult)));
                    }
                    if (eModule.currentThrottle > MinThrottle)
                    {
                        // Translate through space on the back of a Kraken!
                        if (maxspeeddisp >= minMaxSpeed)
                        {
                            distance = Math.Pow(distance, GravityBrakes) * TimeWarp.fixedDeltaTime;
                        }
                        else
                        {
                            distance     = minMaxSpeed * LIGHTSPEED * TimeWarp.fixedDeltaTime;
                            maxspeeddisp = minMaxSpeed;
                        }
                        Vector3d ps = FlightGlobals.ActiveVessel.transform.position + (transform.up * (float)distance);
                        //krakensbane.setOffset(ps);
                        FloatingOrigin.SetOutOfFrameOffset(ps);

                        //AngularMomentum Block
                        if (AMConservationMode == true)
                        {
                            ApplyAngularMomentum();
                        }
                    }
                    if (AMConservationMode == true && eModule.currentThrottle == 0)
                    {
                        SetAMStartStateVars();
                    }
                    double speedcdisp = (distance) / (LIGHTSPEED * TimeWarp.fixedDeltaTime);
                    status = String.Format("{0:g3}c [Max {1:f3}c] T@{2:f3}c", speedcdisp, maxspeeddisp, ts);
                }
            }
            catch (Exception ex)
            {
                print(String.Format("[WARP] Error in OnFixedUpdate - {0}", ex.Message));
            }
        }
示例#19
0
        public void InitializeSystem()
        {
            //Clear old data
            if (generateName)
            {
                name = (new Spaceworks.PhenomicNameGenerator()).Generate(4, 8);
            }

            DestorySystem();

            //Make the floating origin if it does not exist
            FloatingOrigin.Make();

            //Create the sun's reference (0,0,0) in the model (view not made)
            this.sun = new KeplerBody(this.SolarMass, null);

            //Create the initial states of all planetoids
            this.planetStates = new PlanetoidState[this.planetoids.Length];
            for (int i = 0; i < this.planetoids.Length; i++)
            {
                try {
                    //Init references
                    Planetoid      planet   = this.planetoids[i];
                    GameObject     planetGO = new GameObject(string.IsNullOrEmpty(planet.planetData.name) ? this.name + " - " + i : planet.planetData.name);
                    PlanetoidState state    = new PlanetoidState();
                    this.planetStates[i] = state;

                    //Init orbit model
                    state.orbit      = new KeplerOrbit(this.sun, planet.orbit);
                    state.body       = new KeplerBody(planet.mass, state.orbit);
                    state.gameobject = planetGO;

                    //Configure components
                    FloatingTransform transform = planetGO.AddComponent <FloatingTransform>();
                    transform.worldPosition = new WorldPosition(state.orbit.GetCurrentPosition());
                    state.transform         = transform;

                    CubemapMeshGenerator meshService = planetGO.AddComponent <CubemapMeshGenerator>();
                    meshService.range     = planet.mountains;
                    meshService.useSkirts = true;
                    meshService.heights   = planet.heights;
                    meshService.Init();

                    CubemapTextureService textureService = planetGO.AddComponent <CubemapTextureService>();
                    textureService.top = planet.baseMaterial;
                    textureService.top.SetTexture("_MainTex", planet.textures.top);

                    textureService.bottom = planet.baseMaterial;
                    textureService.bottom.SetTexture("_MainTex", planet.textures.bottom);

                    textureService.left = planet.baseMaterial;
                    textureService.left.SetTexture("_MainTex", planet.textures.left);

                    textureService.right = planet.baseMaterial;
                    textureService.right.SetTexture("_MainTex", planet.textures.right);

                    textureService.front = planet.baseMaterial;
                    textureService.front.SetTexture("_MainTex", planet.textures.front);

                    textureService.back = planet.baseMaterial;
                    textureService.back.SetTexture("_MainTex", planet.textures.back);

                    PlanetConfig pcc = new PlanetConfig(planet.planetData);
                    pcc.generationService = meshService;
                    pcc.textureService    = textureService;

                    Planet p = new Planet(pcc);
                    p.RenderOn(planetGO);
                    if (Camera.main)
                    {
                        p.ForceUpdateLODs(Camera.main.transform.position);
                    }

                    state.planet = p;
                }
                catch (Exception e) {
                    Debug.Log("Failed to fully instanciate planetoid: " + i + " because");
                    Debug.Log(e.Message);
                    Debug.Log(e.StackTrace);
                }
            }
        }
示例#20
0
 void Start()
 {
     fo = GetComponent <FloatingOrigin>();
 }
示例#21
0
    void FixedUpdate()
    {
        float forward = Input.GetAxis("Vertical");
        float right   = Input.GetAxis("Horizontal");
        float up      = Input.GetButton("Jump") ? jump : 0.0f;
        //Vector3 force = new Vector3 (right, 0.0f, forward);
        //force = transform.TransformDirection(force) * speed;\
        //o
        //finds the global direction and force to move

        /*Vector3 force = (transform.forward * forward + transform.right * right) * speed;
         * force.y = rb.velocity.y;*/


        Vector3 newVel = transform.InverseTransformDirection(rb.velocity); //converts current velocity to local space

        newVel = new Vector3(right * speed, newVel.y, forward * speed);    //overrides right and forward speed, but preserves y speed
        newVel = transform.TransformDirection(newVel);                     //converts back to global space
        //moves the player
        //rb.AddForce(force*speed, ForceMode.Impulse);
        bool buttonPush = forward != 0 || right != 0;

        //*****************
        //apply force but stop with velocity


        //if a button was pushed this update
        if (buttonPush)
        {
            wasMoving = true;
        }
        //if a button was pushed this update or last
        if (wasMoving)
        {
            rb.velocity = newVel;
        }

        //keeps wasmoving true for an update after it stops moving
        if (!buttonPush)
        {
            wasMoving = false;
        }

        //apply velocity when a button is pushed or a button was pushed the last frame

        //jumps if touching the ground
        if (isGrounded())
        {
            //rb.AddForce(0.0f, up, 0.0f, ForceMode.VelocityChange);
            rb.AddForce(transform.up * up, ForceMode.VelocityChange);
        }

        //planet.Attract(transform);

        Vector3 realPos = FloatingOrigin.getRealPos(rb.position);

        //points player away from planet
        rb.rotation = Quaternion.FromToRotation(transform.up, realPos) * rb.rotation;
        //print(Quaternion.FromToRotation (transform.up, transform.position) * transform.rotation);

        /*Vector3 gravityUp = (transform.position).normalized;
         * Vector3 localUp = transform.up;
         *
         * // Apply downwards gravity to body
         * rb.AddForce(gravityUp * 10);
         * // Allign bodies up axis with the centre of planet
         * rb.rotation = Quaternion.FromToRotation(localUp,gravityUp) * transform.rotation;*/
    }
示例#22
0
 public static void Add(PersistentKSPShurikenEmitter pkpe)
 {
     persistentEmittersShuriken.Add(pkpe);
     FloatingOrigin.RegisterParticleSystem(pkpe.pe);
 }
示例#23
0
 public static void PutInOrbitAround(CelestialBody body, double altitude, double inclination)
 {
     FlightGlobals.fetch.SetShipOrbit(body.flightGlobalsIndex, 0, altitude + body.Radius, inclination, 0, 0, 0, 0);
     FloatingOrigin.ResetTerrainShaderOffset();
 }
示例#24
0
 private void Start()
 {
     floatingOrigin  = OriginManager.instance.floatingOrigin;
     unloader.loader = this;
     unloader.gameObject.SetActive(false);
 }