public double Evaluate(RPMVesselComputer comp, PersistenceAccessor persistence) { float result = comp.ProcessVariable(sourceVariable, persistence).MassageToFloat(); Vector2 sourceRange; if (!string.IsNullOrEmpty(sourceMinStr)) { sourceRange.x = comp.ProcessVariable(sourceMinStr, persistence).MassageToFloat(); } else { sourceRange.x = sourceMin; } if (!string.IsNullOrEmpty(sourceMaxStr)) { sourceRange.y = comp.ProcessVariable(sourceMaxStr, persistence).MassageToFloat(); } else { sourceRange.y = sourceMax; } return(JUtil.DualLerp(mappedRange, sourceRange, result)); }
public double Evaluate(RPMVesselComputer comp, PersistenceAccessor persistence) { float result = comp.ProcessVariable(sourceVariable, persistence).MassageToFloat(); Vector2 sourceRange; if (!string.IsNullOrEmpty(sourceMinStr)) { sourceRange.x = comp.ProcessVariable(sourceMinStr, persistence).MassageToFloat(); } else { sourceRange.x = sourceMin; } if (!string.IsNullOrEmpty(sourceMaxStr)) { sourceRange.y = comp.ProcessVariable(sourceMaxStr, persistence).MassageToFloat(); } else { sourceRange.y = sourceMax; } return JUtil.DualLerp(mappedRange, sourceRange, result); }
public void Start() { string[] tokens = scale.Split(','); if (tokens.Length == 2) { //comp = RasterPropMonitorComputer.Instantiate(internalProp); scaleEnds[0] = new VariableOrNumber(tokens[0], this); scaleEnds[1] = new VariableOrNumber(tokens[1], this); scaleEnds[2] = new VariableOrNumber(variableName, 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; persistence = new PersistenceAccessor(internalProp); } else { JUtil.LogErrorMessage(this, "Could not parse the 'scale' parameter: {0}", scale); } }
public static string ProcessString(string input, RPMVesselComputer comp, PersistenceAccessor persistence) { try { if (input.IndexOf(JUtil.VariableListSeparator[0], StringComparison.Ordinal) >= 0) { string[] tokens = input.Split(JUtil.VariableListSeparator, StringSplitOptions.RemoveEmptyEntries); if (tokens.Length != 2) { return("FORMAT ERROR"); } else { string[] vars = tokens[1].Split(JUtil.VariableSeparator, StringSplitOptions.RemoveEmptyEntries); var variables = new object[vars.Length]; for (int i = 0; i < vars.Length; i++) { variables[i] = comp.ProcessVariable(vars[i], persistence); } string output = string.Format(fp, tokens[0], variables); return(output.TrimEnd()); } } } catch (Exception e) { JUtil.LogMessage(comp, "Bad format on string {0}", input); throw e; } return(input.TrimEnd()); }
public static string ProcessString(string input, RPMVesselComputer comp, PersistenceAccessor persistence) { try { if (input.IndexOf(JUtil.VariableListSeparator[0], StringComparison.Ordinal) >= 0) { string[] tokens = input.Split(JUtil.VariableListSeparator, StringSplitOptions.RemoveEmptyEntries); if (tokens.Length != 2) { return "FORMAT ERROR"; } else { string[] vars = tokens[1].Split(JUtil.VariableSeparator, StringSplitOptions.RemoveEmptyEntries); var variables = new object[vars.Length]; for (int i = 0; i < vars.Length; i++) { variables[i] = comp.ProcessVariable(vars[i], persistence); } string output = string.Format(fp, tokens[0], variables); return output.TrimEnd(); } } } catch (Exception e) { JUtil.LogMessage(comp, "Bad format on string {0}", input); throw e; } return input.TrimEnd(); }
internal void Update(RPMVesselComputer comp, PersistenceAccessor persistence) { float value; if (enablingVariable != null) { if (!enablingVariable.IsInRange(comp, persistence)) { return; } } if (variable.Get(out value, comp, persistence)) { if (useLog10) { value = JUtil.PseudoLog10(value); } float yOffset = JUtil.DualLerp(textureLimit, scale, value); MeshFilter meshFilter = barObject.GetComponent <MeshFilter>(); meshFilter.mesh.uv = new[] { new Vector2(0.0f, yOffset - textureSize), new Vector2(1.0f, yOffset - textureSize), new Vector2(0.0f, yOffset + textureSize), new Vector2(1.0f, yOffset + textureSize) }; JUtil.ShowHide(true, barObject); } }
public void Start() { if (HighLogic.LoadedSceneIsEditor) { return; } try { 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])); } catch (ArgumentException e) { JUtil.LogErrorMessage(this, "Error in building prop number {1} - {0}", e.Message, internalProp.propID); throw; } } break; } } graphMaterial = new Material(Shader.Find("KSP/Alpha/Unlit Transparent")); persistence = new PersistenceAccessor(internalProp); startupComplete = true; } catch { JUtil.AnnoyUser(this); throw; } }
public void OnDestroy() { // MOARdV TODO: Tear down everything. if (screenTexture != null) { screenTexture.Release(); screenTexture = null; } persistence = null; }
public void Start() { 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(); if (!oneshot) { RPMVesselComputer comp = RPMVesselComputer.Instance(vessel); comp.UpdateDataRefreshRate(refreshRate); } persistence = new PersistenceAccessor(internalProp); }
public void Update(double time, RPMVesselComputer comp, PersistenceAccessor persistence) { double value = isFlat ? flatValue : comp.ProcessVariable(variableName, persistence).MassageToDouble(); if (double.IsNaN(value) || double.IsInfinity(value)) { return; } points.Add(new Vector2d(time, value)); if (points.Count > maxPoints) { points.RemoveRange(0, points.Count - maxPoints); } }
public void OnDestroy() { if (HighLogic.LoadedSceneIsEditor) { // Nothing configured, nothing to destroy. return; } JUtil.DisposeOfGameObjects(new GameObject[] { ladderMesh, progradeLadderIcon, overlayMesh, headingMesh, progradeHeadingIcon }); for (int i = 0; i < verticalBars.Count; ++i) { JUtil.DisposeOfGameObjects(new GameObject[] { verticalBars[i].barObject }); } persistence = null; }
public void OnDestroy() { // Makes sure we don't leak our render texture if (screenTexture != null) { screenTexture.Release(); screenTexture = null; } if (frozenScreen != null) { Destroy(frozenScreen); } if (screenMat != null) { Destroy(screenMat); } persistence = null; }
public void Start() { if (HighLogic.LoadedSceneIsEditor) { return; } try { backgroundColorValue = ConfigNode.ParseColor32(backgroundColor); cameraBody = new GameObject(); cameraBody.name = "RPMPFD" + cameraBody.GetInstanceID(); cameraBody.layer = drawingLayer; hudCamera = cameraBody.AddComponent <Camera>(); hudCamera.enabled = false; hudCamera.orthographic = true; hudCamera.eventMask = 0; hudCamera.farClipPlane = 3f; hudCamera.orthographicSize = 1.0f; hudCamera.cullingMask = 1 << drawingLayer; // does this actually work? hudCamera.backgroundColor = backgroundColorValue; hudCamera.clearFlags = CameraClearFlags.Depth | CameraClearFlags.Color; hudCamera.transparencySortMode = TransparencySortMode.Orthographic; hudCamera.transform.position = Vector3.zero; hudCamera.transform.LookAt(new Vector3(0.0f, 0.0f, 1.5f), Vector3.up); if (!string.IsNullOrEmpty(progradeColor)) { progradeColorValue = ConfigNode.ParseColor32(progradeColor); } persistence = new PersistenceAccessor(internalProp); } catch (Exception e) { JUtil.LogErrorMessage(this, "Start() failed with an exception: {0}", e); JUtil.AnnoyUser(this); throw; } startupComplete = true; }
public object Evaluate(RPMVesselComputer comp, PersistenceAccessor persistence) { // MOARdV TODO: Reevaluate (SWIDT?) this method if math expressions are added bool evaluation = sourceVariables[0].Evaluate(comp, persistence); for (int i = 1; i < sourceVariables.Count; ++i) { bool nextValue = sourceVariables[i].Evaluate(comp, persistence); switch (op) { case Operator.AND: case Operator.NAND: evaluation = (evaluation) && (nextValue); break; case Operator.OR: case Operator.NOR: evaluation = (evaluation) || (nextValue); break; case Operator.XOR: evaluation = (evaluation) ^ (nextValue); break; default: throw new ArgumentException("CustomVariable.Evaluate was called with an invalid operator?"); case Operator.NONE: break; } } if (op == Operator.NAND || op == Operator.NOR) { evaluation = !evaluation; } return(evaluation.GetHashCode()); }
public void OnDestroy() { //JUtil.LogMessage(this, "OnDestroy()"); persistence = null; }
public bool Evaluate(RPMVesselComputer comp, PersistenceAccessor persistence) { return(range.IsInRange(comp, persistence) ^ reverse); }
public void Update(RPMVesselComputer comp, PersistenceAccessor persistence) { var scaleResults = new float[3]; for (int i = 0; i < 3; i++) { if (!scaleEnds[i].Get(out scaleResults[i], comp, persistence)) { return; } } float scaledValue = Mathf.InverseLerp(scaleResults[0], scaleResults[1], scaleResults[2]); if (thresholdMode) { if (scaledValue >= threshold.x && scaledValue <= threshold.y) { if (flashingDelay > 0) { if (lastStateChange < Planetarium.GetUniversalTime() - flashingDelay) { if (currentState) { TurnOff(); } else { TurnOn(); } } } else { TurnOn(); } if (audioOutput != null && !alarmActive) { audioOutput.audio.Play(); alarmActive = true; } } else { TurnOff(); if (audioOutput != null && alarmActive) { if (!alarmMustPlayOnce) { audioOutput.audio.Stop(); } alarmActive = false; } } // Resetting the audio volume in case it was muted while the ship was out of IVA. if (alarmActive && audioOutput != null) { audioOutput.audio.volume = alarmSoundVolume * GameSettings.SHIP_VOLUME; } } else { switch (mode) { case Mode.Rotation: Quaternion newRotation = longPath ? Quaternion.Euler(Vector3.Lerp(reverse ? vectorEnd : vectorStart, reverse ? vectorStart : vectorEnd, scaledValue)) : Quaternion.Slerp(reverse ? rotationEnd : rotationStart, reverse ? rotationStart : rotationEnd, scaledValue); controlledTransform.localRotation = initialRotation * newRotation; break; case Mode.Translation: controlledTransform.localPosition = initialPosition + Vector3.Lerp(reverse ? vectorEnd : vectorStart, reverse ? vectorStart : vectorEnd, scaledValue); break; case Mode.Scale: controlledTransform.localScale = initialScale + Vector3.Lerp(reverse ? vectorEnd : vectorStart, reverse ? vectorStart : vectorEnd, scaledValue); break; case Mode.Color: colorShiftRenderer.material.SetColor(colorName, Color.Lerp(reverse ? activeColor : passiveColor, reverse ? passiveColor : activeColor, scaledValue)); break; case Mode.TextureShift: foreach (string token in textureLayer.Split(',')) { affectedMaterial.SetTextureOffset(token.Trim(), Vector2.Lerp(reverse ? textureShiftEnd : textureShiftStart, reverse ? textureShiftStart : textureShiftEnd, scaledValue)); } break; case Mode.TextureScale: foreach (string token in textureLayer.Split(',')) { affectedMaterial.SetTextureScale(token.Trim(), Vector2.Lerp(reverse ? textureScaleEnd : textureScaleStart, reverse ? textureScaleStart : textureScaleEnd, scaledValue)); } break; case Mode.LoopingAnimation: // MOARdV TODO: Define what this actually does case Mode.Animation: float lerp = JUtil.DualLerp(reverse ? 1f : 0f, reverse ? 0f : 1f, scaleResults[0], scaleResults[1], scaleResults[2]); if (float.IsNaN(lerp) || float.IsInfinity(lerp)) { lerp = reverse ? 1f : 0f; } onAnim[animationName].normalizedTime = lerp; break; } } }
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; if (JUtil.debugLoggingEnabled) { 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)) { currentState = vessel.ActionGroups[groupList[actionName]]; // action group switches may not belong to a radio group switchGroupIdentifier = -1; } else { isCustomAction = true; switch (actionName) { case "intlight": persistentVarName = internalLightName; lightObjects = internalModel.FindModelComponents<Light>(); needsElectricChargeValue |= string.IsNullOrEmpty(needsElectricCharge) || needsElectricChargeValue; 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}", pluginConfig.GetValue("name")); } else { if (pluginConfig.HasValue("stateMethod")) { string state = pluginConfig.GetValue("name").Trim() + ":" + pluginConfig.GetValue("stateMethod").Trim(); stateHandler = (Func<bool>)comp.GetMethod(state, internalProp, typeof(Func<bool>)); } 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; } else { // If there's no persistence name, there's no valid group id for this switch switchGroupIdentifier = -1; } } if (needsElectricChargeValue || !string.IsNullOrEmpty(persistentVarName) || !string.IsNullOrEmpty(perPodMasterSwitchName) || !string.IsNullOrEmpty(masterVariableName)) { persistence = new PersistenceAccessor(internalProp); comp.UpdateDataRefreshRate(refreshRate); if (!string.IsNullOrEmpty(masterVariableName)) { masterVariable = new VariableOrNumber(masterVariableName, this); string[] range = masterVariableRange.Split(','); if (range.Length == 2) { masterRange[0] = new VariableOrNumber(range[0], this); masterRange[1] = new VariableOrNumber(range[1], this); } else { masterVariable = null; } } } // set up the toggle switch if (!string.IsNullOrEmpty(switchTransform)) { SmarterButton.CreateButton(internalProp, switchTransform, Click); } if (isCustomAction) { if (isPluginAction && stateHandler != null) { currentState = stateHandler(); } else { if (persistence != null) { if (switchGroupIdentifier >= 0) { int activeSwitch = persistence.GetVar(persistentVarName, 0); currentState = customGroupList[actionName] = (switchGroupIdentifier == activeSwitch); } else { currentState = customGroupList[actionName] = persistence.GetBool(persistentVarName, initialState); } if (actionName == "intlight") { // We have to restore lighting after reading the // persistent variable. SetInternalLights(customGroupList[actionName]); } } } } if (persistence != null && !persistence.HasVar(persistentVarName)) { if (switchGroupIdentifier >= 0) { if (currentState) { persistence.SetVar(persistentVarName, switchGroupIdentifier); } } else { persistence.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. colorShiftRenderer = internalProp.FindModelComponent<Renderer>(coloredObject); disabledColorValue = ConfigNode.ParseColor32(disabledColor); enabledColorValue = ConfigNode.ParseColor32(enabledColor); colorShiftRenderer.material.SetColor(colorName, (currentState ^ reverse ? enabledColorValue : disabledColorValue)); } else { JUtil.LogMessage(this, "Warning, neither color nor animation are defined in prop {0} #{1}.", internalProp.propName, internalProp.propID); } audioOutput = JUtil.SetupIVASound(internalProp, switchSound, switchSoundVolume, false); startupComplete = true; } catch { JUtil.AnnoyUser(this); enabled = false; throw; } }
public void Start() { if (HighLogic.LoadedSceneIsEditor) { return; } try { 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); } } if (labelsEx.Count == 0) { JUtil.LogMessage(this, "No labels defined."); throw new ArgumentException("No labels defined"); } colorShiftRenderer = internalProp.FindModelComponent <Renderer>(coloredObject); if (labelsEx[activeLabel].hasColor) { colorShiftRenderer.material.SetColor(colorName, labelsEx[activeLabel].color); } if (labelsEx[activeLabel].hasText) { if (labelsEx[activeLabel].oneShot) { textObj.text.Text = labelsEx[activeLabel].labelText; } else { textObj.text.Text = ""; } } audioOutput = JUtil.SetupIVASound(internalProp, switchSound, switchSoundVolume, false); persistence = new PersistenceAccessor(internalProp); if (JUtil.debugLoggingEnabled) { JUtil.LogMessage(this, "Configuration complete in prop {1}, supporting {0} variable indicators.", labelsEx.Count, internalProp.propID); } } catch { JUtil.AnnoyUser(this); enabled = false; throw; } }
internal void Update(RPMVesselComputer comp, PersistenceAccessor persistence) { float value; if (enablingVariable != null) { if (!enablingVariable.IsInRange(comp, persistence)) { return; } } if (variable.Get(out value, comp, persistence)) { if (useLog10) { value = JUtil.PseudoLog10(value); } float yOffset = JUtil.DualLerp(textureLimit, scale, value); MeshFilter meshFilter = barObject.GetComponent<MeshFilter>(); meshFilter.mesh.uv = new[] { new Vector2(0.0f, yOffset - textureSize), new Vector2(1.0f, yOffset - textureSize), new Vector2(0.0f, yOffset + textureSize), new Vector2(1.0f, yOffset + textureSize) }; JUtil.ShowHide(true, barObject); } }
public void OnDestroy() { // MOARdV TODO: Destroy all teh things! //JUtil.LogMessage(this, "OnDestroy()"); persistence = null; }
public void Start() { // If we're not in the correct location, there's no point doing anything. if (!InstallationPathWarning.Warn()) 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; } }
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; }
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)) { persistence = new PersistenceAccessor(internalProp); if (persistence.HasPropVar(cameraInfoVarName + "_ID")) { currentCamera = persistence.GetPropVar(cameraInfoVarName + "_ID") - 1; } else { persistence.SetPropVar(cameraInfoVarName + "_ID", currentCamera + 1); } } }
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. RPMVesselComputer comp = RPMVesselComputer.Instance(vessel); comp.UpdateDataRefreshRate(refreshDataRate); persistence = new PersistenceAccessor(internalProp); // 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).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)); } 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 = persistence.GetVar(persistentVarName, pages.Count); 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); // 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; } }
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; }
public void Start() { 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; } if (!string.IsNullOrEmpty(perPodPersistenceName)) { persistence = new PersistenceAccessor(part); } // 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); comp = 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; } }
public object Evaluate(RPMVesselComputer comp, PersistenceAccessor persistence) { // MOARdV TODO: Reevaluate (SWIDT?) this method if math expressions are added bool evaluation = sourceVariables[0].Evaluate(comp, persistence); for (int i = 1; i < sourceVariables.Count; ++i) { bool nextValue = sourceVariables[i].Evaluate(comp, persistence); switch (op) { case Operator.AND: case Operator.NAND: evaluation = (evaluation) && (nextValue); break; case Operator.OR: case Operator.NOR: evaluation = (evaluation) || (nextValue); break; case Operator.XOR: evaluation = (evaluation) ^ (nextValue); break; default: throw new ArgumentException("CustomVariable.Evaluate was called with an invalid operator?"); case Operator.NONE: break; } } if (op == Operator.NAND || op == Operator.NOR) { evaluation = !evaluation; } return evaluation.GetHashCode(); }
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; persistence = new PersistenceAccessor(internalProp); // 7 is the bitmask for ship-station-probe; VesselFilterFromBitmask(persistence.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; }
public void OnDestroy() { persistence = null; }
public void Start() { if (HighLogic.LoadedSceneIsEditor) { return; } try { 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)); } } } persistence = new PersistenceAccessor(internalProp); JUtil.LogMessage(this, "Graphing {0} values.", graphs.Count); startupComplete = true; } catch { JUtil.AnnoyUser(this); throw; } }
public void Start() { if (HighLogic.LoadedSceneIsEditor) { return; } try { 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 { variableSets.Add(new VariableAnimationSet(variableNodes[i], internalProp)); } 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 (variableSets.Count < 1 && moduleConfig != null) { try { variableSets.Add(new VariableAnimationSet(moduleConfig, internalProp)); } catch (ArgumentException e) { JUtil.LogMessage(this, "Error in building prop number {1} - {0}", e.Message, internalProp.propID); } } if (JUtil.debugLoggingEnabled) { JUtil.LogMessage(this, "Configuration complete in prop {1}, supporting {0} variable indicators.", variableSets.Count, internalProp.propID); } foreach (VariableAnimationSet thatSet in variableSets) { alwaysActive |= thatSet.alwaysActive; } RPMVesselComputer comp = RPMVesselComputer.Instance(vessel); comp.UpdateDataRefreshRate(refreshRate); persistence = new PersistenceAccessor(internalProp); startupComplete = true; } catch { JUtil.AnnoyUser(this); enabled = false; throw; } }
private void Start() { InstallationPathWarning.Warn("SCANsatRPM"); // Arrrgh. if (!string.IsNullOrEmpty(iconColorSelf)) iconColorSelfValue = ConfigNode.ParseColor32(iconColorSelf); if (!string.IsNullOrEmpty(iconColorTarget)) iconColorTargetValue = ConfigNode.ParseColor32(iconColorTarget); if (!string.IsNullOrEmpty(iconColorUnvisitedAnomaly)) iconColorUnvisitedAnomalyValue = ConfigNode.ParseColor32(iconColorUnvisitedAnomaly); if (!string.IsNullOrEmpty(iconColorVisitedAnomaly)) iconColorVisitedAnomalyValue = ConfigNode.ParseColor32(iconColorVisitedAnomaly); if (!string.IsNullOrEmpty(iconColorShadow)) iconColorShadowValue = ConfigNode.ParseColor32(iconColorShadow); if (!string.IsNullOrEmpty(iconColorAP)) iconColorAPValue = ConfigNode.ParseColor32(iconColorAP); if (!string.IsNullOrEmpty(iconColorPE)) iconColorPEValue = ConfigNode.ParseColor32(iconColorPE); if (!string.IsNullOrEmpty(iconColorANDN)) iconColorANDNValue = ConfigNode.ParseColor32(iconColorANDN); if (!string.IsNullOrEmpty(iconColorNode)) iconColorNodeValue = ConfigNode.ParseColor32(iconColorNode); if (!string.IsNullOrEmpty(trailColor)) trailColorValue = ConfigNode.ParseColor32(trailColor); // Referencing the parent project should work, shouldn't it. persistentVarName = "scansat" + internalProp.propID; persistence = new PersistenceAccessor(part); showLines = persistence.GetBool(persistentVarName + "lines") ?? true; trailMaterial = JUtil.DrawLineMaterial(); LeaveTrail(); if (!string.IsNullOrEmpty(scaleBar) && !string.IsNullOrEmpty(scaleLabels) && !string.IsNullOrEmpty(scaleLevels)) { scaleBarTexture = GameDatabase.Instance.GetTexture(scaleBar, false); scaleLabelTexture = GameDatabase.Instance.GetTexture(scaleLabels, false); var scales = new List<float>(); foreach (string scl in scaleLevels.Split(',')) { float scale; if (float.TryParse(scl.Trim(), out scale)) scales.Add(scale / 1000); } scaleLevelValues = scales.ToArray(); Array.Sort(scaleLevelValues); scaleLabelSpan = 1f / scaleLevelValues.Length; } // Now the fun bit: Locate all cfg files depicting map features anywhere. foreach (ConfigNode node in GameDatabase.Instance.GetConfigNodes ("JSISCANSATVECTORMARK")) { mapMarkup.Add(new MapMarkupLine(node)); } startupComplete = true; }
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. RPMVesselComputer comp = RPMVesselComputer.Instance(vessel); comp.UpdateDataRefreshRate(refreshDataRate); persistence = new PersistenceAccessor(internalProp); // 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).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)); } 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 = persistence.GetVar(persistentVarName, pages.Count); 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); // 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; } }
public void Start() { if (HighLogic.LoadedSceneIsEditor) { return; } try { 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)) { currentState = 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) { currentState = stateHandler(); } else { if (!string.IsNullOrEmpty(persistentVarName)) { currentState = customGroupList[actionName] = (persistence.GetBool(persistentVarName) ?? currentState); 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 (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. colorShiftRenderer = internalProp.FindModelComponent <Renderer>(coloredObject); disabledColorValue = ConfigNode.ParseColor32(disabledColor); enabledColorValue = ConfigNode.ParseColor32(enabledColor); colorShiftRenderer.material.SetColor(colorName, (currentState ^ reverse ? enabledColorValue : disabledColorValue)); } else { JUtil.LogMessage(this, "Warning, neither color nor animation are defined."); } audioOutput = JUtil.SetupIVASound(internalProp, switchSound, switchSoundVolume, false); startupComplete = true; } catch { JUtil.AnnoyUser(this); enabled = false; throw; } }
public void RenderData(RenderTexture screen, RPMVesselComputer comp, PersistenceAccessor persistence) { float leftVal, rightVal; if (!scale[0].Get(out leftVal, comp, persistence) || !scale[1].Get(out rightVal, comp, persistence)) { return; // bad values - can't render } float eval = comp.ProcessVariable(variableName, persistence).MassageToFloat(); if (float.IsInfinity(eval) || float.IsNaN(eval)) { return; // bad value - can't render } float ratio = Mathf.InverseLerp(leftVal, rightVal, eval); if (thresholdMode) { if (ratio >= threshold.x && ratio <= threshold.y) { if (flashingDelay > 0.0f) { if (lastStateChange + flashingDelay < Planetarium.GetUniversalTime()) { lastStateChange = Planetarium.GetUniversalTime(); lastState = 1.0f - lastState; } ratio = lastState; } else { ratio = 1.0f; } } else { ratio = 0.0f; } } if (reverse) { ratio = 1.0f - ratio; } switch (graphType) { case GraphType.VerticalDown: DrawVerticalDown(ratio); break; case GraphType.VerticalUp: DrawVerticalUp(ratio); break; case GraphType.VerticalSplit: DrawVerticalSplit(ratio); break; case GraphType.HorizontalLeft: DrawHorizontalLeft(ratio); break; case GraphType.HorizontalRight: DrawHorizontalRight(ratio); break; case GraphType.HorizontalSplit: DrawHorizontalSplit(ratio); break; case GraphType.Lamp: DrawLamp(ratio); break; default: throw new NotImplementedException("Unimplemented graphType " + graphType.ToString()); } }
public void Start() { if (HighLogic.LoadedSceneIsEditor) { return; } try { 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); } } if (labelsEx.Count == 0) { JUtil.LogMessage(this, "No labels defined."); throw new ArgumentException("No labels defined"); } colorShiftRenderer = internalProp.FindModelComponent<Renderer>(coloredObject); if (labelsEx[activeLabel].hasColor) { colorShiftRenderer.material.SetColor(colorName, labelsEx[activeLabel].color); } if (labelsEx[activeLabel].hasText) { if (labelsEx[activeLabel].oneShot) { textObj.text.Text = labelsEx[activeLabel].labelText; } else { textObj.text.Text = ""; } } audioOutput = JUtil.SetupIVASound(internalProp, switchSound, switchSoundVolume, false); persistence = new PersistenceAccessor(internalProp); if (JUtil.debugLoggingEnabled) { JUtil.LogMessage(this, "Configuration complete in prop {1}, supporting {0} variable indicators.", labelsEx.Count, internalProp.propID); } } catch { JUtil.AnnoyUser(this); enabled = false; throw; } }
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; persistence = new PersistenceAccessor(internalProp); // 7 is the bitmask for ship-station-probe; VesselFilterFromBitmask(persistence.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; }
public bool Evaluate(RPMVesselComputer comp, PersistenceAccessor persistence) { return range.IsInRange(comp, persistence) ^ reverse; }
public void Start() { if (HighLogic.LoadedSceneIsEditor) { return; } try { backgroundColorValue = ConfigNode.ParseColor32(backgroundColor); cameraBody = new GameObject(); cameraBody.name = "RPMPFD" + cameraBody.GetInstanceID(); cameraBody.layer = drawingLayer; hudCamera = cameraBody.AddComponent<Camera>(); hudCamera.enabled = false; hudCamera.orthographic = true; hudCamera.eventMask = 0; hudCamera.farClipPlane = 3f; hudCamera.orthographicSize = 1.0f; hudCamera.cullingMask = 1 << drawingLayer; // does this actually work? hudCamera.backgroundColor = backgroundColorValue; hudCamera.clearFlags = CameraClearFlags.Depth | CameraClearFlags.Color; hudCamera.transparencySortMode = TransparencySortMode.Orthographic; hudCamera.transform.position = Vector3.zero; hudCamera.transform.LookAt(new Vector3(0.0f, 0.0f, 1.5f), Vector3.up); if (!string.IsNullOrEmpty(progradeColor)) { progradeColorValue = ConfigNode.ParseColor32(progradeColor); } persistence = new PersistenceAccessor(internalProp); } catch (Exception e) { JUtil.LogErrorMessage(this, "Start() failed with an exception: {0}", e); JUtil.AnnoyUser(this); throw; } startupComplete = true; }
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)) { persistence = new PersistenceAccessor(internalProp); if (persistence.HasPropVar(cameraInfoVarName + "_ID")) { currentCamera = persistence.GetPropVar(cameraInfoVarName + "_ID") - 1; } else { persistence.SetPropVar(cameraInfoVarName + "_ID", currentCamera + 1); } } }
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); persistence = new PersistenceAccessor(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; } }
public void Start() { InstallationPathWarning.Warn(); // 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); startupComplete = true; }