コード例 #1
0
        public VariableLabelSet(ConfigNode node, Part part)
        {
            RasterPropMonitorComputer rpmComp = null;

            if (node.HasValue("labelText"))
            {
                string labelText = node.GetValue("labelText").Trim().UnMangleConfigText();
                hasText = true;
                oneShot = !labelText.Contains("$&$");
                rpmComp = RasterPropMonitorComputer.Instantiate(part, true);
                label   = new StringProcessorFormatter(labelText, rpmComp);
            }
            else
            {
                hasText = false;
                oneShot = true;
            }

            if (node.HasValue("color"))
            {
                color    = JUtil.ParseColor32(node.GetValue("color").Trim(), part, ref rpmComp);
                hasColor = true;
            }
            else
            {
                hasColor = false;
            }
        }
コード例 #2
0
        public void Start()
        {
            if (!string.IsNullOrEmpty(borderColor))
            {
                borderColorValue = ConfigNode.ParseColor32(borderColor);
            }
            if (!string.IsNullOrEmpty(backgroundColor))
            {
                backgroundColorValue = ConfigNode.ParseColor32(backgroundColor);
            }

            comp            = RasterPropMonitorComputer.Instantiate(internalProp);
            graphSpace      = new Rect();
            graphSpace.xMin = graphRect.x;
            graphSpace.yMin = graphRect.y;
            graphSpace.xMax = graphRect.z;
            graphSpace.yMax = graphRect.w;
            xGraphSpan      = xSpan;
            interval        = secondsBetweenSamples;
            if (GameDatabase.Instance.ExistsTexture(backgroundTextureURL.EnforceSlashes()))
            {
                backgroundTexture = GameDatabase.Instance.GetTexture(backgroundTextureURL.EnforceSlashes(), false);
            }

            var bottomLeft  = new Vector2(graphSpace.xMin, graphSpace.yMin);
            var bottomRight = new Vector2(graphSpace.xMax, graphSpace.yMin);
            var topLeft     = new Vector2(graphSpace.xMin, graphSpace.yMax);
            var topRight    = new Vector2(graphSpace.xMax, graphSpace.yMax);


            switch (borders)
            {
            case 2:
                borderVertices.Add(bottomRight);
                borderVertices.Add(bottomLeft);
                borderVertices.Add(topLeft);
                break;

            case 4:
                borderVertices.Add(bottomLeft);
                borderVertices.Add(topLeft);
                borderVertices.Add(topRight);
                borderVertices.Add(bottomRight);
                borderVertices.Add(bottomLeft);
                break;
            }

            foreach (ConfigNode node in GameDatabase.Instance.GetConfigNodes("JSIGRAPHSET"))
            {
                if (node.HasValue("name") && node.GetValue("name") == graphSet)
                {
                    foreach (ConfigNode graphNode in node.GetNodes("GRAPH"))
                    {
                        graphs.Add(new GraphLine(graphNode, xGraphSpan, ySpan, interval, comp));
                    }
                }
            }
            JUtil.LogMessage(this, "Graphing {0} values.", graphs.Count);
            startupComplete = true;
        }
コード例 #3
0
        public void Start()
        {
            rpmComp = RasterPropMonitorComputer.Instantiate(internalProp, true);
            if (string.IsNullOrEmpty(soundURL))
            {
                JUtil.LogMessage(this, "JSIInternalBackgroundNoise called with no soundURL");
                Destroy(this);
                return;
            }

            if (needsElectricCharge)
            {
                rpmComp.UpdateDataRefreshRate(soundCheckRate);
                RPMVesselComputer comp = RPMVesselComputer.Instance(vessel.id);
                electricChargeReserve = rpmComp.ProcessVariable(resourceName, comp).MassageToFloat();
            }
            audioOutput            = new FXGroup("RPM" + internalModel.internalName + vessel.id);
            audioOutput.audio      = internalModel.gameObject.AddComponent <AudioSource>();
            audioOutput.audio.clip = GameDatabase.Instance.GetAudioClip(soundURL.EnforceSlashes());
            audioOutput.audio.Stop();
            audioOutput.audio.volume       = GameSettings.SHIP_VOLUME * soundVolume;
            audioOutput.audio.rolloffMode  = AudioRolloffMode.Logarithmic;
            audioOutput.audio.maxDistance  = 10f;
            audioOutput.audio.minDistance  = 8f;
            audioOutput.audio.dopplerLevel = 0f;
            audioOutput.audio.panStereo    = 0f;
            audioOutput.audio.playOnAwake  = false;
            audioOutput.audio.priority     = 255;
            audioOutput.audio.loop         = true;
            audioOutput.audio.pitch        = 1f;
        }
コード例 #4
0
        public void Start()
        {
            if (HighLogic.LoadedSceneIsEditor)
            {
                return;
            }

            rpmComp = RasterPropMonitorComputer.Instantiate(internalProp, true);

            lastOrientation = navBall.rotation;

            if (string.IsNullOrEmpty(variableName) || string.IsNullOrEmpty(range))
            {
                JUtil.LogErrorMessage(this, "variableName or range was null!");
                return;
            }
            string[] tokens = range.Split(',');
            if (tokens.Length != 2)
            {
                JUtil.LogErrorMessage(this, "range '{0}' did not have exactly two values!", range);
                return;
            }

            enablingVariable = new VariableOrNumberRange(rpmComp, variableName, tokens[0], tokens[1]);
        }
コード例 #5
0
 private void UndockCallback(EventReport report)
 {
     if (JUtil.IsActiveVessel(vessel))
     {
         RasterPropMonitorComputer rpmComp = RasterPropMonitorComputer.Instantiate(internalProp, true);
         UpdateMethods(rpmComp);
     }
 }
コード例 #6
0
 public void Start()
 {
     comp             = RasterPropMonitorComputer.Instantiate(internalProp);
     textObjTransform = internalProp.FindModelTransform(transformName);
     textObj          = InternalComponents.Instance.CreateText(fontName, fontSize, textObjTransform, string.Empty);
     // Force oneshot if there's no variables:
     oneshot     |= !labelText.Contains("$&$");
     sourceString = labelText.UnMangleConfigText();
 }
コード例 #7
0
        public void Start()
        {
            if (HighLogic.LoadedSceneIsEditor)
            {
                return;
            }
            try
            {
                rpmComp = RasterPropMonitorComputer.Instantiate(internalProp, true);

                if (string.IsNullOrEmpty(layout))
                {
                    throw new ArgumentNullException("layout");
                }

                foreach (ConfigNode node in GameDatabase.Instance.GetConfigNodes("RPM_GRAPHING_BACKGROUND"))
                {
                    if (node.GetValue("layout") == layout)
                    {
                        if (!node.HasValue("backgroundColor"))
                        {
                            JUtil.LogErrorMessage(this, "?!? no backgroundColor");
                        }
                        string s = node.GetValue("backgroundColor");
                        if (string.IsNullOrEmpty(s))
                        {
                            JUtil.LogErrorMessage(this, "backgroundColor is missing?");
                        }
                        backgroundColorValue = ConfigNode.ParseColor32(node.GetValue("backgroundColor"));

                        ConfigNode[] dataNodes = node.GetNodes("DATA_SET");

                        for (int i = 0; i < dataNodes.Length; i++)
                        {
                            try
                            {
                                dataSets.Add(new DataSet(dataNodes[i], rpmComp));
                            }
                            catch (ArgumentException e)
                            {
                                JUtil.LogErrorMessage(this, "Error in building prop number {1} - {0}", e.Message, internalProp.propID);
                                throw;
                            }
                        }
                        break;
                    }
                }

                startupComplete = true;
            }

            catch
            {
                JUtil.AnnoyUser(this);
                throw;
            }
        }
コード例 #8
0
 /// <summary>
 /// Iterate over all RPMC objects in the craft and set the specified
 /// persistent var to the same value.
 /// </summary>
 /// <param name="name"></param>
 /// <param name="value"></param>
 internal void SetPersistentVariable(string name, object value)
 {
     if (vessel != null)
     {
         for (int partIdx = 0; partIdx < vessel.parts.Count; ++partIdx)
         {
             RasterPropMonitorComputer rpmc = RasterPropMonitorComputer.Instantiate(vessel.parts[partIdx], false);
             rpmc.SetPersistentVariable(name, value, false);
         }
     }
 }
コード例 #9
0
        public void Start()
        {
            if (HighLogic.LoadedSceneIsEditor)
            {
                return;
            }

            try
            {
                rpmComp = RasterPropMonitorComputer.Instantiate(internalProp, true);

                Transform textObjTransform = internalProp.FindModelTransform(transformName);
                textObj = InternalComponents.Instance.CreateText("Arial", fontSize * 15.5f, textObjTransform, "", Color.green, false, "TopLeft");
                // Force oneshot if there's no variables:
                oneshot |= !labelText.Contains("$&$");
                string sourceString = labelText.UnMangleConfigText();

                if (!string.IsNullOrEmpty(sourceString) && sourceString.Length > 1)
                {
                    // Alow a " character to escape leading whitespace
                    if (sourceString[0] == '"')
                    {
                        sourceString = sourceString.Substring(1);
                    }
                }
                spf = new StringProcessorFormatter(sourceString, rpmComp);

                if (!oneshot)
                {
                    rpmComp.UpdateDataRefreshRate(refreshRate);
                }

                if (!(string.IsNullOrEmpty(variableName) || string.IsNullOrEmpty(positiveColor) || string.IsNullOrEmpty(negativeColor) || string.IsNullOrEmpty(zeroColor)))
                {
                    positiveColorValue = JUtil.ParseColor32(positiveColor, part, ref rpmComp);
                    negativeColorValue = JUtil.ParseColor32(negativeColor, part, ref rpmComp);
                    zeroColorValue     = JUtil.ParseColor32(zeroColor, part, ref rpmComp);
                    del = (Action <float>)Delegate.CreateDelegate(typeof(Action <float>), this, "OnCallback");
                    rpmComp.RegisterVariableCallback(variableName, del);
                    registeredVessel = vessel.id;

                    // Initialize the text color. Actually, callback registration took care of that
                }
            }
            catch (Exception e)
            {
                JUtil.LogErrorMessage(this, "Start failed with exception {0}", e);
                spf = new StringProcessorFormatter("x", rpmComp);
            }
        }
コード例 #10
0
        public void Start()
        {
            comp             = RasterPropMonitorComputer.Instantiate(internalProp);
            textObjTransform = internalProp.FindModelTransform(labelTransform);
            textObj          = InternalComponents.Instance.CreateText(fontName, fontSize, textObjTransform, string.Empty);
            activeLabel      = 0;

            SmarterButton.CreateButton(internalProp, switchTransform, Click);

            ConfigNode moduleConfig = null;

            foreach (ConfigNode node in GameDatabase.Instance.GetConfigNodes("PROP"))
            {
                if (node.GetValue("name") == internalProp.propName)
                {
                    moduleConfig = node.GetNodes("MODULE")[moduleID];
                    ConfigNode[] variableNodes = moduleConfig.GetNodes("VARIABLESET");

                    for (int i = 0; i < variableNodes.Length; i++)
                    {
                        try {
                            labelsEx.Add(new VariableLabelSet(variableNodes[i]));
                        } catch (ArgumentException e) {
                            JUtil.LogMessage(this, "Error in building prop number {1} - {0}", e.Message, internalProp.propID);
                        }
                    }
                    break;
                }
            }

            // Fallback: If there are no VARIABLESET blocks, we treat the module configuration itself as a variableset block.
            if (labelsEx.Count < 1 && moduleConfig != null)
            {
                try {
                    labelsEx.Add(new VariableLabelSet(moduleConfig));
                } catch (ArgumentException e) {
                    JUtil.LogMessage(this, "Error in building prop number {1} - {0}", e.Message, internalProp.propID);
                }
            }

            colorShiftRenderer = internalProp.FindModelComponent <Renderer>(coloredObject);
            if (labelsEx[activeLabel].hasColor)
            {
                colorShiftRenderer.material.SetColor(colorName, labelsEx[activeLabel].color);
            }
            textObj.text.Text = StringProcessor.ProcessString(labelsEx[activeLabel].labelText, comp);

            audioOutput = JUtil.SetupIVASound(internalProp, switchSound, switchSoundVolume, false);
            JUtil.LogMessage(this, "Configuration complete in prop {1}, supporting {0} variable indicators.", labelsEx.Count, internalProp.propID);
        }
コード例 #11
0
        /// <summary>
        /// Iterate over every part in the craft to see if any
        /// RasterPropMonitorComputer instances have the specified persistent
        /// variable.
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        internal bool HasPersistentVariable(string name)
        {
            if (vessel != null)
            {
                for (int partIdx = 0; partIdx < vessel.parts.Count; ++partIdx)
                {
                    RasterPropMonitorComputer rpmc = RasterPropMonitorComputer.Instantiate(vessel.parts[partIdx], false);
                    if (rpmc.HasPersistentVariable(name, false))
                    {
                        return(true);
                    }
                }
            }

            return(false);
        }
コード例 #12
0
        /// <summary>
        /// Do a "broadcast" GetPersistentVariable, where we iterate over every
        /// part in the craft and find each RasterPropMonitorComputer.  Return
        /// the value from the first one that contains the variable, or the
        /// default value otherwise.
        /// </summary>
        /// <param name="name"></param>
        /// <param name="defaultValue"></param>
        /// <returns></returns>
        internal object GetPersistentVariable(string name, object defaultValue)
        {
            if (vessel != null)
            {
                for (int partIdx = 0; partIdx < vessel.parts.Count; ++partIdx)
                {
                    RasterPropMonitorComputer rpmc = RasterPropMonitorComputer.Instantiate(vessel.parts[partIdx], false);
                    if (rpmc.HasPersistentVariable(name, false))
                    {
                        return(rpmc.GetPersistentVariable(name, defaultValue, false));
                    }
                }
            }

            return(defaultValue);
        }
コード例 #13
0
 public PersistenceAccessor(MonoBehaviour referenceLocation)
 {
     if (referenceLocation is InternalProp)
     {
         comp   = RasterPropMonitorComputer.Instantiate(referenceLocation);
         propID = (referenceLocation as InternalProp).propID;
     }
     else if (referenceLocation is Part)
     {
         comp   = RasterPropMonitorComputer.Instantiate(referenceLocation);
         propID = -1;
     }
     else
     {
         throw new Exception("Instantiating PersistenceAccessor with indeterminate type");
     }
 }
コード例 #14
0
        public void Start()
        {
            if (HighLogic.LoadedSceneIsEditor)
            {
                return;
            }

            rpmComp = RasterPropMonitorComputer.Instantiate(internalProp, true);

            if (string.IsNullOrEmpty(definitionIn) && definitions != null)
            {
                for (int i = 0; i < definitions.Length; ++i)
                {
                    string[] varrange = definitions[i].range.Split(',');
                    range.Add(new VariableOrNumberRange(rpmComp, definitions[i].variableName, varrange[0], varrange[1]));
                    text.Add(JUtil.LoadPageDefinition(definitions[i].page));
                }
                definitions = null;
                initialized = true;
            }
            else
            {
                string[] tokens = scale.Split(',');

                if (tokens.Length == 2)
                {
                    legacyRange = new VariableOrNumberRange(rpmComp, variableName, tokens[0], tokens[1]);

                    float min = Mathf.Min(threshold.x, threshold.y);
                    float max = Mathf.Max(threshold.x, threshold.y);
                    threshold.x = min;
                    threshold.y = max;

                    text.Add(JUtil.LoadPageDefinition(definitionIn));

                    initialized = true;
                }
                else
                {
                    JUtil.LogErrorMessage(this, "Could not parse the 'scale' parameter: {0}", scale);
                }
            }

            text.Add(JUtil.LoadPageDefinition(definitionOut));
        }
コード例 #15
0
 public void Start()
 {
     if (needsElectricCharge)
     {
         comp = RasterPropMonitorComputer.Instantiate(internalProp);
         comp.UpdateRefreshRates(soundCheckRate, soundCheckRate);
         electricChargeReserve = (double)comp.ProcessVariable("ELECTRIC");
     }
     audioOutput            = new FXGroup("RPM" + internalModel.internalName + vessel.id);
     audioOutput.audio      = internalModel.gameObject.AddComponent <AudioSource>();
     audioOutput.audio.clip = GameDatabase.Instance.GetAudioClip(soundURL.EnforceSlashes());
     audioOutput.audio.Stop();
     audioOutput.audio.volume       = GameSettings.SHIP_VOLUME * soundVolume;
     audioOutput.audio.rolloffMode  = AudioRolloffMode.Logarithmic;
     audioOutput.audio.maxDistance  = 10f;
     audioOutput.audio.minDistance  = 8f;
     audioOutput.audio.dopplerLevel = 0f;
     audioOutput.audio.panLevel     = 0f;
     audioOutput.audio.playOnAwake  = false;
     audioOutput.audio.priority     = 255;
     audioOutput.audio.loop         = true;
     audioOutput.audio.pitch        = 1f;
 }
コード例 #16
0
        public void Start()
        {
            string[] tokens = scale.Split(',');

            if (tokens.Length == 2)
            {
                comp         = RasterPropMonitorComputer.Instantiate(internalProp);
                scaleEnds[0] = new VariableOrNumber(tokens[0], comp, this);
                scaleEnds[1] = new VariableOrNumber(tokens[1], comp, this);
                scaleEnds[2] = new VariableOrNumber(variableName, comp, this);

                textIn  = JUtil.LoadPageDefinition(definitionIn);
                textOut = JUtil.LoadPageDefinition(definitionOut);

                float min = Mathf.Min(threshold.x, threshold.y);
                float max = Mathf.Max(threshold.x, threshold.y);
                threshold.x = min;
                threshold.y = max;
            }
            else
            {
                JUtil.LogErrorMessage(this, "Could not parse the 'scale' parameter: {0}", scale);
            }
        }
コード例 #17
0
        public void Start()
        {
            if (HighLogic.LoadedSceneIsEditor)
            {
                return;
            }
            try
            {
                backgroundColorValue = ConfigNode.ParseColor32(backgroundColor);
                foreach (ConfigNode propNode in GameDatabase.Instance.GetConfigNodes("PROP"))
                {
                    ConfigNode[] moduleNodes = propNode.GetNodes("MODULE");

                    foreach (ConfigNode moduleNode in moduleNodes)
                    {
                        ConfigNode[] pageNodes = moduleNode.GetNodes("PAGE");

                        foreach (ConfigNode pagenode in pageNodes)
                        {
                            ConfigNode[] bghandlerNodes = pagenode.GetNodes("BACKGROUNDHANDLER");

                            foreach (ConfigNode bghandlerNode in bghandlerNodes)
                            {
                                ConfigNode[] gaugeNodes = bghandlerNode.GetNodes("GAUGE");
                                foreach (ConfigNode node in gaugeNodes)
                                {
                                    InfoGauge gauge = new InfoGauge();
                                    JUtil.LogErrorMessage(this, "one item created");
                                    gauge.Texture = node.GetValue("Texture");
                                    JUtil.LogErrorMessage(this, "texture obtained");
                                    gauge.Position = ConfigNode.ParseVector4(node.GetValue("Position"));
                                    JUtil.LogErrorMessage(this, "position obtained");
                                    gauge.Limit = ConfigNode.ParseVector2(node.GetValue("Limit"));
                                    JUtil.LogErrorMessage(this, "limit obtained");
                                    gauge.TextureLimit = ConfigNode.ParseVector4(node.GetValue("TextureLimit"));
                                    JUtil.LogErrorMessage(this, "texlim obtained");
                                    gauge.TextureSize = float.Parse(node.GetValue("TextureSize"));
                                    JUtil.LogErrorMessage(this, "texsiz obtained");
                                    gauge.VerticalMovement = bool.Parse(node.GetValue("VerticalMovement"));
                                    JUtil.LogErrorMessage(this, "vertmov obtained");
                                    gauge.UseLog10 = bool.Parse(node.GetValue("UseLog10"));
                                    JUtil.LogErrorMessage(this, "uselog obtained");
                                    gauge.Use360Horizon = bool.Parse(node.GetValue("Use360Horizon"));
                                    JUtil.LogErrorMessage(this, "360 obtained");
                                    gauge.RotateWithVessel = bool.Parse(node.GetValue("RotateWithVessel"));
                                    JUtil.LogErrorMessage(this, "rotate obtained");
                                    gauge.Variable = node.GetValue("Variable");
                                    JUtil.LogErrorMessage(this, "variable obtained");
                                    gaugeList.Add(gauge);
                                    JUtil.LogErrorMessage(this, "one item added");
                                }
                            }
                        }
                    }
                }

                Shader unlit = Shader.Find("Hidden/Internal-GUITexture");
                foreach (InfoGauge gauge in gaugeList)
                {
                    if (!String.IsNullOrEmpty(gauge.Texture))
                    {
                        gauge.Material             = new Material(unlit);
                        gauge.Material.color       = new Color(0.0f, 0.0f, 0.0f, 0.0f);
                        gauge.Material.mainTexture = GameDatabase.Instance.GetTexture(gauge.Texture.EnforceSlashes(), false);
                    }
                    if (gauge.Material.mainTexture != null)
                    {
                        float height = (float)gauge.Material.mainTexture.height;
                        float width  = (float)gauge.Material.mainTexture.width;
                        gauge.TextureLimit.x = 1.0f - (gauge.TextureLimit.x / width);
                        gauge.TextureLimit.y = 1.0f - (gauge.TextureLimit.y / width);
                        gauge.TextureLimit.z = 1.0f - (gauge.TextureLimit.z / height);
                        gauge.TextureLimit.w = 1.0f - (gauge.TextureLimit.w / height);
                        gauge.TextureSize    = 0.5f * (gauge.TextureSize / height);//实际调用的时候用的是宽和高的一半。
                        if (gauge.Use360Horizon)
                        {
                            gauge.Material.mainTexture.wrapMode = TextureWrapMode.Repeat;
                        }
                        else
                        {
                            gauge.Material.mainTexture.wrapMode = TextureWrapMode.Clamp;
                        }
                    }
                    if (gauge.UseLog10)
                    {
                        gauge.Limit.x = JUtil.PseudoLog10(gauge.Limit.x);
                        gauge.Limit.y = JUtil.PseudoLog10(gauge.Limit.y);
                    }
                }
                JUtil.LogMessage(this, "material read");
                comp            = RasterPropMonitorComputer.Instantiate(internalProp);
                startupComplete = true;
            }
            catch
            {
                JUtil.AnnoyUser(this);
                throw;
            }
        }
コード例 #18
0
        public void Start()
        {
            // If we're not in the correct location, there's no point doing anything.
            if (!InstallationPathWarning.Warn())
            {
                return;
            }

            if (HighLogic.LoadedSceneIsEditor)
            {
                return;
            }

            try
            {
                rpmComp = RasterPropMonitorComputer.Instantiate(internalProp, true);
                JUtil.LogMessage(this, "Attaching monitor {2}-{1} to {0}", rpmComp.RPMCid, internalProp.propID, internalProp.internalModel.internalName);

                // Install the calculator module.
                rpmComp.UpdateDataRefreshRate(refreshDataRate);

                // Loading the font...
                List <Texture2D> fontTexture = new List <Texture2D>();
                fontTexture.Add(LoadFont(this, internalProp, fontTransform));

                // Damn KSP's config parser!!!
                if (!string.IsNullOrEmpty(emptyColor))
                {
                    emptyColorValue = ConfigNode.ParseColor32(emptyColor);
                }
                if (!string.IsNullOrEmpty(defaultFontTint))
                {
                    defaultFontTintValue = ConfigNode.ParseColor32(defaultFontTint);
                }

                if (!string.IsNullOrEmpty(fontDefinition))
                {
                    JUtil.LogMessage(this, "Loading font definition from {0}", fontDefinition);
                    fontDefinitionString = File.ReadAllLines(KSPUtil.ApplicationRootPath + "GameData/" + fontDefinition.EnforceSlashes(), Encoding.UTF8)[0];
                }

                // Now that is done, proceed to setting up the screen.

                screenTexture = new RenderTexture(screenPixelWidth, screenPixelHeight, 24, RenderTextureFormat.ARGB32);
                screenMat     = internalProp.FindModelTransform(screenTransform).GetComponent <Renderer>().material;

                bool manuallyInvertY = false;
                if (SystemInfo.graphicsDeviceVersion.StartsWith("Direct3D 9") || SystemInfo.graphicsDeviceVersion.StartsWith("Direct3D 11") || SystemInfo.graphicsDeviceVersion.StartsWith("Direct3D 12"))
                {
                    manuallyInvertY = (UnityEngine.QualitySettings.antiAliasing > 0);
                }

                foreach (string layerID in textureLayerID.Split())
                {
                    screenMat.SetTexture(layerID.Trim(), screenTexture);
                    // This code was written for a much older flavor of Unity, and the Unity 2017.1 update broke
                    // some assumptions about who managed the y-inversion issue between OpenGL and DX9.
                    if (manuallyInvertY)
                    {
                        screenMat.SetTextureScale(layerID.Trim(), new Vector2(1.0f, -1.0f));
                        screenMat.SetTextureOffset(layerID.Trim(), new Vector2(0.0f, 1.0f));
                    }
                }

                if (GameDatabase.Instance.ExistsTexture(noSignalTextureURL.EnforceSlashes()))
                {
                    noSignalTexture = GameDatabase.Instance.GetTexture(noSignalTextureURL.EnforceSlashes(), false);
                }

                // The neat trick. IConfigNode doesn't work. No amount of kicking got it to work.
                // Well, we don't need it. GameDatabase, gimme config nodes for all props!
                foreach (ConfigNode node in GameDatabase.Instance.GetConfigNodes("PROP"))
                {
                    // Now, we know our own prop name.
                    if (node.GetValue("name") == internalProp.propName)
                    {
                        // So this is the configuration of our prop in memory. Nice place.
                        // We know it contains at least one MODULE node, us.
                        // And we know our moduleID, which is the number in order of being listed in the prop.
                        // Therefore the module by that number is our module's own config node.

                        ConfigNode   moduleConfig = node.GetNodes("MODULE")[moduleID];
                        ConfigNode[] pageNodes    = moduleConfig.GetNodes("PAGE");

                        // Which we can now parse for page definitions.
                        for (int i = 0; i < pageNodes.Length; i++)
                        {
                            // Mwahahaha.
                            try
                            {
                                var newPage = new MonitorPage(i, pageNodes[i], this);
                                activePage = activePage ?? newPage;
                                if (newPage.isDefault)
                                {
                                    activePage = newPage;
                                }
                                pages.Add(newPage);
                            }
                            catch (ArgumentException e)
                            {
                                JUtil.LogMessage(this, "Warning - {0}", e);
                            }
                        }

                        // Now that all pages are loaded, we can use the moment in the loop to suck in all the extra fonts.
                        foreach (string value in moduleConfig.GetValues("extraFont"))
                        {
                            fontTexture.Add(LoadFont(this, internalProp, value));
                        }

                        break;
                    }
                }

                JUtil.LogMessage(this, "Done setting up pages, {0} pages ready.", pages.Count);

                textRenderer = new TextRenderer(fontTexture, new Vector2((float)fontLetterWidth, (float)fontLetterHeight), fontDefinitionString, 17, screenPixelWidth, screenPixelHeight);

                // Load our state from storage...
                persistentVarName = "activePage" + internalProp.propID;
                int activePageID = rpmComp.GetPersistentVariable(persistentVarName, pages.Count, false).MassageToInt();
                if (activePageID < pages.Count)
                {
                    activePage = pages[activePageID];
                }
                activePage.Active(true);

                // If we have global buttons, set them up.
                if (!string.IsNullOrEmpty(globalButtons))
                {
                    string[] tokens = globalButtons.Split(',');
                    for (int i = 0; i < tokens.Length; i++)
                    {
                        string buttonName = tokens[i].Trim();
                        // Notice that holes in the global button list ARE legal.
                        if (!string.IsNullOrEmpty(buttonName))
                        {
                            SmarterButton.CreateButton(internalProp, buttonName, i, GlobalButtonClick, GlobalButtonRelease);
                        }
                    }
                }

                audioOutput = JUtil.SetupIVASound(internalProp, buttonClickSound, buttonClickVolume, false);

                if (needsElectricCharge)
                {
                    delResourceCallback = (Action <bool>)Delegate.CreateDelegate(typeof(Action <bool>), this, "ResourceDepletedCallback");
                    rpmComp.RegisterResourceCallback(resourceName, delResourceCallback);
                }

                if (needsCommConnection)
                {
                    delCommConnectionCallback = (Action <float>)Delegate.CreateDelegate(typeof(Action <float>), this, "CommConnectionCallback");
                    rpmComp.RegisterVariableCallback("COMMNETVESSELCONTROLSTATE", delCommConnectionCallback);
                }

                // And if the try block never completed, startupComplete will never be true.
                startupComplete = true;
            }
            catch
            {
                JUtil.AnnoyUser(this);
                // We can also disable ourselves, that should help.
                enabled = false;
                // And now that we notified the user that config is borked, we rethrow the exception so that
                // it gets logged and we can debug.
                throw;
            }
        }
コード例 #19
0
        public void Start()
        {
            if (!groupList.ContainsKey(actionName) && !customGroupList.ContainsKey(actionName))
            {
                JUtil.LogErrorMessage(this, "Action \"{0}\" is not supported.", actionName);
                return;
            }

            // Parse the needs-electric-charge here.
            if (!string.IsNullOrEmpty(needsElectricCharge))
            {
                switch (needsElectricCharge.ToLowerInvariant().Trim())
                {
                case "true":
                case "yes":
                case "1":
                    needsElectricChargeValue = true;
                    break;

                case "false":
                case "no":
                case "0":
                    needsElectricChargeValue = false;
                    break;
                }
            }

            if (groupList.ContainsKey(actionName))
            {
                oldState = vessel.ActionGroups[groupList[actionName]];
            }
            else
            {
                isCustomAction = true;
                switch (actionName)
                {
                case "intlight":
                    persistentVarName         = internalLightName;
                    lightObjects              = internalModel.FindModelComponents <Light>();
                    needsElectricChargeValue |= string.IsNullOrEmpty(needsElectricCharge) || needsElectricChargeValue;
                    break;

                case "plugin":
                    persistentVarName = string.Empty;
                    foreach (ConfigNode node in GameDatabase.Instance.GetConfigNodes("PROP"))
                    {
                        if (node.GetValue("name") == internalProp.propName)
                        {
                            foreach (ConfigNode pluginConfig in node.GetNodes("MODULE")[moduleID].GetNodes("PLUGINACTION"))
                            {
                                if (pluginConfig.HasValue("name") && pluginConfig.HasValue("actionMethod"))
                                {
                                    if (!InstantiateHandler(pluginConfig, this, out actionHandler, out stateHandler))
                                    {
                                        JUtil.LogErrorMessage(this, "Failed to instantiate action handler {0}", pluginConfig.GetValue("name"));
                                    }
                                    else
                                    {
                                        isPluginAction = true;
                                        break;
                                    }
                                }
                            }
                        }
                    }
                    if (actionHandler == null)
                    {
                        actionName = "dummy";
                        JUtil.LogMessage(this, "Plugin handlers did not start, reverting to dummy mode.");
                    }
                    break;

                default:
                    persistentVarName = "switch" + internalProp.propID + "_" + moduleID;
                    break;
                }
                if (!string.IsNullOrEmpty(perPodPersistenceName))
                {
                    persistentVarName = perPodPersistenceName;
                }
                persistence = new PersistenceAccessor(part);
            }
            if (needsElectricChargeValue)
            {
                comp = RasterPropMonitorComputer.Instantiate(internalProp);
                comp.UpdateRefreshRates(lightCheckRate, lightCheckRate);
            }

            // set up the toggle switch
            if (!string.IsNullOrEmpty(switchTransform))
            {
                SmarterButton.CreateButton(internalProp, switchTransform, Click);
            }

            if (isCustomAction)
            {
                if (isPluginAction && stateHandler != null)
                {
                    oldState = stateHandler();
                }
                else
                {
                    if (!string.IsNullOrEmpty(persistentVarName))
                    {
                        oldState = customGroupList[actionName] = (persistence.GetBool(persistentVarName) ?? oldState);
                        if (actionName == "intlight")
                        {
                            // We have to restore lighting after reading the
                            // persistent variable.
                            SetInternalLights(customGroupList[actionName]);
                        }
                    }
                }
            }

            if (!string.IsNullOrEmpty(animationName))
            {
                // Set up the animation
                Animation[] animators = animateExterior ? part.FindModelAnimators(animationName) : internalProp.FindModelAnimators(animationName);
                if (animators.Length > 0)
                {
                    anim = animators[0];
                }
                else
                {
                    JUtil.LogErrorMessage(this, "Could not find animation \"{0}\" on {2} \"{1}\"",
                                          animationName, animateExterior ? part.name : internalProp.name, animateExterior ? "part" : "prop");
                    return;
                }
                anim[animationName].wrapMode = WrapMode.Once;

                if (oldState ^ reverse)
                {
                    anim[animationName].speed          = float.MaxValue;
                    anim[animationName].normalizedTime = 0;
                }
                else
                {
                    anim[animationName].speed          = float.MinValue;
                    anim[animationName].normalizedTime = 1;
                }
                anim.Play(animationName);
            }
            else if (!string.IsNullOrEmpty(coloredObject))
            {
                // Set up the color shift.
                colorShiftRenderer = internalProp.FindModelComponent <Renderer>(coloredObject);
                disabledColorValue = ConfigNode.ParseColor32(disabledColor);
                enabledColorValue  = ConfigNode.ParseColor32(enabledColor);
                colorShiftRenderer.material.SetColor(colorName, (oldState ^ reverse ? enabledColorValue : disabledColorValue));
            }
            else
            {
                JUtil.LogMessage(this, "Warning, neither color nor animation are defined.");
            }

            audioOutput = JUtil.SetupIVASound(internalProp, switchSound, switchSoundVolume, false);

            startupComplete = true;
        }
コード例 #20
0
        public void Start()
        {
            if (HighLogic.LoadedSceneIsEditor)
            {
                return;
            }

            try
            {
                if (!string.IsNullOrEmpty(odometerMode) && modeList.ContainsKey(odometerMode))
                {
                    oMode = modeList[odometerMode];
                }
                //else if (!string.IsNullOrEmpty(odometerMode)) {
                //	JUtil.LogMessage(this, "found odometerMode {0}, but it's not in the dictionary", odometerMode);
                //}
                //else {
                //	JUtil.LogMessage(this, "Did not find odometerMode");
                //}

                if (string.IsNullOrEmpty(characterTexture) && oMode == OdometerMode.SI)
                {
                    JUtil.LogErrorMessage(this, "Prop configured as SI scaled, but there is no characterTexture");
                    return;
                }

                if (string.IsNullOrEmpty(digitTexture))
                {
                    // We can't do anything without the digit texture
                    JUtil.LogErrorMessage(this, "Prop can not function without a digitTexture");
                    return;
                }

                digitTex = GameDatabase.Instance.GetTexture(digitTexture.EnforceSlashes(), false);
                if (digitTex == null)
                {
                    JUtil.LogErrorMessage(this, "Failed to load digitTexture {0}", digitTexture);
                    return;
                }

                if (!string.IsNullOrEmpty(characterTexture))
                {
                    characterTex = GameDatabase.Instance.GetTexture(characterTexture.EnforceSlashes(), false);
                    if (characterTex == null)
                    {
                        JUtil.LogErrorMessage(this, "Failed to load characterTexture {0}", characterTexture);
                        return;
                    }
                }

                if (!string.IsNullOrEmpty(overlayTexture))
                {
                    overlayTex = GameDatabase.Instance.GetTexture(overlayTexture.EnforceSlashes(), false);
                    if (overlayTex == null)
                    {
                        JUtil.LogErrorMessage(this, "Failed to load overlayTexture {0}", overlayTexture);
                        return;
                    }
                }

                if (string.IsNullOrEmpty(altVariable) != string.IsNullOrEmpty(perPodPersistenceName))
                {
                    JUtil.LogErrorMessage(this, "Both altVariable and perPodPeristenceName must be defined, or neither");
                    return;
                }

                // MOARdV: Which one are we using?  HUD uses the latter, OrbitDisplay, the former.
                Shader unlit = Shader.Find("KSP/Alpha/Unlit Transparent");
                //Shader unlit = Shader.Find("Hidden/Internal-GUITexture");
                digitMaterial = new Material(unlit);

                rpmComp = RasterPropMonitorComputer.Instantiate(internalProp);

                backgroundColorValue = ConfigNode.ParseColor32(backgroundColor);

                lastUpdate = Planetarium.GetUniversalTime();

                screenTexture = new RenderTexture(screenPixelWidth, screenPixelHeight, 24, RenderTextureFormat.ARGB32);
                screenMat     = internalProp.FindModelTransform(screenTransform).renderer.material;

                foreach (string layerID in textureLayerID.Split())
                {
                    screenMat.SetTexture(layerID.Trim(), screenTexture);
                }

                startupComplete = true;
            }
            catch
            {
                JUtil.AnnoyUser(this);
                throw;
            }
        }
コード例 #21
0
        public void Start()
        {
            if (HighLogic.LoadedSceneIsEditor)
            {
                return;
            }

            if (string.IsNullOrEmpty(cameraTransform))
            {
                // Nothing to do if there're no camera transforms.
                return;
            }

            string[] cameraTransformList = cameraTransform.Split('|');

            // I'm sure this and the loop can be done a little differently to
            // make it clearer, but this works.
            string[] fovLimitsList   = (string.IsNullOrEmpty(fovLimits)) ? null : fovLimits.Split('|');
            string[] yawLimitsList   = (string.IsNullOrEmpty(yawLimits)) ? null : yawLimits.Split('|');
            string[] pitchLimitsList = (string.IsNullOrEmpty(pitchLimits)) ? null : pitchLimits.Split('|');
            string[] zoomRateList    = (string.IsNullOrEmpty(zoomRate)) ? null : zoomRate.Split('|');
            string[] yawRateList     = (string.IsNullOrEmpty(yawRate)) ? null : yawRate.Split('|');
            string[] pitchRateList   = (string.IsNullOrEmpty(pitchRate)) ? null : pitchRate.Split('|');

            // cameraTransformList controls the number of cameras instantiated.
            // Every other value has a default, so if it's not specified, we
            // will use that default.
            for (int i = 0; i < cameraTransformList.Length; ++i)
            {
                Vector2 thisFovLimit   = (fovLimitsList != null && i < fovLimitsList.Length) ? (Vector2)ConfigNode.ParseVector2(fovLimitsList[i]) : defaultFovLimits;
                Vector2 thisYawLimit   = (yawLimitsList != null && i < yawLimitsList.Length) ? (Vector2)ConfigNode.ParseVector2(yawLimitsList[i]) : defaultYawLimits;
                Vector2 thisPitchLimit = (pitchLimitsList != null && i < pitchLimitsList.Length) ? (Vector2)ConfigNode.ParseVector2(pitchLimitsList[i]) : defaultPitchLimits;
                float   thisZoomRate   = (zoomRateList != null && i < zoomRateList.Length) ? JUtil.GetFloat(zoomRateList[i]) ?? 0.0f : 0.0f;
                float   thisYawRate    = (yawRateList != null && i < yawRateList.Length) ? JUtil.GetFloat(yawRateList[i]) ?? 0.0f : 0.0f;
                float   thisPitchRate  = (pitchRateList != null && i < pitchRateList.Length) ? JUtil.GetFloat(pitchRateList[i]) ?? 0.0f : 0.0f;

                var thatCamera = new SteerableCameraParameters(cameraTransformList[i],
                                                               thisFovLimit, thisYawLimit, thisPitchLimit,
                                                               thisZoomRate, thisYawRate, thisPitchRate, i + 1);
                cameras.Add(thatCamera);
            }

            gizmoTexture = JUtil.GetGizmoTexture();

            iconMaterial = new Material(Shader.Find("KSP/Alpha/Unlit Transparent"));

            // MOARdV: The maneuver gizmo texture is white. Unity's DrawTexture
            // expects a (0.5, 0.5, 0.5, 0.5) texture to be neutral for coloring
            // purposes.  Multiplying the desired alpha by 1/2 gets around the
            // gizmo texture's color, and gets correct alpha effects.
            Color32 iconColor = ConfigNode.ParseColor32(targetIconColor);

            iconColor.a       /= 2;
            iconMaterial.color = iconColor;

            homeCrosshairMaterial       = new Material(Shader.Find("KSP/Alpha/Unlit Transparent"));
            homeCrosshairMaterial.color = ConfigNode.ParseColor32(homeCrosshairColor);

            if (!string.IsNullOrEmpty(cameraInfoVarName))
            {
                rpmComp = RasterPropMonitorComputer.Instantiate(internalProp);
                if (rpmComp.HasPropVar(cameraInfoVarName + "_ID", internalProp.propID))
                {
                    currentCamera = rpmComp.GetPropVar(cameraInfoVarName + "_ID", internalProp.propID) - 1;
                }
                else
                {
                    rpmComp.SetPropVar(cameraInfoVarName + "_ID", internalProp.propID, currentCamera + 1);
                }
            }
        }
コード例 #22
0
        public void Start()
        {
            if (HighLogic.LoadedSceneIsEditor)
            {
                return;
            }
            try {
                backgroundColorValue = ConfigNode.ParseColor32(backgroundColor);

                Shader unlit = Shader.Find("Hidden/Internal-GUITexture");
                ladderMaterial       = new Material(unlit);
                ladderMaterial.color = new Color(0.5f, 0.5f, 0.5f, 1.0f);
                if (!String.IsNullOrEmpty(horizonTexture))
                {
                    ladderMaterial.mainTexture = GameDatabase.Instance.GetTexture(horizonTexture.EnforceSlashes(), false);
                    if (ladderMaterial.mainTexture != null)
                    {
                        horizonTextureSize.x = horizonTextureSize.x / ladderMaterial.mainTexture.width;
                        ladderMaterial.mainTexture.wrapMode = TextureWrapMode.Clamp;
                    }
                }

                if (!String.IsNullOrEmpty(headingBar))
                {
                    headingMaterial             = new Material(unlit);
                    headingMaterial.color       = new Color(0.5f, 0.5f, 0.5f, 1.0f);
                    headingMaterial.mainTexture = GameDatabase.Instance.GetTexture(headingBar.EnforceSlashes(), false);
                }

                if (!String.IsNullOrEmpty(staticOverlay))
                {
                    overlayMaterial             = new Material(unlit);
                    overlayMaterial.color       = new Color(0.5f, 0.5f, 0.5f, 1.0f);
                    overlayMaterial.mainTexture = GameDatabase.Instance.GetTexture(staticOverlay.EnforceSlashes(), false);
                }

                if (!String.IsNullOrEmpty(vertBar1Texture) && !String.IsNullOrEmpty(vertBar1Variable))
                {
                    vertBar1Material             = new Material(unlit);
                    vertBar1Material.color       = new Color(0.5f, 0.5f, 0.5f, 1.0f);
                    vertBar1Material.mainTexture = GameDatabase.Instance.GetTexture(vertBar1Texture.EnforceSlashes(), false);
                    if (vertBar1Material.mainTexture != null)
                    {
                        float height = (float)vertBar1Material.mainTexture.height;
                        vertBar1TextureLimit.x = 1.0f - (vertBar1TextureLimit.x / height);
                        vertBar1TextureLimit.y = 1.0f - (vertBar1TextureLimit.y / height);
                        vertBar1TextureSize    = 0.5f * (vertBar1TextureSize / height);
                        vertBar1Material.mainTexture.wrapMode = TextureWrapMode.Clamp;
                    }
                }

                if (!String.IsNullOrEmpty(vertBar2Texture) && !String.IsNullOrEmpty(vertBar2Variable))
                {
                    vertBar2Material             = new Material(unlit);
                    vertBar2Material.color       = new Color(0.5f, 0.5f, 0.5f, 1.0f);
                    vertBar2Material.mainTexture = GameDatabase.Instance.GetTexture(vertBar2Texture.EnforceSlashes(), false);
                    if (vertBar2Material.mainTexture != null)
                    {
                        float height = (float)vertBar2Material.mainTexture.height;
                        vertBar2TextureLimit.x = 1.0f - (vertBar2TextureLimit.x / height);
                        vertBar2TextureLimit.y = 1.0f - (vertBar2TextureLimit.y / height);
                        vertBar2TextureSize    = 0.5f * (vertBar2TextureSize / height);
                        vertBar2Material.mainTexture.wrapMode = TextureWrapMode.Clamp;
                    }
                }

                if (vertBar1UseLog10)
                {
                    vertBar1Limit.x = JUtil.PseudoLog10(vertBar1Limit.x);
                    vertBar1Limit.y = JUtil.PseudoLog10(vertBar1Limit.y);
                }

                if (vertBar2UseLog10)
                {
                    vertBar2Limit.x = JUtil.PseudoLog10(vertBar2Limit.x);
                    vertBar2Limit.y = JUtil.PseudoLog10(vertBar2Limit.y);
                }

                if (!string.IsNullOrEmpty(progradeColor))
                {
                    progradeColorValue = ConfigNode.ParseColor32(progradeColor);
                }

                comp = RasterPropMonitorComputer.Instantiate(internalProp);

                iconMaterial       = new Material(unlit);
                iconMaterial.color = new Color(0.5f, 0.5f, 0.5f, 1.0f);
                gizmoTexture       = JUtil.GetGizmoTexture();

                startupComplete = true;
            } catch {
                JUtil.AnnoyUser(this);
                throw;
            }
        }
コード例 #23
0
        /// <summary>
        /// Start everything up and get it configured.
        /// </summary>
        public void Start()
        {
            try
            {
                rpmComp = RasterPropMonitorComputer.Instantiate(internalProp, true);

                Transform textObjTransform = internalProp.FindModelTransform(transformName);
                Vector3   localScale       = internalProp.transform.localScale;

                Transform offsetTransform = new GameObject().transform;
                offsetTransform.gameObject.name  = "JSILabel-" + this.internalProp.propID + "-" + this.GetHashCode().ToString();
                offsetTransform.gameObject.layer = textObjTransform.gameObject.layer;
                offsetTransform.SetParent(textObjTransform, false);
                offsetTransform.Translate(transformOffset.x * localScale.x, transformOffset.y * localScale.y, 0.0f);

                textObj = offsetTransform.gameObject.AddComponent <JSITextMesh>();

                font = JUtil.LoadFont(fontName, fontQuality);

                textObj.font = font;
                //textObj.fontSize = fontQuality; // This doesn't work with Unity-embedded fonts
                textObj.fontSize = font.fontSize;

                if (!string.IsNullOrEmpty(anchor))
                {
                    if (anchor == TextAnchor.LowerCenter.ToString())
                    {
                        textObj.anchor = TextAnchor.LowerCenter;
                    }
                    else if (anchor == TextAnchor.LowerLeft.ToString())
                    {
                        textObj.anchor = TextAnchor.LowerLeft;
                    }
                    else if (anchor == TextAnchor.LowerRight.ToString())
                    {
                        textObj.anchor = TextAnchor.LowerRight;
                    }
                    else if (anchor == TextAnchor.MiddleCenter.ToString())
                    {
                        textObj.anchor = TextAnchor.MiddleCenter;
                    }
                    else if (anchor == TextAnchor.MiddleLeft.ToString())
                    {
                        textObj.anchor = TextAnchor.MiddleLeft;
                    }
                    else if (anchor == TextAnchor.MiddleRight.ToString())
                    {
                        textObj.anchor = TextAnchor.MiddleRight;
                    }
                    else if (anchor == TextAnchor.UpperCenter.ToString())
                    {
                        textObj.anchor = TextAnchor.UpperCenter;
                    }
                    else if (anchor == TextAnchor.UpperLeft.ToString())
                    {
                        textObj.anchor = TextAnchor.UpperLeft;
                    }
                    else if (anchor == TextAnchor.UpperRight.ToString())
                    {
                        textObj.anchor = TextAnchor.UpperRight;
                    }
                    else
                    {
                        JUtil.LogErrorMessage(this, "Unrecognized anchor '{0}' in config for {1} ({2})", anchor, internalProp.propID, internalProp.propName);
                    }
                }

                if (!string.IsNullOrEmpty(alignment))
                {
                    if (alignment == TextAlignment.Center.ToString())
                    {
                        textObj.alignment = TextAlignment.Center;
                    }
                    else if (alignment == TextAlignment.Left.ToString())
                    {
                        textObj.alignment = TextAlignment.Left;
                    }
                    else if (alignment == TextAlignment.Right.ToString())
                    {
                        textObj.alignment = TextAlignment.Right;
                    }
                    else
                    {
                        JUtil.LogErrorMessage(this, "Unrecognized alignment '{0}' in config for {1} ({2})", alignment, internalProp.propID, internalProp.propName);
                    }
                }

                float sizeScalar = 32.0f / (float)font.fontSize;
                textObj.characterSize = fontSize * 0.00005f * sizeScalar;
                textObj.lineSpacing   = textObj.lineSpacing * lineSpacing;

                // "Normal" mode
                if (string.IsNullOrEmpty(switchTransform))
                {
                    // Force oneshot if there's no variables:
                    oneshot |= !labelText.Contains("$&$");
                    string sourceString = labelText.UnMangleConfigText();

                    if (!string.IsNullOrEmpty(sourceString) && sourceString.Length > 1)
                    {
                        // Alow a " character to escape leading whitespace
                        if (sourceString[0] == '"')
                        {
                            sourceString = sourceString.Substring(1);
                        }
                    }
                    labels.Add(new JSILabelSet(sourceString, rpmComp, oneshot));

                    if (!oneshot)
                    {
                        rpmComp.UpdateDataRefreshRate(refreshRate);
                    }
                }
                else // Switchable mode
                {
                    SmarterButton.CreateButton(internalProp, switchTransform, Click);
                    audioOutput = JUtil.SetupIVASound(internalProp, switchSound, switchSoundVolume, false);

                    foreach (ConfigNode node in GameDatabase.Instance.GetConfigNodes("PROP"))
                    {
                        if (node.GetValue("name") == internalProp.propName)
                        {
                            ConfigNode   moduleConfig  = node.GetNodes("MODULE")[moduleID];
                            ConfigNode[] variableNodes = moduleConfig.GetNodes("VARIABLESET");

                            for (int i = 0; i < variableNodes.Length; i++)
                            {
                                try
                                {
                                    bool lOneshot = false;
                                    if (variableNodes[i].HasValue("oneshot"))
                                    {
                                        bool.TryParse(variableNodes[i].GetValue("oneshot"), out lOneshot);
                                    }
                                    if (variableNodes[i].HasValue("labelText"))
                                    {
                                        string lText        = variableNodes[i].GetValue("labelText");
                                        string sourceString = lText.UnMangleConfigText();
                                        lOneshot |= !lText.Contains("$&$");
                                        labels.Add(new JSILabelSet(sourceString, rpmComp, lOneshot));
                                        if (!lOneshot)
                                        {
                                            rpmComp.UpdateDataRefreshRate(refreshRate);
                                        }
                                    }
                                }
                                catch (ArgumentException e)
                                {
                                    JUtil.LogErrorMessage(this, "Error in building prop number {1} - {0}", e.Message, internalProp.propID);
                                }
                            }
                            break;
                        }
                    }
                }

                if (!string.IsNullOrEmpty(zeroColor))
                {
                    zeroColorValue = JUtil.ParseColor32(zeroColor, part, ref rpmComp);
                    textObj.color  = zeroColorValue;
                }

                bool usesMultiColor = false;
                if (!(string.IsNullOrEmpty(variableName) || string.IsNullOrEmpty(positiveColor) || string.IsNullOrEmpty(negativeColor) || string.IsNullOrEmpty(zeroColor)))
                {
                    usesMultiColor     = true;
                    positiveColorValue = JUtil.ParseColor32(positiveColor, part, ref rpmComp);
                    negativeColorValue = JUtil.ParseColor32(negativeColor, part, ref rpmComp);
                    del = (Action <float>)Delegate.CreateDelegate(typeof(Action <float>), this, "OnCallback");
                    rpmComp.RegisterVariableCallback(variableName, del);
                    registeredVessel = vessel.id;

                    // Initialize the text color.  Actually, callback registration takes care of that.
                }

                if (string.IsNullOrEmpty(emissive))
                {
                    if (usesMultiColor)
                    {
                        emissiveMode = EmissiveMode.active;
                    }
                    else
                    {
                        emissiveMode = EmissiveMode.always;
                    }
                }
                else if (emissive.ToLower() == EmissiveMode.always.ToString())
                {
                    emissiveMode = EmissiveMode.always;
                }
                else if (emissive.ToLower() == EmissiveMode.never.ToString())
                {
                    emissiveMode = EmissiveMode.never;
                }
                else if (emissive.ToLower() == EmissiveMode.active.ToString())
                {
                    emissiveMode = EmissiveMode.active;
                }
                else if (emissive.ToLower() == EmissiveMode.passive.ToString())
                {
                    emissiveMode = EmissiveMode.passive;
                }
                else if (emissive.ToLower() == EmissiveMode.flash.ToString())
                {
                    if (flashRate > 0.0f)
                    {
                        emissiveMode = EmissiveMode.flash;
                        fm           = JUtil.InstallFlashModule(part, flashRate);
                        if (fm != null)
                        {
                            fm.flashSubscribers += FlashToggle;
                        }
                    }
                    else
                    {
                        emissiveMode = EmissiveMode.active;
                    }
                }
                else
                {
                    JUtil.LogErrorMessage(this, "Unrecognized emissive mode '{0}' in config for {1} ({2})", emissive, internalProp.propID, internalProp.propName);
                    emissiveMode = EmissiveMode.always;
                }

                UpdateShader();
            }
            catch (Exception e)
            {
                JUtil.LogErrorMessage(this, "Start failed in prop {1} ({2}) with exception {0}", e, internalProp.propID, internalProp.propName);
                labels.Add(new JSILabelSet("ERR", rpmComp, true));
            }
        }
コード例 #24
0
        public void Start()
        {
            if (HighLogic.LoadedSceneIsEditor)
            {
                return;
            }

            rpmComp = RasterPropMonitorComputer.Instantiate(internalProp, true);

            if (string.IsNullOrEmpty(cameraTransform))
            {
                // Nothing to do if there're no camera transforms.
                return;
            }

            string[] cameraTransformList = cameraTransform.Split('|');

            // I'm sure this and the loop can be done a little differently to
            // make it clearer, but this works.
            string[] fovLimitsList   = (string.IsNullOrEmpty(fovLimits)) ? null : fovLimits.Split('|');
            string[] yawLimitsList   = (string.IsNullOrEmpty(yawLimits)) ? null : yawLimits.Split('|');
            string[] pitchLimitsList = (string.IsNullOrEmpty(pitchLimits)) ? null : pitchLimits.Split('|');
            string[] zoomRateList    = (string.IsNullOrEmpty(zoomRate)) ? null : zoomRate.Split('|');
            string[] yawRateList     = (string.IsNullOrEmpty(yawRate)) ? null : yawRate.Split('|');
            string[] pitchRateList   = (string.IsNullOrEmpty(pitchRate)) ? null : pitchRate.Split('|');

            // cameraTransformList controls the number of cameras instantiated.
            // Every other value has a default, so if it's not specified, we
            // will use that default.
            for (int i = 0; i < cameraTransformList.Length; ++i)
            {
                Vector2 thisFovLimit   = (fovLimitsList != null && i < fovLimitsList.Length) ? (Vector2)ConfigNode.ParseVector2(fovLimitsList[i]) : defaultFovLimits;
                Vector2 thisYawLimit   = (yawLimitsList != null && i < yawLimitsList.Length) ? (Vector2)ConfigNode.ParseVector2(yawLimitsList[i]) : defaultYawLimits;
                Vector2 thisPitchLimit = (pitchLimitsList != null && i < pitchLimitsList.Length) ? (Vector2)ConfigNode.ParseVector2(pitchLimitsList[i]) : defaultPitchLimits;
                float   thisZoomRate   = (zoomRateList != null && i < zoomRateList.Length) ? JUtil.GetFloat(zoomRateList[i]) ?? 0.0f : 0.0f;
                float   thisYawRate    = (yawRateList != null && i < yawRateList.Length) ? JUtil.GetFloat(yawRateList[i]) ?? 0.0f : 0.0f;
                float   thisPitchRate  = (pitchRateList != null && i < pitchRateList.Length) ? JUtil.GetFloat(pitchRateList[i]) ?? 0.0f : 0.0f;

                var thatCamera = new SteerableCameraParameters(cameraTransformList[i],
                                                               thisFovLimit, thisYawLimit, thisPitchLimit,
                                                               thisZoomRate, thisYawRate, thisPitchRate, i + 1);
                cameras.Add(thatCamera);
            }

            gizmoTexture = JUtil.GetGizmoTexture();

            iconMaterial = new Material(Shader.Find("KSP/Alpha/Unlit Transparent"));

            // MOARdV: The maneuver gizmo texture is white. Unity's DrawTexture
            // expects a (0.5, 0.5, 0.5, 0.5) texture to be neutral for coloring
            // purposes.  Multiplying the desired alpha by 1/2 gets around the
            // gizmo texture's color, and gets correct alpha effects.
            Color32 iconColor = ConfigNode.ParseColor32(targetIconColor);

            iconColor.a       /= 2;
            iconMaterial.color = iconColor;

            homeCrosshairMaterial       = new Material(Shader.Find("KSP/Alpha/Unlit Transparent"));
            homeCrosshairMaterial.color = ConfigNode.ParseColor32(homeCrosshairColor);

            if (!string.IsNullOrEmpty(cameraInfoVarName))
            {
                //rpmComp = RasterPropMonitorComputer.Instantiate(internalProp);
                //if (rpmComp.HasPropVar(cameraInfoVarName + "_ID", internalProp.propID))
                //{
                //    currentCamera = rpmComp.GetPropVar(cameraInfoVarName + "_ID", internalProp.propID) - 1;
                //}
                //else
                //{
                //    rpmComp.SetPropVar(cameraInfoVarName + "_ID", internalProp.propID, currentCamera + 1);
                //}
            }

            if (!string.IsNullOrEmpty(cameraEffectShader))
            {
                cameraEffectMaterial = new Material(JUtil.LoadInternalShader(cameraEffectShader));

                if (!string.IsNullOrEmpty(cameraEffectVariables))
                {
                    try
                    {
                        string[] vars = cameraEffectVariables.Split('|');
                        for (int i = 0; i < vars.Length; ++i)
                        {
                            string[] components = vars[i].Split(',');
                            if (components.Length == 2)
                            {
                                ShaderEffectVariable sev = new ShaderEffectVariable();
                                sev.variable = Shader.PropertyToID(components[0].Trim());
                                sev.value    = rpmComp.InstantiateVariableOrNumber(components[1]);
                                ceVariables.Add(sev);
                            }
                        }
                    }
                    catch { }
                }

                if (!string.IsNullOrEmpty(cameraEffectTextures))
                {
                    try
                    {
                        string[] vars = cameraEffectTextures.Split('|');
                        for (int i = 0; i < vars.Length; ++i)
                        {
                            string[] components = vars[i].Split(',');
                            if (components.Length == 2)
                            {
                                Texture tex = GameDatabase.Instance.GetTexture(components[1], false);
                                cameraEffectMaterial.SetTexture(components[0], tex);
                            }
                        }
                    }
                    catch { }
                }
            }

            if (!string.IsNullOrEmpty(cameraPixelSize))
            {
                string[] vars = cameraPixelSize.Split(',');
                if (vars.Length == 2)
                {
                    if (!int.TryParse(vars[0], out rentexWidth) || !int.TryParse(vars[1], out rentexHeight) || rentexHeight < 0 || rentexWidth < 0)
                    {
                        JUtil.LogMessage(this, "Bad image dimensions? {0} and {1}", vars[0], vars[1]);
                        rentexHeight = rentexWidth = 0;
                    }
                    else
                    {
                        JUtil.LogMessage(this, "Setting rentex to {0} x {1}", rentexWidth, rentexHeight);
                    }
                }
            }
        }
コード例 #25
0
        public void Start()
        {
            // I guess I shouldn't have expected Squad to actually do something nice for a modder like that.
            // In 0.23, loading in non-alphabetical order is still broken.

            // But now we have KSPAssembly and KSPAssemblyDependency, which actually sidestep the issue, and finally
            // Mu told someone about it and now I can avoid this path hardlinking.
            // Actually, better yet. Let it check for the new canonical location instead. Because f**k installation problems.
            if (!JSI.InstallationPathWarning.Warn())
            {
                return;
            }

            GameEvents.onUndock.Add(UndockCallback);

            if (!string.IsNullOrEmpty(itemColor))
            {
                itemColorValue = ConfigNode.ParseColor32(itemColor);
            }
            if (!string.IsNullOrEmpty(selectedColor))
            {
                selectedColorValue = ConfigNode.ParseColor32(selectedColor);
            }
            if (!string.IsNullOrEmpty(unavailableColor))
            {
                unavailableColorValue = ConfigNode.ParseColor32(unavailableColor);
            }

            topMenu.labelColor    = JUtil.ColorToColorTag(itemColorValue);
            topMenu.selectedColor = JUtil.ColorToColorTag(selectedColorValue);
            topMenu.disabledColor = JUtil.ColorToColorTag(unavailableColorValue);

            RasterPropMonitorComputer rpmComp = RasterPropMonitorComputer.Instantiate(internalProp, true);
            Func <bool> isMjAvailable         = (Func <bool>)rpmComp.GetMethod("JSIMechJeb:GetMechJebAvailable", internalProp, typeof(Func <bool>));

            if (isMjAvailable == null)
            {
                throw new NotImplementedException("isMjAvailable");
            }
            UpdateMethods(rpmComp);

            // If MechJeb is installed, but not found on the craft, menu options can't be populated correctly.
            if (isMjAvailable())
            {
                mjAvailable       = true;
                smartassAvailable = GetModuleExists("MechJebModuleSmartASS");

                topMenu.Add(new TextMenu.Item(JSIMechJeb.TargetTexts[(int)JSIMechJeb.Target.OFF], SmartASS_Off));
                topMenu.Add(new TextMenu.Item(JSIMechJeb.TargetTexts[(int)JSIMechJeb.Target.KILLROT].Replace('\n', ' '), SmartASS_KillRot));
                nodeMenuItem = new TextMenu.Item(JSIMechJeb.TargetTexts[(int)JSIMechJeb.Target.NODE], SmartASS_Node);
                topMenu.Add(nodeMenuItem);
                topMenu.Add(new TextMenu.Item(JSIMechJeb.ModeTexts[(int)JSIMechJeb.Mode.ORBITAL], OrbitalMenu));
                topMenu.Add(new TextMenu.Item(JSIMechJeb.ModeTexts[(int)JSIMechJeb.Mode.SURFACE], SurfaceMenu));
                targetMenuItem = new TextMenu.Item(JSIMechJeb.ModeTexts[(int)JSIMechJeb.Mode.TARGET], TargetMenu);
                topMenu.Add(targetMenuItem);
                forceRollMenuItem = new TextMenu.Item(String.Format("Force Roll: {0:f0}", GetForceRollAngle()), ToggleForceRoll);
                topMenu.Add(forceRollMenuItem);
                topMenu.Add(new TextMenu.Item("Execute Next Node", ExecuteNode, (int)MJMenu.ExecuteNodeMenu));
                topMenu.Add(new TextMenu.Item("Ascent Guidance", AscentGuidance, (int)MJMenu.AscentGuidanceMenu));
                topMenu.Add(new TextMenu.Item("Land Somewhere", LandingGuidance, (int)MJMenu.LandingGuidanceMenu));
                topMenu.Add(new TextMenu.Item("Docking Guidance", DockingGuidance, (int)MJMenu.DockingGuidanceMenu));
                //topMenu.Add(new TextMenu.Item("Hold Alt & Heading", SpaceplaneGuidance, (int)MJMenu.SpacePlaneMenu));
                topMenu.Add(new TextMenu.Item("Circularize", CircularizeMenu, (int)MJMenu.CircularizeMenu));
            }
            else
            {
                mjAvailable       = false;
                smartassAvailable = false;
            }
            activeMenu = topMenu;
        }
コード例 #26
0
        public void Start()
        {
            if (HighLogic.LoadedSceneIsEditor)
            {
                return;
            }

            try
            {
                rpmComp = RasterPropMonitorComputer.Instantiate(internalProp, true);

                if (string.IsNullOrEmpty(perPodPersistenceName))
                {
                    JUtil.LogErrorMessage(this, "perPodPersistenceName must be defined");
                    return;
                }
                if (string.IsNullOrEmpty(defaultValue))
                {
                    JUtil.LogErrorMessage(this, "defaultValue must be defined");
                    return;
                }

                if (stepSize < 0.0f)
                {
                    stepSize = 0.0f;
                }

                //JUtil.LogMessage(this, "Start(): {0}, {1}, {2}, {3}, {4}", perPodPersistenceName, defaultValue, minValue, maxValue, stepSize);

                if (!string.IsNullOrEmpty(minValue))
                {
                    minRange = rpmComp.InstantiateVariableOrNumber(minValue);
                    //JUtil.LogMessage(this, "Created lower bound variable");
                }
                if (!string.IsNullOrEmpty(maxValue))
                {
                    maxRange = rpmComp.InstantiateVariableOrNumber(maxValue);
                    //JUtil.LogMessage(this, "Created upper bound variable");
                }
                if ((minRange == null || maxRange == null) && loopInput == true)
                {
                    JUtil.LogErrorMessage(this, "Overriding loopInput - minValue or maxValue is missing");
                    loopInput = false;
                }

                if (!rpmComp.HasPersistentVariable(perPodPersistenceName, perPodPersistenceIsGlobal))
                {
                    //JUtil.LogMessage(this, "Initializing per pod persistence value {0}", perPodPersistenceName);

                    VariableOrNumber von   = rpmComp.InstantiateVariableOrNumber(defaultValue);
                    float            value = von.AsFloat();

                    if (stepSize > 0.0f)
                    {
                        float remainder = value % stepSize;
                        value -= remainder;
                    }
                    rpmComp.SetPersistentVariable(perPodPersistenceName, value, perPodPersistenceIsGlobal);
                }

                ConfigNode moduleConfig = null;
                foreach (ConfigNode node in GameDatabase.Instance.GetConfigNodes("PROP"))
                {
                    if (node.GetValue("name") == internalProp.propName)
                    {
                        moduleConfig = node.GetNodes("MODULE")[moduleID];
                        ConfigNode[] inputNodes = moduleConfig.GetNodes("USERINPUTSET");

                        for (int i = 0; i < inputNodes.Length; i++)
                        {
                            try
                            {
                                numericInputs.Add(new NumericInput(inputNodes[i], internalProp));
                                //JUtil.LogMessage(this, "Added USERINPUTSET {0}", inputNodes[i].GetValue("switchTransform"));
                            }
                            catch (ArgumentException e)
                            {
                                JUtil.LogErrorMessage(this, "Error in building prop number {1} - {0}", e.Message, internalProp.propID);
                            }
                        }
                        break;
                    }
                }

                enabled = true;
            }
            catch
            {
                JUtil.AnnoyUser(this);
                enabled = false;
                throw;
            }
        }
コード例 #27
0
        public void Start()
        {
            if (HighLogic.LoadedSceneIsEditor)
            {
                return;
            }

            try
            {
                RPMVesselComputer comp = RPMVesselComputer.Instance(vessel);

                if (!groupList.ContainsKey(actionName) && !customGroupList.ContainsKey(actionName))
                {
                    JUtil.LogErrorMessage(this, "Action \"{0}\" is not supported.", actionName);
                    return;
                }

                // Parse the needs-electric-charge here.
                if (!string.IsNullOrEmpty(needsElectricCharge))
                {
                    switch (needsElectricCharge.ToLowerInvariant().Trim())
                    {
                    case "true":
                    case "yes":
                    case "1":
                        needsElectricChargeValue = true;
                        break;

                    case "false":
                    case "no":
                    case "0":
                        needsElectricChargeValue = false;
                        break;
                    }
                }

                // Now parse consumeOnToggle and consumeWhileActive...
                if (!string.IsNullOrEmpty(consumeOnToggle))
                {
                    string[] tokens = consumeOnToggle.Split(',');
                    if (tokens.Length == 3)
                    {
                        consumeOnToggleName = tokens[0].Trim();
                        if (!(PartResourceLibrary.Instance.GetDefinition(consumeOnToggleName) != null &&
                              float.TryParse(tokens[1].Trim(), NumberStyles.Any, CultureInfo.InvariantCulture,
                                             out consumeOnToggleAmount)))
                        {
                            JUtil.LogErrorMessage(this, "Could not parse \"{0}\"", consumeOnToggle);
                        }
                        switch (tokens[2].Trim().ToLower())
                        {
                        case "on":
                            consumingOnToggleUp = true;
                            break;

                        case "off":
                            consumingOnToggleDown = true;
                            break;

                        case "both":
                            consumingOnToggleUp   = true;
                            consumingOnToggleDown = true;
                            break;

                        default:
                            JUtil.LogErrorMessage(this, "So should I consume resources when turning on, turning off, or both in \"{0}\"?", consumeOnToggle);
                            break;
                        }
                    }
                }

                if (!string.IsNullOrEmpty(consumeWhileActive))
                {
                    string[] tokens = consumeWhileActive.Split(',');
                    if (tokens.Length == 2)
                    {
                        consumeWhileActiveName = tokens[0].Trim();
                        if (!(PartResourceLibrary.Instance.GetDefinition(consumeWhileActiveName) != null &&
                              float.TryParse(tokens[1].Trim(),
                                             NumberStyles.Any, CultureInfo.InvariantCulture,
                                             out consumeWhileActiveAmount)))
                        {
                            JUtil.LogErrorMessage(this, "Could not parse \"{0}\"", consumeWhileActive);
                        }
                        else
                        {
                            consumingWhileActive = true;
                            JUtil.LogMessage(this, "Switch in prop {0} prop id {1} will consume {2} while active at a rate of {3}", internalProp.propName,
                                             internalProp.propID, consumeWhileActiveName, consumeWhileActiveAmount);
                        }
                    }
                }

                if (groupList.ContainsKey(actionName))
                {
                    kspAction    = groupList[actionName];
                    currentState = vessel.ActionGroups[kspAction];
                    // action group switches may not belong to a radio group
                    switchGroupIdentifier = -1;
                }
                else
                {
                    isCustomAction = true;
                    switch (actionName)
                    {
                    case "intlight":
                        persistentVarName = internalLightName;
                        if (!string.IsNullOrEmpty(internalLightName))
                        {
                            Light[] availableLights = internalModel.FindModelComponents <Light>();
                            if (availableLights != null && availableLights.Length > 0)
                            {
                                List <Light> lights = new List <Light>(availableLights);
                                for (int i = lights.Count - 1; i >= 0; --i)
                                {
                                    if (lights[i].name != internalLightName)
                                    {
                                        lights.RemoveAt(i);
                                    }
                                }
                                if (lights.Count > 0)
                                {
                                    lightObjects              = lights.ToArray();
                                    needsElectricChargeValue |= string.IsNullOrEmpty(needsElectricCharge) || needsElectricChargeValue;
                                }
                                else
                                {
                                    actionName = "dummy";
                                }
                            }
                        }
                        else
                        {
                            actionName = "dummy";
                        }
                        break;

                    case "plugin":
                        persistentVarName = string.Empty;
                        comp.UpdateDataRefreshRate(refreshRate);

                        foreach (ConfigNode node in GameDatabase.Instance.GetConfigNodes("PROP"))
                        {
                            if (node.GetValue("name") == internalProp.propName)
                            {
                                foreach (ConfigNode pluginConfig in node.GetNodes("MODULE")[moduleID].GetNodes("PLUGINACTION"))
                                {
                                    if (pluginConfig.HasValue("name") && pluginConfig.HasValue("actionMethod"))
                                    {
                                        string action = pluginConfig.GetValue("name").Trim() + ":" + pluginConfig.GetValue("actionMethod").Trim();
                                        actionHandler = (Action <bool>)comp.GetMethod(action, internalProp, typeof(Action <bool>));

                                        if (actionHandler == null)
                                        {
                                            JUtil.LogErrorMessage(this, "Failed to instantiate action handler {0}", action);
                                        }
                                        else
                                        {
                                            if (pluginConfig.HasValue("stateMethod"))
                                            {
                                                string state = pluginConfig.GetValue("name").Trim() + ":" + pluginConfig.GetValue("stateMethod").Trim();
                                                stateVariable = "PLUGIN_" + state;
                                            }
                                            else if (pluginConfig.HasValue("stateVariable"))
                                            {
                                                stateVariable = pluginConfig.GetValue("stateVariable").Trim();
                                            }
                                            isPluginAction = true;
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                        if (actionHandler == null)
                        {
                            actionName = "dummy";
                            JUtil.LogMessage(this, "Plugin handlers did not start, reverting to dummy mode.");
                        }
                        break;

                    case "transfer":
                        persistentVarName = string.Empty;
                        comp.UpdateDataRefreshRate(refreshRate);

                        foreach (ConfigNode node in GameDatabase.Instance.GetConfigNodes("PROP"))
                        {
                            if (node.GetValue("name") == internalProp.propName)
                            {
                                foreach (ConfigNode pluginConfig in node.GetNodes("MODULE")[moduleID].GetNodes("TRANSFERACTION"))
                                {
                                    if ((pluginConfig.HasValue("name") || pluginConfig.HasValue("getVariable")) && pluginConfig.HasValue("perPodPersistenceName"))
                                    {
                                        transferPersistentName = pluginConfig.GetValue("perPodPersistenceName").Trim();
                                        if (pluginConfig.HasValue("stateMethod"))
                                        {
                                            string state = pluginConfig.GetValue("name").Trim() + ":" + pluginConfig.GetValue("stateMethod").Trim();
                                            stateVariable = "PLUGIN_" + state;
                                        }
                                        else if (pluginConfig.HasValue("stateVariable"))
                                        {
                                            stateVariable = pluginConfig.GetValue("stateVariable").Trim();
                                        }
                                        if (pluginConfig.HasValue("setMethod"))
                                        {
                                            string action = pluginConfig.GetValue("name").Trim() + ":" + pluginConfig.GetValue("setMethod").Trim();
                                            transferSetter = (Action <double>)comp.GetMethod(action, internalProp, typeof(Action <double>));

                                            if (transferSetter == null)
                                            {
                                                JUtil.LogErrorMessage(this, "Failed to instantiate transfer handler {0}", pluginConfig.GetValue("name"));
                                            }
                                            else
                                            {
                                                //JUtil.LogMessage(this, "Got setter {0}", action);
                                                break;
                                            }
                                        }
                                        else if (pluginConfig.HasValue("getMethod"))
                                        {
                                            string action = pluginConfig.GetValue("name").Trim() + ":" + pluginConfig.GetValue("getMethod").Trim();
                                            var    getter = (Func <double>)comp.GetMethod(action, internalProp, typeof(Func <double>));

                                            if (getter == null)
                                            {
                                                JUtil.LogErrorMessage(this, "Failed to instantiate transfer handler {0}", pluginConfig.GetValue("name"));
                                            }
                                            else
                                            {
                                                transferGetter = "PLUGIN_" + action;
                                                //JUtil.LogMessage(this, "Got getter {0}", action);
                                                break;
                                            }
                                        }
                                        else if (pluginConfig.HasValue("getVariable"))
                                        {
                                            transferGetter = pluginConfig.GetValue("getVariable").Trim();
                                        }
                                    }
                                }
                            }
                        }
                        if (string.IsNullOrEmpty(transferGetter) && transferSetter == null)
                        {
                            actionName    = "dummy";
                            stateVariable = string.Empty;
                            JUtil.LogMessage(this, "Transfer handlers did not start, reverting to dummy mode.");
                        }
                        break;

                    default:
                        persistentVarName = "switch" + internalProp.propID + "_" + moduleID;
                        break;
                    }
                    if (!string.IsNullOrEmpty(perPodPersistenceName))
                    {
                        persistentVarName = perPodPersistenceName;
                    }
                    else
                    {
                        // If there's no persistence name, there's no valid group id for this switch
                        switchGroupIdentifier = -1;
                    }
                }

                if (customGroupList.ContainsKey(actionName))
                {
                    customAction = customGroupList[actionName];
                }

                if (needsElectricChargeValue || !string.IsNullOrEmpty(persistentVarName) || !string.IsNullOrEmpty(perPodMasterSwitchName) || !string.IsNullOrEmpty(masterVariableName) ||
                    !string.IsNullOrEmpty(transferGetter) || transferSetter != null)
                {
                    rpmComp = RasterPropMonitorComputer.Instantiate(internalProp);

                    comp.UpdateDataRefreshRate(refreshRate);

                    if (!string.IsNullOrEmpty(masterVariableName))
                    {
                        string[] range = masterVariableRange.Split(',');
                        if (range.Length == 2)
                        {
                            masterVariable = new VariableOrNumberRange(masterVariableName, range[0], range[1]);
                        }
                        else
                        {
                            masterVariable = null;
                        }
                    }
                }

                // set up the toggle switch
                if (!string.IsNullOrEmpty(switchTransform))
                {
                    if (momentarySwitch)
                    {
                        SmarterButton.CreateButton(internalProp, switchTransform, Click, Click);
                    }
                    else
                    {
                        SmarterButton.CreateButton(internalProp, switchTransform, Click);
                    }
                }

                if (isCustomAction)
                {
                    if (isPluginAction && !string.IsNullOrEmpty(stateVariable))
                    {
                        try
                        {
                            currentState = (comp.ProcessVariable(stateVariable, -1).MassageToInt()) > 0;
                        }
                        catch
                        {
                            // no-op
                        }
                    }
                    else
                    {
                        if (rpmComp != null && !string.IsNullOrEmpty(persistentVarName))
                        {
                            if (switchGroupIdentifier >= 0)
                            {
                                int activeSwitch = rpmComp.GetVar(persistentVarName, 0);

                                currentState = customGroupState = (switchGroupIdentifier == activeSwitch);
                            }
                            else
                            {
                                currentState = customGroupState = rpmComp.GetBool(persistentVarName, initialState);
                            }

                            if (customAction == CustomActions.IntLight)
                            {
                                // We have to restore lighting after reading the
                                // persistent variable.
                                SetInternalLights(customGroupState);
                            }
                        }
                    }
                }

                if (rpmComp != null && !rpmComp.HasVar(persistentVarName))
                {
                    if (switchGroupIdentifier >= 0)
                    {
                        if (currentState)
                        {
                            rpmComp.SetVar(persistentVarName, switchGroupIdentifier);
                        }
                    }
                    else
                    {
                        rpmComp.SetVar(persistentVarName, currentState);
                    }
                }

                if (!string.IsNullOrEmpty(animationName))
                {
                    // Set up the animation
                    Animation[] animators = animateExterior ? part.FindModelAnimators(animationName) : internalProp.FindModelAnimators(animationName);
                    if (animators.Length > 0)
                    {
                        anim = animators[0];
                    }
                    else
                    {
                        JUtil.LogErrorMessage(this, "Could not find animation \"{0}\" on {2} \"{1}\"",
                                              animationName, animateExterior ? part.name : internalProp.name, animateExterior ? "part" : "prop");
                        return;
                    }
                    anim[animationName].wrapMode = WrapMode.Once;

                    if (currentState ^ reverse)
                    {
                        anim[animationName].speed          = float.MaxValue;
                        anim[animationName].normalizedTime = 0;
                    }
                    else
                    {
                        anim[animationName].speed          = float.MinValue;
                        anim[animationName].normalizedTime = 1;
                    }
                    anim.Play(animationName);
                }
                else if (!string.IsNullOrEmpty(coloredObject))
                {
                    // Set up the color shift.
                    Renderer colorShiftRenderer = internalProp.FindModelComponent <Renderer>(coloredObject);
                    disabledColorValue = ConfigNode.ParseColor32(disabledColor);
                    enabledColorValue  = ConfigNode.ParseColor32(enabledColor);
                    colorShiftMaterial = colorShiftRenderer.material;
                    colorShiftMaterial.SetColor(colorName, (currentState ^ reverse ? enabledColorValue : disabledColorValue));
                }
                else
                {
                    JUtil.LogMessage(this, "Warning, neither color nor animation are defined in prop {0} #{1} (this may be okay).", internalProp.propName, internalProp.propID);
                }

                audioOutput = JUtil.SetupIVASound(internalProp, switchSound, switchSoundVolume, false);

                if (!string.IsNullOrEmpty(loopingSound) && loopingSoundVolume > 0.0f)
                {
                    loopingOutput = JUtil.SetupIVASound(internalProp, loopingSound, loopingSoundVolume, true);
                }

                startupComplete = true;
            }
            catch
            {
                JUtil.AnnoyUser(this);
                enabled = false;
                throw;
            }
        }
コード例 #28
0
        public void Start()
        {
            // If we're not in the correct location, there's no point doing anything.
            if (!InstallationPathWarning.Warn())
            {
                return;
            }

            if (HighLogic.LoadedSceneIsEditor)
            {
                return;
            }

            try {
                // Install the calculator module.
                comp = RasterPropMonitorComputer.Instantiate(internalProp);
                comp.UpdateRefreshRates(refreshTextRate, refreshDataRate);

                // Loading the font...
                fontTexture.Add(LoadFont(this, internalProp, fontTransform, false));

                // Damn KSP's config parser!!!
                if (!string.IsNullOrEmpty(emptyColor))
                {
                    emptyColorValue = ConfigNode.ParseColor32(emptyColor);
                }
                if (!string.IsNullOrEmpty(defaultFontTint))
                {
                    defaultFontTintValue = ConfigNode.ParseColor32(defaultFontTint);
                }

                if (!string.IsNullOrEmpty(fontDefinition))
                {
                    JUtil.LogMessage(this, "Loading font definition from {0}", fontDefinition);
                    fontDefinitionString = File.ReadAllLines(KSPUtil.ApplicationRootPath + "GameData/" + fontDefinition.EnforceSlashes(), Encoding.UTF8)[0];
                }

                // We can pre-compute the rectangles the font characters will be copied from, this seems to make it slightly quicker...
                // although I'm not sure I'm not seeing things by this point.
                int   fontLettersX  = (fontTexture[0].width / fontLetterWidth);
                int   fontLettersY  = (fontTexture[0].height / fontLetterHeight);
                float letterSpanX   = 1f / fontLettersX;
                float letterSpanY   = 1f / fontLettersY;
                int   lastCharacter = fontLettersX * fontLettersY;

                if (lastCharacter != fontDefinitionString.Length)
                {
                    JUtil.LogMessage(this, "Warning, number of letters in the font definition does not match font bitmap size.");
                }

                for (int i = 0; i < lastCharacter && i < fontDefinitionString.Length; i++)
                {
                    int xSource = i % fontLettersX;
                    int ySource = (i - xSource) / fontLettersX;
                    if (!fontCharacters.ContainsKey(fontDefinitionString[i]))
                    {
                        fontCharacters[fontDefinitionString[i]] = new Rect(letterSpanX * xSource, letterSpanY * (fontLettersY - ySource - 1), letterSpanX, letterSpanY);
                    }
                }

                // And a little optimisation for superscript/subscript:
                fontLetterHalfHeight  = fontLetterHeight / 2f;
                fontLetterHalfWidth   = fontLetterWidth / 2f;
                fontLetterDoubleWidth = fontLetterWidth * 2f;

                // Now that is done, proceed to setting up the screen.

                screenTexture = new RenderTexture(screenPixelWidth, screenPixelHeight, 24, RenderTextureFormat.ARGB32);
                screenMat     = internalProp.FindModelTransform(screenTransform).renderer.material;
                foreach (string layerID in textureLayerID.Split())
                {
                    screenMat.SetTexture(layerID.Trim(), screenTexture);
                }

                if (GameDatabase.Instance.ExistsTexture(noSignalTextureURL.EnforceSlashes()))
                {
                    noSignalTexture = GameDatabase.Instance.GetTexture(noSignalTextureURL.EnforceSlashes(), false);
                }

                // Create camera instance...
                cameraStructure = new FlyingCamera(part, screenTexture, cameraAspect);

                // The neat trick. IConfigNode doesn't work. No amount of kicking got it to work.
                // Well, we don't need it. GameDatabase, gimme config nodes for all props!
                foreach (ConfigNode node in GameDatabase.Instance.GetConfigNodes("PROP"))
                {
                    // Now, we know our own prop name.
                    if (node.GetValue("name") == internalProp.propName)
                    {
                        // So this is the configuration of our prop in memory. Nice place.
                        // We know it contains at least one MODULE node, us.
                        // And we know our moduleID, which is the number in order of being listed in the prop.
                        // Therefore the module by that number is our module's own config node.

                        ConfigNode   moduleConfig = node.GetNodes("MODULE")[moduleID];
                        ConfigNode[] pageNodes    = moduleConfig.GetNodes("PAGE");

                        // Which we can now parse for page definitions.
                        for (int i = 0; i < pageNodes.Length; i++)
                        {
                            // Mwahahaha.
                            try {
                                var newPage = new MonitorPage(i, pageNodes[i], this);
                                activePage = activePage ?? newPage;
                                if (newPage.isDefault)
                                {
                                    activePage = newPage;
                                }
                                pages.Add(newPage);
                            } catch (ArgumentException e) {
                                JUtil.LogMessage(this, "Warning - {0}", e);
                            }
                        }

                        // Now that all pages are loaded, we can use the moment in the loop to suck in all the extra fonts.
                        foreach (string value in moduleConfig.GetValues("extraFont"))
                        {
                            fontTexture.Add(LoadFont(this, internalProp, value, true));
                        }

                        break;
                    }
                }
                JUtil.LogMessage(this, "Done setting up pages, {0} pages ready.", pages.Count);

                // Load our state from storage...
                persistentVarName = "activePage" + internalProp.propID;
                persistence       = new PersistenceAccessor(part);
                int?activePageID = persistence.GetVar(persistentVarName);
                if (activePageID != null && activePageID.Value < pages.Count)
                {
                    activePage = pages[activePageID.Value];
                }
                activePage.Active(true);

                // If we have global buttons, set them up.
                if (!string.IsNullOrEmpty(globalButtons))
                {
                    string[] tokens = globalButtons.Split(',');
                    for (int i = 0; i < tokens.Length; i++)
                    {
                        string buttonName = tokens[i].Trim();
                        // Notice that holes in the global button list ARE legal.
                        if (!string.IsNullOrEmpty(buttonName))
                        {
                            SmarterButton.CreateButton(internalProp, buttonName, i, GlobalButtonClick, GlobalButtonRelease);
                        }
                    }
                }

                audioOutput = JUtil.SetupIVASound(internalProp, buttonClickSound, buttonClickVolume, false);

                // One last thing to make sure of: If our pod is transparent, we're always active.
                ourPodIsTransparent = JUtil.IsPodTransparent(part);

                // And if the try block never completed, startupComplete will never be true.
                startupComplete = true;
            } catch {
                JUtil.AnnoyUser(this);
                startupFailed = true;
                // We can also disable ourselves, that should help.
                enabled = false;
                // And now that we notified the user that config is borked, we rethrow the exception so that
                // it gets logged and we can debug.
                throw;
            }
        }
コード例 #29
0
        public void Start()
        {
            if (!HighLogic.LoadedSceneIsFlight)
            {
                return;
            }

            // Grrrrrr.
            if (!string.IsNullOrEmpty(nameColor))
            {
                nameColorValue = ConfigNode.ParseColor32(nameColor);
            }
            if (!string.IsNullOrEmpty(distanceColor))
            {
                distanceColorValue = ConfigNode.ParseColor32(distanceColor);
            }
            if (!string.IsNullOrEmpty(selectedColor))
            {
                selectedColorValue = ConfigNode.ParseColor32(selectedColor);
            }
            if (!string.IsNullOrEmpty(unavailableColor))
            {
                unavailableColorValue = ConfigNode.ParseColor32(unavailableColor);
            }

            persistentVarName = "targetfilter" + internalProp.propID;
            rpmComp           = RasterPropMonitorComputer.Instantiate(internalProp);
            // 7 is the bitmask for ship-station-probe;
            VesselFilterFromBitmask(rpmComp.GetVar(persistentVarName, defaultFilter));

            nameColorTag          = JUtil.ColorToColorTag(nameColorValue);
            distanceColorTag      = JUtil.ColorToColorTag(distanceColorValue);
            selectedColorTag      = JUtil.ColorToColorTag(selectedColorValue);
            unavailableColorTag   = JUtil.ColorToColorTag(unavailableColorValue);
            distanceFormatString  = distanceFormatString.UnMangleConfigText();
            menuTitleFormatString = menuTitleFormatString.UnMangleConfigText();

            topMenu.labelColor    = nameColorTag;
            topMenu.selectedColor = selectedColorTag;
            topMenu.disabledColor = unavailableColorTag;

            if (!string.IsNullOrEmpty(pageTitle))
            {
                pageTitle = pageTitle.UnMangleConfigText();
            }

            foreach (CelestialBody body in FlightGlobals.Bodies)
            {
                celestialsList.Add(new Celestial(body, vessel.transform.position));
            }

            FindReferencePoints();
            UpdateUndockablesList();

            var menuActions = new List <Action <int, TextMenu.Item> >();

            menuActions.Add(ShowCelestialMenu);
            menuActions.Add(ShowVesselMenu);
            menuActions.Add(ShowSpaceObjectMenu);
            menuActions.Add(ShowReferenceMenu);
            menuActions.Add(ShowUndockMenu);
            menuActions.Add(ArmGrapple);
            menuActions.Add(ShowFiltersMenu);
            menuActions.Add(ClearTarget);

            for (int i = 0; i < rootMenu.Count; ++i)
            {
                var menuitem = new TextMenu.Item();
                menuitem.labelText = rootMenu[i];
                menuitem.action    = menuActions[i];
                topMenu.Add(menuitem);
                switch (menuitem.labelText)
                {
                case clearTargetItemText:
                    clearTarget = topMenu[i];
                    break;

                case undockItemText:
                    undockMenuItem = topMenu[i];
                    break;

                case armGrappleText:
                    grappleMenuItem = topMenu[i];
                    break;
                }
            }

            activeMenu = topMenu;
        }
コード例 #30
0
        public VariableAnimationSet(ConfigNode node, InternalProp thisProp)
        {
            if (!node.HasData)
            {
                throw new ArgumentException("No data?!");
            }

            comp = RasterPropMonitorComputer.Instantiate(thisProp);

            string[] tokens = { };

            if (node.HasValue("scale"))
            {
                tokens = node.GetValue("scale").Split(',');
            }

            if (tokens.Length != 2)
            {
                throw new ArgumentException("Could not parse 'scale' parameter.");
            }

            string variableName;

            if (node.HasValue("variableName"))
            {
                variableName = node.GetValue("variableName").Trim();
            }
            else
            {
                throw new ArgumentException("Missing variable name.");
            }

            scaleEnds[0] = new VariableOrNumber(tokens[0], comp, this);
            scaleEnds[1] = new VariableOrNumber(tokens[1], comp, this);
            scaleEnds[2] = new VariableOrNumber(variableName, comp, this);

            // That takes care of the scale, now what to do about that scale:

            if (node.HasValue("reverse"))
            {
                if (!bool.TryParse(node.GetValue("reverse"), out reverse))
                {
                    throw new ArgumentException("So is 'reverse' true or false?");
                }
            }

            if (node.HasValue("animationName"))
            {
                animationName = node.GetValue("animationName");
                Animation[] anims = node.HasValue("animateExterior") ? thisProp.part.FindModelAnimators(animationName) : thisProp.FindModelAnimators(animationName);
                if (anims.Length > 0)
                {
                    anim         = anims[0];
                    anim.enabled = true;
                    anim[animationName].speed          = 0;
                    anim[animationName].normalizedTime = reverse ? 1f : 0f;
                    anim.Play();
                    mode         = Mode.Animation;
                    alwaysActive = node.HasValue("animateExterior");
                }
                else
                {
                    throw new ArgumentException("Animation could not be found.");
                }
            }
            else if (node.HasValue("activeColor") && node.HasValue("passiveColor") && node.HasValue("coloredObject"))
            {
                if (node.HasValue("colorName"))
                {
                    colorName = node.GetValue("colorName");
                }
                passiveColor       = ConfigNode.ParseColor32(node.GetValue("passiveColor"));
                activeColor        = ConfigNode.ParseColor32(node.GetValue("activeColor"));
                colorShiftRenderer = thisProp.FindModelComponent <Renderer>(node.GetValue("coloredObject"));
                colorShiftRenderer.material.SetColor(colorName, reverse ? activeColor : passiveColor);
                mode = Mode.Color;
            }
            else if (node.HasValue("controlledTransform") && node.HasValue("localRotationStart") && node.HasValue("localRotationEnd"))
            {
                controlledTransform = thisProp.FindModelTransform(node.GetValue("controlledTransform").Trim());
                initialRotation     = controlledTransform.localRotation;
                if (node.HasValue("longPath"))
                {
                    longPath    = true;
                    vectorStart = ConfigNode.ParseVector3(node.GetValue("localRotationStart"));
                    vectorEnd   = ConfigNode.ParseVector3(node.GetValue("localRotationEnd"));
                }
                else
                {
                    rotationStart = Quaternion.Euler(ConfigNode.ParseVector3(node.GetValue("localRotationStart")));
                    rotationEnd   = Quaternion.Euler(ConfigNode.ParseVector3(node.GetValue("localRotationEnd")));
                }
                mode = Mode.Rotation;
            }
            else if (node.HasValue("controlledTransform") && node.HasValue("localTranslationStart") && node.HasValue("localTranslationEnd"))
            {
                controlledTransform = thisProp.FindModelTransform(node.GetValue("controlledTransform").Trim());
                initialPosition     = controlledTransform.localPosition;
                vectorStart         = ConfigNode.ParseVector3(node.GetValue("localTranslationStart"));
                vectorEnd           = ConfigNode.ParseVector3(node.GetValue("localTranslationEnd"));
                mode = Mode.Translation;
            }
            else if (node.HasValue("controlledTransform") && node.HasValue("localScaleStart") && node.HasValue("localScaleEnd"))
            {
                controlledTransform = thisProp.FindModelTransform(node.GetValue("controlledTransform").Trim());
                initialScale        = controlledTransform.localScale;
                vectorStart         = ConfigNode.ParseVector3(node.GetValue("localScaleStart"));
                vectorEnd           = ConfigNode.ParseVector3(node.GetValue("localScaleEnd"));
                mode = Mode.Scale;
            }
            else if (node.HasValue("controlledTransform") && node.HasValue("textureLayers") && node.HasValue("textureShiftStart") && node.HasValue("textureShiftEnd"))
            {
                affectedMaterial  = thisProp.FindModelTransform(node.GetValue("controlledTransform").Trim()).renderer.material;
                textureLayer      = node.GetValue("textureLayers");
                textureShiftStart = ConfigNode.ParseVector2(node.GetValue("textureShiftStart"));
                textureShiftEnd   = ConfigNode.ParseVector2(node.GetValue("textureShiftEnd"));
                mode = Mode.TextureShift;
            }
            else if (node.HasValue("controlledTransform") && node.HasValue("textureLayers") && node.HasValue("textureScaleStart") && node.HasValue("textureScaleEnd"))
            {
                affectedMaterial  = thisProp.FindModelTransform(node.GetValue("controlledTransform").Trim()).renderer.material;
                textureLayer      = node.GetValue("textureLayers");
                textureScaleStart = ConfigNode.ParseVector2(node.GetValue("textureScaleStart"));
                textureScaleEnd   = ConfigNode.ParseVector2(node.GetValue("textureScaleEnd"));
                mode = Mode.TextureScale;
            }
            else
            {
                throw new ArgumentException("Cannot initiate any of the possible action modes.");
            }

            if (node.HasValue("threshold"))
            {
                threshold = ConfigNode.ParseVector2(node.GetValue("threshold"));
            }

            if (threshold != Vector2.zero)
            {
                thresholdMode = true;

                float min = Mathf.Min(threshold.x, threshold.y);
                float max = Mathf.Max(threshold.x, threshold.y);
                threshold.x = min;
                threshold.y = max;

                if (node.HasValue("flashingDelay"))
                {
                    flashingDelay = double.Parse(node.GetValue("flashingDelay"));
                }

                if (node.HasValue("alarmSound"))
                {
                    alarmSoundVolume = 0.5f;
                    if (node.HasValue("alarmSoundVolume"))
                    {
                        alarmSoundVolume = float.Parse(node.GetValue("alarmSoundVolume"));
                    }
                    audioOutput = JUtil.SetupIVASound(thisProp, node.GetValue("alarmSound"), alarmSoundVolume, false);
                    if (node.HasValue("alarmMustPlayOnce"))
                    {
                        if (!bool.TryParse(node.GetValue("alarmMustPlayOnce"), out alarmMustPlayOnce))
                        {
                            throw new ArgumentException("So is 'alarmMustPlayOnce' true or false?");
                        }
                    }
                    if (node.HasValue("alarmShutdownButton"))
                    {
                        SmarterButton.CreateButton(thisProp, node.GetValue("alarmShutdownButton"), AlarmShutdown);
                    }
                    if (node.HasValue("alarmSoundLooping"))
                    {
                        if (!bool.TryParse(node.GetValue("alarmSoundLooping"), out alarmSoundLooping))
                        {
                            throw new ArgumentException("So is 'alarmSoundLooping' true or false?");
                        }
                        audioOutput.audio.loop = alarmSoundLooping;
                    }
                }
                TurnOff();
            }
        }