Skip to content

Commit

Permalink
Complete the vanilla tool for the vessel freq list, refine CNCCommNet…
Browse files Browse the repository at this point in the history
…Vessel and clear for editor use
  • Loading branch information
KSP-TaxiService committed Jul 2, 2017
1 parent 4127e2f commit be75ba7
Show file tree
Hide file tree
Showing 6 changed files with 229 additions and 29 deletions.
83 changes: 75 additions & 8 deletions src/CommNetConstellation/CommNetLayer/CNCCommNetVessel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,10 @@ namespace CommNetConstellation.CommNetLayer
//This class is coupled with the MM patch (cnc_module_MM.cfg) that inserts CNConstellationModule into every command part
public class CNConstellationModule : PartModule
{
[KSPEvent(guiActive = true, guiActiveEditor = true, guiActiveUnfocused = false, guiName = "CNC: Frequency List", active = true)]
[KSPEvent(guiActive = true, guiActiveEditor = false, guiActiveUnfocused = true, guiName = "CNC: Communication", active = true)]
public void KSPEventVesselSetup()
{
new VesselSetupDialog("Vessel - <color=#00ff00>Frequency List</color>", this.vessel, null).launch();
{
new VesselSetupDialog("Vessel - <color=#00ff00>Communication</color>", this.vessel, null).launch();
}
}

Expand All @@ -38,7 +38,7 @@ public String Name

//TODO: auto-detect if antenna is deployed or retracted

[KSPEvent(guiActive = true, guiActiveEditor = true, guiActiveUnfocused = false, guiName = "CNC: Antenna Setup", active = true)]
[KSPEvent(guiActive = true, guiActiveEditor = true, guiActiveUnfocused = true, guiName = "CNC: Antenna Setup", active = true)]
public void KSPEventAntennaConfig()
{
new AntennaSetupDialog("Antenna - <color=#00ff00>Setup</color>", this.vessel, this.part).launch();
Expand Down Expand Up @@ -270,6 +270,11 @@ private short computeStrongestFrequency(Dictionary<short, double> dict)
return freq;
}

public bool canUpdateFreqList()
{
return this.FreqListOperation != CNCCommNetVessel.FrequencyListOperation.LockList;
}

/// <summary>
/// Notify CommNet vessel on antenna change (like changing frequency and deploy/retract antenna)
/// </summary>
Expand All @@ -285,6 +290,7 @@ public void OnAntennaChange(uint GUID = 0, bool antennaDeployment = true, short
break;
case FrequencyListOperation.LockList: // dont change current freq dict
this.strongestFreq = computeStrongestFrequency(this.FrequencyDict);
ScreenMessages.PostScreenMessage(new ScreenMessage("Note: Lock List mode is in effect.", CNCSettings.ScreenMessageDuration, ScreenMessageStyle.UPPER_LEFT));
break;
case FrequencyListOperation.UpdateOnly:
//TODO: complete updateonly function
Expand All @@ -293,7 +299,7 @@ public void OnAntennaChange(uint GUID = 0, bool antennaDeployment = true, short
}

/// <summary>
/// Action to rebuild the frequency list from all antennas
/// Rebuild the frequency list from all antennas
/// </summary>
public void rebuildFreqList()
{
Expand All @@ -303,7 +309,68 @@ public void rebuildFreqList()
}

/// <summary>
/// Replace one frequency in the vessel's antenna
/// Add a new (or existing) frequency and its comm power to vessel's frequency list
/// </summary>
public void addToFreqList(short frequency, double commPower)
{
if (this.FrequencyDict.ContainsKey(frequency))
this.FrequencyDict[frequency] = commPower;
else
this.FrequencyDict.Add(frequency, commPower);
}

/// <summary>
/// Drop the specific frequency from the vessel's frequency list
/// </summary>
public void removeFromFreqList(short frequency)
{
this.FrequencyDict.Remove(frequency);
}

/// <summary>
/// Clear the vessel's frequency list
/// </summary>
public void clearFreqList()
{
this.FrequencyDict.Clear();
}

/// <summary>
/// Replace one frequency in the particular antenna
/// </summary>
public bool replaceFrequency(uint GUID, short newFrequency)
{
try
{
if (!Constellation.isFrequencyValid(newFrequency))
throw new Exception(string.Format("The new frequency {0} is out of the range [0,{1}]!", newFrequency, short.MaxValue));

if (this.Vessel.loaded)
{
CNConstellationAntennaModule mod = this.Vessel.FindPartModulesImplementing<CNConstellationAntennaModule>().Find(x => x.part.craftID == GUID);
mod.Frequency = newFrequency;
}
else
{
ProtoPartSnapshot part = this.vessel.protoVessel.protoPartSnapshots.Find(x => x.partInfo.partPrefab.craftID == GUID);
ProtoPartModuleSnapshot cncAntMod = part.FindModule("CNConstellationAntennaModule");
cncAntMod.moduleValues.SetValue("Frequency", newFrequency);
}
}
catch (Exception e)
{
CNCLog.Error("Error encounted when updating CommNet vessel '{0}''s frequency to {2}: {1}", this.Vessel.GetName(), e.Message, newFrequency);
return false;
}

OnAntennaChange();

CNCLog.Debug("Update CommNet vessel '{0}''s frequency to {1}", this.Vessel.GetName(), newFrequency);
return true;
}

/// <summary>
/// Replace one frequency in all antennas
/// </summary>
public bool replaceFrequency(short oldFrequency, short newFrequency)
{
Expand All @@ -315,7 +382,7 @@ public bool replaceFrequency(short oldFrequency, short newFrequency)
if (this.Vessel.loaded)
{
List<CNConstellationAntennaModule> mods = this.Vessel.FindPartModulesImplementing<CNConstellationAntennaModule>();
for(int i=0; i< mods.Count; i++)
for (int i = 0; i < mods.Count; i++)
{
if (mods[i].Frequency == oldFrequency)
mods[i].Frequency = newFrequency;
Expand Down Expand Up @@ -367,7 +434,7 @@ public void toggleAntenna(uint GUID, bool inUse)
partInfo.inUse = inUse;

int numParts = (!this.vessel.loaded) ? this.vessel.protoVessel.protoPartSnapshots.Count : this.vessel.Parts.Count;
for (int partIndex = 0; partIndex < numParts; partIndex++)
for (int partIndex = 0; partIndex < numParts; partIndex++) // TODO: simplify this
{
if (this.Vessel.loaded)
{
Expand Down
9 changes: 6 additions & 3 deletions src/CommNetConstellation/UI/VesselMgtTools/AntennaTool.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public override List<DialogGUIBase> getContentComponents()
{
List<DialogGUIBase> layout = new List<DialogGUIBase>();

DialogGUILabel msgLbl = new DialogGUILabel("Choose some antennas to build the frequency list\n");
DialogGUILabel msgLbl = new DialogGUILabel("Choose some antennas to build the frequency list", 100, 16);
layout.Add(new DialogGUIHorizontalLayout(true, false, 0, new RectOffset(), TextAnchor.MiddleLeft, new DialogGUIBase[] { msgLbl }));

toggleAntennaColumn = new DialogGUIVerticalLayout(false, false, 0, new RectOffset(), TextAnchor.MiddleLeft);
Expand Down Expand Up @@ -69,9 +69,12 @@ private void toggleAllAntennas(bool state)
List<CNCAntennaPartInfo> allAntennas = cncVessel.getAllAntennaInfo();

for (int i = 0; i < allAntennas.Count; i++)
vesselAntennaSelected(state, allAntennas[i].GUID);
{
cncVessel.toggleAntenna(allAntennas[i].GUID, state);
}

this.selfRefresh(); //TODO: force retrieve antenna data
cncVessel.OnAntennaChange();
this.selfRefresh();
}
}
}
30 changes: 18 additions & 12 deletions src/CommNetConstellation/UI/VesselMgtTools/ToolContentManagement.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,6 @@ public AbstractMgtTool(CommNetVessel thisVessel, string uniqueCodename, string t
}

this.cncVessel = (CNCCommNetVessel)thisVessel;
this.initialFrequencies = this.cncVessel.getFrequencies();
this.antennas = this.cncVessel.getAllAntennaInfo();

this.codename = uniqueCodename + "_mgttool";
this.toolName = toolName;
this.actionCallbacks = actionCallbacks;
Expand All @@ -41,15 +38,24 @@ protected void selfRefresh()
}

public abstract List<DialogGUIBase> getContentComponents();
public virtual void precompute() { }
public virtual void cleanup() { }
public virtual void cleanup()
{
this.antennas = null;
this.initialFrequencies = null;
}

public virtual void precompute()
{
this.antennas = this.cncVessel.getAllAntennaInfo(true);
this.initialFrequencies = this.cncVessel.getFrequencies();
}
}

public class ToolContentManagement
{
protected DialogGUIVerticalLayout toolContentLayout;
protected List<AbstractMgtTool> tools;
private AbstractMgtTool currentTool;
private AbstractMgtTool currentTool;

public ToolContentManagement()
{
Expand Down Expand Up @@ -82,8 +88,8 @@ public List<DialogGUIBase> getLayoutContents()
layout.Add(new DialogGUIHorizontalLayout(true, false, 0, new RectOffset(), TextAnchor.MiddleLeft, buttons));

//Tool content
toolContentLayout = new DialogGUIVerticalLayout(10, 100, 4, new RectOffset(5, 25, 5, 5), TextAnchor.UpperLeft, new DialogGUIBase[] { new DialogGUIContentSizer(ContentSizeFitter.FitMode.Unconstrained, ContentSizeFitter.FitMode.PreferredSize, true) });
layout.Add(new DialogGUIScrollList(Vector2.one, false, true, toolContentLayout));
this.toolContentLayout = new DialogGUIVerticalLayout(10, 100, 4, new RectOffset(5, 25, 5, 5), TextAnchor.UpperLeft, new DialogGUIBase[] { new DialogGUIContentSizer(ContentSizeFitter.FitMode.Unconstrained, ContentSizeFitter.FitMode.PreferredSize, true) });
layout.Add(new DialogGUIScrollList(Vector2.one, false, true, this.toolContentLayout));

return layout;
}
Expand All @@ -93,19 +99,19 @@ public void selectTool(string toolCodename)
if(this.currentTool != null)
this.currentTool.cleanup();

AbstractDialog.deregisterLayoutComponents(toolContentLayout);
AbstractDialog.deregisterLayoutComponents(this.toolContentLayout);

if ((this.currentTool = this.tools.Find(x => x.codename.Equals(toolCodename))) == null)
{
toolContentLayout.AddChildren(new DialogGUIBase[] { }); // empty
this.toolContentLayout.AddChildren(new DialogGUIBase[] { }); // empty
}
else
{
toolContentLayout.AddChildren(this.currentTool.getContentComponents().ToArray());
this.currentTool.precompute();
this.toolContentLayout.AddChildren(this.currentTool.getContentComponents().ToArray());
}

AbstractDialog.registerLayoutComponents(toolContentLayout);
AbstractDialog.registerLayoutComponents(this.toolContentLayout);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ public override List<DialogGUIBase> getContentComponents()
{
List<DialogGUIBase> layout = new List<DialogGUIBase>();

DialogGUILabel msgLbl = new DialogGUILabel("Decide how the vessel's frequency list is updated whenever one antenna is changed (eg deployed/retracted or frequency change)\n");
DialogGUILabel msgLbl = new DialogGUILabel("Decide how the vessel's frequency list is updated whenever one antenna is changed (eg deployed/retracted or frequency change)", 100, 32);
layout.Add(new DialogGUIHorizontalLayout(true, false, 0, new RectOffset(), TextAnchor.MiddleLeft, new DialogGUIBase[] { msgLbl }));

DialogGUIToggleGroup toggleGrp = new DialogGUIToggleGroup();
Expand Down
128 changes: 126 additions & 2 deletions src/CommNetConstellation/UI/VesselMgtTools/VanillaFreqTool.cs
Original file line number Diff line number Diff line change
@@ -1,11 +1,20 @@
using System.Collections.Generic;
using System;
using System.Collections.Generic;
using CommNet;
using UnityEngine;
using TMPro;
using CommNetConstellation.CommNetLayer;
using UnityEngine.UI;

namespace CommNetConstellation.UI.VesselMgtTools
{
public class VanillaFreqTool : AbstractMgtTool
{
private static readonly Texture2D colorTexture = UIUtils.loadImage("colorDisplay");
private DialogGUITextInput frequencyInput;
private DialogGUIImage constellationColorImage;
private bool membershipOption;

public VanillaFreqTool(CommNetVessel thisVessel, Callback updateFreqRowsCallback) : base(thisVessel, "vanilla", "Vanilla", new List<Callback>() { updateFreqRowsCallback })
{
}
Expand All @@ -14,10 +23,125 @@ public override List<DialogGUIBase> getContentComponents()
{
List<DialogGUIBase> layout = new List<DialogGUIBase>();

DialogGUILabel msgLbl = new DialogGUILabel("Original functionality of setting a single frequency of this vessel\n");
DialogGUILabel msgLbl = new DialogGUILabel("Set a single frequency of this vessel quickly", 100, 16);
layout.Add(new DialogGUIHorizontalLayout(true, false, 0, new RectOffset(), TextAnchor.MiddleLeft, new DialogGUIBase[] { msgLbl }));

DialogGUILabel freqLabel = new DialogGUILabel("<b>Frequency</b>", 52, 12);
frequencyInput = new DialogGUITextInput(CNCSettings.Instance.PublicRadioFrequency+"", false, CNCSettings.MaxDigits, setConstellFreq, 45, 25);
DialogGUIToggle membershipToggle = new DialogGUIToggle(false, "", membershipFlagToggle);
DialogGUILabel membershipLabel = new DialogGUILabel("<b>Talk to constellation members only</b>", 200, 12);

DialogGUIHorizontalLayout constellationGroup = new DialogGUIHorizontalLayout(true, false, 4, new RectOffset(), TextAnchor.MiddleCenter, new DialogGUIBase[] { freqLabel, frequencyInput, new DialogGUISpace(20), membershipToggle, membershipLabel });
layout.Add(constellationGroup);

constellationColorImage = new DialogGUIImage(new Vector2(32, 32), Vector2.one, Color.white, colorTexture);
DialogGUILabel constNameLabel = new DialogGUILabel(getConstellationName, 200, 12);
layout.Add(new DialogGUIHorizontalLayout(false, false, 0, new RectOffset(), TextAnchor.MiddleLeft, new DialogGUIBase[] { constNameLabel, constellationColorImage }));

DialogGUIButton updateButton = new DialogGUIButton("Update", updateClick, false);
DialogGUIButton publicButton = new DialogGUIButton("Revert to public", defaultClick, false);
DialogGUIHorizontalLayout actionGroup = new DialogGUIHorizontalLayout(true, false, 4, new RectOffset(), TextAnchor.MiddleCenter, new DialogGUIBase[] { new DialogGUIFlexibleSpace(), updateButton, publicButton, new DialogGUIFlexibleSpace() });
layout.Add(actionGroup);

return layout;
}

private void membershipFlagToggle(bool state)
{
this.membershipOption = state;
}

private string setConstellFreq(string freqInput)
{
//do nothing
return freqInput;
}

private string getConstellationName()
{
try
{
Constellation thisConstellation = CNCCommNetScenario.Instance.constellations.Find(x => x.frequency == short.Parse(frequencyInput.uiItem.GetComponent<TMP_InputField>().text));

if (thisConstellation != null)
{
constellationColorImage.uiItem.GetComponent<RawImage>().color = thisConstellation.color;
return "<b>Constellation</b>: " + thisConstellation.name;
}
}
catch (Exception e) { }

constellationColorImage.uiItem.GetComponent<RawImage>().color = Color.clear;
return "<b>Constellation</b>: Unrecognised";
}

private void defaultClick()
{
frequencyInput.uiItem.GetComponent<TMP_InputField>().text = CNCSettings.Instance.PublicRadioFrequency.ToString();
}

private void updateClick()
{
try
{
try
{
short userFreq = short.Parse(frequencyInput.uiItem.GetComponent<TMP_InputField>().text);

//Check frequency
if (userFreq < 0)
{
throw new Exception("Frequency cannot be negative");
}
else if (!Constellation.isFrequencyValid(userFreq))
{
throw new Exception("Frequency must be between 0 and " + short.MaxValue);
}

//ALL OK
if (!this.cncVessel.canUpdateFreqList())
{
this.cncVessel.OnAntennaChange();
return;
}

this.antennas = this.cncVessel.getAllAntennaInfo(true);
this.cncVessel.clearFreqList();

//update all antennas to new freq
for (int i=0; i< this.antennas.Count; i++)
{
CNCAntennaPartInfo thisAntenna = this.antennas[i];
this.cncVessel.toggleAntenna(thisAntenna.GUID, true);
if (thisAntenna.frequency != userFreq) // update each antenna to user freq
this.cncVessel.replaceFrequency(thisAntenna.GUID, userFreq);
}
this.cncVessel.rebuildFreqList();

//if membership option is not enabled, add public freq of same comm power
if (!membershipOption && userFreq != CNCSettings.Instance.PublicRadioFrequency)
{
double commPower = this.cncVessel.getMaxComPower(userFreq);
this.cncVessel.addToFreqList(CNCSettings.Instance.PublicRadioFrequency, commPower);
}

actionCallbacks[0]();
}
catch (FormatException e)
{
throw new FormatException("Frequency must be numeric only");
}
catch (OverflowException e)
{
throw new OverflowException(string.Format("Frequency must be equal to or less than {0}", short.MaxValue));
}

}
catch (Exception e)
{
ScreenMessage msg = new ScreenMessage("<color=red>" + e.Message + "</color>", CNCSettings.ScreenMessageDuration, ScreenMessageStyle.UPPER_LEFT);
ScreenMessages.PostScreenMessage(msg);
}
}
}
}
Loading

0 comments on commit be75ba7

Please sign in to comment.