Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* v:1.114 [Countdown, DateTime with format, Mass of cargo, Centered Time & Date, multiline separator \, Booting text]
- * In-game script by MMaster
- !
- ! You can now use LCD Private Text to enter commands line by line by using command UseTextCommands
- !
- * Last update: Countdown, DateTime with format, ChargeX, better Inventory performance
- * ingots and ores translatable, Oxygen & Hydrogen bottles now in single category
- *
- * Previous updates: Mass of items in cargo
- * Centered TimeC & DateC, Multiline separator \ in Private Text commands
- * Booting text (automatic/manual using 'boot' argument) + Clear LCDs using 'clear' argument
- * Hydrogen & Superconductors + Support for any gas tank using Tanks command
- * Working command now shows updated recharge status of batteries (+), (-) or (±)
- * DamageNoC command variants to not show deconstructed blocks
- * Commands in Private Text by using UseTextCommands command!
- * Battery charge state in Working command, Oxygen and Working command when air is leaking instead of showing 0%
- * Date & Time offset, PosGPS showing position in gps format, TextLCD to append text from another LCD
- * and more.. look at change logs on steam page.
- *
- Customize these: (do not report problems with modified values!) */
- // Use this tag to identify LCDs managed by this script
- public static string LCD_TAG = "[HANNIBAL]";
- // How many panels to update per one step
- public static int PANELS_PER_STEP = 1;
- // How many lines to scroll per step
- public static int SCROLL_LINES_PER_STEP = 5;
- // Force redraw of panels? (EXPERIMENTAL, default = true)
- // false - Massively reduces lag caused by LCD redraw, but can be buggy
- public static bool FORCE_REDRAW = true;
- // Enable initial boot sequence (after compile / world load)
- public static bool ENABLE_BOOT = true;
- // (for developer) Enable debug to LCD marked with [DEBUG]
- public static bool EnableDebug = false;
- /*
- READ THIS FULL GUIDE
- http://steamcommunity.com/sharedfiles/filedetails/?id=407158161
- Basic video guide
- Please watch the video guide even if you don't understand my English. You can see how things are done there.
- http://www.youtube.com/watch?v=oopzyQ0t6Dk
- EXAMPLE WORLD
- http://steamcommunity.com/sharedfiles/filedetails/?id=412154340
- Read Change Notes (above screenshots) for latest updates and new features.
- I notify about updates on twitter so follow if interested.
- Please carefully read the FULL GUIDE before asking questions I had to remove guide from here to add more features :(
- Please DO NOT publish this script or its derivations without my permission! Feel free to use it in blueprints!
- Special Thanks
- bssespaceengineers.com - awesome server
- Rhedd - for his contribution to modded items entries
- Textor and CyberVic for their great script related contributions on Keen forums.
- Watch Twitter: https://twitter.com/MattsPlayCorner
- and Facebook: https://www.facebook.com/MattsPlayCorner1080p
- for more crazy stuff from me in the future :)
- */
- // For german clients
- public static string SECONDARY_TAG = "!LCD!";
- public static int step;
- void Main(string argument)
- {
- if (LCDsProgram.bootFrames == null) {
- LCDsProgram.bootFrames = new List<string>()
- {
- /* BOOT FRAMES
- * Each @"<text>" marks single frame, add as many as you want each will be displayed for one second
- * @"" is multiline string so you can write multiple lines
- */
- @"
- Initializing systems"
- ,
- @"
- Verifying connections"
- ,
- @"
- Loading commands"
- /* END OF BOOT FRAMES */
- // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
- // DO NOT MODIFY ANYTHING BELOW THIS
- // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
- };
- LCDsProgram.bootStep = (ENABLE_BOOT ? 0 : int.MaxValue);
- LCDsProgram.bootScreens = ENABLE_BOOT;
- }
- // Init MMAPI and debug panels marked with [DEBUG]
- MM.EnableDebug = EnableDebug;
- MM.Me = Me;
- MM.ElapsedTime = ElapsedTime;
- MM.Init(GridTerminalSystem);
- MMLCDMgr.forceRedraw = FORCE_REDRAW;
- LCDsProgram.SECONDARY_TAG = SECONDARY_TAG;
- LCDsProgram lcdProg = new LCDsProgram(LCD_TAG, SCROLL_LINES_PER_STEP, PANELS_PER_STEP);
- lcdProg.Run(argument.ToLower(), step++);
- }
- }
- public static class MMItems
- {
- public static Dictionary<string, MMItem> items = new Dictionary<string, MMItem>();
- public static List<string> keys = new List<string>();
- public static Dictionary<string, MMItem> itemsByShort = new Dictionary<string, MMItem>();
- public static void Init()
- {
- if (items.Count > 0)
- return;
- // **************************************************
- // OK MAYBE YOU CAN ADD MODDED ITEMS AND MODIFY QUOTAS
- // IF THAT WARNING DIDN'T SCARE YOU
- // **************************************************
- // ITEMS AND QUOTAS LIST
- // (subType, mainType, quota, display name, short name)
- // ADD MODDED ITEMS TO THIS LIST
- // !! MAIN TYPES MUST GO TOGETHER FOR INV CATEGORIES !!
- // VANILLA ITEMS
- Add("Stone", "Ore");
- Add("Iron", "Ore");
- Add("Nickel", "Ore");
- Add("Cobalt", "Ore");
- Add("Magnesium", "Ore");
- Add("Silicon", "Ore");
- Add("Silver", "Ore");
- Add("Gold", "Ore");
- Add("Platinum", "Ore");
- Add("Uranium", "Ore");
- Add("Ice", "Ore");
- Add("Stone", "Ingot", 40000, "Gravel", "gravel");
- Add("Iron", "Ingot", 100000);
- Add("Nickel", "Ingot", 80000);
- Add("Cobalt", "Ingot", 30000);
- Add("Magnesium", "Ingot", 30000);
- Add("Silicon", "Ingot", 50000);
- Add("Silver", "Ingot", 50000);
- Add("Gold", "Ingot", 60000);
- Add("Platinum", "Ingot", 40000);
- Add("Uranium", "Ingot", 10000);
- Add("Scrap", "Ingot");
- Add("AutomaticRifleItem", "PhysicalGunObject", 10, "Automatic Rifle");
- Add("WelderItem", "PhysicalGunObject", 0, "Welder");
- Add("AngleGrinderItem", "PhysicalGunObject", 0, "Angle Grinder");
- Add("HandDrillItem", "PhysicalGunObject", 0, "Hand Drill");
- Add("Construction", "Component", 40000);
- Add("MetalGrid", "Component", 8000, "Metal Grid");
- Add("InteriorPlate", "Component", 25000, "Interior Plate");
- Add("SteelPlate", "Component", 200000, "Steel Plate");
- Add("Girder", "Component", 2000);
- Add("SmallTube", "Component", 16000, "Small Tube");
- Add("LargeTube", "Component", 3000, "Large Tube");
- Add("Motor", "Component", 3000);
- Add("Display", "Component", 350);
- Add("BulletproofGlass", "Component", 3000, "Bulletp. Glass", "bpglass");
- Add("Computer", "Component", 5000);
- Add("Reactor", "Component", 10000);
- Add("Thrust", "Component", 16000, "Thruster", "thruster");
- Add("GravityGenerator", "Component", 50, "GravGen", "gravgen");
- Add("Medical", "Component", 120);
- Add("RadioCommunication", "Component", 200, "Radio-comm", "radio");
- Add("Detector", "Component", 100);
- Add("Explosives", "Component", 100);
- Add("SolarCell", "Component", 1500, "Solar Cell");
- Add("PowerCell", "Component", 1500, "Power Cell");
- Add("Superconductor", "Component", 300);
- Add("NATO_5p56x45mm", "AmmoMagazine", 1000, "5.56x45mm", "5.56x45mm");
- Add("NATO_25x184mm", "AmmoMagazine", 2000, "25x184mm", "25x184mm");
- Add("Missile200mm", "AmmoMagazine", 1600, "200mm Missile", "200mmmissile");
- Add("OxygenBottle", "OxygenContainerObject", 0, "Oxygen Bottle");
- Add("HydrogenBottle", "GasContainerObject", 0, "Hydrogen Bottle");
- // MODDED ITEMS
- // (subType, mainType, quota, display name, short name, used)
- // * if used is true, item will be shown in inventory even for 0 items
- // * if used is false, item will be used only for display name and short name
- // AzimuthSupercharger
- Add("AzimuthSupercharger", "Component", 1600, "Supercharger", "supercharger", false);
- // OKI Ammo
- Add("OKI23mmAmmo", "AmmoMagazine", 500, "23x180mm", "23x180mm", false);
- Add("OKI50mmAmmo", "AmmoMagazine", 500, "50x450mm", "50x450mm", false);
- Add("OKI122mmAmmo", "AmmoMagazine", 200, "122x640mm", "122x640mm", false);
- Add("OKI230mmAmmo", "AmmoMagazine", 100, "230x920mm", "230x920mm", false);
- }
- /* REALLY REALLY REALLY
- * DO NOT MODIFY ANYTHING BELOW THIS
- */
- // displayName - how the item will be displayed
- // shortName - how the item can be called in arguments (eg: +supercharger)
- public static void Add(string subType, string mainType, int quota = 0, string displayName = "", string shortName = "", bool used = true)
- {
- string fullType = subType + ' ' + mainType;
- MMItem item = new MMItem(subType, mainType, quota, displayName, shortName, used);
- items.Add(fullType, item);
- if (shortName != "")
- itemsByShort.Add(shortName.ToLower(), item);
- keys.Add(fullType);
- }
- public static MMItem GetItemOfType(string subType = "", string mainType = "")
- {
- if (items.ContainsKey(subType + " " + mainType))
- return items[subType + " " + mainType];
- if (mainType == "")
- for (int i = 0; i < items.Count; i++)
- {
- MMItem item = items[keys[i]];
- if (subType == item.subType)
- return item;
- }
- if (subType == "")
- for (int i = 0; i < items.Count; i++)
- {
- MMItem item = items[keys[i]];
- if (mainType == item.mainType)
- return item;
- }
- return null;
- }
- }
- public class LCDsProgram
- {
- // for german clients
- public static string SECONDARY_TAG = "";
- // approximate width of LCD panel line
- public const float LCD_LINE_WIDTH = 730;
- // x position of inventory numbers
- public const float LCD_LINE_NUMERS_POS = LCD_LINE_WIDTH - 30;
- public const float LCD_LINE_INV_NUMBERS_POS = LCD_LINE_WIDTH - 130;
- public const float LCD_LINE_INGOT_NUMBERS_POS = 375;
- public const float LCD_LINE_DMG_NUMBERS_POS = LCD_LINE_WIDTH - 230;
- public const float LCD_LINE_WORK_STATE_POS = LCD_LINE_WIDTH - 30;
- public const float LCD_LINE_BLOCK_COUNT_POS = LCD_LINE_WIDTH - 30;
- public const float PERCENT_TEXT_SIZE = 110f;
- // number of component progress bar characters
- public const int INV_PROGRESS_CHARS = 38;
- // full line of progress bar
- public const int FULL_PROGRESS_CHARS = 116;
- public static int PANELS_PER_STEP = 1;
- public MMPanelDict panels = new MMPanelDict();
- public double velocity;
- public static VRageMath.Vector3D lastPos;
- public static int bootStep = 0;
- public static bool bootScreens = true;
- public static List<string> bootFrames = null;
- public LCDsProgram(string nameLike, int sps, int pps)
- {
- MMBlockCollection lcds = new MMBlockCollection();
- PANELS_PER_STEP = pps;
- lcds.AddBlocksOfType("textpanel", nameLike);
- if (nameLike == "[LCD]" && SECONDARY_TAG != "")
- lcds.AddBlocksOfType("textpanel", SECONDARY_TAG);
- for (int i = 0; i < lcds.Count(); i++)
- {
- IMyTextPanel panel = (lcds.Blocks[i] as IMyTextPanel);
- string text = panel.CustomName + " " + panel.NumberInGrid + " " + panel.GetPosition().ToString("F0");
- MMPanel p = null;
- int joinpos = text.IndexOf("!LINK:");
- if (joinpos < 0 || text.Length == joinpos + 6)
- {
- p = new MMPanel();
- p.panels.AddItem(text, panel);
- panels.AddItem(text, p);
- p.SCROLL_LINES = sps;
- continue;
- }
- text = text.Substring(joinpos + 6);
- string[] subs = text.Split(' ');
- string group = subs[0];
- p = panels.GetItem(group);
- if (p == null)
- {
- p = new MMPanel();
- panels.AddItem(group, p);
- }
- p.panels.AddItem(text, panel);
- p.SCROLL_LINES = sps;
- }
- }
- public void Run(string argument, int step)
- {
- if (panels.CountAll() == 0)
- return;
- velocity = (MM.Me.GetPosition() - lastPos).Length() / MM.ElapsedTime.TotalSeconds;
- if (argument == "clear")
- {
- bootStep = (bootScreens ? 0 : int.MaxValue);
- for (int i = 0; i < panels.CountAll(); i++)
- {
- MMPanel p = panels.GetItemAt(i);
- p.SortPanels();
- MMLCDMgr.SetupLCDText(p);
- MMLCDMgr.ClearText(p);
- MMLCDMgr.UpdatePanel(p);
- }
- } else
- if (argument == "boot" || bootStep <= bootFrames.Count)
- {
- if (bootStep > bootFrames.Count)
- bootStep = 0;
- for (int i = 0; i < panels.CountAll(); i++)
- {
- MMPanel p = panels.GetItemAt(i);
- p.SortPanels();
- MMLCDMgr.SetupLCDText(p);
- MMLCDMgr.ClearText(p);
- // don't display on LCDs with really large font
- if (p.first.GetValueFloat("FontSize") > 3f)
- continue;
- MMLCDMgr.AddCenterLn(p, "Booting up...", LCD_LINE_WIDTH / 2);
- double perc = (double)bootStep / bootFrames.Count * 100;
- MMLCDMgr.AddProgressBarLn(p, perc, FULL_PROGRESS_CHARS);
- if (bootStep == bootFrames.Count)
- {
- MMLCDMgr.AddLn(p, "");
- MMLCDMgr.AddCenterLn(p, "Configurable Automatic LCDs", LCD_LINE_WIDTH / 2);
- MMLCDMgr.AddCenterLn(p, "by MMaster", LCD_LINE_WIDTH / 2);
- } else
- MMLCDMgr.AddMultiLn(p, bootFrames[bootStep]);
- MMLCDMgr.UpdatePanel(p);
- }
- bootStep++;
- } else {
- for (int i = 0; i < PANELS_PER_STEP; i++)
- {
- RunSingle(panels.GetItemAt((step * PANELS_PER_STEP + i) % panels.CountAll()));
- }
- }
- lastPos = MM.Me.GetPosition();
- }
- public void RunSingle(MMPanel panel)
- {
- bool useText = false;
- panel.SortPanels();
- MMLCDMgr.SetupLCDText(panel);
- string pubText = panel.first.CustomName;
- pubText = (pubText.Contains("#") ? pubText.Substring(pubText.LastIndexOf('#') + 1) : "");
- MMLCDMgr.ClearText(panel);
- if (pubText != "")
- MMLCDMgr.AddLn(panel, pubText);
- string title = panel.first.GetPrivateTitle();
- if (title == "Title" || title == "")
- title = panel.first.GetPublicTitle();
- if (title.Trim() == "UseTextCommands")
- {
- useText = true;
- title = panel.first.GetPrivateText();
- title = title.Replace("\\\n", " ");
- }
- if (title.StartsWith("Public") || title == "")
- {
- if (useText)
- MMLCDMgr.AddLn(panel, "Write commands to Private Text.");
- else
- MMLCDMgr.AddLn(panel, "Write commands to Public or Private Title.");
- MMLCDMgr.UpdatePanel(panel);
- return;
- }
- char[] delim = { ';', '\n' };
- string[] cmds = title.Split(delim);
- for (int i = 0; i < cmds.Length; i++)
- {
- MM.Debug("Running command " + cmds[i]);
- MMCommand cmd = new MMCommand(cmds[i]);
- if (cmd.cmdstr.StartsWith("inventory") ||
- cmd.cmdstr == "missing" ||
- cmd.cmdstr.StartsWith("invlist"))
- RunInvListing(panel, cmd);
- else
- if (cmd.cmdstr.StartsWith("cargo"))
- RunCargoStatus(panel, cmd);
- else
- if (cmd.cmdstr.StartsWith("mass"))
- RunMass(panel, cmd);
- else
- if (cmd.cmdstr == "oxygen")
- RunOxygenStatus(panel, cmd);
- else
- if (cmd.cmdstr == "tanks")
- RunTankStatus(panel, cmd);
- else
- if (cmd.cmdstr.StartsWith("power"))
- RunPowerStatus(panel, cmd);
- else
- if (cmd.cmdstr == "speed")
- RunVelocity(panel, cmd);
- else
- if (cmd.cmdstr.StartsWith("charge"))
- RunCharge(panel, cmd);
- else
- if (cmd.cmdstr.StartsWith("time") ||
- cmd.cmdstr.StartsWith("date"))
- RunCurrentTime(panel, cmd);
- else
- if (cmd.cmdstr.StartsWith("countdown"))
- RunCountdown(panel, cmd);
- else
- if (cmd.cmdstr == "echo" ||
- cmd.cmdstr == "center")
- RunEcho(panel, cmd);
- else
- if (cmd.cmdstr.StartsWith("text"))
- RunText(panel, cmd);
- else
- if (cmd.cmdstr.EndsWith("count"))
- RunBlockCount(panel, cmd);
- else
- if (cmd.cmdstr.StartsWith("working"))
- RunWorkingList(panel, cmd);
- else
- if (cmd.cmdstr.StartsWith("damage"))
- RunDamage(panel, cmd);
- else
- if (cmd.cmdstr.StartsWith("amount"))
- RunItemAmount(panel, cmd);
- else
- if (cmd.cmdstr.StartsWith("pos"))
- RunPosition(panel, cmd);
- else
- if (cmd.cmdstr.StartsWith("details"))
- RunDetails(panel, cmd);
- else
- MMLCDMgr.AddLn(panel, "Unknown command: " + cmd.cmdstr);
- MM.Debug("Done.");
- }
- MMLCDMgr.UpdatePanel(panel);
- }
- public void RunCharge(MMPanel panel, MMCommand cmd)
- {
- bool simple = cmd.cmdstr.Contains("x");
- MMBlockCollection blocks = new MMBlockCollection();
- blocks.AddBlocksOfType("jumpdrive", cmd.nameLike);
- if (blocks.Count() <= 0)
- {
- MMLCDMgr.AddLn(panel, "Charge: No blocks found.");
- return;
- }
- for (int i = 0; i < blocks.Count(); i++)
- {
- IMyJumpDrive jd = blocks.Blocks[i] as IMyJumpDrive;
- double cur, max, perc;
- perc = MMStatus.GetJumpDriveChargeValues(jd, out cur, out max);
- MMLCDMgr.Add(panel, jd.CustomName);
- if (!simple)
- {
- MMLCDMgr.AddRightAlignLn(panel, MM.FormatLargeNumber(cur) + "Wh / " + MM.FormatLargeNumber(max) + "Wh", LCD_LINE_WIDTH);
- MMLCDMgr.AddProgressBar(panel, perc, FULL_PROGRESS_CHARS, PERCENT_TEXT_SIZE);
- }
- MMLCDMgr.AddRightAlignLn(panel, ' ' + perc.ToString("0.0") + "%", LCD_LINE_WIDTH);
- }
- }
- public void RunVelocity(MMPanel panel, MMCommand cmd)
- {
- MMLCDMgr.Add(panel, "Speed:");
- MMLCDMgr.AddRightAlignLn(panel, velocity.ToString("F1") + " m/s", LCD_LINE_WIDTH);
- }
- public void RunText(MMPanel panel, MMCommand cmd)
- {
- bool fromLCD = (cmd.cmdstr == "textlcd");
- IMyTextPanel p = panel.first;
- if (p == null)
- return;
- string text = p.GetPrivateText();
- if (fromLCD)
- {
- if (cmd.nameLike != "" && cmd.nameLike != "*")
- {
- IMyTextPanel tp = MM._GridTerminalSystem.GetBlockWithName(cmd.nameLike) as IMyTextPanel;
- if (tp == null)
- {
- MMLCDMgr.AddLn(panel, "TextLCD source LCD not found: " + cmd.nameLike);
- return;
- }
- text = tp.GetPublicText();
- }
- else
- {
- MMLCDMgr.AddLn(panel, "TextLCD is missing source LCD name");
- return;
- }
- }
- string[] lines = text.Split('\n');
- if (lines.Length == 0)
- {
- if (!fromLCD)
- MMLCDMgr.AddLn(panel, "Text: LCD Private Text is empty");
- return;
- }
- for (int i = 0; i < lines.Length; i++)
- MMLCDMgr.AddLn(panel, lines[i]);
- }
- private void PrintDetails(MMPanel panel, IMyTerminalBlock block)
- {
- string[] lines = block.DetailedInfo.Split('\n');
- for (int j = 0; j < lines.Length; j++)
- if (lines[j] != "")
- MMLCDMgr.AddLn(panel, " " + lines[j]);
- }
- public void RunDetails(MMPanel panel, MMCommand cmd)
- {
- if (cmd.nameLike == "" || cmd.nameLike == "*")
- {
- MMLCDMgr.AddLn(panel, "Details: You need to enter name.");
- return;
- }
- MMBlockCollection blocks = new MMBlockCollection();
- blocks.AddBlocksOfNameLike(cmd.nameLike);
- if (blocks.Count() <= 0)
- {
- MMLCDMgr.AddLn(panel, "Details: No blocks found.");
- return;
- }
- IMyTerminalBlock block = blocks.Blocks[0];
- MMLCDMgr.AddLn(panel, block.CustomName);
- PrintDetails(panel, block);
- for (int i = 1; i < blocks.Count(); i++)
- {
- block = blocks.Blocks[i];
- MMLCDMgr.AddLn(panel, "");
- MMLCDMgr.AddLn(panel, block.CustomName);
- PrintDetails(panel, block);
- }
- }
- public void RunPosition(MMPanel panel, MMCommand cmd)
- {
- bool posxyz = (cmd.cmdstr == "posxyz");
- bool gps = (cmd.cmdstr == "posgps");
- IMyTerminalBlock block = panel.first;
- if (cmd.nameLike != "" && cmd.nameLike != "*")
- {
- block = MM._GridTerminalSystem.GetBlockWithName(cmd.nameLike);
- if (block == null)
- {
- MMLCDMgr.AddLn(panel, "Block not found: " + cmd.nameLike);
- return;
- }
- }
- if (gps)
- {
- VRageMath.Vector3D pos = block.GetPosition();
- MMLCDMgr.AddLn(panel, "GPS:Location:" +
- pos.GetDim(0).ToString("F2") + ":" +
- pos.GetDim(1).ToString("F2") + ":" +
- pos.GetDim(2).ToString("F2") + ":");
- return;
- }
- MMLCDMgr.Add(panel, "Location: ");
- if (!posxyz)
- {
- MMLCDMgr.AddRightAlignLn(panel, block.GetPosition().ToString("F0"), LCD_LINE_WORK_STATE_POS);
- return;
- }
- MMLCDMgr.AddLn(panel, "");
- MMLCDMgr.Add(panel, " X: ");
- MMLCDMgr.AddRightAlignLn(panel, block.GetPosition().GetDim(0).ToString("F0"), LCD_LINE_WORK_STATE_POS);
- MMLCDMgr.Add(panel, " Y: ");
- MMLCDMgr.AddRightAlignLn(panel, block.GetPosition().GetDim(1).ToString("F0"), LCD_LINE_WORK_STATE_POS);
- MMLCDMgr.Add(panel, " Z: ");
- MMLCDMgr.AddRightAlignLn(panel, block.GetPosition().GetDim(2).ToString("F0"), LCD_LINE_WORK_STATE_POS);
- }
- public void RunBlockCount(MMPanel panel, MMCommand cmd)
- {
- bool enabledCnt = (cmd.cmdstr == "enabledcount");
- bool producingCnt = (cmd.cmdstr == "prodcount");
- for (int i = 0; i < cmd.args.Count; i++)
- {
- MMArgument arg = cmd.args[i];
- for (int subi = 0; subi < arg.sub.Count; subi++)
- {
- MMBlockCollection blocks = new MMBlockCollection();
- blocks.AddBlocksOfType(arg.sub[subi], cmd.nameLike);
- string name;
- if (blocks.Count() == 0)
- {
- name = arg.sub[subi];
- name = char.ToUpper(name[0]) + name.Substring(1).ToLower();
- MMLCDMgr.Add(panel, name + " count: ");
- string countstr = (enabledCnt || producingCnt ? "0 / 0" : "0");
- MMLCDMgr.AddRightAlignLn(panel, countstr, LCD_LINE_BLOCK_COUNT_POS);
- }
- else
- {
- Dictionary<string, int> typeCount = new Dictionary<string, int>();
- Dictionary<string, int> typeWorkingCount = new Dictionary<string, int>();
- List<string> blockTypes = new List<string>();
- for (int j = 0; j < blocks.Count(); j++)
- {
- IMyProductionBlock prod = blocks.Blocks[j] as IMyProductionBlock;
- name = blocks.Blocks[j].DefinitionDisplayNameText;
- if (blockTypes.Contains(name))
- {
- typeCount[name]++;
- if ((enabledCnt && blocks.Blocks[j].IsWorking) ||
- (producingCnt && prod != null && prod.IsProducing))
- typeWorkingCount[name]++;
- }
- else
- {
- typeCount.Add(name, 1);
- blockTypes.Add(name);
- if (enabledCnt || producingCnt)
- if ((enabledCnt && blocks.Blocks[j].IsWorking) ||
- (producingCnt && prod != null && prod.IsProducing))
- typeWorkingCount.Add(name, 1);
- else
- typeWorkingCount.Add(name, 0);
- }
- }
- for (int j = 0; j < typeCount.Count; j++)
- {
- MMLCDMgr.Add(panel, blockTypes[j] + " count: ");
- string countstr = (enabledCnt || producingCnt ?
- typeWorkingCount[blockTypes[j]] + " / " : "") +
- typeCount[blockTypes[j]];
- MMLCDMgr.AddRightAlignLn(panel, countstr, LCD_LINE_BLOCK_COUNT_POS);
- }
- }
- }
- }
- }
- public string GetWorkingString(IMyTerminalBlock block)
- {
- if (!block.IsWorking)
- return "OFF";
- IMyProductionBlock prod = block as IMyProductionBlock;
- if (prod != null)
- if (prod.IsProducing)
- return "WORK";
- else
- return "IDLE";
- IMyAirVent vent = block as IMyAirVent;
- if (vent != null)
- {
- if (vent.CanPressurize)
- return (vent.GetOxygenLevel() * 100).ToString("F1") + "%";
- else
- return "LEAK";
- }
- IMyOxygenTank tank = block as IMyOxygenTank;
- if (tank != null)
- return (tank.GetOxygenLevel() * 100).ToString("F1") + "%";
- IMyBatteryBlock battery = block as IMyBatteryBlock;
- if (battery != null)
- return MMStatus.GetBatteryWorkingString(battery);
- IMyJumpDrive jd = block as IMyJumpDrive;
- if (jd != null)
- return MMStatus.GetJumpDriveCharge(jd).ToString("0.0") + "%";
- IMyLandingGear gear = block as IMyLandingGear;
- if (gear != null)
- return MMStatus.GetLandingGearStatus(gear);
- IMyDoor door = block as IMyDoor;
- if (door != null)
- {
- if (door.Open)
- return "OPEN";
- return "CLOSED";
- }
- IMyShipConnector conn = block as IMyShipConnector;
- if (conn != null)
- if (conn.IsLocked)
- return "LOCK";
- else
- return "UNLOCK";
- IMyLaserAntenna lasant = block as IMyLaserAntenna;
- if (lasant != null)
- return MMStatus.GetLaserAntennaStatus(lasant);
- IMyRadioAntenna ant = block as IMyRadioAntenna;
- if (ant != null)
- return MM.FormatLargeNumber(ant.Radius) + "m";
- IMyBeacon beacon = block as IMyBeacon;
- if (beacon != null)
- return MM.FormatLargeNumber(beacon.Radius) + "m";
- return "ON";
- }
- public void RunWorkingList(MMPanel panel, MMCommand cmd)
- {
- bool enabledList = (cmd.cmdstr == "workingx");
- for (int i = 0; i < cmd.args.Count; i++)
- {
- MMArgument arg = cmd.args[i];
- for (int subi = 0; subi < arg.sub.Count; subi++)
- {
- MMBlockCollection blocks = new MMBlockCollection();
- if (arg.sub[subi] == "")
- continue;
- string[] subparts = arg.sub[subi].Split(':');
- string subargtype = subparts[0];
- string subargstate = (subparts.Length > 1 ? subparts[1].ToLower() : "");
- blocks.AddBlocksOfType(subargtype, cmd.nameLike);
- if (blocks.Count() > 0) {
- for (int j = 0; j < blocks.Count(); j++)
- {
- IMyTerminalBlock block = blocks.Blocks[j];
- string onoff = (enabledList ? (block.IsWorking ? "ON" : "OFF") : GetWorkingString(block));
- if (subargstate != "" && onoff.ToLower() != subargstate)
- continue;
- if (enabledList)
- onoff = GetWorkingString(block);
- string blockName = block.CustomName;
- blockName = MMStringFunc.GetStringTrimmed(blockName, LCD_LINE_WORK_STATE_POS - 100);
- MMLCDMgr.Add(panel, blockName);
- MMLCDMgr.AddRightAlignLn(panel, onoff, LCD_LINE_WORK_STATE_POS);
- }
- }
- }
- }
- }
- public void RunItemAmount(MMPanel panel, MMCommand cmd)
- {
- bool progressbars = true;
- if (cmd.cmdstr[cmd.cmdstr.Length - 1] == 'x')
- {
- cmd.cmdstr = cmd.cmdstr.Substring(0, cmd.cmdstr.Length - 1);
- progressbars = false;
- }
- if (cmd.args.Count == 0)
- cmd.args.Add(new MMArgument(
- "reactor,gatlingturret,missileturret,interiorturret,gatlinggun,launcherreload,launcher,oxygenerator"));
- for (int i = 0; i < cmd.args.Count; i++)
- {
- MMArgument arg = cmd.args[i];
- for (int subi = 0; subi < arg.sub.Count; subi++)
- {
- MMBlockCollection blocks = new MMBlockCollection();
- if (arg.sub[subi] == "")
- continue;
- string subargtype = arg.sub[subi];
- blocks.AddBlocksOfType(subargtype, cmd.nameLike);
- if (blocks.Count() > 0)
- {
- for (int j = 0; j < blocks.Count(); j++)
- {
- IMyTerminalBlock block = blocks.Blocks[j];
- IMyInventory inv = block.GetInventory(0);
- if (inv == null)
- continue;
- double amt = 0;
- double maxAmt = 0;
- double otherAmt = 0;
- List<IMyInventoryItem> items = inv.GetItems();
- string itemType = (items.Count > 0 ? items[0].Content.ToString() : "");
- for (int idx = 0; idx < items.Count; idx++)
- {
- IMyInventoryItem item = items[idx];
- if (item.Content.ToString() != itemType)
- otherAmt += (double)item.Amount;
- else
- amt += (double)item.Amount;
- }
- string amountStr = "EMPTY";
- string blockName = block.CustomName;
- if (amt > 0 && (double)inv.CurrentVolume > 0)
- {
- double otherVol = otherAmt * (double)inv.CurrentVolume / (amt + otherAmt);
- maxAmt = Math.Floor(amt * ((double)inv.MaxVolume - otherVol) / (double)inv.CurrentVolume - otherVol);
- amountStr = MM.FormatLargeNumber(amt) + " / " + (otherAmt > 0 ? "~" : "") + MM.FormatLargeNumber(maxAmt);
- }
- blockName = MMStringFunc.GetStringTrimmed(blockName, LCD_LINE_WORK_STATE_POS - 60);
- MMLCDMgr.Add(panel, blockName);
- MMLCDMgr.AddRightAlignLn(panel, amountStr, LCD_LINE_WORK_STATE_POS);
- if (progressbars && maxAmt > 0)
- {
- double perc = 100 * amt / maxAmt;
- MMLCDMgr.AddProgressBarLn(panel, perc, FULL_PROGRESS_CHARS);
- }
- }
- }
- }
- }
- }
- public void RunEcho(MMPanel panel, MMCommand cmd)
- {
- bool center = (cmd.cmdstr == "center");
- int idx = cmd.cmdLine.IndexOf(' ');
- string msg = "";
- if (idx >= 0)
- msg = cmd.cmdLine.Substring(idx + 1);
- if (!center)
- MMLCDMgr.AddLn(panel, msg);
- else
- MMLCDMgr.AddCenterLn(panel, msg, LCD_LINE_WIDTH / 2);
- }
- public void RunDamage(MMPanel panel, MMCommand cmd)
- {
- bool simple = cmd.cmdstr.StartsWith("damagex");
- bool onlyDmg = cmd.cmdstr.EndsWith("noc"); // no construct
- MMBlockCollection blocks = new MMBlockCollection();
- blocks.AddBlocksOfNameLike(cmd.nameLike);
- bool found = false;
- for (int i = 0; i < blocks.Count(); i++)
- {
- IMyTerminalBlock block = blocks.Blocks[i];
- IMySlimBlock slim = block.CubeGrid.GetCubeBlock(block.Position);
- float hull = (onlyDmg? slim.MaxIntegrity : slim.BuildIntegrity) - slim.CurrentDamage;
- float perc = 100 * (hull / slim.MaxIntegrity);
- if (perc >= 100)
- continue;
- found = true;
- MMLCDMgr.Add(panel, MMStringFunc.GetStringTrimmed(slim.FatBlock.DisplayNameText,
- LCD_LINE_DMG_NUMBERS_POS - 70) + " ");
- if (!simple)
- {
- MMLCDMgr.AddRightAlign(panel, MM.FormatLargeNumber(hull) + " / ",
- LCD_LINE_DMG_NUMBERS_POS);
- MMLCDMgr.Add(panel, MM.FormatLargeNumber(slim.MaxIntegrity));
- }
- MMLCDMgr.AddRightAlignLn(panel, ' ' + perc.ToString("0.0") + "%", LCD_LINE_WIDTH);
- MMLCDMgr.AddProgressBarLn(panel, perc, FULL_PROGRESS_CHARS);
- }
- if (!found)
- MMLCDMgr.AddLn(panel, "No damaged blocks found.");
- }
- public void RunTankStatus(MMPanel panel, MMCommand cmd)
- {
- List<MMArgument> args = cmd.args;
- string tankType;
- if (args.Count == 0 || args[0].sub.Count == 0)
- {
- MMLCDMgr.AddLn(panel, "Missing tank type. eg: 'Tanks * Hydrogen'");
- return;
- }
- tankType = args[0].sub[0];
- double percent;
- MMBlockCollection blocks = new MMBlockCollection();
- blocks.AddBlocksOfType("oxytank", cmd.nameLike);
- double tankSum = 0;
- int cnt = blocks.Count();
- for (int i = 0; i < blocks.Count(); i++)
- {
- IMyOxygenTank tank = blocks.Blocks[i] as IMyOxygenTank;
- if ((tankType == "oxygen" && tank.BlockDefinition.SubtypeId == "") ||
- tank.BlockDefinition.SubtypeId.ToLower().Contains(tankType)) // only selected tank type
- tankSum += tank.GetOxygenLevel() * 100;
- else
- cnt--;
- }
- if (cnt == 0)
- {
- MMLCDMgr.AddLn(panel, "No " + tankType + " tanks found.");
- return;
- }
- percent = tankSum / cnt;
- tankType = char.ToUpper(tankType[0]) + tankType.Substring(1);
- MMLCDMgr.Add(panel, tankType + " Tanks");
- MMLCDMgr.AddRightAlignLn(panel, percent.ToString("F2") + "%", LCD_LINE_WORK_STATE_POS);
- MMLCDMgr.AddProgressBarLn(panel, percent, FULL_PROGRESS_CHARS);
- }
- public void RunOxygenStatus(MMPanel panel, MMCommand cmd)
- {
- double percent;
- MMBlockCollection blocks = new MMBlockCollection();
- blocks.AddBlocksOfType("airvent", cmd.nameLike);
- bool found = (blocks.Count() > 0);
- for (int i = 0; i < blocks.Count(); i++)
- {
- IMyAirVent vent = blocks.Blocks[i] as IMyAirVent;
- percent = Math.Max(vent.GetOxygenLevel() * 100, 0f);
- MMLCDMgr.Add(panel, vent.CustomName);
- if (vent.CanPressurize)
- MMLCDMgr.AddRightAlignLn(panel, percent.ToString("F1") + "%", LCD_LINE_WORK_STATE_POS);
- else
- MMLCDMgr.AddRightAlignLn(panel, "Leaking", LCD_LINE_WORK_STATE_POS);
- MMLCDMgr.AddProgressBarLn(panel, percent, FULL_PROGRESS_CHARS);
- }
- blocks.Clear();
- blocks.AddBlocksOfType("oxyfarm", cmd.nameLike);
- int cnt = blocks.Count();
- if (cnt > 0)
- {
- double farmSum = 0;
- for (int i = 0; i < cnt; i++)
- {
- IMyOxygenFarm farm = blocks.Blocks[i] as IMyOxygenFarm;
- farmSum += farm.GetOutput() * 100;
- }
- percent = farmSum / cnt;
- if (found)
- MMLCDMgr.AddLn(panel, "");
- found |= (cnt > 0);
- MMLCDMgr.Add(panel, "Oxygen Farms");
- MMLCDMgr.AddRightAlignLn(panel, percent.ToString("F2") + "%", LCD_LINE_WORK_STATE_POS);
- MMLCDMgr.AddProgressBarLn(panel, percent, FULL_PROGRESS_CHARS);
- }
- blocks.Clear();
- blocks.AddBlocksOfType("oxytank", cmd.nameLike);
- cnt = blocks.Count();
- if (cnt == 0)
- {
- if (!found)
- MMLCDMgr.AddLn(panel, "No oxygen blocks found.");
- return;
- }
- double tankSum = 0;
- int tankCnt = cnt;
- for (int i = 0; i < cnt; i++)
- {
- IMyOxygenTank tank = blocks.Blocks[i] as IMyOxygenTank;
- if (tank.BlockDefinition.SubtypeId == "" ||
- tank.BlockDefinition.SubtypeId.Contains("Oxygen")) // only oxygen tanks
- tankSum += tank.GetOxygenLevel() * 100;
- else
- tankCnt--;
- }
- if (tankCnt == 0)
- {
- if (!found)
- MMLCDMgr.AddLn(panel, "No oxygen blocks found.");
- return;
- }
- percent = tankSum / tankCnt;
- if (found)
- MMLCDMgr.AddLn(panel, "");
- MMLCDMgr.Add(panel, "Oxygen Tanks");
- MMLCDMgr.AddRightAlignLn(panel, percent.ToString("F2") + "%", LCD_LINE_WORK_STATE_POS);
- MMLCDMgr.AddProgressBarLn(panel, percent, FULL_PROGRESS_CHARS);
- }
- public void RunMass(MMPanel panel, MMCommand cmd)
- {
- MMBlockCollection blocks = new MMBlockCollection();
- bool simple = (cmd.cmdstr[cmd.cmdstr.Length - 1] == 'x');
- bool progress = (cmd.cmdstr[cmd.cmdstr.Length - 1] == 'p');
- blocks.AddBlocksOfNameLike(cmd.nameLike);
- double used = blocks.GetMassSummary();
- double total = 0;
- int argCnt = cmd.args.Count;
- if (argCnt > 0)
- {
- if (cmd.args[0].sub.Count > 0)
- double.TryParse(cmd.args[0].sub[0].Trim(), out total);
- if ((argCnt > 1) && (cmd.args[1].sub.Count > 0)) {
- string unit = cmd.args[1].sub[0].Trim().ToLower();
- if (unit != "")
- total *= Math.Pow(1000.0, "kmgtpezy".IndexOf(unit[0]));
- }
- total *= 1000.0;
- }
- MMLCDMgr.Add(panel, "Cargo Mass: ");
- if (total <= 0)
- {
- MMLCDMgr.AddRightAlignLn(panel, MM.FormatLargeNumber(used), LCD_LINE_WIDTH);
- return;
- }
- double perc = used / total * 100;
- if (!simple && !progress)
- {
- MMLCDMgr.AddRightAlignLn(panel, MM.FormatLargeNumber(used) + "g / " + MM.FormatLargeNumber(total) + "g", LCD_LINE_WIDTH);
- MMLCDMgr.AddProgressBar(panel, perc, FULL_PROGRESS_CHARS, PERCENT_TEXT_SIZE);
- MMLCDMgr.AddLn(panel, ' ' + perc.ToString("0.0") + "%");
- }
- else if (progress)
- {
- MMLCDMgr.AddRightAlignLn(panel, perc.ToString("0.0") + "%", LCD_LINE_WIDTH);
- MMLCDMgr.AddProgressBarLn(panel, perc, FULL_PROGRESS_CHARS);
- }
- else
- MMLCDMgr.AddRightAlignLn(panel, perc.ToString("0.0") + "%", LCD_LINE_WIDTH);
- }
- public void RunCargoStatus(MMPanel panel, MMCommand cmd)
- {
- MMBlockCollection blocks = new MMBlockCollection();
- bool alltypes = cmd.cmdstr.Contains("all");
- bool simple = (cmd.cmdstr[cmd.cmdstr.Length - 1] == 'x');
- bool progress = (cmd.cmdstr[cmd.cmdstr.Length - 1] == 'p');
- if (alltypes)
- blocks.AddBlocksOfNameLike(cmd.nameLike);
- else
- blocks.AddBlocksOfType("cargocontainer",
- cmd.nameLike);
- double usedCargo;
- double totalCargo;
- double percentCargo = blocks.GetCargoSpaceSummary(
- out usedCargo, out totalCargo);
- MMLCDMgr.Add(panel, "Cargo Used: ");
- if (!simple && !progress)
- {
- MMLCDMgr.AddRightAlignLn(panel, MM.FormatLargeNumber(usedCargo) + "L / " + MM.FormatLargeNumber(totalCargo) + "L", LCD_LINE_WIDTH);
- MMLCDMgr.AddProgressBar(panel, percentCargo, FULL_PROGRESS_CHARS, PERCENT_TEXT_SIZE);
- MMLCDMgr.AddLn(panel, ' ' + percentCargo.ToString("0.0") + "%");
- }
- else if (progress)
- {
- MMLCDMgr.AddRightAlignLn(panel, percentCargo.ToString("0.0") + "%", LCD_LINE_WIDTH);
- MMLCDMgr.AddProgressBarLn(panel, percentCargo, FULL_PROGRESS_CHARS);
- }
- else
- MMLCDMgr.AddRightAlignLn(panel, percentCargo.ToString("0.0") + "%", LCD_LINE_WIDTH);
- }
- // type: simple, progress, normal
- public void ShowPowerOutput(MMPanel panel, MMBlockCollection generators, string title, string type = "normal")
- {
- double usedPower, totalPower;
- double percentPower = generators.GetPowerOutput(out usedPower, out totalPower);
- MMLCDMgr.Add(panel, title + ": ");
- switch (type)
- {
- case "simple":
- MMLCDMgr.AddRightAlignLn(panel, ' ' + percentPower.ToString("0.0") + "%", LCD_LINE_WIDTH);
- break;
- case "progress":
- MMLCDMgr.AddRightAlignLn(panel, ' ' + percentPower.ToString("0.0") + "%", LCD_LINE_WIDTH);
- MMLCDMgr.AddProgressBarLn(panel, percentPower, FULL_PROGRESS_CHARS);
- break;
- default:
- MMLCDMgr.AddRightAlignLn(panel, MM.FormatLargeNumber(usedPower) + "W / " + MM.FormatLargeNumber(totalPower) + "W", LCD_LINE_WIDTH);
- MMLCDMgr.AddProgressBar(panel, percentPower, FULL_PROGRESS_CHARS, PERCENT_TEXT_SIZE);
- MMLCDMgr.AddRightAlignLn(panel, ' ' + percentPower.ToString("0.0") + "%", LCD_LINE_WIDTH);
- break;
- }
- }
- public void ShowSolarOutput(MMPanel panel, MMBlockCollection generators, string title, string type = "normal")
- {
- double usedPower, totalPower;
- generators.GetPowerOutput(out usedPower, out totalPower);
- double percentPower = (totalPower > 0 ? (usedPower / totalPower) * 100 : 100);
- MMLCDMgr.Add(panel, title + ": ");
- switch (type)
- {
- case "simple":
- MMLCDMgr.AddRightAlignLn(panel, ' ' + percentPower.ToString("0.0") + "%", LCD_LINE_WIDTH);
- break;
- case "progress":
- MMLCDMgr.AddRightAlignLn(panel, ' ' + percentPower.ToString("0.0") + "%", LCD_LINE_WIDTH);
- MMLCDMgr.AddProgressBarLn(panel, percentPower, FULL_PROGRESS_CHARS);
- break;
- default:
- MMLCDMgr.AddRightAlignLn(panel, MM.FormatLargeNumber(usedPower) + "W / " + MM.FormatLargeNumber(totalPower) + "W", LCD_LINE_WIDTH);
- MMLCDMgr.AddProgressBar(panel, percentPower, FULL_PROGRESS_CHARS, PERCENT_TEXT_SIZE);
- MMLCDMgr.AddRightAlignLn(panel, ' ' + percentPower.ToString("0.0") + "%", LCD_LINE_WIDTH);
- break;
- }
- }
- public void ShowBatteriesInfo(MMPanel panel, MMBlockCollection batteries, string title, bool onlystored = false, string type = "normal")
- {
- double output, maxOutput, input, maxInput;
- double stored, maxStored;
- double percentStored =
- batteries.GetBatteryStats(
- out output, out maxOutput,
- out input, out maxInput,
- out stored, out maxStored);
- double percentOutput = (maxOutput > 0 ? (output / maxOutput) * 100 : 100);
- double percentInput = (maxInput > 0 ? (input / maxInput) * 100 : 100);
- if (!onlystored)
- {
- if (type != "progress")
- {
- MMLCDMgr.Add(panel, title + ": ");
- MMLCDMgr.AddRightAlignLn(panel, "(IN " + MM.FormatLargeNumber(input) + "W / OUT " + MM.FormatLargeNumber(output) + "W)", LCD_LINE_WIDTH);
- }
- else
- MMLCDMgr.AddLn(panel, title + ": ");
- MMLCDMgr.Add(panel, " Stored: ");
- } else
- MMLCDMgr.Add(panel, title + ": ");
- switch (type)
- {
- case "simple":
- MMLCDMgr.AddRightAlignLn(panel, ' ' + percentStored.ToString("0.0") + "%", LCD_LINE_WIDTH);
- break;
- case "progress":
- MMLCDMgr.AddRightAlignLn(panel, ' ' + percentStored.ToString("0.0") + "%", LCD_LINE_WIDTH);
- MMLCDMgr.AddProgressBarLn(panel, percentStored, FULL_PROGRESS_CHARS);
- break;
- default:
- MMLCDMgr.AddRightAlignLn(panel, MM.FormatLargeNumber(stored) + "Wh / " + MM.FormatLargeNumber(maxStored) + "Wh", LCD_LINE_WIDTH);
- MMLCDMgr.AddProgressBar(panel, percentStored, FULL_PROGRESS_CHARS, PERCENT_TEXT_SIZE);
- MMLCDMgr.AddRightAlignLn(panel, ' ' + percentStored.ToString("0.0") + "%", LCD_LINE_WIDTH);
- break;
- }
- if (onlystored)
- return;
- MMLCDMgr.Add(panel, " Output: ");
- switch (type)
- {
- case "simple":
- MMLCDMgr.AddRightAlignLn(panel, ' ' + percentOutput.ToString("0.0") + "%", LCD_LINE_WIDTH);
- break;
- case "progress":
- MMLCDMgr.AddRightAlignLn(panel, ' ' + percentOutput.ToString("0.0") + "%", LCD_LINE_WIDTH);
- MMLCDMgr.AddProgressBarLn(panel, percentOutput, FULL_PROGRESS_CHARS);
- break;
- default:
- MMLCDMgr.AddRightAlignLn(panel, MM.FormatLargeNumber(output) + "W / " + MM.FormatLargeNumber(maxOutput) + "W", LCD_LINE_WIDTH);
- MMLCDMgr.AddProgressBar(panel, percentOutput, FULL_PROGRESS_CHARS, PERCENT_TEXT_SIZE);
- MMLCDMgr.AddRightAlignLn(panel, ' ' + percentOutput.ToString("0.0") + "%", LCD_LINE_WIDTH);
- break;
- }
- MMLCDMgr.Add(panel, " Input: ");
- switch (type)
- {
- case "simple":
- MMLCDMgr.AddRightAlignLn(panel, ' ' + percentInput.ToString("0.0") + "%", LCD_LINE_WIDTH);
- break;
- case "progress":
- MMLCDMgr.AddRightAlignLn(panel, ' ' + percentInput.ToString("0.0") + "%", LCD_LINE_WIDTH);
- MMLCDMgr.AddProgressBarLn(panel, percentInput, FULL_PROGRESS_CHARS);
- break;
- default:
- MMLCDMgr.AddRightAlignLn(panel, MM.FormatLargeNumber(input) + "W / " + MM.FormatLargeNumber(maxInput) + "W", LCD_LINE_WIDTH);
- MMLCDMgr.AddProgressBar(panel, percentInput, FULL_PROGRESS_CHARS, PERCENT_TEXT_SIZE);
- MMLCDMgr.AddRightAlignLn(panel, ' ' + percentInput.ToString("0.0") + "%", LCD_LINE_WIDTH);
- break;
- }
- }
- public void RunPowerStatus(MMPanel panel, MMCommand cmd)
- {
- MMBlockCollection reactors = new MMBlockCollection();
- MMBlockCollection solars = new MMBlockCollection();
- MMBlockCollection batteries = new MMBlockCollection();
- int got;
- string displayType = (cmd.cmdstr.EndsWith("x") ? "simple" : (cmd.cmdstr.EndsWith("p") ? "progress" : "normal"));
- bool issummary = (cmd.cmdstr.StartsWith("powersummary"));
- bool isstored = (cmd.cmdstr.StartsWith("powerstored"));
- if (!isstored)
- {
- reactors.AddBlocksOfType("reactor", cmd.nameLike);
- solars.AddBlocksOfType("solarpanel", cmd.nameLike);
- }
- batteries.AddBlocksOfType("battery", cmd.nameLike);
- got = 0;
- int reactCnt = reactors.Count();
- int solarCnt = solars.Count();
- int batteCnt = batteries.Count();
- if (reactCnt > 0) got++;
- if (solarCnt > 0) got++;
- if (batteCnt > 0) got++;
- if (got < 1)
- {
- MMLCDMgr.AddLn(panel, "No power source found!");
- return;
- }
- if (isstored)
- {
- ShowBatteriesInfo(panel, batteries, "Batteries", true, displayType);
- return;
- }
- string title = "Total Output";
- if (!issummary)
- {
- if (reactCnt > 0)
- ShowPowerOutput(panel, reactors, "Reactors", displayType);
- if (solarCnt > 0)
- ShowSolarOutput(panel, solars, "Solars", displayType);
- if (batteCnt > 0)
- ShowBatteriesInfo(panel, batteries, "Batteries", false, displayType);
- }
- else
- {
- title = "Power";
- got = 10; // hack ;)
- }
- if (got == 1)
- return;
- MMBlockCollection blocks = new MMBlockCollection();
- blocks.AddFromCollection(reactors);
- blocks.AddFromCollection(solars);
- blocks.AddFromCollection(batteries);
- ShowPowerOutput(panel, blocks, title, displayType);
- }
- public void RunCountdown(MMPanel panel, MMCommand cmd)
- {
- bool center = cmd.cmdstr.EndsWith("c");
- bool right = cmd.cmdstr.EndsWith("r");
- string input = "";
- int firstSpace = cmd.cmdLine.IndexOf(' ');
- if (firstSpace >= 0)
- input = cmd.cmdLine.Substring(firstSpace + 1).Trim();
- DateTime now = DateTime.Now;
- DateTime inputt;
- // 19:02 3.9.2015
- if (!DateTime.TryParseExact(input, "H:mm d.M.yyyy", System.Globalization.CultureInfo.InvariantCulture,
- System.Globalization.DateTimeStyles.None, out inputt))
- {
- MMLCDMgr.AddLn(panel, "Invalid countdown format, use:");
- MMLCDMgr.AddLn(panel, " Countdown 19:02 28.2.2015");
- return;
- }
- TimeSpan dt = inputt - now;
- string text = "";
- if (dt.Ticks <= 0)
- text = "EXPIRED";
- else
- {
- if ((int)dt.TotalDays > 0)
- text += (int)dt.TotalDays + " days ";
- if (dt.Hours > 0 || text != "")
- text += dt.Hours + "h ";
- if (dt.Minutes > 0 || text != "")
- text += dt.Minutes + "m ";
- text += dt.Seconds + "s";
- }
- if (center)
- MMLCDMgr.AddCenterLn(panel, text, LCD_LINE_WIDTH / 2);
- else if (right)
- MMLCDMgr.AddRightAlignLn(panel, text, LCD_LINE_WIDTH);
- else
- MMLCDMgr.AddLn(panel, text);
- }
- public void RunCurrentTime(MMPanel panel, MMCommand cmd)
- {
- bool datetime = (cmd.cmdstr.StartsWith("datetime"));
- bool date = (cmd.cmdstr.StartsWith("date"));
- bool center = cmd.cmdstr.Contains("c");
- int offsetIdx = cmd.cmdstr.IndexOf('+');
- if (offsetIdx < 0)
- offsetIdx = cmd.cmdstr.IndexOf('-');
- float offset = 0;
- if (offsetIdx >= 0)
- float.TryParse(cmd.cmdstr.Substring(offsetIdx), out offset);
- DateTime dt = DateTime.Now.AddHours(offset);
- string text = "";
- int firstSpace = cmd.cmdLine.IndexOf(' ');
- if (firstSpace >= 0)
- text = cmd.cmdLine.Substring(firstSpace + 1);
- if (!datetime)
- {
- if (!date)
- text += dt.ToShortTimeString();
- else
- text += dt.ToShortDateString();
- }
- else
- {
- if (text == "")
- text = String.Format("{0:d} {0:t}", dt);
- else
- {
- // try to prevent exceptions
- text = text.Replace("/", "\\/");
- text = text.Replace(":", "\\:");
- text = text.Replace("\"", "\\\"");
- text = text.Replace("'", "\\'");
- text = dt.ToString(text + ' ');
- text = text.Substring(0, text.Length - 1);
- }
- }
- if (center)
- MMLCDMgr.AddCenterLn(panel, text, LCD_LINE_WIDTH / 2);
- else
- MMLCDMgr.AddLn(panel, text);
- }
- private void ShowInventoryLine(MMPanel panel, string msg, double num, int quota)
- {
- if (quota > 0)
- {
- MMLCDMgr.AddProgressBar(panel, Math.Min(100, 100 * num / quota), INV_PROGRESS_CHARS);
- MMLCDMgr.Add(panel, ' ' + msg + ' ');
- MMLCDMgr.AddRightAlign(panel, MM.FormatLargeNumber(num), LCD_LINE_INV_NUMBERS_POS);
- MMLCDMgr.AddLn(panel, " / " + MM.FormatLargeNumber(quota));
- }
- else
- {
- MMLCDMgr.Add(panel, msg + ':');
- MMLCDMgr.AddRightAlignLn(panel, MM.FormatLargeNumber(num), LCD_LINE_NUMERS_POS);
- }
- }
- private void ShowInventoryIngotLine(MMPanel panel, string msg, double num, double numOres, int quota)
- {
- if (quota > 0)
- {
- MMLCDMgr.Add(panel, msg + ' ');
- MMLCDMgr.AddRightAlign(panel, MM.FormatLargeNumber(num), LCD_LINE_INGOT_NUMBERS_POS);
- MMLCDMgr.Add(panel, " / " + MM.FormatLargeNumber(quota));
- MMLCDMgr.AddRightAlignLn(panel, "+" + MM.FormatLargeNumber(numOres) + " ore", LCD_LINE_WIDTH);
- MMLCDMgr.AddProgressBarLn(panel, Math.Min(100, 100 * num / quota), FULL_PROGRESS_CHARS);
- }
- else
- {
- MMLCDMgr.Add(panel, msg + ':');
- MMLCDMgr.AddRightAlign(panel, MM.FormatLargeNumber(num), LCD_LINE_INGOT_NUMBERS_POS);
- MMLCDMgr.AddRightAlignLn(panel, "+" + MM.FormatLargeNumber(numOres) + " ore", LCD_LINE_WIDTH);
- }
- }
- public void PrintItemsOfMain(MMPanel panel, MMItemAmounts amounts, bool missing, bool simple, string mainType, string displayType)
- {
- List<MMAmountSpec> items = amounts.GetAmountsOfMain(mainType);
- if (items.Count > 0)
- {
- if (!simple)
- {
- if (MMLCDMgr.GetLCDText(panel).curLine > 0 && MMLCDMgr.GetLCDText(panel).lines[0] != "")
- MMLCDMgr.AddLn(panel, ""); // add empty line
- MMLCDMgr.AddCenterLn(panel, "<< " + displayType + " summary >>", LCD_LINE_WIDTH / 2);
- }
- for (int i = 0; i < items.Count; i++)
- {
- double num = items[i].current;
- if (missing && num >= items[i].min)
- continue;
- int quota = items[i].max;
- if (missing)
- quota = items[i].min;
- string msg = MM.TranslateToDisplay(items[i].subType, items[i].mainType);
- ShowInventoryLine(panel, msg, num, quota);
- }
- }
- }
- public void RunInvListing(MMPanel panel, MMCommand cmd)
- {
- MMBlockCollection blocks = new MMBlockCollection();
- bool noexpand = false;
- bool simple = false;
- if (cmd.cmdstr[cmd.cmdstr.Length - 1] == 's')
- {
- cmd.cmdstr = cmd.cmdstr.Substring(0, cmd.cmdstr.Length - 1);
- simple = true;
- }
- if (cmd.cmdstr[cmd.cmdstr.Length - 1] == 'x')
- {
- cmd.cmdstr = cmd.cmdstr.Substring(0, cmd.cmdstr.Length - 1);
- noexpand = true;
- }
- bool missing = (cmd.cmdstr == "missing");
- bool nocats = (cmd.cmdstr == "invlist");
- blocks.AddBlocksOfNameLike(cmd.nameLike);
- MMItemAmounts amounts = new MMItemAmounts();
- List<MMArgument> args = cmd.args;
- if (args.Count == 0)
- args.Add(new MMArgument("all", false));
- for (int i = 0; i < args.Count; i++)
- {
- MMArgument arg = args[i];
- string mainType = arg.main.ToLower();
- for (int subi = 0; subi < arg.sub.Count; subi++)
- {
- string[] subs = arg.sub[subi].Split(':');
- double number;
- MM.Debug("Processing sub arg " + subs[0]);
- if (subs[0] == "all")
- subs[0] = "";
- int min = 1;
- int max = -1;
- if (subs.Length > 1)
- {
- if (Double.TryParse(subs[1], out number))
- {
- if (missing)
- min = (int)Math.Ceiling(number);
- else
- max = (int)Math.Ceiling(number);
- }
- }
- string subfulltype = subs[0];
- if (mainType != "")
- subfulltype += ' ' + mainType;
- amounts.AddSpec(subfulltype, (arg.op == "-"), min, max);
- }
- }
- MM.Debug("All args processed");
- if (!noexpand)
- {
- amounts.ExpandSpecs();
- MM.Debug("Expanded specs");
- }
- MM.Debug("Entering process function");
- amounts.ProcessItemsFromBlockCollection(blocks);
- MM.Debug("Processed items from blocks");
- PrintItemsOfMain(panel, amounts, missing, nocats, "Ore", "Ores");
- MM.Debug("Printed ores");
- if (simple)
- PrintItemsOfMain(panel, amounts, missing, nocats, "Ingot", "Ingots");
- else
- {
- List<MMAmountSpec> ingots = amounts.GetAmountsOfMain("Ingot");
- if (ingots.Count > 0)
- {
- if (!nocats)
- {
- if (MMLCDMgr.GetLCDText(panel).curLine > 0 && MMLCDMgr.GetLCDText(panel).lines[0] != "")
- MMLCDMgr.AddLn(panel, ""); // add empty line
- MMLCDMgr.AddCenterLn(panel, "<< Ingots summary >>", LCD_LINE_WIDTH / 2);
- }
- for (int i = 0; i < ingots.Count; i++)
- {
- double num = ingots[i].current;
- if (missing && num >= ingots[i].min)
- continue;
- int quota = ingots[i].max;
- if (missing)
- quota = ingots[i].min;
- string msg = MM.TranslateToDisplay(ingots[i].subType, ingots[i].mainType);
- if (ingots[i].subType != "Scrap")
- {
- double numOres = amounts.GetAmountSpec(ingots[i].subType + " Ore", ingots[i].subType, "Ore").current;
- ShowInventoryIngotLine(panel, msg, num, numOres, quota);
- }
- else
- ShowInventoryLine(panel, msg, num, quota);
- }
- }
- }
- MM.Debug("Printed ingots");
- PrintItemsOfMain(panel, amounts, missing, nocats, "Component", "Components");
- PrintItemsOfMain(panel, amounts, missing, nocats, "OxygenContainerObject", "Gas");
- PrintItemsOfMain(panel, amounts, missing, true, "GasContainerObject", "");
- PrintItemsOfMain(panel, amounts, missing, nocats, "AmmoMagazine", "Ammo");
- PrintItemsOfMain(panel, amounts, missing, nocats, "PhysicalGunObject", "Tools");
- }
- }
- // MMAPI below (do not modify)
- public class MMCommand
- {
- public string cmdstr = "";
- public string nameLike = "";
- public string cmdLine;
- public List<MMArgument> args = new List<MMArgument>();
- public MMCommand(string _cmdLine)
- {
- cmdLine = _cmdLine.TrimStart(' ');
- if (cmdLine == "")
- return;
- string[] targs = cmdLine.Split(' ');
- string fullArg = "";
- bool multiWord = false;
- cmdstr = targs[0].ToLower();
- for (int i = 1; i < targs.Length; i++)
- {
- string arg = targs[i];
- if (arg == "")
- continue;
- if (arg[0] == '{' && arg[arg.Length - 1] == '}')
- {
- arg = arg.Substring(1, arg.Length - 2);
- if (arg == "")
- continue;
- if (nameLike == "")
- nameLike = arg;
- else
- args.Add(new MMArgument(arg.ToLower(), false));
- continue;
- }
- if (arg[0] == '{')
- {
- multiWord = true;
- fullArg = arg.Substring(1);
- continue;
- }
- if (arg[arg.Length - 1] == '}')
- {
- multiWord = false;
- fullArg += ' ' + arg.Substring(0, arg.Length - 1);
- if (nameLike == "")
- nameLike = fullArg;
- else
- args.Add(new MMArgument(fullArg.ToLower(), false));
- continue;
- }
- if (multiWord)
- {
- if (fullArg.Length != 0)
- fullArg += ' ';
- fullArg += arg;
- continue;
- }
- if (nameLike == "")
- nameLike = arg;
- else
- args.Add(new MMArgument(arg.ToLower()));
- }
- }
- }
- public class MMArgument
- {
- public string op = "";
- public string main;
- public List<string> sub = new List<string>();
- public MMArgument(string arg, bool parse = true)
- {
- if (!parse)
- {
- main = "";
- sub.Add(arg);
- return;
- }
- string cur = arg.Trim();
- if (cur[0] == '+' || cur[0] == '-')
- {
- op += cur[0];
- cur = arg.Substring(1);
- }
- string[] parts = cur.Split('/');
- string subargs = parts[0];
- if (parts.Length > 1)
- {
- main = parts[0];
- subargs = parts[1];
- }
- else
- main = "";
- if (subargs.Length > 0)
- {
- string[] subs = subargs.Split(',');
- for (int i = 0; i < subs.Length; i++)
- if (subs[i] != "")
- sub.Add(subs[i]);
- }
- }
- }
- // IMyTerminal reactors collection with useful methods
- public class MMBlockCollection
- {
- public List<IMyTerminalBlock> Blocks = new List<IMyTerminalBlock>();
- public double GetCargoSpaceSummary(out double usedAmount, out double totalAmount)
- {
- usedAmount = 0;
- totalAmount = 0;
- for (int i = 0; i < Blocks.Count; i++)
- {
- IMyInventory inv = Blocks[i].GetInventory(0);
- if (inv == null)
- continue;
- usedAmount += (double)inv.CurrentVolume;
- totalAmount += (double)inv.MaxVolume;
- }
- usedAmount *= 1000;
- totalAmount *= 1000;
- return MM.GetPercent(usedAmount, totalAmount);
- }
- public double GetMassSummary()
- {
- double used = 0;
- for (int i = 0; i < Blocks.Count; i++) {
- for (int invId = 0; invId < 2; invId++) {
- IMyInventory inv = Blocks[i].GetInventory(invId);
- if (inv == null)
- continue;
- used += (double)inv.CurrentMass;
- }
- }
- return used * 1000;
- }
- public double GetPowerOutput(out double current, out double max)
- {
- max = 0;
- current = 0;
- for (int i = 0; i < Blocks.Count; i++)
- {
- IMyBatteryBlock bat = (Blocks[i] as IMyBatteryBlock);
- List<double> vals = MMStatus.GetDetailedInfoValues(Blocks[i]);
- if ((bat != null && vals.Count < 6) ||
- (bat == null && vals.Count < 2))
- continue;
- max += vals[0];
- if (bat != null)
- current += vals[4];
- else
- current += vals[1];
- }
- return MM.GetPercent(current, max);
- }
- // returns percent stored
- public double GetBatteryStats(out double output, out double max_output,
- out double input, out double max_input,
- out double stored, out double max_stored)
- {
- max_output = 0;
- output = 0;
- max_input = 0;
- input = 0;
- max_stored = 0;
- stored = 0;
- for (int i = 0; i < Blocks.Count; i++)
- {
- List<double> vals = MMStatus.GetDetailedInfoValues(Blocks[i]);
- if (vals.Count < 6)
- continue;
- max_output += vals[0];
- max_input += vals[1];
- max_stored += vals[2];
- input += vals[3];
- output += vals[4];
- stored += vals[5];
- }
- return MM.GetPercent(stored, max_stored);
- }
- // add Blocks with name containing nameLike
- public void AddBlocksOfNameLike(string nameLike)
- {
- if (nameLike == "" || nameLike == "*")
- {
- List<IMyTerminalBlock> lBlocks = new List<IMyTerminalBlock>();
- MM._GridTerminalSystem.GetBlocks(lBlocks);
- Blocks.AddList(lBlocks);
- return;
- }
- string group = (nameLike.StartsWith("G:") ? nameLike.Substring(2).Trim().ToLower() : "");
- if (group != "")
- {
- List<IMyBlockGroup> BlockGroups = new List<IMyBlockGroup>();
- MM._GridTerminalSystem.GetBlockGroups(BlockGroups);
- for (int i = 0; i < BlockGroups.Count; i++)
- {
- IMyBlockGroup g = BlockGroups[i];
- if (g.Name.ToLower() == group)
- Blocks.AddList(g.Blocks);
- }
- return;
- }
- MM._GridTerminalSystem.SearchBlocksOfName(nameLike, Blocks);
- }
- // add Blocks of type (optional: with name containing nameLike)
- public void AddBlocksOfType(string type, string nameLike = "")
- {
- if (nameLike == "" || nameLike == "*")
- {
- List<IMyTerminalBlock> blocksOfType = new List<IMyTerminalBlock>();
- MMBlkMgr.GetBlocksOfType(ref blocksOfType, type);
- Blocks.AddList(blocksOfType);
- }
- else
- {
- string group = (nameLike.StartsWith("G:") ? nameLike.Substring(2).Trim().ToLower() : "");
- if (group != "")
- {
- List<IMyBlockGroup> BlockGroups = new List<IMyBlockGroup>();
- MM._GridTerminalSystem.GetBlockGroups(BlockGroups);
- for (int i = 0; i < BlockGroups.Count; i++)
- {
- IMyBlockGroup g = BlockGroups[i];
- if (g.Name.ToLower() == group)
- {
- for (int j = 0; j < g.Blocks.Count; j++)
- if (MMBlkMgr.IsBlockOfType(g.Blocks[j], type))
- Blocks.Add(g.Blocks[j]);
- return;
- }
- }
- return;
- }
- List<IMyTerminalBlock> blocksOfType = new List<IMyTerminalBlock>();
- MMBlkMgr.GetBlocksOfType(ref blocksOfType, type);
- for (int i = 0; i < blocksOfType.Count; i++)
- if (blocksOfType[i].CustomName.Contains(nameLike))
- Blocks.Add(blocksOfType[i]);
- }
- }
- // add all Blocks from collection col to this collection
- public void AddFromCollection(MMBlockCollection col)
- {
- Blocks.AddList(col.Blocks);
- }
- // clear all reactors from this collection
- public void Clear()
- {
- Blocks.Clear();
- }
- // number of reactors in collection
- public int Count()
- {
- return Blocks.Count;
- }
- }
- public class MMAmountSpec
- {
- public int min;
- public int max;
- public string subType = "";
- public string mainType = "";
- public bool ignore;
- public double current;
- public MMAmountSpec(bool _ignore = false, int _min = 1, int _max = -1)
- {
- min = _min;
- ignore = _ignore;
- max = _max;
- }
- }
- // Item amounts class
- public class MMItemAmounts
- {
- public MMAmountSpecDict specBySubLower;
- public MMAmountSpecDict specByMainLower;
- public MMAmountSpecDict specByFullLower;
- public bool specAll;
- public MMAmountSpecDict amountByFullType;
- public MMItemAmounts(int size = 20)
- {
- specBySubLower = new MMAmountSpecDict();
- specByMainLower = new MMAmountSpecDict();
- specByFullLower = new MMAmountSpecDict();
- specAll = false;
- amountByFullType = new MMAmountSpecDict();
- }
- private bool IsMain(string subarg)
- {
- return (subarg == "ingot" || subarg == "ore" ||
- subarg == "component" || subarg == "ammo" ||
- subarg == "tool" || subarg == "physicalgunobject" ||
- subarg == "ammomagazine" || subarg == "oxygencontainerobject" ||
- subarg == "oxygen" || subarg == "gascontainerobject" || subarg == "gas");
- }
- public void AddSpec(string subfulltype, bool ignore = false, int min = 1, int max = -1)
- {
- if (subfulltype == "")
- {
- specAll = true;
- return;
- }
- string[] parts = subfulltype.Split(' ');
- string mainType = "";
- MMAmountSpec spec = new MMAmountSpec(ignore, min, max);
- if (parts.Length == 2)
- {
- mainType = parts[1];
- if (mainType == "tool")
- mainType = "physicalgunobject";
- else
- if (mainType == "ammo")
- mainType = "ammomagazine";
- else
- if (mainType == "oxygen")
- mainType = "oxygencontainerobject";
- else
- if (mainType == "gas")
- mainType = "gascontainerobject";
- }
- string subType = parts[0].ToLower();
- if (IsMain(subType))
- {
- if (subType == "tool")
- subType = "physicalgunobject";
- else
- if (subType == "ammo")
- subType = "ammomagazine";
- else
- if (subType == "oxygen")
- subType = "oxygencontainerobject";
- else
- if (subType == "gas")
- subType = "gascontainerobject";
- spec.mainType = subType;
- specByMainLower.AddItem(spec.mainType, spec);
- return;
- }
- MM.TranslateToInternal(ref subType, ref mainType);
- if (mainType == "")
- {
- spec.subType = subType.ToLower();
- specBySubLower.AddItem(spec.subType, spec);
- return;
- }
- spec.subType = subType;
- spec.mainType = mainType;
- specByFullLower.AddItem(subType.ToLower() + ' ' + mainType.ToLower(), spec);
- }
- public MMAmountSpec GetSpec(string fullType, string subType, string mainType)
- {
- MMAmountSpec spec;
- fullType = fullType.ToLower();
- spec = specByFullLower.GetItem(fullType);
- if (spec != null)
- return spec;
- subType = subType.ToLower();
- spec = specBySubLower.GetItem(subType);
- if (spec != null)
- return spec;
- mainType = mainType.ToLower();
- spec = specByMainLower.GetItem(mainType);
- if (spec != null)
- return spec;
- return null;
- }
- public bool IsIgnored(string fullType, string subType, string mainType)
- {
- MMAmountSpec spec;
- bool found = false;
- spec = specByMainLower.GetItem(mainType.ToLower());
- if (spec != null)
- {
- if (spec.ignore)
- return true;
- found = true;
- }
- spec = specBySubLower.GetItem(subType.ToLower());
- if (spec != null)
- {
- if (spec.ignore)
- return true;
- found = true;
- }
- spec = specByFullLower.GetItem(fullType.ToLower());
- if (spec != null)
- {
- if (spec.ignore)
- return true;
- found = true;
- }
- return !(specAll || found);
- }
- public MMAmountSpec CreateAmountSpec(string fullType, string subType, string mainType)
- {
- MMAmountSpec amount = new MMAmountSpec();
- fullType = fullType.ToLower();
- MMAmountSpec spec = GetSpec(fullType, subType.ToLower(), mainType.ToLower());
- if (spec != null)
- {
- amount.min = spec.min;
- amount.max = spec.max;
- }
- amount.subType = subType;
- amount.mainType = mainType;
- amountByFullType.AddItem(fullType, amount);
- return amount;
- }
- public MMAmountSpec GetAmountSpec(string fullType, string subType, string mainType)
- {
- MMAmountSpec amount = amountByFullType.GetItem(fullType.ToLower());
- if (amount == null)
- amount = CreateAmountSpec(fullType, subType, mainType);
- return amount;
- }
- public List<MMAmountSpec> GetAmountsOfMain(string mainType)
- {
- List<MMAmountSpec> result = new List<MMAmountSpec>();
- for (int i = 0; i < amountByFullType.CountAll(); i++)
- {
- MMAmountSpec spec = amountByFullType.GetItemAt(i);
- if (IsIgnored((spec.subType + ' ' + spec.mainType).ToLower(),
- spec.subType, spec.mainType))
- continue;
- if (spec.mainType == mainType)
- result.Add(spec);
- }
- return result;
- }
- public void ExpandSpecs()
- {
- for (int i = 0; i < MMItems.keys.Count; i++)
- {
- MMItem item = MMItems.items[MMItems.keys[i]];
- if (!item.used)
- continue;
- string fullType = item.subType + ' ' + item.mainType;
- if (IsIgnored(fullType, item.subType, item.mainType))
- continue;
- MMAmountSpec amount = GetAmountSpec(fullType, item.subType, item.mainType);
- if (amount.max == -1)
- amount.max = item.defaultQuota;
- }
- }
- public void ProcessItemsFromBlockCollection(MMBlockCollection col)
- {
- for (int i = 0; i < col.Count(); i++)
- {
- for (int invId = 0; invId < col.Blocks[i].GetInventoryCount(); invId++)
- {
- IMyInventory inv = col.Blocks[i].GetInventory(invId);
- List<IMyInventoryItem> items = inv.GetItems();
- for (int j = 0; j < items.Count; j++)
- {
- IMyInventoryItem item = items[j];
- string fullType = MM.GetItemFullType(item);
- string fullTypeL = fullType.ToLower();
- string subType, mainType;
- MM.ParseFullType(fullTypeL, out subType, out mainType);
- if (mainType == "ore")
- {
- if (IsIgnored(subType.ToLower() + " ingot", subType, "Ingot") &&
- IsIgnored(fullType, subType, mainType))
- continue;
- }
- else
- {
- if (IsIgnored(fullType, subType, mainType))
- continue;
- }
- MM.ParseFullType(fullType, out subType, out mainType);
- MMAmountSpec amount = GetAmountSpec(fullTypeL, subType, mainType);
- amount.current += (double)item.Amount;
- }
- }
- }
- }
- }
- // MMAPI Helper functions
- public static class MMBlkMgr
- {
- public static IMyGridTerminalSystem _GridTerminalSystem;
- private static bool IsCryoChamber(IMyTerminalBlock block)
- {
- return block.BlockDefinition.ToString().Contains("Cryo");
- }
- public static void GetBlocksOfExactType(ref List<IMyTerminalBlock> blocks, string exact)
- {
- if (exact == "CargoContainer") _GridTerminalSystem.GetBlocksOfType<IMyCargoContainer>(blocks);
- else if (exact == "TextPanel") _GridTerminalSystem.GetBlocksOfType<IMyTextPanel>(blocks);
- else if (exact == "Assembler") _GridTerminalSystem.GetBlocksOfType<IMyAssembler>(blocks);
- else if (exact == "Refinery") _GridTerminalSystem.GetBlocksOfType<IMyRefinery>(blocks);
- else if (exact == "Reactor") _GridTerminalSystem.GetBlocksOfType<IMyReactor>(blocks);
- else if (exact == "SolarPanel") _GridTerminalSystem.GetBlocksOfType<IMySolarPanel>(blocks);
- else if (exact == "BatteryBlock") _GridTerminalSystem.GetBlocksOfType<IMyBatteryBlock>(blocks);
- else if (exact == "Beacon") _GridTerminalSystem.GetBlocksOfType<IMyBeacon>(blocks);
- else if (exact == "RadioAntenna") _GridTerminalSystem.GetBlocksOfType<IMyRadioAntenna>(blocks);
- else if (exact == "AirVent") _GridTerminalSystem.GetBlocksOfType<IMyAirVent>(blocks);
- else if (exact == "ConveyorSorter") _GridTerminalSystem.GetBlocksOfType<IMyConveyorSorter>(blocks);
- else if (exact == "OxygenTank") _GridTerminalSystem.GetBlocksOfType<IMyOxygenTank>(blocks);
- else if (exact == "OxygenGenerator") _GridTerminalSystem.GetBlocksOfType<IMyOxygenGenerator>(blocks);
- else if (exact == "OxygenFarm") _GridTerminalSystem.GetBlocksOfType<IMyOxygenFarm>(blocks);
- // FIXME!
- else if (exact == "CryoChamber") _GridTerminalSystem.GetBlocksOfType<IMyTerminalBlock>(blocks, IsCryoChamber);
- else if (exact == "LaserAntenna") _GridTerminalSystem.GetBlocksOfType<IMyLaserAntenna>(blocks);
- else if (exact == "Thrust") _GridTerminalSystem.GetBlocksOfType<IMyThrust>(blocks);
- else if (exact == "Gyro") _GridTerminalSystem.GetBlocksOfType<IMyGyro>(blocks);
- else if (exact == "SensorBlock") _GridTerminalSystem.GetBlocksOfType<IMySensorBlock>(blocks);
- else if (exact == "ShipConnector") _GridTerminalSystem.GetBlocksOfType<IMyShipConnector>(blocks);
- else if (exact == "ReflectorLight") _GridTerminalSystem.GetBlocksOfType<IMyReflectorLight>(blocks);
- else if (exact == "InteriorLight") _GridTerminalSystem.GetBlocksOfType<IMyInteriorLight>(blocks);
- else if (exact == "LandingGear") _GridTerminalSystem.GetBlocksOfType<IMyLandingGear>(blocks);
- else if (exact == "ProgrammableBlock") _GridTerminalSystem.GetBlocksOfType<IMyProgrammableBlock>(blocks);
- else if (exact == "TimerBlock") _GridTerminalSystem.GetBlocksOfType<IMyTimerBlock>(blocks);
- else if (exact == "MotorStator") _GridTerminalSystem.GetBlocksOfType<IMyMotorStator>(blocks);
- else if (exact == "PistonBase") _GridTerminalSystem.GetBlocksOfType<IMyPistonBase>(blocks);
- else if (exact == "Projector") _GridTerminalSystem.GetBlocksOfType<IMyProjector>(blocks);
- else if (exact == "ShipMergeBlock") _GridTerminalSystem.GetBlocksOfType<IMyShipMergeBlock>(blocks);
- else if (exact == "SoundBlock") _GridTerminalSystem.GetBlocksOfType<IMySoundBlock>(blocks);
- else if (exact == "Collector") _GridTerminalSystem.GetBlocksOfType<IMyCollector>(blocks);
- else if (exact == "JumpDrive") _GridTerminalSystem.GetBlocksOfType<IMyJumpDrive>(blocks);
- else if (exact == "Door") _GridTerminalSystem.GetBlocksOfType<IMyDoor>(blocks);
- else if (exact == "GravityGeneratorSphere") _GridTerminalSystem.GetBlocksOfType<IMyGravityGeneratorSphere>(blocks);
- else if (exact == "GravityGenerator") _GridTerminalSystem.GetBlocksOfType<IMyGravityGenerator>(blocks);
- else if (exact == "ShipDrill") _GridTerminalSystem.GetBlocksOfType<IMyShipDrill>(blocks);
- else if (exact == "ShipGrinder") _GridTerminalSystem.GetBlocksOfType<IMyShipGrinder>(blocks);
- else if (exact == "ShipWelder") _GridTerminalSystem.GetBlocksOfType<IMyShipWelder>(blocks);
- else if (exact == "LargeGatlingTurret") _GridTerminalSystem.GetBlocksOfType<IMyLargeGatlingTurret>(blocks);
- else if (exact == "LargeInteriorTurret") _GridTerminalSystem.GetBlocksOfType<IMyLargeInteriorTurret>(blocks);
- else if (exact == "LargeMissileTurret") _GridTerminalSystem.GetBlocksOfType<IMyLargeMissileTurret>(blocks);
- else if (exact == "SmallGatlingGun") _GridTerminalSystem.GetBlocksOfType<IMySmallGatlingGun>(blocks);
- else if (exact == "SmallMissileLauncherReload") _GridTerminalSystem.GetBlocksOfType<IMySmallMissileLauncherReload>(blocks);
- else if (exact == "SmallMissileLauncher") _GridTerminalSystem.GetBlocksOfType<IMySmallMissileLauncher>(blocks);
- else if (exact == "VirtualMass") _GridTerminalSystem.GetBlocksOfType<IMyVirtualMass>(blocks);
- else if (exact == "Warhead") _GridTerminalSystem.GetBlocksOfType<IMyWarhead>(blocks);
- else if (exact == "FunctionalBlock") _GridTerminalSystem.GetBlocksOfType<IMyFunctionalBlock>(blocks);
- else if (exact == "LightingBlock") _GridTerminalSystem.GetBlocksOfType<IMyLightingBlock>(blocks);
- else if (exact == "ControlPanel") _GridTerminalSystem.GetBlocksOfType<IMyControlPanel>(blocks);
- else if (exact == "Cockpit") _GridTerminalSystem.GetBlocksOfType<IMyCockpit>(blocks);
- else if (exact == "MedicalRoom") _GridTerminalSystem.GetBlocksOfType<IMyMedicalRoom>(blocks);
- else if (exact == "RemoteControl") _GridTerminalSystem.GetBlocksOfType<IMyRemoteControl>(blocks);
- else if (exact == "ButtonPanel") _GridTerminalSystem.GetBlocksOfType<IMyButtonPanel>(blocks);
- else if (exact == "CameraBlock") _GridTerminalSystem.GetBlocksOfType<IMyCameraBlock>(blocks);
- else if (exact == "OreDetector") _GridTerminalSystem.GetBlocksOfType<IMyOreDetector>(blocks);
- }
- public static void GetBlocksOfType(ref List<IMyTerminalBlock> blocks, string typestr)
- {
- GetBlocksOfExactType(ref blocks, TranslateToExactBlockType(typestr.Trim()));
- }
- public static bool IsBlockOfType(IMyTerminalBlock block, string typestr)
- {
- return block.BlockDefinition.ToString().Contains(TranslateToExactBlockType(typestr));
- }
- public static string TranslateToExactBlockType(string typeInStr)
- {
- typeInStr = typeInStr.ToLower();
- if (typeInStr.StartsWith("carg")
- || typeInStr.StartsWith("conta")) return "CargoContainer";
- if (typeInStr.StartsWith("text")
- || typeInStr.StartsWith("lcd")) return "TextPanel";
- if (typeInStr.StartsWith("ass")) return "Assembler";
- if (typeInStr.StartsWith("refi")) return "Refinery";
- if (typeInStr.StartsWith("reac")) return "Reactor";
- if (typeInStr.StartsWith("solar")) return "SolarPanel";
- if (typeInStr.StartsWith("bat")) return "BatteryBlock";
- if (typeInStr.StartsWith("bea")) return "Beacon";
- if (typeInStr.Contains("vent")) return "AirVent";
- if (typeInStr.Contains("sorter")) return "ConveyorSorter";
- if (typeInStr.Contains("tank")) return "OxygenTank";
- if (typeInStr.Contains("farm")
- && typeInStr.Contains("oxy")) return "OxygenFarm";
- if (typeInStr.Contains("gene")
- && typeInStr.Contains("oxy")) return "OxygenGenerator";
- if (typeInStr.Contains("cryo")) return "CryoChamber";
- if (typeInStr == "laserantenna") return "LaserAntenna";
- if (typeInStr.Contains("antenna")) return "RadioAntenna";
- if (typeInStr.StartsWith("thrust")) return "Thrust";
- if (typeInStr.StartsWith("gyro")) return "Gyro";
- if (typeInStr.StartsWith("sensor")) return "SensorBlock";
- if (typeInStr.Contains("connector")) return "ShipConnector";
- if (typeInStr.StartsWith("reflector")) return "ReflectorLight";
- if ((typeInStr.StartsWith("inter")
- && typeInStr.EndsWith("light"))) return "InteriorLight";
- if (typeInStr.StartsWith("land")) return "LandingGear";
- if (typeInStr.StartsWith("program")) return "ProgrammableBlock";
- if (typeInStr.StartsWith("timer")) return "TimerBlock";
- if (typeInStr.StartsWith("motor")) return "MotorStator";
- if (typeInStr.StartsWith("piston")) return "PistonBase";
- if (typeInStr.StartsWith("proj")) return "Projector";
- if (typeInStr.Contains("merge")) return "ShipMergeBlock";
- if (typeInStr.StartsWith("sound")) return "SoundBlock";
- if (typeInStr.StartsWith("col")) return "Collector";
- if (typeInStr.Contains("jump")) return "JumpDrive";
- if (typeInStr == "door") return "Door";
- if ((typeInStr.Contains("grav")
- && typeInStr.Contains("sphe"))) return "GravityGeneratorSphere";
- if (typeInStr.Contains("grav")) return "GravityGenerator";
- if (typeInStr.EndsWith("drill")) return "ShipDrill";
- if (typeInStr.Contains("grind")) return "ShipGrinder";
- if (typeInStr.EndsWith("welder")) return "ShipWelder";
- if ((typeInStr.Contains("turret")
- && typeInStr.Contains("gatl"))) return "LargeGatlingTurret";
- if ((typeInStr.Contains("turret")
- && typeInStr.Contains("inter"))) return "LargeInteriorTurret";
- if ((typeInStr.Contains("turret")
- && typeInStr.Contains("miss"))) return "LargeMissileTurret";
- if (typeInStr.Contains("gatl")) return "SmallGatlingGun";
- if ((typeInStr.Contains("launcher")
- && typeInStr.Contains("reload"))) return "SmallMissileLauncherReload";
- if ((typeInStr.Contains("launcher"))) return "SmallMissileLauncher";
- if (typeInStr.Contains("mass")) return "VirtualMass";
- if (typeInStr == "warhead") return "Warhead";
- if (typeInStr.StartsWith("func")) return "FunctionalBlock";
- if (typeInStr.StartsWith("light")) return "LightingBlock";
- if (typeInStr.StartsWith("contr")) return "ControlPanel";
- if (typeInStr.StartsWith("coc")) return "Cockpit";
- if (typeInStr.StartsWith("medi")) return "MedicalRoom";
- if (typeInStr.StartsWith("remote")) return "RemoteControl";
- if (typeInStr.StartsWith("but")) return "ButtonPanel";
- if (typeInStr.StartsWith("cam")) return "CameraBlock";
- if (typeInStr.Contains("detect")) return "OreDetector";
- return "Unknown";
- }
- }
- public static class MMStatus
- {
- public static List<double> GetDetailedInfoValues(IMyTerminalBlock block, int lines = -1)
- {
- List<double> result = new List<double>();
- string[] attrLines = block.DetailedInfo.Split('\n');
- int max = Math.Min(attrLines.Length, (lines > 0 ? lines : attrLines.Length));
- for (int i = 0; i < max; i++)
- {
- string[] parts = attrLines[i].Split(':');
- // broken line? (try German)
- if (parts.Length < 2)
- {
- parts = attrLines[i].Split('r');
- // still broken line? (try Portuguese)
- if (parts.Length < 2)
- parts = attrLines[i].Split('x');
- }
- string valStr = (parts.Length < 2 ? parts[0] : parts[1]);
- string[] valParts = valStr.Trim().Split(' ');
- string strVal = valParts[0];
- char strUnit = (valParts.Length > 1?valParts[1][0]:'.');
- double val;
- if (Double.TryParse(strVal, out val))
- {
- double finalVal = val * Math.Pow(1000.0, ".kMGTPEZY".IndexOf(strUnit));
- result.Add(finalVal);
- }
- }
- return result;
- }
- public static string GetLastDetailedValue(IMyTerminalBlock block)
- {
- string[] infoLines = block.DetailedInfo.Split('\n');
- string[] stateParts = infoLines[infoLines.Length - 1].Split(':');
- string state = (stateParts.Length > 1?stateParts[1]:stateParts[0]);
- return state;
- }
- public static string GetBatteryWorkingString(IMyBatteryBlock battery)
- {
- string prefix = "";
- if (battery.GetValueBool("Recharge"))
- prefix = "(+) ";
- else
- if (battery.GetValueBool("Discharge"))
- prefix = "(-) ";
- else
- prefix = "(±) ";
- return prefix + ((battery.CurrentStoredPower / battery.MaxStoredPower) * 100.0f).ToString("0.0") + "%";
- }
- // Get laser antenna status
- public static string GetLaserAntennaStatus(IMyLaserAntenna gear)
- {
- string[] infoLines = gear.DetailedInfo.Split('\n');
- return infoLines[infoLines.Length - 1].Split(' ')[0].ToUpper();
- }
- public static double GetJumpDriveChargeValues(IMyJumpDrive jd, out double cur, out double max)
- {
- List<double> vals = GetDetailedInfoValues(jd, 5);
- if (vals.Count < 4) {
- max = 0;
- cur = 0;
- return 0;
- }
- max = vals[1];
- cur = vals[3];
- return MM.GetPercent(cur, max);
- }
- public static double GetJumpDriveCharge(IMyJumpDrive jd)
- {
- List<double> vals = GetDetailedInfoValues(jd, 5);
- double max = 0, cur = 0;
- if (vals.Count < 4)
- return 0;
- max = vals[1];
- cur = vals[3];
- return MM.GetPercent(cur, max);
- }
- // Get landing gear status
- public static string GetLandingGearStatus(IMyLandingGear gear)
- {
- string unlockchars = "udoesnp";
- string[] infoLines = gear.DetailedInfo.Split('\n');
- string attrLine = infoLines[infoLines.Length - 1];
- string[] attr = attrLine.Split(':');
- string state;
- if (attr.Length < 2)
- state = attr[0].Trim().ToLower();
- else
- state = attr[1].Trim().ToLower();
- if (state == "")
- return "UNLOCK";
- // hope it will be more words in other langs too
- if (state.Split(' ').Length > 1)
- return "READY";
- if ((unlockchars.IndexOf(state[0]) < 0) && !state.StartsWith("au"))
- return "LOCK";
- return "UNLOCK";
- }
- }
- public static class MM
- {
- public static bool EnableDebug;
- public static IMyGridTerminalSystem _GridTerminalSystem;
- public static MMBlockCollection _DebugTextPanels;
- public static IMyProgrammableBlock Me;
- public static TimeSpan ElapsedTime;
- public static void Init(IMyGridTerminalSystem gridSystem)
- {
- _GridTerminalSystem = gridSystem;
- MMBlkMgr._GridTerminalSystem = gridSystem;
- _DebugTextPanels = new MMBlockCollection();
- MMStringFunc.InitCharSizes();
- // prepare debug panels
- // select all text panels with [DEBUG] in name
- if (MM.EnableDebug)
- {
- _DebugTextPanels.AddBlocksOfType("textpanel", "[DEBUG]");
- Debug("DEBUG Panel started.", false, "DEBUG PANEL");
- }
- MMItems.Init();
- }
- public static double GetPercent(double current, double max)
- {
- return (max > 0 ? (current / max) * 100 : 100);
- }
- // return full type of item
- public static string GetItemFullType(IMyInventoryItem item)
- {
- string typeid = item.Content.TypeId.ToString();
- typeid = typeid.Substring(typeid.LastIndexOf('_') + 1);
- return item.Content.SubtypeName + " " + typeid;
- }
- // parse full type into subType and mainType
- public static void ParseFullType(string fullType, out string subType, out string mainType)
- {
- string[] substr = fullType.Split(' ');
- if (substr.Length == 2)
- {
- subType = substr[0];
- mainType = substr[1];
- return;
- }
- subType = fullType;
- mainType = "";
- }
- public static string TranslateToDisplay(string fullType)
- {
- string subType;
- string mainType;
- ParseFullType(fullType, out subType, out mainType);
- return TranslateToDisplay(subType, mainType);
- }
- public static string TranslateToDisplay(string subType, string mainType)
- {
- MMItem item = MMItems.GetItemOfType(subType, mainType);
- if (item != null) {
- if (item.displayName != "")
- return item.displayName;
- return item.subType;
- }
- return System.Text.RegularExpressions.Regex.Replace(
- subType, "([a-z])([A-Z])", "$1 $2");
- }
- public static void TranslateToInternal(ref string subType, ref string mainType)
- {
- string shortName = subType.ToLower();
- MMItem item;
- if (MMItems.itemsByShort.TryGetValue(shortName, out item)) {
- subType = item.subType;
- mainType = item.mainType;
- return;
- }
- item = MMItems.GetItemOfType(subType, mainType);
- if (item != null)
- {
- subType = item.subType;
- if (mainType == "Ore" || mainType == "Ingot")
- return;
- mainType = item.mainType;
- }
- }
- public static string FormatLargeNumber(double number, bool compress = true)
- {
- if (!compress)
- return number.ToString(
- "#,###,###,###,###,###,###,###,###,###");
- string ordinals = " kMGTPEZY";
- double compressed = number;
- var ordinal = 0;
- while (compressed >= 1000)
- {
- compressed /= 1000;
- ordinal++;
- }
- string res = Math.Round(compressed, 1, MidpointRounding.AwayFromZero).ToString();
- if (ordinal > 0)
- res += " " + ordinals[ordinal];
- return res;
- }
- public static void WriteLine(IMyTextPanel textpanel, string message, bool append = true, string title = "")
- {
- textpanel.WritePublicText(message + "\n", append);
- if (title != "")
- textpanel.WritePublicTitle(title);
- textpanel.ShowTextureOnScreen();
- textpanel.ShowPublicTextOnScreen();
- }
- public static void Debug(string message, bool append = true, string title = "")
- {
- if (EnableDebug && _DebugTextPanels != null && _DebugTextPanels.Count() != 0)
- DebugTextPanel(message, append, title);
- }
- public static void DebugTextPanel(string message, bool append = true, string title = "")
- {
- for (int i = 0; i < _DebugTextPanels.Count(); i++)
- {
- IMyTextPanel debugpanel = _DebugTextPanels.Blocks[i] as IMyTextPanel;
- debugpanel.SetCustomName("[DEBUG] Prog: " + message);
- WriteLine(debugpanel, message, append, title);
- }
- }
- }
- public class MMPanel
- {
- // approximate width of LCD panel line
- public const float LCD_LINE_WIDTH = 730;
- public int SCROLL_LINES = 5;
- public MMTextPanelDict panels = new MMTextPanelDict();
- public MMLCDMgr.MMLCDText text;
- public IMyTextPanel first;
- public void SetFontSize(float size)
- {
- for (int i = 0; i < panels.CountAll(); i++)
- panels.GetItemAt(i).SetValueFloat("FontSize", size);
- }
- public void SortPanels()
- {
- panels.SortAll();
- first = panels.GetItemAt(0);
- }
- public bool IsWide()
- {
- return (first.BlockDefinition.SubtypeId.Contains("Wide")
- || first.DefinitionDisplayNameText == "Computer Monitor");
- }
- public void Update()
- {
- if (text == null)
- return;
- int cnt = panels.CountAll();
- if (cnt > 1)
- SetFontSize(first.GetValueFloat("FontSize"));
- for (int i = 0; i < panels.CountAll(); i++)
- {
- IMyTextPanel panel = panels.GetItemAt(i);
- panel.WritePublicText(text.GetDisplayString(i));
- if (MMLCDMgr.forceRedraw)
- {
- panel.ShowTextureOnScreen();
- panel.ShowPublicTextOnScreen();
- }
- }
- }
- }
- public static class MMLCDMgr
- {
- private static Dictionary<IMyTextPanel, MMLCDText> texts = new Dictionary<IMyTextPanel, MMLCDText>();
- public static bool forceRedraw = true;
- public static void SetupLCDText(MMPanel p)
- {
- MMLCDText lcdText = GetLCDText(p);
- lcdText.SetFontSize(p.first.GetValueFloat("FontSize"));
- lcdText.SetNrScreens(p.panels.CountAll());
- lcdText.widthMod = (p.IsWide() ? 2.0f : 1.0f) * (0.8f / lcdText.fontSize);
- lcdText.SCROLL_LINES = p.SCROLL_LINES;
- }
- public static MMLCDText GetLCDText(MMPanel p)
- {
- MMLCDText lcdText;
- IMyTextPanel panel = p.first;
- if (!texts.TryGetValue(panel, out lcdText))
- {
- lcdText = new MMLCDText();
- p.text = lcdText;
- texts.Add(panel, lcdText);
- }
- p.text = lcdText;
- return lcdText;
- }
- public static void AddLn(MMPanel panel, string line)
- {
- MMLCDText lcd = GetLCDText(panel);
- lcd.AddLine(line);
- }
- public static void AddMultiLn(MMPanel panel, string multiline)
- {
- MMLCDText lcd = GetLCDText(panel);
- lcd.AddMultiLine(multiline);
- }
- public static void Add(MMPanel panel, string text)
- {
- MMLCDText lcd = GetLCDText(panel);
- lcd.AddFast(text);
- lcd.curWidth += MMStringFunc.GetStringSize(text);
- }
- public static void AddRightAlignLn(MMPanel panel, string text, float endScreenX)
- {
- AddRightAlign(panel, text, endScreenX);
- AddLn(panel,"");
- }
- public static void AddRightAlign(MMPanel panel, string text, float endScreenX)
- {
- MMLCDText lcd = GetLCDText(panel);
- float textWidth = MMStringFunc.GetStringSize(text);
- endScreenX *= lcd.widthMod;
- endScreenX -= lcd.curWidth;
- if (endScreenX < textWidth)
- {
- lcd.AddFast(text);
- lcd.curWidth += textWidth;
- return;
- }
- endScreenX -= textWidth;
- int fillchars = (int)Math.Round(endScreenX / MMStringFunc.WHITESPACE_WIDTH, MidpointRounding.AwayFromZero);
- float fillWidth = fillchars * MMStringFunc.WHITESPACE_WIDTH;
- string filler = new String(' ', fillchars);
- lcd.AddFast(filler + text);
- lcd.curWidth += fillWidth + textWidth;
- }
- public static void AddCenterLn(MMPanel panel, string text, float screenX)
- {
- AddCenter(panel, text, screenX);
- AddLn(panel, "");
- }
- public static void AddCenter(MMPanel panel, string text, float screenX)
- {
- MMLCDText lcd = GetLCDText(panel);
- float textWidth = MMStringFunc.GetStringSize(text);
- screenX *= lcd.widthMod;
- screenX -= lcd.curWidth;
- if (screenX < textWidth / 2)
- {
- lcd.AddFast(text);
- lcd.curWidth += textWidth;
- return;
- }
- screenX -= textWidth / 2;
- int fillchars = (int)Math.Round(screenX / MMStringFunc.WHITESPACE_WIDTH, MidpointRounding.AwayFromZero);
- float fillWidth = fillchars * MMStringFunc.WHITESPACE_WIDTH;
- string filler = new String(' ', fillchars);
- lcd.AddFast(filler + text);
- lcd.curWidth += fillWidth + textWidth;
- }
- public static void AddProgressBarLn(MMPanel panel, double percent, int width = 22, float leaveSpaceX = 0f)
- {
- AddProgressBar(panel, percent, width, leaveSpaceX);
- AddLn(panel, "");
- }
- public static void AddProgressBar(MMPanel panel, double percent, int width = 22, float leaveSpaceX = 0f)
- {
- MMLCDText lcd = GetLCDText(panel);
- int totalBars = (int)(width * lcd.widthMod) - 2 - (int)(leaveSpaceX / MMStringFunc.PROGRESSCHAR_WIDTH);
- int fill = (int)(percent * totalBars) / 100;
- if (fill > totalBars)
- fill = totalBars;
- string progress = "[" + new String('|', fill) + new String('\'', totalBars - fill) + "]";
- lcd.AddFast(progress);
- lcd.curWidth += MMStringFunc.PROGRESSCHAR_WIDTH * totalBars + 18f;
- }
- public static void ClearText(MMPanel panel)
- {
- GetLCDText(panel).ClearText();
- }
- public static void UpdatePanel(MMPanel panel)
- {
- panel.Update();
- GetLCDText(panel).Scroll();
- }
- public class MMLCDText
- {
- public int SCROLL_LINES = 5;
- public float fontSize = 0.8f;
- public float widthMod = 1.0f;
- public int scrollPos;
- public int scrollDir = 1;
- public int DisplayLines = 22; // 22 for font size 0.8
- public int screens = 1;
- public List<string> lines = new List<string>();
- public int curLine;
- public float curWidth;
- public MMLCDText(float fontSize = 0.8f)
- {
- SetFontSize(fontSize);
- lines.Add("");
- }
- public void SetFontSize(float size)
- {
- fontSize = size;
- DisplayLines = (int)Math.Round(22 * (0.8 / fontSize) * screens);
- }
- public void SetNrScreens(int cnt)
- {
- screens = cnt;
- DisplayLines = (int)Math.Round(22 * (0.8 / fontSize) * screens);
- }
- public void AddFast(string text)
- {
- lines[curLine] += text;
- }
- public void AddMultiLine(string multiline)
- {
- string[] lines = multiline.Split('\n');
- for (int i = 0; i < lines.Length; i++)
- AddLine(lines[i]);
- }
- public void AddLine(string line)
- {
- lines[curLine] += line;
- lines.Add("");
- curLine++;
- curWidth = 0;
- }
- public void ClearText()
- {
- lines.Clear();
- lines.Add("");
- curWidth = 0;
- curLine = 0;
- }
- public string GetFullString()
- {
- return String.Join("\n", lines);
- }
- // Display only X lines from scrollPos
- public string GetDisplayString(int screenidx = 0)
- {
- if (lines.Count < DisplayLines / screens)
- {
- if (screenidx != 0) return "";
- scrollPos = 0;
- scrollDir = 1;
- return GetFullString();
- }
- int pos = scrollPos + screenidx * (DisplayLines / screens);
- if (pos > lines.Count)
- pos = lines.Count;
- List<string> display =
- lines.GetRange(pos,
- Math.Min(lines.Count - pos, DisplayLines / screens));
- return String.Join("\n", display);
- }
- public void Scroll()
- {
- int linesCnt = lines.Count - 1;
- if (linesCnt <= DisplayLines)
- {
- scrollPos = 0;
- scrollDir = 1;
- return;
- }
- if (scrollDir > 0)
- {
- if (scrollPos + SCROLL_LINES + DisplayLines > linesCnt)
- {
- scrollDir = -1;
- scrollPos = Math.Max(linesCnt - DisplayLines, 0);
- return;
- }
- scrollPos += SCROLL_LINES;
- }
- else
- {
- if (scrollPos - SCROLL_LINES < 0)
- {
- scrollPos = 0;
- scrollDir = 1;
- return;
- }
- scrollPos -= SCROLL_LINES;
- }
- }
- }
- }
- public static class MMStringFunc
- {
- private static Dictionary<char, float> charSize = new Dictionary<char, float>();
- public const float WHITESPACE_WIDTH = 8f;
- public const float PROGRESSCHAR_WIDTH = 6.4f;
- public static void InitCharSizes()
- {
- if (charSize.Count > 0)
- return;
- AddCharsSize("3FKTabdeghknopqsuy£µÝàáâãäåèéêëðñòóôõöøùúûüýþÿāăąďđēĕėęěĝğġģĥħĶķńņňʼnōŏőśŝşšŢŤŦũūŭůűųŶŷŸșȚЎЗКЛбдекруцяёђћўџ", 17f);
- AddCharsSize("#0245689CXZ¤¥ÇßĆĈĊČŹŻŽƒЁЌАБВДИЙПРСТУХЬ€", 19f);
- AddCharsSize("$&GHPUVY§ÙÚÛÜÞĀĜĞĠĢĤĦŨŪŬŮŰŲОФЦЪЯжы†‡", 20f);
- AddCharsSize("ABDNOQRSÀÁÂÃÄÅÐÑÒÓÔÕÖØĂĄĎĐŃŅŇŌŎŐŔŖŘŚŜŞŠȘЅЊЖф□", 21f);
- AddCharsSize("(),.1:;[]ft{}·ţťŧț", 9f);
- AddCharsSize("+<=>E^~¬±¶ÈÉÊË×÷ĒĔĖĘĚЄЏЕНЭ−", 18f);
- AddCharsSize(" !I`ijl ¡¨¯´¸ÌÍÎÏìíîïĨĩĪīĮįİıĵĺļľłˆˇ˘˙˚˛˜˝ІЇії‹›∙", 8f);
- AddCharsSize("7?Jcz¢¿çćĉċčĴźżžЃЈЧавийнопсъьѓѕќ", 16f);
- AddCharsSize("L_vx«»ĹĻĽĿŁГгзлхчҐ–•", 15f);
- AddCharsSize("\"-rªºŀŕŗř", 10f);
- AddCharsSize("mw¼ŵЮщ", 27f);
- AddCharsSize("MМШ", 26f);
- AddCharsSize("WÆŒŴ—…‰", 31f);
- AddCharsSize("'|¦ˉ‘’‚", 6f);
- AddCharsSize("*²³¹", 11f);
- AddCharsSize("\\°“”„", 12f);
- AddCharsSize("/ijтэє", 14f);
- AddCharsSize("%IJЫ", 24f);
- AddCharsSize("@©®мшњ", 25f);
- AddCharsSize("\n", 0f);
- AddCharsSize("¾æœЉ", 28f);
- AddCharsSize("½Щ", 29f);
- AddCharsSize("ј", 7f);
- AddCharsSize("љ", 22f);
- AddCharsSize("ґ", 13f);
- AddCharsSize("ю", 23f);
- AddCharsSize("™", 30f);
- AddCharsSize("", 34f);
- AddCharsSize("", 32f);
- AddCharsSize("", 41f);
- }
- private static void AddCharsSize(string chars, float size)
- {
- for (int i = 0; i < chars.Length; i++)
- charSize.Add(chars[i], size);
- }
- public static float GetCharSize(char c)
- {
- float width = 40;
- charSize.TryGetValue(c, out width);
- return width;
- }
- public static float GetStringSize(string str)
- {
- float sum = 0;
- for (int i = 0; i < str.Length; i++)
- sum += GetCharSize(str[i]);
- return sum;
- }
- public static string GetStringTrimmed(string text, float pixelWidth)
- {
- int trimlen = Math.Min((int)pixelWidth / 14, text.Length - 2);
- float stringSize = GetStringSize(text);
- if (stringSize <= pixelWidth)
- return text;
- while (stringSize > pixelWidth - 20)
- {
- text = text.Substring(0, trimlen);
- stringSize = GetStringSize(text);
- trimlen -= 2;
- }
- return text + "..";
- }
- }
- public class MMItem
- {
- public string subType;
- public string mainType;
- public int defaultQuota;
- public string displayName;
- public string shortName;
- public bool used;
- public MMItem(string _subType, string _mainType, int _defaultQuota = 0, string _displayName = "", string _shortName = "", bool _used = true)
- {
- subType = _subType;
- mainType = _mainType;
- defaultQuota = _defaultQuota;
- displayName = _displayName;
- shortName = _shortName;
- used = _used;
- }
- }
- public class MMPanelDict
- {
- public Dictionary<string, MMPanel> dict = new Dictionary<string, MMPanel>();
- public List<string> keys = new List<string>();
- public void AddItem(string key, MMPanel item) { if (!dict.ContainsKey(key)) { keys.Add(key); dict.Add(key, item); } }
- public int CountAll() { return dict.Count; }
- public MMPanel GetItem(string key) { if (dict.ContainsKey(key)) return dict[key]; return null; }
- public MMPanel GetItemAt(int index) { return dict[keys[index]]; }
- public void ClearAll() { keys.Clear(); dict.Clear(); }
- public void SortAll() { keys.Sort(); }
- }
- public class MMTextPanelDict
- {
- public Dictionary<string, IMyTextPanel> dict = new Dictionary<string, IMyTextPanel>();
- public List<string> keys = new List<string>();
- public void AddItem(string key, IMyTextPanel item) { if (!dict.ContainsKey(key)) { keys.Add(key); dict.Add(key, item); } }
- public int CountAll() { return dict.Count; }
- public IMyTextPanel GetItem(string key) { if (dict.ContainsKey(key)) return dict[key]; return null; }
- public IMyTextPanel GetItemAt(int index) { return dict[keys[index]]; }
- public void ClearAll() { keys.Clear(); dict.Clear(); }
- public void SortAll() { keys.Sort(); }
- }
- public class MMAmountSpecDict
- {
- public Dictionary<string, MMAmountSpec> dict = new Dictionary<string, MMAmountSpec>();
- public List<string> keys = new List<string>();
- public void AddItem(string key, MMAmountSpec item) { if (!dict.ContainsKey(key)) { keys.Add(key); dict.Add(key, item); } }
- public int CountAll() { return dict.Count; }
- public MMAmountSpec GetItem(string key) { if (dict.ContainsKey(key)) return dict[key]; return null; }
- public MMAmountSpec GetItemAt(int index) { return dict[keys[index]]; }
- public void ClearAll() { keys.Clear(); dict.Clear(); }
- public void SortAll() { keys.Sort(); }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement