Example #1
0
        private void CloseFileIfOpen()
        {
            using (PooledDebugLogger logger = PooledDebugLogger.New(this))
            {
                logger.AppendFormat("Cleaning up file {0}...", this.fileName);

                if (this.csvBytes != null && this.csvBytes.Count > 0)
                {
                    logger.Append(" Writing remaining data...");
                    this.AsyncWriteData();
                }

                logger.Append(" Waiting for writes to finish.");
                while (this.outstandingWrites > 0)
                {
                    logger.Append('.');
                    System.Threading.Thread.Sleep(10);
                }

                if (this._outputFile != null)
                {
                    this._outputFile.Close();
                    this._outputFile = null;
                    logger.Append(" File closed.");
                }

                logger.Print(false);
            }
        }
Example #2
0
        public void OnDestroy()
        {
            using (PooledDebugLogger logger = PooledDebugLogger.New(this))
            {
                logger.Append("Destroying...");

                this.CloseFileIfOpen();

                logger.Append(" Done.");
                logger.Print(false);
            }
        }
Example #3
0
        public void FixedUpdate()
        {
            if (
                HighLogic.LoadedSceneIsFlight &&
                FlightGlobals.Vessels != null &&
                this.vessel != null &&
                this.dockingModule != null
                )
            {
                                #if DEBUG
                bool foundApproach = false;
                                #endif

                PooledDebugLogger verboseLog = PooledDebugLogger.New(this);

                                #if DEBUG
                try
                {
                                #endif

                verboseLog.AppendFormat(" ({0}_{1}) on {2}",
                                        this.part.partInfo.name, this.part.craftID, this.vessel.vesselName);
                verboseLog.AppendFormat("\nChecking within acquireRangeSqr: {0}", this.acquireRangeSqr);

                verboseLog.AppendFormat("this.dockingModule: {0}\n", this.dockingModule == null ?
                                        "null" : this.dockingModule.ToString());

                verboseLog.AppendFormat("this.dockingModule.state: {0}\n",
                                        this.dockingModule == null || this.dockingModule.state == null ?
                                        "null" :this.dockingModule.state.ToString());

                // If we're already docked or pre-attached...
                if (this.dockingModule.state == "Docked" || this.dockingModule.state == "PreAttached")
                {
                    // ...and if the timeout timer is running...
                    if (this.timeoutTimer.IsRunning)
                    {
                        // ...reset the timeout timer
                        this.timeoutTimer.Reset();
                    }

                    // ...skip this check
                    return;
                }

                // If the timeout timer is running, we found a match recently.  If we haven't found a match in more than
                // five seconds, it's not recent anymore, so reset our size to default.
                if (this.timeoutTimer.IsRunning && this.timeoutTimer.ElapsedMilliseconds > 5000)
                {
                    verboseLog.AppendFormat("\nNo target detected within 5 seconds, timing out.");

                    if (this.dockingModule.state != "Docked")
                    {
                        verboseLog.AppendFormat("\nReverting to default nodeType: {0}", this.defaultSize);
                        this.currentSize = this.defaultSize;
                    }

                    this.timeoutTimer.Reset();
                }

                bool foundTargetNode     = false;
                float closestNodeDistSqr = this.acquireRangeSqr * 4f;

                verboseLog.Append("Starting Vessels loop.");

                // Check all vessels for potential docking targets
                Vessel vessel;
                for (int vIdx = 0; vIdx < FlightGlobals.Vessels.Count; vIdx++)
                {
                    vessel = FlightGlobals.Vessels[vIdx];
                    if (vessel == null)
                    {
                        verboseLog.Append("Skipping null vessel.");
                        continue;
                    }

                    // Skip vessels that are just way too far away.
                    if (this.vessel.sqrDistanceTo(vessel) > this.vesselFilterDistanceSqr)
                    {
                        verboseLog.AppendFormat("\nSkipping distant vessel {0} (sqrDistance {1})",
                                                vessel.vesselName,
                                                (vessel.GetWorldPos3D() - this.dockingModule.nodeTransform.position).sqrMagnitude
                                                );
                        continue;
                    }

                    verboseLog.AppendFormat("\nChecking nearby vessel {0} (sqrDistance {1})",
                                            vessel.vesselName,
                                            (vessel.GetWorldPos3D() - this.dockingModule.nodeTransform.position).sqrMagnitude
                                            );

                    // Since this vessel is not too far away, check all docking nodes on the vessel.
                    IList <ModuleDockingNode> potentialNodes = vessel.getModulesOfType <ModuleDockingNode>();
                    ModuleDockingNode         potentialTargetNode;
                    for (int nIdx = 0; nIdx < potentialNodes.Count; nIdx++)
                    {
                        potentialTargetNode = potentialNodes[nIdx];

                        if (potentialTargetNode == null)
                        {
                            verboseLog.AppendFormat("\nSkipping potentialTargetNode at index {0} because it is null",
                                                    nIdx);
                            continue;
                        }

                        if (potentialTargetNode.part == null)
                        {
                            verboseLog.AppendFormat("\nSkipping potentialTargetNode at index {0} because its part is null",
                                                    nIdx);
                            continue;
                        }

                        if (potentialTargetNode.nodeTransform == null)
                        {
                            verboseLog.AppendFormat("\nSkipping potentialTargetNode at index {0} because its node transform is null",
                                                    nIdx);
                            continue;
                        }

                        verboseLog.AppendFormat("\nFound potentialTargetNode: {0}", potentialTargetNode);
                        verboseLog.AppendFormat("\n\tpotentialTargetNode.state: {0}", potentialTargetNode.state);
                        verboseLog.AppendFormat("\n\tpotentialTargetNode.nodeType: {0}", potentialTargetNode.nodeType);

                        // We can't skip the current vessel, because it's possible to dock parts on a single vessel to
                        // each other.  Still, we can't dock a port to itself, so skip this part.
                        if (potentialTargetNode.part == this.part)
                        {
                            verboseLog.AppendFormat("\nDiscarding potentialTargetNode: on this part.");
                            continue;
                        }

                        // If this docking node is already docked, we can't dock to it, so skip it.
                        if (
                            potentialTargetNode.state.Contains("Docked") ||
                            potentialTargetNode.state.Contains("PreAttached"))
                        {
                            verboseLog.Append("\nDiscarding potentialTargetNode: not ready.");
                            continue;
                        }

                        float thisNodeDistSqr =
                            (potentialTargetNode.nodeTransform.position - this.dockingModule.nodeTransform.position)
                            .sqrMagnitude;

                        verboseLog.AppendFormat(
                            "\n\tChecking potentialTargetNode sqrDistance against the lesser of acquireRangeSqr and " +
                            "closestNodeDistSqr ({0})",
                            Mathf.Min(this.acquireRangeSqr * 4f, closestNodeDistSqr)
                            );

                        // Only bother checking nodes closer than twice our acquire range.  We have to check before we
                        // get within acquire range to make sure Squad's code will catch us when we get there.
                        if (thisNodeDistSqr <= Mathf.Min(this.acquireRangeSqr * 4f, closestNodeDistSqr))
                        {
                                                        #if DEBUG
                            foundApproach = true;
                                                        #endif

                            verboseLog.AppendFormat(
                                "\n\tpotentialTargetNode is nearby ({0}), checking if adaptive.", thisNodeDistSqr);

                            ModuleAdaptiveDockingNode targetAdaptiveNode = null;

                            string targetSize;
                            targetSize = string.Empty;

                            // adapt to non-adaptive docking nodes
                            if (this.validSizes.Contains(potentialTargetNode.nodeType))
                            {
                                targetSize       = potentialTargetNode.nodeType;
                                this.currentSize = targetSize;
                            }
                            // Otherwise, look for another adaptive node.
                            else
                            {
                                // Check the part for an AdaptiveDockingNode
                                targetAdaptiveNode = potentialTargetNode.part
                                                     .getFirstModuleOfType <ModuleAdaptiveDockingNode>();
                            }

                            // If we've found an AdaptiveDockingNode...
                            if (targetAdaptiveNode != null)
                            {
                                verboseLog.AppendFormat("\n\tpotentialTargetNode is adaptive.");
                                verboseLog.AppendFormat("\n\tdefaultSize: {0}", targetAdaptiveNode.defaultSize);
                                verboseLog.AppendFormat("\n\tvalidSizes: {0}", targetAdaptiveNode.validSizes);

                                // ...and if we can become its largest (default) size...
                                // to their default size.
                                if (this.validSizes.Contains(targetAdaptiveNode.defaultSize))
                                {
                                    // ...target its default size.
                                    targetSize = targetAdaptiveNode.defaultSize;
                                }
                                // ...otherwise, look for a common size.
                                else
                                {
                                    string commonNodeType = GetGreatestCommonNodeType(this, targetAdaptiveNode);

                                    // ...if we didn't find a common size, stop processing this node
                                    if (commonNodeType == string.Empty)
                                    {
                                        verboseLog.AppendFormat("\n\tInvalid adaptive target: no common node types.");
                                        continue;
                                    }

                                    targetSize = commonNodeType;
                                    targetAdaptiveNode.currentSize = targetSize;

                                    verboseLog.AppendFormat(
                                        "\n\tTarget nodeType set to commonNodeType: {0}", targetSize);
                                }
                            }
                                                        #if DEBUG
                            else
                            {
                                verboseLog.AppendFormat("\n\tpotentialTargetNode is not adaptive.");
                                verboseLog.AppendFormat("\n\tnodeType: {0}", potentialTargetNode.nodeType);
                            }
                                                        #endif

                            // If we never found a target size, it's not a match, so stop processing.
                            if (targetSize == string.Empty)
                            {
                                continue;
                            }

                            // ...otherwise, log this node as the closest and adapt to the target size.
                            closestNodeDistSqr = thisNodeDistSqr;
                            this.currentSize   = targetSize;
                            foundTargetNode    = true;


                            verboseLog.AppendFormat("\n\tLocal nodeType set to commonNodeType: {0}", targetSize);
                            verboseLog.AppendFormat("\n\tFound suitable docking node.");
                            verboseLog.AppendFormat("\n\ttargetSize: {0}", targetSize);

                            verboseLog.AppendFormat("\n\tForward vector dot product: {0} (acquire minimum: {1})",
                                                    Vector3.Dot(potentialTargetNode.nodeTransform.forward,
                                                                this.dockingModule.nodeTransform.forward),
                                                    this.dockingModule.acquireMinFwdDot
                                                    );

                            verboseLog.AppendFormat("\n\tUp vector dot product: {0} (acquire minimum: {1})",
                                                    Vector3.Dot(potentialTargetNode.nodeTransform.up, this.dockingModule.nodeTransform.up),
                                                    this.dockingModule.acquireMinRollDot
                                                    );
                        }
                        else
                        {
                            verboseLog.AppendFormat(
                                "\nDiscarding potentialTargetNode: too far away (thisNodeDistSqr: {0})",
                                thisNodeDistSqr
                                );
                        }
                    }

                    verboseLog.Append('\n');
                }

                verboseLog.Append("\nFixedUpdate Finished.");

                if (foundTargetNode)
                {
                    if (this.timeoutTimer.IsRunning)
                    {
                        this.timeoutTimer.Reset();
                    }

                    this.timeoutTimer.Start();
                }

                                #if DEBUG
            }
            finally
            {
                // if (foundApproach)
                verboseLog.Print();
            }
                                #endif
            }
        }
        private void Update()
        {
            if (MapView.MapIsEnabled && this.mapRenderer == null)
            {
                this.mapRenderer = MapView.MapCamera.gameObject.AddComponent <ARMapRenderer>();
            }

            if (this.toolbarButton != null)
            {
                this.toolbarButton.Enabled = MapView.MapIsEnabled;
            }

            if (this.appLauncherButton == null && !ToolbarManager.ToolbarAvailable && ApplicationLauncher.Ready)
            {
                this.appLauncherButton = ApplicationLauncher.Instance.AddModApplication(
                    this.buttonToggle, this.buttonToggle,
                    ApplicationLauncher.AppScenes.FLIGHT | ApplicationLauncher.AppScenes.MAPVIEW,
                    this.appLauncherTextures[ConnectionStatus.None]
                    );
            }

            if (!this.updateTimer.IsRunning || this.updateTimer.ElapsedMilliseconds > ARConfiguration.UpdateDelay)
            {
                this.updateTimer.Restart();
            }
            else
            {
                return;
            }

            this.log.Clear();

            this.log.Append("[ARFlightController]: Update");

            if (HighLogic.LoadedSceneIsFlight && FlightGlobals.ready && FlightGlobals.ActiveVessel != null)
            {
                Vessel                vessel;
                IAntennaRelay         relay;
                IAntennaRelay         bestActiveRelay = null;
                IList <IAntennaRelay> activeVesselRelays;

                usefulRelays.Clear();

                for (int vIdx = 0; vIdx < FlightGlobals.Vessels.Count; vIdx++)
                {
                    vessel = FlightGlobals.Vessels[vIdx];

                    if (vessel == null || vessel == FlightGlobals.ActiveVessel)
                    {
                        continue;
                    }

                    switch (vessel.vesselType)
                    {
                    case VesselType.Debris:
                    case VesselType.Flag:
                    case VesselType.Unknown:
                        continue;
                    }

                    log.AppendFormat("\nFetching best relay for vessel {0}", vessel);

                    relay = vessel.GetBestRelay();

                    if (relay != null)
                    {
                        log.AppendFormat("\n\tAdding useful relay {0}", relay);

                        usefulRelays.Add(relay);
                    }
                }

                activeVesselRelays = RelayDatabase.Instance[FlightGlobals.ActiveVessel];

                if (activeVesselRelays.Count > 0)
                {
                    bestActiveRelay = RelayDatabase.Instance.GetBestVesselRelay(FlightGlobals.ActiveVessel);

                    log.AppendFormat("\n\tAdding best active vessel relay {0} to usefulRelays", bestActiveRelay);

                    usefulRelays.Add(bestActiveRelay);
                }

                log.AppendFormat("\n\tDoing target searches for {0} useful relays", usefulRelays.Count);

                for (int uIdx = 0; uIdx < usefulRelays.Count; uIdx++)
                {
                    relay = usefulRelays[uIdx];

                    if (relay == null)
                    {
                        continue;
                    }

                    log.AppendFormat("\n\tDoing target search for useful relay {0}", relay);

                    relay.FindNearestRelay();
                    relay.RecalculateTransmissionRates();
                }

                // Very last, find routes for the non-best relays on the active vessel.
                for (int rIdx = 0; rIdx < activeVesselRelays.Count; rIdx++)
                {
                    relay = activeVesselRelays[rIdx];

                    // The best active relay will get checked with the other useful relays later.
                    if (relay == null || relay == bestActiveRelay)
                    {
                        continue;
                    }

                    log.AppendFormat("\nFinding nearest relay for active vessel relay {0}", relay);

                    relay.FindNearestRelay();
                    relay.RecalculateTransmissionRates();
                }

                if (this.toolbarButton != null || this.appLauncherButton != null)
                {
                    log.Append("\nChecking active vessel relay status.");

                    this.currentConnectionStatus = FlightGlobals.ActiveVessel.GetConnectionStatus();

                    log.AppendFormat("\n\tcurrentConnectionStatus: {0}, setting texture to {1}",
                                     this.currentConnectionStatus, this.currentConnectionTexture);

                    if (this.toolbarButton != null)
                    {
                        this.toolbarButton.TexturePath = this.currentConnectionTexture;

                        if (this.currentConnectionStatus == ConnectionStatus.None)
                        {
                            if (!this.toolbarButton.Important)
                            {
                                this.toolbarButton.Important = true;
                            }
                        }
                        else
                        {
                            if (this.toolbarButton.Important)
                            {
                                this.toolbarButton.Important = false;
                            }
                        }
                    }
                    if (this.appLauncherButton != null)
                    {
                        this.appLauncherButton.SetTexture(this.currentAppLauncherTexture);
                    }
                }
            }

            log.Print(false);
        }
Example #5
0
        // Runs on start.
        public override void OnStart(StartState state)
        {
            using (PooledDebugLogger log = PooledDebugLogger.New(this))
            {
                                #if DEBUG
                try {
                                #endif

                log.AppendFormat("{0}: starting up", this.ToString());

                // Start up the underlying PartModule stuff.
                base.OnStart(state);

                log.Append("\n\tbase started up");

                ModuleReactionWheel prefabModule;

                // Fetch the reaction wheel module.
                if (this.part.tryGetFirstModuleOfType <ModuleReactionWheel>(out this.reactionWheelModule))
                {
                    log.AppendFormat("\n\tFound ModuleReactionWheel {0}", this.reactionWheelModule);

                    if (PartLoader.getPartInfoByName(this.part.partInfo.name).partPrefab
                        .tryGetFirstModuleOfType <ModuleReactionWheel>(out prefabModule))
                    {
                        log.AppendFormat("\n\tFound prefab module {0}", prefabModule);

                        TweakableTools.InitializeTweakable <ModuleTweakableReactionWheel>(
                            this.Fields["RollTorque"].uiControlCurrent(),
                            ref this.RollTorque,
                            ref this.reactionWheelModule.RollTorque,
                            prefabModule.RollTorque
                            );

                        log.Append("\n\tRollTorque setup");

                        TweakableTools.InitializeTweakable <ModuleTweakableReactionWheel>(
                            this.Fields["PitchTorque"].uiControlCurrent(),
                            ref this.PitchTorque,
                            ref this.reactionWheelModule.PitchTorque,
                            prefabModule.PitchTorque
                            );

                        log.Append("\n\tPitchTorque setup");

                        TweakableTools.InitializeTweakable <ModuleTweakableReactionWheel>(
                            this.Fields["YawTorque"].uiControlCurrent(),
                            ref this.YawTorque,
                            ref this.reactionWheelModule.YawTorque,
                            prefabModule.YawTorque
                            );

                        log.Append("\n\tYawTorque setup");
                    }
                }

                var torqueGainCtl = this.Fields["TorqueGain"].uiControlCurrent();

                if (torqueGainCtl is UI_FloatRange)
                {
                    var torqueGainSlider = torqueGainCtl as UI_FloatRange;

                    torqueGainSlider.maxValue      = 1f;
                    torqueGainSlider.stepIncrement = 0.025f;
                }

                log.Append("\n\tStarted!");
                                #if DEBUG
            } finally {
                log.Print();
            }
                                #endif
            }
        }
Example #6
0
        private void SetRelayVertices(IAntennaRelay relay)
        {
            log.AppendFormat("\n\t\tDrawing line for relay chain starting at {0}.", relay);

            if (relay.vessel == null)
            {
                log.Append("\n\t\tvessel is null, bailing out");
                return;
            }

            LineRenderer renderer = this[relay.vessel.id];
            Vector3      start    = ScaledSpace.LocalToScaledSpace(relay.vessel.GetWorldPos3D());

            float lineWidth;
            float d = Screen.height / 2f + 0.01f;

            if (MapView.Draw3DLines)
            {
                lineWidth = 0.00833333333f * MapView.MapCamera.Distance;
            }
            else
            {
                lineWidth = 3f;

                // TODO: No idea if this substitution is right.
                // start = MapView.MapCamera.camera.WorldToScreenPoint(start);
                start = PlanetariumCamera.Camera.WorldToScreenPoint(start);

                start.z = start.z >= 0f ? d : -d;
            }

            renderer.SetWidth(lineWidth, lineWidth);

            renderer.SetPosition(0, start);

            int idx = 0;

                        #if DEBUG
            relayStart = timer.ElapsedMilliseconds;
                        #endif

            Vector3 nextPoint;

            renderer.enabled = true;

            if (!relay.CanTransmit())
            {
                thisColor = Color.red;
            }
            else
            {
                if (relay.LinkStatus == ConnectionStatus.Optimal)
                {
                    thisColor = Color.green;
                }
                else
                {
                    thisColor = Color.yellow;
                }
            }

            if (relay.KerbinDirect)
            {
                nextPoint = ScaledSpace.LocalToScaledSpace(AntennaRelay.Kerbin.position);
            }
            else
            {
                if (relay.targetRelay == null || relay.targetRelay.vessel == null)
                {
                    this.LogError(
                        "SetRelayVertices: relay {0} has null target relay or vessel when not KerbinDirect, bailing out!",
                        relay
                        );

                    renderer.enabled = false;
                    return;
                }

                switch (relay.targetRelay.vessel.vesselType)
                {
                case VesselType.Debris:
                case VesselType.Flag:
                case VesselType.Unknown:
                    renderer.enabled = false;
                    return;

                default:
                    break;
                }

                nextPoint = ScaledSpace.LocalToScaledSpace(relay.targetRelay.vessel.GetWorldPos3D());
            }

            renderer.SetColors(thisColor, thisColor);

            if (!MapView.Draw3DLines)
            {
                // TODO: No idea if this substitution is right.
                // nextPoint = MapView.MapCamera.camera.WorldToScreenPoint(nextPoint);
                nextPoint   = PlanetariumCamera.Camera.WorldToScreenPoint(nextPoint);
                nextPoint.z = nextPoint.z >= 0f ? d : -d;
            }

            idx++;

            renderer.SetVertexCount(idx + 1);
            renderer.SetPosition(idx, nextPoint);

            log.AppendFormat("\n\t\t\t...finished segment in {0} ms", timer.ElapsedMilliseconds - relayStart);
        }