fix indents everywhere

This commit is contained in:
Chris Forbes
2011-10-18 15:10:17 +13:00
parent 227bbc109e
commit bc6af1841b
180 changed files with 2707 additions and 2707 deletions

View File

@@ -266,10 +266,10 @@ namespace OpenRA.Editor
// menuStrip1 // menuStrip1
// //
this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.fileToolStripMenuItem, this.fileToolStripMenuItem,
this.mapToolStripMenuItem, this.mapToolStripMenuItem,
this.toolStripComboBox1, this.toolStripComboBox1,
this.toolStripLabel1}); this.toolStripLabel1});
this.menuStrip1.Location = new System.Drawing.Point(0, 0); this.menuStrip1.Location = new System.Drawing.Point(0, 0);
this.menuStrip1.Name = "menuStrip1"; this.menuStrip1.Name = "menuStrip1";
this.menuStrip1.Size = new System.Drawing.Size(985, 27); this.menuStrip1.Size = new System.Drawing.Size(985, 27);
@@ -279,16 +279,16 @@ namespace OpenRA.Editor
// fileToolStripMenuItem // fileToolStripMenuItem
// //
this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.newToolStripMenuItem, this.newToolStripMenuItem,
this.toolStripSeparator1, this.toolStripSeparator1,
this.openToolStripMenuItem, this.openToolStripMenuItem,
this.saveToolStripMenuItem, this.saveToolStripMenuItem,
this.saveAsToolStripMenuItem, this.saveAsToolStripMenuItem,
this.toolStripSeparator2, this.toolStripSeparator2,
this.toolStripMenuItem1, this.toolStripMenuItem1,
this.mnuExport, this.mnuExport,
this.toolStripSeparator3, this.toolStripSeparator3,
this.exitToolStripMenuItem}); this.exitToolStripMenuItem});
this.fileToolStripMenuItem.Name = "fileToolStripMenuItem"; this.fileToolStripMenuItem.Name = "fileToolStripMenuItem";
this.fileToolStripMenuItem.Size = new System.Drawing.Size(37, 23); this.fileToolStripMenuItem.Size = new System.Drawing.Size(37, 23);
this.fileToolStripMenuItem.Text = "&File"; this.fileToolStripMenuItem.Text = "&File";
@@ -340,8 +340,8 @@ namespace OpenRA.Editor
// toolStripMenuItem1 // toolStripMenuItem1
// //
this.toolStripMenuItem1.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripMenuItem1.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.cCRedAlertMapToolStripMenuItem, this.cCRedAlertMapToolStripMenuItem,
this.bitmapToolStripMenuItem}); this.bitmapToolStripMenuItem});
this.toolStripMenuItem1.Name = "toolStripMenuItem1"; this.toolStripMenuItem1.Name = "toolStripMenuItem1";
this.toolStripMenuItem1.Size = new System.Drawing.Size(123, 22); this.toolStripMenuItem1.Size = new System.Drawing.Size(123, 22);
this.toolStripMenuItem1.Text = "&Import"; this.toolStripMenuItem1.Text = "&Import";
@@ -365,7 +365,7 @@ namespace OpenRA.Editor
// mnuExport // mnuExport
// //
this.mnuExport.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.mnuExport.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.mnuMinimapToPNG}); this.mnuMinimapToPNG});
this.mnuExport.Name = "mnuExport"; this.mnuExport.Name = "mnuExport";
this.mnuExport.Size = new System.Drawing.Size(123, 22); this.mnuExport.Size = new System.Drawing.Size(123, 22);
this.mnuExport.Text = "&Export"; this.mnuExport.Text = "&Export";
@@ -394,11 +394,11 @@ namespace OpenRA.Editor
// mapToolStripMenuItem // mapToolStripMenuItem
// //
this.mapToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.mapToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.propertiesToolStripMenuItem, this.propertiesToolStripMenuItem,
this.resizeToolStripMenuItem, this.resizeToolStripMenuItem,
this.showActorNamesToolStripMenuItem, this.showActorNamesToolStripMenuItem,
this.showGridToolStripMenuItem, this.showGridToolStripMenuItem,
this.fixOpenAreasToolStripMenuItem, this.fixOpenAreasToolStripMenuItem,
this.setupDefaultPlayersMenuItem}); this.setupDefaultPlayersMenuItem});
this.mapToolStripMenuItem.Name = "mapToolStripMenuItem"; this.mapToolStripMenuItem.Name = "mapToolStripMenuItem";
this.mapToolStripMenuItem.Size = new System.Drawing.Size(43, 23); this.mapToolStripMenuItem.Size = new System.Drawing.Size(43, 23);
@@ -453,8 +453,8 @@ namespace OpenRA.Editor
// statusStrip1 // statusStrip1
// //
this.statusStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.statusStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.toolStripStatusLabelFiller, this.toolStripStatusLabelFiller,
this.toolStripStatusLabelMousePosition}); this.toolStripStatusLabelMousePosition});
this.statusStrip1.Location = new System.Drawing.Point(0, 751); this.statusStrip1.Location = new System.Drawing.Point(0, 751);
this.statusStrip1.Name = "statusStrip1"; this.statusStrip1.Name = "statusStrip1";
this.statusStrip1.Size = new System.Drawing.Size(985, 22); this.statusStrip1.Size = new System.Drawing.Size(985, 22);
@@ -538,9 +538,9 @@ namespace OpenRA.Editor
private System.Windows.Forms.TabPage tabPage2; private System.Windows.Forms.TabPage tabPage2;
private System.Windows.Forms.FlowLayoutPanel actorPalette; private System.Windows.Forms.FlowLayoutPanel actorPalette;
private System.Windows.Forms.TabPage tabPage3; private System.Windows.Forms.TabPage tabPage3;
private System.Windows.Forms.FlowLayoutPanel resourcePalette; private System.Windows.Forms.FlowLayoutPanel resourcePalette;
private Surface surface1; private Surface surface1;
private System.Windows.Forms.PictureBox pmMiniMap; private System.Windows.Forms.PictureBox pmMiniMap;
private System.Windows.Forms.SplitContainer splitContainer2; private System.Windows.Forms.SplitContainer splitContainer2;
private System.Windows.Forms.SaveFileDialog saveFileDialog; private System.Windows.Forms.SaveFileDialog saveFileDialog;
private System.Windows.Forms.SplitContainer splitContainer3; private System.Windows.Forms.SplitContainer splitContainer3;

View File

@@ -157,9 +157,9 @@ namespace OpenRA.Editor
var etf = info.Traits.GetOrDefault<EditorTilesetFilterInfo>(); var etf = info.Traits.GetOrDefault<EditorTilesetFilterInfo>();
if (etf != null && etf.ExcludeTilesets != null if (etf != null && etf.ExcludeTilesets != null
&& etf.ExcludeTilesets.Contains(tileset.Id)) continue; && etf.ExcludeTilesets.Contains(tileset.Id)) continue;
if (etf != null && etf.RequireTilesets != null if (etf != null && etf.RequireTilesets != null
&& !etf.RequireTilesets.Contains(tileset.Id)) continue; && !etf.RequireTilesets.Contains(tileset.Id)) continue;
var template = RenderUtils.RenderActor(info, tileset, palette); var template = RenderUtils.RenderActor(info, tileset, palette);
var ibox = new PictureBox var ibox = new PictureBox

View File

@@ -427,10 +427,10 @@ namespace OpenRA.Editor
NonCombatant = section == "Neutral", NonCombatant = section == "Neutral",
Race = isRA ? (section == "BadGuy" ? "soviet" : "allies") : (section == "BadGuy" ? "nod" : "gdi"), Race = isRA ? (section == "BadGuy" ? "soviet" : "allies") : (section == "BadGuy" ? "nod" : "gdi"),
ColorRamp = new ColorRamp( ColorRamp = new ColorRamp(
(byte)((color.First.GetHue() / 360.0f) * 255), (byte)((color.First.GetHue() / 360.0f) * 255),
(byte)(color.First.GetSaturation() * 255), (byte)(color.First.GetSaturation() * 255),
(byte)(color.First.GetBrightness() * 255), (byte)(color.First.GetBrightness() * 255),
(byte)(color.Second.GetBrightness() * 255)) (byte)(color.Second.GetBrightness() * 255))
}; };
var Neutral = new [] {"Neutral"}; var Neutral = new [] {"Neutral"};

View File

@@ -10,33 +10,33 @@
namespace OpenRA.Editor namespace OpenRA.Editor
{ {
partial class MapSelect partial class MapSelect
{ {
/// <summary> /// <summary>
/// TODO /// TODO
/// </summary> /// </summary>
private System.ComponentModel.IContainer components = null; private System.ComponentModel.IContainer components = null;
/// <summary> /// <summary>
/// TODO /// TODO
/// </summary> /// </summary>
/// <param name="disposing">TODO</param> /// <param name="disposing">TODO</param>
protected override void Dispose(bool disposing) protected override void Dispose(bool disposing)
{ {
if (disposing && (components != null)) if (disposing && (components != null))
{ {
components.Dispose(); components.Dispose();
} }
base.Dispose(disposing); base.Dispose(disposing);
} }
#region Код, автоматически созданный конструктором форм Windows #region Код, автоматически созданный конструктором форм Windows
/// <summary> /// <summary>
/// TODO /// TODO
/// </summary> /// </summary>
private void InitializeComponent() private void InitializeComponent()
{ {
this.components = new System.ComponentModel.Container(); this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MapSelect)); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MapSelect));
this.MapList = new System.Windows.Forms.ListView(); this.MapList = new System.Windows.Forms.ListView();
@@ -75,7 +75,7 @@ namespace OpenRA.Editor
// //
this.MapList.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.MapList.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.MapList.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.MapList.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.colMapName}); this.colMapName});
this.MapList.FullRowSelect = true; this.MapList.FullRowSelect = true;
this.MapList.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.None; this.MapList.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.None;
this.MapList.LargeImageList = this.MapIconsList; this.MapList.LargeImageList = this.MapIconsList;
@@ -353,33 +353,33 @@ namespace OpenRA.Editor
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
this.ResumeLayout(false); this.ResumeLayout(false);
} }
#endregion #endregion
public System.Windows.Forms.ListView MapList; public System.Windows.Forms.ListView MapList;
public System.Windows.Forms.Button btnCancel; public System.Windows.Forms.Button btnCancel;
public System.Windows.Forms.Button btnOk; public System.Windows.Forms.Button btnOk;
public System.Windows.Forms.Label lblNew; public System.Windows.Forms.Label lblNew;
public System.Windows.Forms.TextBox txtNew; public System.Windows.Forms.TextBox txtNew;
public System.Windows.Forms.ColumnHeader colMapName; public System.Windows.Forms.ColumnHeader colMapName;
public System.Windows.Forms.ImageList MapIconsList; public System.Windows.Forms.ImageList MapIconsList;
public System.Windows.Forms.PictureBox pbMinimap; public System.Windows.Forms.PictureBox pbMinimap;
public System.Windows.Forms.Panel pnlBottom; public System.Windows.Forms.Panel pnlBottom;
public System.Windows.Forms.SplitContainer splitContainer1; public System.Windows.Forms.SplitContainer splitContainer1;
public System.Windows.Forms.Label lblMinimap; public System.Windows.Forms.Label lblMinimap;
public System.Windows.Forms.TextBox txtTheater; public System.Windows.Forms.TextBox txtTheater;
public System.Windows.Forms.Label lblTheater; public System.Windows.Forms.Label lblTheater;
public System.Windows.Forms.TextBox txtAuthor; public System.Windows.Forms.TextBox txtAuthor;
public System.Windows.Forms.Label lblAuthor; public System.Windows.Forms.Label lblAuthor;
public System.Windows.Forms.TextBox txtTitle; public System.Windows.Forms.TextBox txtTitle;
public System.Windows.Forms.Label lblMapName; public System.Windows.Forms.Label lblMapName;
public System.Windows.Forms.TextBox txtDesc; public System.Windows.Forms.TextBox txtDesc;
public System.Windows.Forms.Label lblDesc; public System.Windows.Forms.Label lblDesc;
public System.Windows.Forms.Label lblMapList; public System.Windows.Forms.Label lblMapList;
public System.Windows.Forms.Label lblPathOut; public System.Windows.Forms.Label lblPathOut;
public System.Windows.Forms.Label lblPath; public System.Windows.Forms.Label lblPath;
public System.Windows.Forms.TextBox txtPathOut; public System.Windows.Forms.TextBox txtPathOut;
private System.Windows.Forms.PictureBox pictureBox1; private System.Windows.Forms.PictureBox pictureBox1;
} }
} }

View File

@@ -17,68 +17,68 @@ using System.Linq;
namespace OpenRA.Editor namespace OpenRA.Editor
{ {
public partial class MapSelect : Form public partial class MapSelect : Form
{ {
public string MapFolderPath; public string MapFolderPath;
public MapSelect(string currentMod) public MapSelect(string currentMod)
{ {
MapFolderPath = new string[] { Environment.CurrentDirectory, "mods", currentMod, "maps" } MapFolderPath = new string[] { Environment.CurrentDirectory, "mods", currentMod, "maps" }
.Aggregate(Path.Combine); .Aggregate(Path.Combine);
InitializeComponent(); InitializeComponent();
MapIconsList.Images.Add(pictureBox1.Image); MapIconsList.Images.Add(pictureBox1.Image);
} }
void MapSelect_Load(object sender, EventArgs e) void MapSelect_Load(object sender, EventArgs e)
{ {
MapList.Items.Clear(); MapList.Items.Clear();
txtPathOut.Text = MapFolderPath; txtPathOut.Text = MapFolderPath;
foreach (var map in ModData.FindMapsIn(MapFolderPath)) foreach (var map in ModData.FindMapsIn(MapFolderPath))
{ {
ListViewItem map1 = new ListViewItem(); ListViewItem map1 = new ListViewItem();
map1.Tag = map; map1.Tag = map;
map1.Text = Path.GetFileNameWithoutExtension(map); map1.Text = Path.GetFileNameWithoutExtension(map);
map1.ImageIndex = 0; map1.ImageIndex = 0;
MapList.Items.Add(map1); MapList.Items.Add(map1);
} }
// hack // hack
if (txtNew.Text != "unnamed") if (txtNew.Text != "unnamed")
MapList.Items[0].Selected = true; MapList.Items[0].Selected = true;
} }
void MapList_SelectedIndexChanged(object sender, EventArgs e) void MapList_SelectedIndexChanged(object sender, EventArgs e)
{ {
if (MapList.SelectedItems.Count == 1) if (MapList.SelectedItems.Count == 1)
{ {
txtNew.Text = MapList.SelectedItems[0].Text; txtNew.Text = MapList.SelectedItems[0].Text;
txtNew.Tag = MapList.SelectedItems[0].Tag; txtNew.Tag = MapList.SelectedItems[0].Tag;
var map = new Map(txtNew.Tag as string); var map = new Map(txtNew.Tag as string);
txtTitle.Text = map.Title; txtTitle.Text = map.Title;
txtAuthor.Text = map.Author; txtAuthor.Text = map.Author;
txtTheater.Text = map.Tileset; txtTheater.Text = map.Tileset;
txtDesc.Text = map.Description; txtDesc.Text = map.Description;
pbMinimap.Image = null; pbMinimap.Image = null;
try try
{ {
pbMinimap.Image = Minimap.AddStaticResources(map, Minimap.TerrainBitmap(map, true)); pbMinimap.Image = Minimap.AddStaticResources(map, Minimap.TerrainBitmap(map, true));
} }
catch (Exception ed) catch (Exception ed)
{ {
Console.WriteLine("No map preview image found: {0}", ed.ToString()); Console.WriteLine("No map preview image found: {0}", ed.ToString());
} }
finally { } finally { }
} }
} }
void txtPathOut_TextChanged(object sender, EventArgs e) void txtPathOut_TextChanged(object sender, EventArgs e)
{ {
MapFolderPath = txtPathOut.Text; MapFolderPath = txtPathOut.Text;
} }
} }
} }

View File

@@ -110,118 +110,118 @@ namespace OpenRA.Editor
// //
this.cordonBottom.Location = new System.Drawing.Point(280, 75); this.cordonBottom.Location = new System.Drawing.Point(280, 75);
this.cordonBottom.Maximum = new decimal(new int[] { this.cordonBottom.Maximum = new decimal(new int[] {
2048, 2048,
0, 0,
0, 0,
0}); 0});
this.cordonBottom.Name = "cordonBottom"; this.cordonBottom.Name = "cordonBottom";
this.cordonBottom.Size = new System.Drawing.Size(105, 20); this.cordonBottom.Size = new System.Drawing.Size(105, 20);
this.cordonBottom.TabIndex = 5; this.cordonBottom.TabIndex = 5;
this.cordonBottom.Value = new decimal(new int[] { this.cordonBottom.Value = new decimal(new int[] {
112, 112,
0, 0,
0, 0,
0}); 0});
this.cordonBottom.Enter += new System.EventHandler(this.SelectText); this.cordonBottom.Enter += new System.EventHandler(this.SelectText);
// //
// cordonTop // cordonTop
// //
this.cordonTop.Location = new System.Drawing.Point(280, 49); this.cordonTop.Location = new System.Drawing.Point(280, 49);
this.cordonTop.Maximum = new decimal(new int[] { this.cordonTop.Maximum = new decimal(new int[] {
2048, 2048,
0, 0,
0, 0,
0}); 0});
this.cordonTop.Name = "cordonTop"; this.cordonTop.Name = "cordonTop";
this.cordonTop.Size = new System.Drawing.Size(105, 20); this.cordonTop.Size = new System.Drawing.Size(105, 20);
this.cordonTop.TabIndex = 3; this.cordonTop.TabIndex = 3;
this.cordonTop.Value = new decimal(new int[] { this.cordonTop.Value = new decimal(new int[] {
16, 16,
0, 0,
0, 0,
0}); 0});
this.cordonTop.Enter += new System.EventHandler(this.SelectText); this.cordonTop.Enter += new System.EventHandler(this.SelectText);
// //
// cordonRight // cordonRight
// //
this.cordonRight.Location = new System.Drawing.Point(169, 75); this.cordonRight.Location = new System.Drawing.Point(169, 75);
this.cordonRight.Maximum = new decimal(new int[] { this.cordonRight.Maximum = new decimal(new int[] {
2048, 2048,
0, 0,
0, 0,
0}); 0});
this.cordonRight.Name = "cordonRight"; this.cordonRight.Name = "cordonRight";
this.cordonRight.Size = new System.Drawing.Size(105, 20); this.cordonRight.Size = new System.Drawing.Size(105, 20);
this.cordonRight.TabIndex = 4; this.cordonRight.TabIndex = 4;
this.cordonRight.Value = new decimal(new int[] { this.cordonRight.Value = new decimal(new int[] {
112, 112,
0, 0,
0, 0,
0}); 0});
this.cordonRight.Enter += new System.EventHandler(this.SelectText); this.cordonRight.Enter += new System.EventHandler(this.SelectText);
// //
// cordonLeft // cordonLeft
// //
this.cordonLeft.Location = new System.Drawing.Point(169, 49); this.cordonLeft.Location = new System.Drawing.Point(169, 49);
this.cordonLeft.Maximum = new decimal(new int[] { this.cordonLeft.Maximum = new decimal(new int[] {
2048, 2048,
0, 0,
0, 0,
0}); 0});
this.cordonLeft.Name = "cordonLeft"; this.cordonLeft.Name = "cordonLeft";
this.cordonLeft.Size = new System.Drawing.Size(105, 20); this.cordonLeft.Size = new System.Drawing.Size(105, 20);
this.cordonLeft.TabIndex = 2; this.cordonLeft.TabIndex = 2;
this.cordonLeft.Value = new decimal(new int[] { this.cordonLeft.Value = new decimal(new int[] {
16, 16,
0, 0,
0, 0,
0}); 0});
this.cordonLeft.Enter += new System.EventHandler(this.SelectText); this.cordonLeft.Enter += new System.EventHandler(this.SelectText);
// //
// height // height
// //
this.height.Increment = new decimal(new int[] { this.height.Increment = new decimal(new int[] {
8, 8,
0, 0,
0, 0,
0}); 0});
this.height.Location = new System.Drawing.Point(280, 23); this.height.Location = new System.Drawing.Point(280, 23);
this.height.Maximum = new decimal(new int[] { this.height.Maximum = new decimal(new int[] {
2048, 2048,
0, 0,
0, 0,
0}); 0});
this.height.Name = "height"; this.height.Name = "height";
this.height.Size = new System.Drawing.Size(105, 20); this.height.Size = new System.Drawing.Size(105, 20);
this.height.TabIndex = 1; this.height.TabIndex = 1;
this.height.Value = new decimal(new int[] { this.height.Value = new decimal(new int[] {
128, 128,
0, 0,
0, 0,
0}); 0});
this.height.Enter += new System.EventHandler(this.SelectText); this.height.Enter += new System.EventHandler(this.SelectText);
// //
// width // width
// //
this.width.Increment = new decimal(new int[] { this.width.Increment = new decimal(new int[] {
8, 8,
0, 0,
0, 0,
0}); 0});
this.width.Location = new System.Drawing.Point(169, 23); this.width.Location = new System.Drawing.Point(169, 23);
this.width.Maximum = new decimal(new int[] { this.width.Maximum = new decimal(new int[] {
2048, 2048,
0, 0,
0, 0,
0}); 0});
this.width.Name = "width"; this.width.Name = "width";
this.width.Size = new System.Drawing.Size(105, 20); this.width.Size = new System.Drawing.Size(105, 20);
this.width.TabIndex = 0; this.width.TabIndex = 0;
this.width.Value = new decimal(new int[] { this.width.Value = new decimal(new int[] {
128, 128,
0, 0,
0, 0,
0}); 0});
this.width.Enter += new System.EventHandler(this.SelectText); this.width.Enter += new System.EventHandler(this.SelectText);
// //
// label4 // label4

View File

@@ -44,15 +44,15 @@ namespace OpenRA.Editor
.Aggregate(Path.Combine); .Aggregate(Path.Combine);
foreach (var path in ModData.FindMapsIn(MapFolderPath)) foreach (var path in ModData.FindMapsIn(MapFolderPath))
{ {
var map = new Map(path); var map = new Map(path);
// Touch the lazy bits to initialize them // Touch the lazy bits to initialize them
map.Actors.Force(); map.Actors.Force();
map.Smudges.Force(); map.Smudges.Force();
map.MapTiles.Force(); map.MapTiles.Force();
map.MapResources.Force(); map.MapResources.Force();
map.Save(path); map.Save(path);
} }
} }
} }

View File

@@ -38,131 +38,131 @@ namespace OpenRA.Editor
/// </summary> /// </summary>
private void InitializeComponent() private void InitializeComponent()
{ {
this.button2 = new System.Windows.Forms.Button(); this.button2 = new System.Windows.Forms.Button();
this.button1 = new System.Windows.Forms.Button(); this.button1 = new System.Windows.Forms.Button();
this.label1 = new System.Windows.Forms.Label(); this.label1 = new System.Windows.Forms.Label();
this.title = new System.Windows.Forms.TextBox(); this.title = new System.Windows.Forms.TextBox();
this.label2 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label();
this.desc = new System.Windows.Forms.TextBox(); this.desc = new System.Windows.Forms.TextBox();
this.selectable = new System.Windows.Forms.CheckBox(); this.selectable = new System.Windows.Forms.CheckBox();
this.label3 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label();
this.author = new System.Windows.Forms.TextBox(); this.author = new System.Windows.Forms.TextBox();
this.useAsShellmap = new System.Windows.Forms.CheckBox(); this.useAsShellmap = new System.Windows.Forms.CheckBox();
this.SuspendLayout(); this.SuspendLayout();
// //
// button2 // button2
// //
this.button2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.button2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.button2.DialogResult = System.Windows.Forms.DialogResult.OK; this.button2.DialogResult = System.Windows.Forms.DialogResult.OK;
this.button2.Location = new System.Drawing.Point(196, 193); this.button2.Location = new System.Drawing.Point(196, 193);
this.button2.Name = "button2"; this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(75, 23); this.button2.Size = new System.Drawing.Size(75, 23);
this.button2.TabIndex = 14; this.button2.TabIndex = 14;
this.button2.Text = "OK"; this.button2.Text = "OK";
this.button2.UseVisualStyleBackColor = true; this.button2.UseVisualStyleBackColor = true;
// //
// button1 // button1
// //
this.button1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.button1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.button1.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.button1.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.button1.Location = new System.Drawing.Point(277, 193); this.button1.Location = new System.Drawing.Point(277, 193);
this.button1.Name = "button1"; this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23); this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 15; this.button1.TabIndex = 15;
this.button1.Text = "Cancel"; this.button1.Text = "Cancel";
this.button1.UseVisualStyleBackColor = true; this.button1.UseVisualStyleBackColor = true;
// //
// label1 // label1
// //
this.label1.AutoSize = true; this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(12, 50); this.label1.Location = new System.Drawing.Point(12, 50);
this.label1.Name = "label1"; this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(27, 13); this.label1.Size = new System.Drawing.Size(27, 13);
this.label1.TabIndex = 16; this.label1.TabIndex = 16;
this.label1.Text = "Title"; this.label1.Text = "Title";
// //
// title // title
// //
this.title.Location = new System.Drawing.Point(66, 47); this.title.Location = new System.Drawing.Point(66, 47);
this.title.Name = "title"; this.title.Name = "title";
this.title.Size = new System.Drawing.Size(286, 20); this.title.Size = new System.Drawing.Size(286, 20);
this.title.TabIndex = 17; this.title.TabIndex = 17;
// //
// label2 // label2
// //
this.label2.AutoSize = true; this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(12, 76); this.label2.Location = new System.Drawing.Point(12, 76);
this.label2.Name = "label2"; this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(32, 13); this.label2.Size = new System.Drawing.Size(32, 13);
this.label2.TabIndex = 16; this.label2.TabIndex = 16;
this.label2.Text = "Desc"; this.label2.Text = "Desc";
// //
// desc // desc
// //
this.desc.Location = new System.Drawing.Point(66, 73); this.desc.Location = new System.Drawing.Point(66, 73);
this.desc.Name = "desc"; this.desc.Name = "desc";
this.desc.Size = new System.Drawing.Size(286, 20); this.desc.Size = new System.Drawing.Size(286, 20);
this.desc.TabIndex = 17; this.desc.TabIndex = 17;
// //
// selectable // selectable
// //
this.selectable.AutoSize = true; this.selectable.AutoSize = true;
this.selectable.Location = new System.Drawing.Point(118, 138); this.selectable.Location = new System.Drawing.Point(118, 138);
this.selectable.Name = "selectable"; this.selectable.Name = "selectable";
this.selectable.Size = new System.Drawing.Size(130, 17); this.selectable.Size = new System.Drawing.Size(130, 17);
this.selectable.TabIndex = 18; this.selectable.TabIndex = 18;
this.selectable.Text = "Show in Map Chooser"; this.selectable.Text = "Show in Map Chooser";
this.selectable.UseVisualStyleBackColor = true; this.selectable.UseVisualStyleBackColor = true;
// //
// label3 // label3
// //
this.label3.AutoSize = true; this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(12, 102); this.label3.Location = new System.Drawing.Point(12, 102);
this.label3.Name = "label3"; this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(38, 13); this.label3.Size = new System.Drawing.Size(38, 13);
this.label3.TabIndex = 16; this.label3.TabIndex = 16;
this.label3.Text = "Author"; this.label3.Text = "Author";
// //
// author // author
// //
this.author.Location = new System.Drawing.Point(66, 99); this.author.Location = new System.Drawing.Point(66, 99);
this.author.Name = "author"; this.author.Name = "author";
this.author.Size = new System.Drawing.Size(286, 20); this.author.Size = new System.Drawing.Size(286, 20);
this.author.TabIndex = 17; this.author.TabIndex = 17;
// //
// checkBox1 // checkBox1
// //
this.useAsShellmap.AutoSize = true; this.useAsShellmap.AutoSize = true;
this.useAsShellmap.Location = new System.Drawing.Point(118, 161); this.useAsShellmap.Location = new System.Drawing.Point(118, 161);
this.useAsShellmap.Name = "checkBox1"; this.useAsShellmap.Name = "checkBox1";
this.useAsShellmap.Size = new System.Drawing.Size(105, 17); this.useAsShellmap.Size = new System.Drawing.Size(105, 17);
this.useAsShellmap.TabIndex = 18; this.useAsShellmap.TabIndex = 18;
this.useAsShellmap.Text = "Use as Shellmap"; this.useAsShellmap.Text = "Use as Shellmap";
this.useAsShellmap.UseVisualStyleBackColor = true; this.useAsShellmap.UseVisualStyleBackColor = true;
// //
// PropertiesDialog // PropertiesDialog
// //
this.AcceptButton = this.button2; this.AcceptButton = this.button2;
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.CancelButton = this.button1; this.CancelButton = this.button1;
this.ClientSize = new System.Drawing.Size(370, 228); this.ClientSize = new System.Drawing.Size(370, 228);
this.Controls.Add(this.useAsShellmap); this.Controls.Add(this.useAsShellmap);
this.Controls.Add(this.selectable); this.Controls.Add(this.selectable);
this.Controls.Add(this.author); this.Controls.Add(this.author);
this.Controls.Add(this.label3); this.Controls.Add(this.label3);
this.Controls.Add(this.desc); this.Controls.Add(this.desc);
this.Controls.Add(this.label2); this.Controls.Add(this.label2);
this.Controls.Add(this.title); this.Controls.Add(this.title);
this.Controls.Add(this.label1); this.Controls.Add(this.label1);
this.Controls.Add(this.button2); this.Controls.Add(this.button2);
this.Controls.Add(this.button1); this.Controls.Add(this.button1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Name = "PropertiesDialog"; this.Name = "PropertiesDialog";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "PropertiesDialog"; this.Text = "PropertiesDialog";
this.ResumeLayout(false); this.ResumeLayout(false);
this.PerformLayout(); this.PerformLayout();
} }
@@ -177,6 +177,6 @@ namespace OpenRA.Editor
public System.Windows.Forms.CheckBox selectable; public System.Windows.Forms.CheckBox selectable;
private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label3;
public System.Windows.Forms.TextBox author; public System.Windows.Forms.TextBox author;
public System.Windows.Forms.CheckBox useAsShellmap; public System.Windows.Forms.CheckBox useAsShellmap;
} }
} }

View File

@@ -45,9 +45,9 @@ namespace OpenRA.Editor
public static ActorTemplate RenderActor(ActorInfo info, TileSet tileset, Palette p) public static ActorTemplate RenderActor(ActorInfo info, TileSet tileset, Palette p)
{ {
var image = RenderSimple.GetImage(info); var image = RenderSimple.GetImage(info);
using (var s = FileSystem.OpenWithExts(image, tileset.Extensions)) using (var s = FileSystem.OpenWithExts(image, tileset.Extensions))
{ {
var shp = new ShpReader(s); var shp = new ShpReader(s);
var bitmap = RenderShp(shp, p); var bitmap = RenderShp(shp, p);

View File

@@ -60,16 +60,16 @@ namespace OpenRA.Editor
// width // width
// //
this.width.Increment = new decimal(new int[] { this.width.Increment = new decimal(new int[] {
8, 8,
0, 0,
0, 0,
0}); 0});
this.width.Location = new System.Drawing.Point(161, 18); this.width.Location = new System.Drawing.Point(161, 18);
this.width.Maximum = new decimal(new int[] { this.width.Maximum = new decimal(new int[] {
2048, 2048,
0, 0,
0, 0,
0}); 0});
this.width.Name = "width"; this.width.Name = "width";
this.width.Size = new System.Drawing.Size(105, 20); this.width.Size = new System.Drawing.Size(105, 20);
this.width.TabIndex = 0; this.width.TabIndex = 0;
@@ -96,10 +96,10 @@ namespace OpenRA.Editor
// //
this.cordonLeft.Location = new System.Drawing.Point(161, 44); this.cordonLeft.Location = new System.Drawing.Point(161, 44);
this.cordonLeft.Maximum = new decimal(new int[] { this.cordonLeft.Maximum = new decimal(new int[] {
2048, 2048,
0, 0,
0, 0,
0}); 0});
this.cordonLeft.Name = "cordonLeft"; this.cordonLeft.Name = "cordonLeft";
this.cordonLeft.Size = new System.Drawing.Size(105, 20); this.cordonLeft.Size = new System.Drawing.Size(105, 20);
this.cordonLeft.TabIndex = 0; this.cordonLeft.TabIndex = 0;
@@ -108,10 +108,10 @@ namespace OpenRA.Editor
// //
this.cordonTop.Location = new System.Drawing.Point(272, 44); this.cordonTop.Location = new System.Drawing.Point(272, 44);
this.cordonTop.Maximum = new decimal(new int[] { this.cordonTop.Maximum = new decimal(new int[] {
2048, 2048,
0, 0,
0, 0,
0}); 0});
this.cordonTop.Name = "cordonTop"; this.cordonTop.Name = "cordonTop";
this.cordonTop.Size = new System.Drawing.Size(105, 20); this.cordonTop.Size = new System.Drawing.Size(105, 20);
this.cordonTop.TabIndex = 0; this.cordonTop.TabIndex = 0;
@@ -120,10 +120,10 @@ namespace OpenRA.Editor
// //
this.cordonRight.Location = new System.Drawing.Point(161, 70); this.cordonRight.Location = new System.Drawing.Point(161, 70);
this.cordonRight.Maximum = new decimal(new int[] { this.cordonRight.Maximum = new decimal(new int[] {
2048, 2048,
0, 0,
0, 0,
0}); 0});
this.cordonRight.Name = "cordonRight"; this.cordonRight.Name = "cordonRight";
this.cordonRight.Size = new System.Drawing.Size(105, 20); this.cordonRight.Size = new System.Drawing.Size(105, 20);
this.cordonRight.TabIndex = 0; this.cordonRight.TabIndex = 0;
@@ -132,10 +132,10 @@ namespace OpenRA.Editor
// //
this.cordonBottom.Location = new System.Drawing.Point(272, 70); this.cordonBottom.Location = new System.Drawing.Point(272, 70);
this.cordonBottom.Maximum = new decimal(new int[] { this.cordonBottom.Maximum = new decimal(new int[] {
2048, 2048,
0, 0,
0, 0,
0}); 0});
this.cordonBottom.Name = "cordonBottom"; this.cordonBottom.Name = "cordonBottom";
this.cordonBottom.Size = new System.Drawing.Size(105, 20); this.cordonBottom.Size = new System.Drawing.Size(105, 20);
this.cordonBottom.TabIndex = 0; this.cordonBottom.TabIndex = 0;
@@ -172,16 +172,16 @@ namespace OpenRA.Editor
// height // height
// //
this.height.Increment = new decimal(new int[] { this.height.Increment = new decimal(new int[] {
8, 8,
0, 0,
0, 0,
0}); 0});
this.height.Location = new System.Drawing.Point(272, 18); this.height.Location = new System.Drawing.Point(272, 18);
this.height.Maximum = new decimal(new int[] { this.height.Maximum = new decimal(new int[] {
2048, 2048,
0, 0,
0, 0,
0}); 0});
this.height.Name = "height"; this.height.Name = "height";
this.height.Size = new System.Drawing.Size(105, 20); this.height.Size = new System.Drawing.Size(105, 20);
this.height.TabIndex = 0; this.height.TabIndex = 0;

View File

@@ -12,27 +12,27 @@ using System.Drawing;
namespace OpenRA.FileFormats namespace OpenRA.FileFormats
{ {
public struct ColorRamp public struct ColorRamp
{ {
public byte H,S,L,R; public byte H,S,L,R;
public ColorRamp(byte h, byte s, byte l, byte r) public ColorRamp(byte h, byte s, byte l, byte r)
{ {
H = h; S = s; L = l; R = r; H = h; S = s; L = l; R = r;
} }
/* returns a color along the Lum ramp */ /* returns a color along the Lum ramp */
public Color GetColor( float t ) public Color GetColor( float t )
{ {
return ColorFromHSL( H / 255f, S / 255f, float2.Lerp( L / 255f, L*R / (255f * 255f), t ) ); return ColorFromHSL( H / 255f, S / 255f, float2.Lerp( L / 255f, L*R / (255f * 255f), t ) );
} }
public override string ToString() public override string ToString()
{ {
return "{0},{1},{2},{3}".F(H, S, L, R); return "{0},{1},{2},{3}".F(H, S, L, R);
} }
// hk is hue in the range [0,1] instead of [0,360] // hk is hue in the range [0,1] instead of [0,360]
public static Color ColorFromHSL(float hk, float s, float l) public static Color ColorFromHSL(float hk, float s, float l)
{ {
// Convert from HSL to RGB // Convert from HSL to RGB
@@ -60,5 +60,5 @@ namespace OpenRA.FileFormats
return Color.FromArgb((int)(rgb[0] * 255), (int)(rgb[1] * 255), (int)(rgb[2] * 255)); return Color.FromArgb((int)(rgb[0] * 255), (int)(rgb[1] * 255), (int)(rgb[2] * 255));
} }
} }
} }

View File

@@ -113,10 +113,10 @@ namespace OpenRA
return r.Contains(p.ToPointF()); return r.Contains(p.ToPointF());
} }
public static bool HasModifier(this Modifiers k, Modifiers mod) public static bool HasModifier(this Modifiers k, Modifiers mod)
{ {
return (k & mod) == mod; return (k & mod) == mod;
} }
public static bool IsValidInput(this KeyInput key) public static bool IsValidInput(this KeyInput key)
{ {
@@ -125,36 +125,36 @@ namespace OpenRA
char.IsPunctuation(key.UnicodeChar); char.IsPunctuation(key.UnicodeChar);
} }
public static V GetOrAdd<K, V>(this Dictionary<K, V> d, K k) public static V GetOrAdd<K, V>(this Dictionary<K, V> d, K k)
where V : new() where V : new()
{ {
return d.GetOrAdd(k, _ => new V()); return d.GetOrAdd(k, _ => new V());
} }
public static V GetOrAdd<K, V>(this Dictionary<K, V> d, K k, Func<K, V> createFn) public static V GetOrAdd<K, V>(this Dictionary<K, V> d, K k, Func<K, V> createFn)
{ {
V ret; V ret;
if (!d.TryGetValue(k, out ret)) if (!d.TryGetValue(k, out ret))
d.Add(k, ret = createFn(k)); d.Add(k, ret = createFn(k));
return ret; return ret;
} }
public static T Random<T>(this IEnumerable<T> ts, Thirdparty.Random r) public static T Random<T>(this IEnumerable<T> ts, Thirdparty.Random r)
{ {
var xs = ts.ToArray(); var xs = ts.ToArray();
return xs[r.Next(xs.Length)]; return xs[r.Next(xs.Length)];
} }
public static float Product(this IEnumerable<float> xs) public static float Product(this IEnumerable<float> xs)
{ {
return xs.Aggregate(1f, (a, x) => a * x); return xs.Aggregate(1f, (a, x) => a * x);
} }
public static IEnumerable<T> SymmetricDifference<T>(this IEnumerable<T> xs, IEnumerable<T> ys) public static IEnumerable<T> SymmetricDifference<T>(this IEnumerable<T> xs, IEnumerable<T> ys)
{ {
// this is probably a shockingly-slow way to do this, but it's concise. // this is probably a shockingly-slow way to do this, but it's concise.
return xs.Except(ys).Concat(ys.Except(xs)); return xs.Except(ys).Concat(ys.Except(xs));
} }
public static IEnumerable<T> Iterate<T>( this T t, Func<T,T> f ) public static IEnumerable<T> Iterate<T>( this T t, Func<T,T> f )
{ {

View File

@@ -143,63 +143,63 @@ namespace OpenRA.FileFormats
return InvalidValueAction(x,fieldType, field); return InvalidValueAction(x,fieldType, field);
} }
else if (fieldType == typeof(ColorRamp)) else if (fieldType == typeof(ColorRamp))
{ {
var parts = x.Split(','); var parts = x.Split(',');
if (parts.Length == 4) if (parts.Length == 4)
return new ColorRamp( return new ColorRamp(
(byte)int.Parse(parts[0]).Clamp(0, 255), (byte)int.Parse(parts[0]).Clamp(0, 255),
(byte)int.Parse(parts[1]).Clamp(0, 255), (byte)int.Parse(parts[1]).Clamp(0, 255),
(byte)int.Parse(parts[2]).Clamp(0, 255), (byte)int.Parse(parts[2]).Clamp(0, 255),
(byte)int.Parse(parts[3]).Clamp(0, 255)); (byte)int.Parse(parts[3]).Clamp(0, 255));
return InvalidValueAction(x, fieldType, field); return InvalidValueAction(x, fieldType, field);
} }
else if (fieldType.IsEnum) else if (fieldType.IsEnum)
{ {
if (!Enum.GetNames(fieldType).Select(a => a.ToLower()).Contains(x.ToLower())) if (!Enum.GetNames(fieldType).Select(a => a.ToLower()).Contains(x.ToLower()))
return InvalidValueAction(x, fieldType, field); return InvalidValueAction(x, fieldType, field);
return Enum.Parse(fieldType, x, true); return Enum.Parse(fieldType, x, true);
} }
else if (fieldType == typeof(bool)) else if (fieldType == typeof(bool))
return ParseYesNo(x, fieldType, field); return ParseYesNo(x, fieldType, field);
else if (fieldType.IsArray) else if (fieldType.IsArray)
{ {
if (x == null) if (x == null)
return Array.CreateInstance(fieldType.GetElementType(), 0); return Array.CreateInstance(fieldType.GetElementType(), 0);
var parts = x.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); var parts = x.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
var ret = Array.CreateInstance(fieldType.GetElementType(), parts.Length); var ret = Array.CreateInstance(fieldType.GetElementType(), parts.Length);
for (int i = 0; i < parts.Length; i++) for (int i = 0; i < parts.Length; i++)
ret.SetValue(GetValue(field, fieldType.GetElementType(), parts[i].Trim()), i); ret.SetValue(GetValue(field, fieldType.GetElementType(), parts[i].Trim()), i);
return ret; return ret;
} }
else if (fieldType == typeof(int2)) else if (fieldType == typeof(int2))
{ {
var parts = x.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); var parts = x.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
return new int2(int.Parse(parts[0]), int.Parse(parts[1])); return new int2(int.Parse(parts[0]), int.Parse(parts[1]));
} }
else if (fieldType == typeof(float2)) else if (fieldType == typeof(float2))
{ {
var parts = x.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); var parts = x.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
float xx = 0; float xx = 0;
float yy = 0; float yy = 0;
float res; float res;
if (float.TryParse(parts[0].Replace("%", ""), out res)) if (float.TryParse(parts[0].Replace("%", ""), out res))
xx = res * (parts[0].Contains('%') ? 0.01f : 1f); xx = res * (parts[0].Contains('%') ? 0.01f : 1f);
if (float.TryParse(parts[1].Replace("%", ""), out res)) if (float.TryParse(parts[1].Replace("%", ""), out res))
yy = res * (parts[1].Contains('%') ? 0.01f : 1f); yy = res * (parts[1].Contains('%') ? 0.01f : 1f);
return new float2(xx, yy); return new float2(xx, yy);
} }
else if (fieldType == typeof(Rectangle)) else if (fieldType == typeof(Rectangle))
{ {
var parts = x.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); var parts = x.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
return new Rectangle(int.Parse(parts[0]), int.Parse(parts[1]), int.Parse(parts[2]), int.Parse(parts[3])); return new Rectangle(int.Parse(parts[0]), int.Parse(parts[1]), int.Parse(parts[2]), int.Parse(parts[3]));
} }
else if (fieldType.IsGenericType && fieldType.GetGenericTypeDefinition() == typeof(Bits<>)) else if (fieldType.IsGenericType && fieldType.GetGenericTypeDefinition() == typeof(Bits<>))
{ {
var parts = x.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); var parts = x.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

View File

@@ -182,13 +182,13 @@ namespace OpenRA.FileFormats
class BitReader class BitReader
{ {
readonly byte[] src; readonly byte[] src;
int offset = 0; int offset = 0;
int bitBuffer = 0; int bitBuffer = 0;
int bitCount = 0; int bitCount = 0;
public BitReader(byte[] src) public BitReader(byte[] src)
{ {
this.src = src; this.src = src;
} }
public int ReadBits(int count) public int ReadBits(int count)

View File

@@ -13,516 +13,516 @@ using System.Linq;
namespace OpenRA.FileFormats namespace OpenRA.FileFormats
{ {
/* possibly the fugliest C# i've ever seen. */ /* possibly the fugliest C# i've ever seen. */
class BlowfishKeyProvider class BlowfishKeyProvider
{ {
const string pubkeyStr = "AihRvNoIbTn85FZRYNZRcT+i6KpU+maCsEqr3Q5q+LDB5tH7Tz2qQ38V"; const string pubkeyStr = "AihRvNoIbTn85FZRYNZRcT+i6KpU+maCsEqr3Q5q+LDB5tH7Tz2qQ38V";
static sbyte[] char2num = { static sbyte[] char2num = {
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63,
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1,
-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1,
-1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1};
class PublicKey class PublicKey
{ {
public uint[] key1 = new uint[64]; public uint[] key1 = new uint[64];
public uint[] key2 = new uint[64]; public uint[] key2 = new uint[64];
public uint len; public uint len;
} }
PublicKey pubkey = new PublicKey(); PublicKey pubkey = new PublicKey();
uint[] glob1 = new uint[64]; uint[] glob1 = new uint[64];
uint glob1_bitlen, glob1_len_x2; uint glob1_bitlen, glob1_len_x2;
uint[] glob2 = new uint[130]; uint[] glob2 = new uint[130];
uint[] glob1_hi = new uint[4]; uint[] glob1_hi = new uint[4];
uint[] glob1_hi_inv = new uint[4]; uint[] glob1_hi_inv = new uint[4];
uint glob1_hi_bitlen; uint glob1_hi_bitlen;
uint glob1_hi_inv_lo, glob1_hi_inv_hi; uint glob1_hi_inv_lo, glob1_hi_inv_hi;
void init_bignum(uint[] n, uint val, uint len) void init_bignum(uint[] n, uint val, uint len)
{ {
for (int i = 0; i < len; i++) n[i] = 0; for (int i = 0; i < len; i++) n[i] = 0;
n[0] = val; n[0] = val;
} }
void move_key_to_big(uint[] n, byte[] key, uint klen, uint blen) void move_key_to_big(uint[] n, byte[] key, uint klen, uint blen)
{ {
byte sign; byte sign;
if ((key[0] & 0x80) != 0) sign = 0xff; if ((key[0] & 0x80) != 0) sign = 0xff;
else sign = 0; else sign = 0;
unsafe unsafe
{ {
fixed (uint* _pn = &n[0]) fixed (uint* _pn = &n[0])
{ {
byte* pn = (byte*)_pn; byte* pn = (byte*)_pn;
uint i = blen * 4; uint i = blen * 4;
for (; i > klen; i--) pn[i - 1] = (byte)sign; for (; i > klen; i--) pn[i - 1] = (byte)sign;
for (; i > 0; i--) pn[i - 1] = key[klen - i]; for (; i > 0; i--) pn[i - 1] = key[klen - i];
} }
} }
} }
void key_to_bignum(uint[] n, byte[] key, uint len) void key_to_bignum(uint[] n, byte[] key, uint len)
{ {
uint keylen; uint keylen;
int i; int i;
int j = 0; int j = 0;
if (key[j] != 2) return; if (key[j] != 2) return;
j++; j++;
if ((key[j] & 0x80) != 0) if ((key[j] & 0x80) != 0)
{ {
keylen = 0; keylen = 0;
for (i = 0; i < (key[j] & 0x7f); i++) keylen = (keylen << 8) | key[j + i + 1]; for (i = 0; i < (key[j] & 0x7f); i++) keylen = (keylen << 8) | key[j + i + 1];
j += (key[j] & 0x7f) + 1; j += (key[j] & 0x7f) + 1;
} }
else else
{ {
keylen = key[j]; keylen = key[j];
j++; j++;
} }
if (keylen <= len * 4) if (keylen <= len * 4)
move_key_to_big(n, key.Skip(j).ToArray(), keylen, len); move_key_to_big(n, key.Skip(j).ToArray(), keylen, len);
} }
uint len_bignum(uint[] n, uint len) uint len_bignum(uint[] n, uint len)
{ {
uint i; uint i;
i = len - 1; i = len - 1;
while ((i >= 0) && (n[i] == 0)) i--; while ((i >= 0) && (n[i] == 0)) i--;
return i + 1; return i + 1;
} }
uint bitlen_bignum(uint[] n, uint len) uint bitlen_bignum(uint[] n, uint len)
{ {
uint ddlen, bitlen, mask; uint ddlen, bitlen, mask;
ddlen = len_bignum(n, len); ddlen = len_bignum(n, len);
if (ddlen == 0) return 0; if (ddlen == 0) return 0;
bitlen = ddlen * 32; bitlen = ddlen * 32;
mask = 0x80000000; mask = 0x80000000;
while ((mask & n[ddlen - 1]) == 0) while ((mask & n[ddlen - 1]) == 0)
{ {
mask >>= 1; mask >>= 1;
bitlen--; bitlen--;
} }
return bitlen; return bitlen;
} }
void init_pubkey() void init_pubkey()
{ {
int i = 0; int i = 0;
uint i2, tmp; uint i2, tmp;
byte[] keytmp = new byte[256]; byte[] keytmp = new byte[256];
init_bignum(pubkey.key2, 0x10001, 64); init_bignum(pubkey.key2, 0x10001, 64);
i2 = 0; i2 = 0;
while (i < pubkeyStr.Length) while (i < pubkeyStr.Length)
{ {
tmp = (uint)char2num[pubkeyStr[i++]]; tmp = (uint)char2num[pubkeyStr[i++]];
tmp <<= 6; tmp |= (uint)(byte)char2num[pubkeyStr[i++]]; tmp <<= 6; tmp |= (uint)(byte)char2num[pubkeyStr[i++]];
tmp <<= 6; tmp |= (uint)(byte)char2num[pubkeyStr[i++]]; tmp <<= 6; tmp |= (uint)(byte)char2num[pubkeyStr[i++]];
tmp <<= 6; tmp |= (uint)(byte)char2num[pubkeyStr[i++]]; tmp <<= 6; tmp |= (uint)(byte)char2num[pubkeyStr[i++]];
keytmp[i2++] = (byte)((tmp >> 16) & 0xff); keytmp[i2++] = (byte)((tmp >> 16) & 0xff);
keytmp[i2++] = (byte)((tmp >> 8) & 0xff); keytmp[i2++] = (byte)((tmp >> 8) & 0xff);
keytmp[i2++] = (byte)(tmp & 0xff); keytmp[i2++] = (byte)(tmp & 0xff);
} }
key_to_bignum(pubkey.key1, keytmp, 64); key_to_bignum(pubkey.key1, keytmp, 64);
pubkey.len = bitlen_bignum(pubkey.key1, 64) - 1; pubkey.len = bitlen_bignum(pubkey.key1, 64) - 1;
} }
uint len_predata() uint len_predata()
{ {
uint a = (pubkey.len - 1) / 8; uint a = (pubkey.len - 1) / 8;
return (55 / a + 1) * (a + 1); return (55 / a + 1) * (a + 1);
} }
int cmp_bignum(uint[] n1, uint[] n2, uint len) int cmp_bignum(uint[] n1, uint[] n2, uint len)
{ {
while (len > 0) while (len > 0)
{ {
--len; --len;
if (n1[len] < n2[len]) return -1; if (n1[len] < n2[len]) return -1;
if (n1[len] > n2[len]) return 1; if (n1[len] > n2[len]) return 1;
} }
return 0; return 0;
} }
void mov_bignum(uint[] dest, uint[] src, uint len) void mov_bignum(uint[] dest, uint[] src, uint len)
{ {
Array.Copy(src, dest, len); Array.Copy(src, dest, len);
} }
void shr_bignum(uint[] n, int bits, int len) void shr_bignum(uint[] n, int bits, int len)
{ {
int i; int i2 = bits / 32; int i; int i2 = bits / 32;
if (i2 > 0) if (i2 > 0)
{ {
for (i = 0; i < len - i2; i++) n[i] = n[i + i2]; for (i = 0; i < len - i2; i++) n[i] = n[i + i2];
for (; i < len; i++) n[i] = 0; for (; i < len; i++) n[i] = 0;
bits = bits % 32; bits = bits % 32;
} }
if (bits == 0) return; if (bits == 0) return;
for (i = 0; i < len - 1; i++) n[i] = (n[i] >> bits) | (n[i + 1] << (32 - for (i = 0; i < len - 1; i++) n[i] = (n[i] >> bits) | (n[i + 1] << (32 -
bits)); bits));
n[i] = n[i] >> bits; n[i] = n[i] >> bits;
} }
void shl_bignum(uint[] n, int bits, int len) void shl_bignum(uint[] n, int bits, int len)
{ {
int i, i2; int i, i2;
i2 = bits / 32; i2 = bits / 32;
if (i2 > 0) if (i2 > 0)
{ {
for (i = len - 1; i > i2; i--) n[i] = n[i - i2]; for (i = len - 1; i > i2; i--) n[i] = n[i - i2];
for (; i > 0; i--) n[i] = 0; for (; i > 0; i--) n[i] = 0;
bits = bits % 32; bits = bits % 32;
} }
if (bits == 0) return; if (bits == 0) return;
for (i = len - 1; i > 0; i--) n[i] = (n[i] << bits) | (n[i - 1] >> (32 - for (i = len - 1; i > 0; i--) n[i] = (n[i] << bits) | (n[i - 1] >> (32 -
bits)); bits));
n[0] <<= bits; n[0] <<= bits;
} }
uint sub_bignum(uint[] dest, uint[] src1, uint[] src2, uint carry, int len) uint sub_bignum(uint[] dest, uint[] src1, uint[] src2, uint carry, int len)
{ {
uint i1, i2; uint i1, i2;
len += len; len += len;
unsafe unsafe
{ {
fixed (uint* _ps1 = &src1[0]) fixed (uint* _ps1 = &src1[0])
fixed (uint* _ps2 = &src2[0]) fixed (uint* _ps2 = &src2[0])
fixed (uint* _pd = &dest[0]) fixed (uint* _pd = &dest[0])
{ {
ushort* ps1 = (ushort*)_ps1; ushort* ps1 = (ushort*)_ps1;
ushort* ps2 = (ushort*)_ps2; ushort* ps2 = (ushort*)_ps2;
ushort* pd = (ushort*)_pd; ushort* pd = (ushort*)_pd;
while (--len != -1) while (--len != -1)
{ {
i1 = *ps1++; i1 = *ps1++;
i2 = *ps2++; i2 = *ps2++;
*pd++ = (ushort)(i1 - i2 - carry); *pd++ = (ushort)(i1 - i2 - carry);
if (((i1 - i2 - carry) & 0x10000) != 0) carry = 1; else carry = 0; if (((i1 - i2 - carry) & 0x10000) != 0) carry = 1; else carry = 0;
} }
} }
} }
return carry; return carry;
} }
unsafe uint sub_bignum(uint* dest, uint* src1, uint* src2, uint carry, int len) unsafe uint sub_bignum(uint* dest, uint* src1, uint* src2, uint carry, int len)
{ {
uint i1, i2; uint i1, i2;
len += len; len += len;
ushort* ps1 = (ushort*)src1; ushort* ps1 = (ushort*)src1;
ushort* ps2 = (ushort*)src2; ushort* ps2 = (ushort*)src2;
ushort* pd = (ushort*)dest; ushort* pd = (ushort*)dest;
while (--len != -1) while (--len != -1)
{ {
i1 = *ps1++; i1 = *ps1++;
i2 = *ps2++; i2 = *ps2++;
*pd++ = (ushort)(i1 - i2 - carry); *pd++ = (ushort)(i1 - i2 - carry);
if (((i1 - i2 - carry) & 0x10000) != 0) carry = 1; else carry = 0; if (((i1 - i2 - carry) & 0x10000) != 0) carry = 1; else carry = 0;
} }
return carry; return carry;
} }
void inv_bignum(uint[] n1, uint[] n2, uint len) void inv_bignum(uint[] n1, uint[] n2, uint len)
{ {
uint[] n_tmp = new uint[64]; uint[] n_tmp = new uint[64];
uint n2_bytelen, bit; uint n2_bytelen, bit;
int n2_bitlen; int n2_bitlen;
int j = 0; int j = 0;
init_bignum(n_tmp, 0, len); init_bignum(n_tmp, 0, len);
init_bignum(n1, 0, len); init_bignum(n1, 0, len);
n2_bitlen = (int)bitlen_bignum(n2, len); n2_bitlen = (int)bitlen_bignum(n2, len);
bit = ((uint)1) << (n2_bitlen % 32); bit = ((uint)1) << (n2_bitlen % 32);
j = ((n2_bitlen + 32) / 32) - 1; j = ((n2_bitlen + 32) / 32) - 1;
n2_bytelen = (uint)((n2_bitlen - 1) / 32) * 4; n2_bytelen = (uint)((n2_bitlen - 1) / 32) * 4;
n_tmp[n2_bytelen / 4] |= ((uint)1) << ((n2_bitlen - 1) & 0x1f); n_tmp[n2_bytelen / 4] |= ((uint)1) << ((n2_bitlen - 1) & 0x1f);
while (n2_bitlen > 0) while (n2_bitlen > 0)
{ {
n2_bitlen--; n2_bitlen--;
shl_bignum(n_tmp, 1, (int)len); shl_bignum(n_tmp, 1, (int)len);
if (cmp_bignum(n_tmp, n2, len) != -1) if (cmp_bignum(n_tmp, n2, len) != -1)
{ {
sub_bignum(n_tmp, n_tmp, n2, 0, (int)len); sub_bignum(n_tmp, n_tmp, n2, 0, (int)len);
n1[j] |= bit; n1[j] |= bit;
} }
bit >>= 1; bit >>= 1;
if (bit == 0) if (bit == 0)
{ {
j--; j--;
bit = 0x80000000; bit = 0x80000000;
} }
} }
init_bignum(n_tmp, 0, len); init_bignum(n_tmp, 0, len);
} }
void inc_bignum(uint[] n, uint len) void inc_bignum(uint[] n, uint len)
{ {
int i = 0; int i = 0;
while ((++n[i] == 0) && (--len > 0)) i++; while ((++n[i] == 0) && (--len > 0)) i++;
} }
void init_two_dw(uint[] n, uint len) void init_two_dw(uint[] n, uint len)
{ {
mov_bignum(glob1, n, len); mov_bignum(glob1, n, len);
glob1_bitlen = bitlen_bignum(glob1, len); glob1_bitlen = bitlen_bignum(glob1, len);
glob1_len_x2 = (glob1_bitlen + 15) / 16; glob1_len_x2 = (glob1_bitlen + 15) / 16;
mov_bignum(glob1_hi, glob1.Skip((int)len_bignum(glob1, len) - 2).ToArray(), 2); mov_bignum(glob1_hi, glob1.Skip((int)len_bignum(glob1, len) - 2).ToArray(), 2);
glob1_hi_bitlen = bitlen_bignum(glob1_hi, 2) - 32; glob1_hi_bitlen = bitlen_bignum(glob1_hi, 2) - 32;
shr_bignum(glob1_hi, (int)glob1_hi_bitlen, 2); shr_bignum(glob1_hi, (int)glob1_hi_bitlen, 2);
inv_bignum(glob1_hi_inv, glob1_hi, 2); inv_bignum(glob1_hi_inv, glob1_hi, 2);
shr_bignum(glob1_hi_inv, 1, 2); shr_bignum(glob1_hi_inv, 1, 2);
glob1_hi_bitlen = (glob1_hi_bitlen + 15) % 16 + 1; glob1_hi_bitlen = (glob1_hi_bitlen + 15) % 16 + 1;
inc_bignum(glob1_hi_inv, 2); inc_bignum(glob1_hi_inv, 2);
if (bitlen_bignum(glob1_hi_inv, 2) > 32) if (bitlen_bignum(glob1_hi_inv, 2) > 32)
{ {
shr_bignum(glob1_hi_inv, 1, 2); shr_bignum(glob1_hi_inv, 1, 2);
glob1_hi_bitlen--; glob1_hi_bitlen--;
} }
glob1_hi_inv_lo = (ushort)glob1_hi_inv[0]; glob1_hi_inv_lo = (ushort)glob1_hi_inv[0];
glob1_hi_inv_hi = (ushort)(glob1_hi_inv[0] >> 16); glob1_hi_inv_hi = (ushort)(glob1_hi_inv[0] >> 16);
} }
unsafe void mul_bignum_word(ushort *pn1, uint[] n2, uint mul, uint len) unsafe void mul_bignum_word(ushort *pn1, uint[] n2, uint mul, uint len)
{ {
uint i, tmp; uint i, tmp;
unsafe unsafe
{ {
fixed (uint* _pn2 = &n2[0]) fixed (uint* _pn2 = &n2[0])
{ {
ushort* pn2 = (ushort*)_pn2; ushort* pn2 = (ushort*)_pn2;
tmp = 0; tmp = 0;
for (i = 0; i < len; i++) for (i = 0; i < len; i++)
{ {
tmp = mul * (*pn2) + (*pn1) + tmp; tmp = mul * (*pn2) + (*pn1) + tmp;
*pn1 = (ushort)tmp; *pn1 = (ushort)tmp;
pn1++; pn1++;
pn2++; pn2++;
tmp >>= 16; tmp >>= 16;
} }
*pn1 += (ushort)tmp; *pn1 += (ushort)tmp;
} }
} }
} }
void mul_bignum(uint[] dest, uint[] src1, uint[] src2, uint len) void mul_bignum(uint[] dest, uint[] src1, uint[] src2, uint len)
{ {
uint i; uint i;
unsafe unsafe
{ {
fixed( uint * _psrc2 = &src2[0] ) fixed( uint * _psrc2 = &src2[0] )
fixed(uint* _pdest = &dest[0]) fixed(uint* _pdest = &dest[0])
{ {
ushort* psrc2 = (ushort*)_psrc2; ushort* psrc2 = (ushort*)_psrc2;
ushort* pdest = (ushort*)_pdest; ushort* pdest = (ushort*)_pdest;
init_bignum(dest, 0, len * 2); init_bignum(dest, 0, len * 2);
for (i = 0; i < len * 2; i++) for (i = 0; i < len * 2; i++)
mul_bignum_word(pdest++, src1, *psrc2++, len * 2); mul_bignum_word(pdest++, src1, *psrc2++, len * 2);
} }
} }
} }
void not_bignum(uint[] n, uint len) void not_bignum(uint[] n, uint len)
{ {
uint i; uint i;
for (i = 0; i < len; i++) n[i] = ~n[i]; for (i = 0; i < len; i++) n[i] = ~n[i];
} }
void neg_bignum(uint[] n, uint len) void neg_bignum(uint[] n, uint len)
{ {
not_bignum(n, len); not_bignum(n, len);
inc_bignum(n, len); inc_bignum(n, len);
} }
unsafe uint get_mulword(uint* n) unsafe uint get_mulword(uint* n)
{ {
ushort* wn = (ushort*)n; ushort* wn = (ushort*)n;
uint i = (uint)((((((((((*(wn - 1) ^ 0xffff) & 0xffff) * glob1_hi_inv_lo + 0x10000) >> 1) uint i = (uint)((((((((((*(wn - 1) ^ 0xffff) & 0xffff) * glob1_hi_inv_lo + 0x10000) >> 1)
+ (((*(wn - 2) ^ 0xffff) * glob1_hi_inv_hi + glob1_hi_inv_hi) >> 1) + 1) + (((*(wn - 2) ^ 0xffff) * glob1_hi_inv_hi + glob1_hi_inv_hi) >> 1) + 1)
>> 16) + ((((*(wn - 1) ^ 0xffff) & 0xffff) * glob1_hi_inv_hi) >> 1) + >> 16) + ((((*(wn - 1) ^ 0xffff) & 0xffff) * glob1_hi_inv_hi) >> 1) +
(((*wn ^ 0xffff) * glob1_hi_inv_lo) >> 1) + 1) >> 14) + glob1_hi_inv_hi (((*wn ^ 0xffff) * glob1_hi_inv_lo) >> 1) + 1) >> 14) + glob1_hi_inv_hi
* (*wn ^ 0xffff) * 2) >> (int)glob1_hi_bitlen); * (*wn ^ 0xffff) * 2) >> (int)glob1_hi_bitlen);
if (i > 0xffff) i = 0xffff; if (i > 0xffff) i = 0xffff;
return i & 0xffff; return i & 0xffff;
} }
void dec_bignum(uint[] n, uint len) void dec_bignum(uint[] n, uint len)
{ {
int i = 0; int i = 0;
while ((--n[i] == 0xffffffff) && (--len > 0)) while ((--n[i] == 0xffffffff) && (--len > 0))
i++; i++;
} }
void calc_a_bignum(uint[] n1, uint[] n2, uint[] n3, uint len) void calc_a_bignum(uint[] n1, uint[] n2, uint[] n3, uint len)
{ {
uint g2_len_x2, len_diff; uint g2_len_x2, len_diff;
unsafe unsafe
{ {
fixed( uint* g1 = &glob1[0]) fixed( uint* g1 = &glob1[0])
fixed (uint* g2 = &glob2[0]) fixed (uint* g2 = &glob2[0])
{ {
mul_bignum(glob2, n2, n3, len); mul_bignum(glob2, n2, n3, len);
glob2[len * 2] = 0; glob2[len * 2] = 0;
g2_len_x2 = len_bignum(glob2, len * 2 + 1) * 2; g2_len_x2 = len_bignum(glob2, len * 2 + 1) * 2;
if (g2_len_x2 >= glob1_len_x2) if (g2_len_x2 >= glob1_len_x2)
{ {
inc_bignum(glob2, len * 2 + 1); inc_bignum(glob2, len * 2 + 1);
neg_bignum(glob2, len * 2 + 1); neg_bignum(glob2, len * 2 + 1);
len_diff = g2_len_x2 + 1 - glob1_len_x2; len_diff = g2_len_x2 + 1 - glob1_len_x2;
ushort* esi = ((ushort*)g2) + (1 + g2_len_x2 - glob1_len_x2); ushort* esi = ((ushort*)g2) + (1 + g2_len_x2 - glob1_len_x2);
ushort* edi = ((ushort*)g2) + (g2_len_x2 + 1); ushort* edi = ((ushort*)g2) + (g2_len_x2 + 1);
for (; len_diff != 0; len_diff--) for (; len_diff != 0; len_diff--)
{ {
edi--; edi--;
uint tmp = get_mulword((uint*)edi); uint tmp = get_mulword((uint*)edi);
esi--; esi--;
if (tmp > 0) if (tmp > 0)
{ {
mul_bignum_word(esi, glob1, tmp, 2 * len); mul_bignum_word(esi, glob1, tmp, 2 * len);
if ((*edi & 0x8000) == 0) if ((*edi & 0x8000) == 0)
{ {
if (0 != sub_bignum((uint*)esi, (uint*)esi, g1, 0, (int)len)) (*edi)--; if (0 != sub_bignum((uint*)esi, (uint*)esi, g1, 0, (int)len)) (*edi)--;
} }
} }
} }
neg_bignum(glob2, len); neg_bignum(glob2, len);
dec_bignum(glob2, len); dec_bignum(glob2, len);
} }
mov_bignum(n1, glob2, len); mov_bignum(n1, glob2, len);
} }
} }
} }
void clear_tmp_vars(uint len) void clear_tmp_vars(uint len)
{ {
init_bignum(glob1, 0, len); init_bignum(glob1, 0, len);
init_bignum(glob2, 0, len); init_bignum(glob2, 0, len);
init_bignum(glob1_hi_inv, 0, 4); init_bignum(glob1_hi_inv, 0, 4);
init_bignum(glob1_hi, 0, 4); init_bignum(glob1_hi, 0, 4);
glob1_bitlen = 0; glob1_bitlen = 0;
glob1_hi_bitlen = 0; glob1_hi_bitlen = 0;
glob1_len_x2 = 0; glob1_len_x2 = 0;
glob1_hi_inv_lo = 0; glob1_hi_inv_lo = 0;
glob1_hi_inv_hi = 0; glob1_hi_inv_hi = 0;
} }
void calc_a_key(uint[] n1, uint[] n2, uint[] n3, uint[] n4, uint len) void calc_a_key(uint[] n1, uint[] n2, uint[] n3, uint[] n4, uint len)
{ {
uint[] n_tmp = new uint[64]; uint[] n_tmp = new uint[64];
uint n3_len, n4_len; uint n3_len, n4_len;
int n3_bitlen; int n3_bitlen;
uint bit_mask; uint bit_mask;
unsafe unsafe
{ {
fixed (uint* _pn3 = &n3[0]) fixed (uint* _pn3 = &n3[0])
{ {
uint* pn3 = _pn3; uint* pn3 = _pn3;
init_bignum(n1, 1, len); init_bignum(n1, 1, len);
n4_len = len_bignum(n4, len); n4_len = len_bignum(n4, len);
init_two_dw(n4, n4_len); init_two_dw(n4, n4_len);
n3_bitlen = (int)bitlen_bignum(n3, n4_len); n3_bitlen = (int)bitlen_bignum(n3, n4_len);
n3_len = (uint)((n3_bitlen + 31) / 32); n3_len = (uint)((n3_bitlen + 31) / 32);
bit_mask = (((uint)1) << ((n3_bitlen - 1) % 32)) >> 1; bit_mask = (((uint)1) << ((n3_bitlen - 1) % 32)) >> 1;
pn3 += n3_len - 1; pn3 += n3_len - 1;
n3_bitlen--; n3_bitlen--;
mov_bignum(n1, n2, n4_len); mov_bignum(n1, n2, n4_len);
while (--n3_bitlen != -1) while (--n3_bitlen != -1)
{ {
if (bit_mask == 0) if (bit_mask == 0)
{ {
bit_mask = 0x80000000; bit_mask = 0x80000000;
pn3--; pn3--;
} }
calc_a_bignum(n_tmp, n1, n1, n4_len); calc_a_bignum(n_tmp, n1, n1, n4_len);
if ((*pn3 & bit_mask) != 0) if ((*pn3 & bit_mask) != 0)
calc_a_bignum(n1, n_tmp, n2, n4_len); calc_a_bignum(n1, n_tmp, n2, n4_len);
else else
mov_bignum(n1, n_tmp, n4_len); mov_bignum(n1, n_tmp, n4_len);
bit_mask >>= 1; bit_mask >>= 1;
} }
init_bignum(n_tmp, 0, n4_len); init_bignum(n_tmp, 0, n4_len);
clear_tmp_vars(len); clear_tmp_vars(len);
} }
} }
} }
unsafe void memcpy(byte* dest, byte* src, int len) unsafe void memcpy(byte* dest, byte* src, int len)
{ {
while (len-- != 0) *dest++ = *src++; while (len-- != 0) *dest++ = *src++;
} }
unsafe void process_predata(byte* pre, uint pre_len, byte *buf) unsafe void process_predata(byte* pre, uint pre_len, byte *buf)
{ {
uint[] n2 = new uint[64]; uint[] n2 = new uint[64];
uint[] n3 = new uint[64]; uint[] n3 = new uint[64];
uint a = (pubkey.len - 1) / 8; uint a = (pubkey.len - 1) / 8;
while (a + 1 <= pre_len) while (a + 1 <= pre_len)
{ {
init_bignum(n2, 0, 64); init_bignum(n2, 0, 64);
fixed( uint * pn2 = &n2[0] ) fixed( uint * pn2 = &n2[0] )
memcpy((byte *)pn2, pre, (int)a + 1); memcpy((byte *)pn2, pre, (int)a + 1);
calc_a_key(n3, n2, pubkey.key2, pubkey.key1, 64); calc_a_key(n3, n2, pubkey.key2, pubkey.key1, 64);
fixed( uint * pn3 = &n3[0] ) fixed( uint * pn3 = &n3[0] )
memcpy(buf, (byte *)pn3, (int)a); memcpy(buf, (byte *)pn3, (int)a);
pre_len -= a + 1; pre_len -= a + 1;
pre += a + 1; pre += a + 1;
buf += a; buf += a;
} }
} }
public byte[] DecryptKey(byte[] src) public byte[] DecryptKey(byte[] src)
{ {
init_pubkey(); init_pubkey();
byte[] dest = new byte[256]; byte[] dest = new byte[256];
unsafe unsafe
{ {
fixed (byte* pdest = &dest[0]) fixed (byte* pdest = &dest[0])
fixed (byte* psrc = &src[0]) fixed (byte* psrc = &src[0])
process_predata(psrc, len_predata(), pdest); process_predata(psrc, len_predata(), pdest);
} }
return dest.Take(56).ToArray(); return dest.Take(56).ToArray();
} }
} }
} }

View File

@@ -14,20 +14,20 @@ namespace OpenRA.FileFormats
{ {
public static int DecodeInto( byte[] src, byte[] dest ) public static int DecodeInto( byte[] src, byte[] dest )
{ {
var ctx = new FastByteReader(src); var ctx = new FastByteReader(src);
int destIndex = 0; int destIndex = 0;
while( true ) while( true )
{ {
byte i = ctx.ReadByte(); byte i = ctx.ReadByte();
if( ( i & 0x80 ) == 0 ) if( ( i & 0x80 ) == 0 )
{ {
int count = i & 0x7F; int count = i & 0x7F;
if( count == 0 ) if( count == 0 )
{ {
// case 6 // case 6
count = ctx.ReadByte(); count = ctx.ReadByte();
byte value = ctx.ReadByte(); byte value = ctx.ReadByte();
for( int end = destIndex + count ; destIndex < end ; destIndex++ ) for( int end = destIndex + count ; destIndex < end ; destIndex++ )
dest[ destIndex ] ^= value; dest[ destIndex ] ^= value;
} }
@@ -35,7 +35,7 @@ namespace OpenRA.FileFormats
{ {
// case 5 // case 5
for( int end = destIndex + count ; destIndex < end ; destIndex++ ) for( int end = destIndex + count ; destIndex < end ; destIndex++ )
dest[destIndex] ^= ctx.ReadByte(); dest[destIndex] ^= ctx.ReadByte();
} }
} }
else else
@@ -43,7 +43,7 @@ namespace OpenRA.FileFormats
int count = i & 0x7F; int count = i & 0x7F;
if( count == 0 ) if( count == 0 )
{ {
count = ctx.ReadWord(); count = ctx.ReadWord();
if( count == 0 ) if( count == 0 )
return destIndex; return destIndex;
@@ -56,12 +56,12 @@ namespace OpenRA.FileFormats
{ {
// case 3 // case 3
for( int end = destIndex + ( count & 0x3FFF ) ; destIndex < end ; destIndex++ ) for( int end = destIndex + ( count & 0x3FFF ) ; destIndex < end ; destIndex++ )
dest[destIndex] ^= ctx.ReadByte(); dest[destIndex] ^= ctx.ReadByte();
} }
else else
{ {
// case 4 // case 4
byte value = ctx.ReadByte(); byte value = ctx.ReadByte();
for( int end = destIndex + ( count & 0x3FFF ) ; destIndex < end ; destIndex++ ) for( int end = destIndex + ( count & 0x3FFF ) ; destIndex < end ; destIndex++ )
dest[ destIndex ] ^= value; dest[ destIndex ] ^= value;
} }

View File

@@ -13,32 +13,32 @@ using System.IO;
namespace OpenRA.FileFormats namespace OpenRA.FileFormats
{ {
class FastByteReader class FastByteReader
{ {
readonly byte[] src; readonly byte[] src;
int offset = 0; int offset = 0;
public FastByteReader(byte[] src) public FastByteReader(byte[] src)
{ {
this.src = src; this.src = src;
} }
public bool Done() { return offset >= src.Length; } public bool Done() { return offset >= src.Length; }
public byte ReadByte() { return src[offset++]; } public byte ReadByte() { return src[offset++]; }
public int ReadWord() public int ReadWord()
{ {
int x = ReadByte(); int x = ReadByte();
return x | (ReadByte() << 8); return x | (ReadByte() << 8);
} }
public void CopyTo(byte[] dest, int offset, int count) public void CopyTo(byte[] dest, int offset, int count)
{ {
Array.Copy(src, this.offset, dest, offset, count); Array.Copy(src, this.offset, dest, offset, count);
this.offset += count; this.offset += count;
} }
public int Remaining() { return src.Length - offset; } public int Remaining() { return src.Length - offset; }
} }
public static class Format80 public static class Format80
{ {
@@ -61,16 +61,16 @@ namespace OpenRA.FileFormats
public static int DecodeInto( byte[] src, byte[] dest ) public static int DecodeInto( byte[] src, byte[] dest )
{ {
var ctx = new FastByteReader(src); var ctx = new FastByteReader(src);
int destIndex = 0; int destIndex = 0;
while( true ) while( true )
{ {
byte i = ctx.ReadByte(); byte i = ctx.ReadByte();
if( ( i & 0x80 ) == 0 ) if( ( i & 0x80 ) == 0 )
{ {
// case 2 // case 2
byte secondByte = ctx.ReadByte(); byte secondByte = ctx.ReadByte();
int count = ( ( i & 0x70 ) >> 4 ) + 3; int count = ( ( i & 0x70 ) >> 4 ) + 3;
int rpos = ( ( i & 0xf ) << 8 ) + secondByte; int rpos = ( ( i & 0xf ) << 8 ) + secondByte;
@@ -93,8 +93,8 @@ namespace OpenRA.FileFormats
if( count3 == 0x3E ) if( count3 == 0x3E )
{ {
// case 4 // case 4
int count = ctx.ReadWord(); int count = ctx.ReadWord();
byte color = ctx.ReadByte(); byte color = ctx.ReadByte();
for( int end = destIndex + count ; destIndex < end ; destIndex++ ) for( int end = destIndex + count ; destIndex < end ; destIndex++ )
dest[ destIndex ] = color; dest[ destIndex ] = color;
@@ -102,8 +102,8 @@ namespace OpenRA.FileFormats
else if( count3 == 0x3F ) else if( count3 == 0x3F )
{ {
// case 5 // case 5
int count = ctx.ReadWord(); int count = ctx.ReadWord();
int srcIndex = ctx.ReadWord(); int srcIndex = ctx.ReadWord();
if( srcIndex >= destIndex ) if( srcIndex >= destIndex )
throw new NotImplementedException( string.Format( "srcIndex >= destIndex {0} {1}", srcIndex, destIndex ) ); throw new NotImplementedException( string.Format( "srcIndex >= destIndex {0} {1}", srcIndex, destIndex ) );
@@ -114,7 +114,7 @@ namespace OpenRA.FileFormats
{ {
// case 3 // case 3
int count = count3 + 3; int count = count3 + 3;
int srcIndex = ctx.ReadWord(); int srcIndex = ctx.ReadWord();
if( srcIndex >= destIndex ) if( srcIndex >= destIndex )
throw new NotImplementedException( string.Format( "srcIndex >= destIndex {0} {1}", srcIndex, destIndex ) ); throw new NotImplementedException( string.Format( "srcIndex >= destIndex {0} {1}", srcIndex, destIndex ) );

View File

@@ -38,36 +38,36 @@ namespace OpenRA.FileFormats
static IFolder OpenPackage(string filename) static IFolder OpenPackage(string filename)
{ {
return OpenPackage(filename, order++); return OpenPackage(filename, order++);
} }
public static IFolder CreatePackage(string filename, int order, Dictionary<string, byte[]> content) public static IFolder CreatePackage(string filename, int order, Dictionary<string, byte[]> content)
{ {
if (filename.EndsWith(".mix", StringComparison.InvariantCultureIgnoreCase)) if (filename.EndsWith(".mix", StringComparison.InvariantCultureIgnoreCase))
return new MixFile(filename, order, content); return new MixFile(filename, order, content);
else if (filename.EndsWith(".zip", StringComparison.InvariantCultureIgnoreCase)) else if (filename.EndsWith(".zip", StringComparison.InvariantCultureIgnoreCase))
return new ZipFile(filename, order, content); return new ZipFile(filename, order, content);
else if (filename.EndsWith(".oramap", StringComparison.InvariantCultureIgnoreCase)) else if (filename.EndsWith(".oramap", StringComparison.InvariantCultureIgnoreCase))
return new ZipFile(filename, order, content); return new ZipFile(filename, order, content);
else if (filename.EndsWith(".Z", StringComparison.InvariantCultureIgnoreCase)) else if (filename.EndsWith(".Z", StringComparison.InvariantCultureIgnoreCase))
throw new NotImplementedException("Creating .Z archives is unsupported"); throw new NotImplementedException("Creating .Z archives is unsupported");
else else
return new Folder(filename, order, content); return new Folder(filename, order, content);
} }
public static IFolder OpenPackage(string filename, int order) public static IFolder OpenPackage(string filename, int order)
{ {
if (filename.EndsWith(".mix", StringComparison.InvariantCultureIgnoreCase)) if (filename.EndsWith(".mix", StringComparison.InvariantCultureIgnoreCase))
return new MixFile(filename, order); return new MixFile(filename, order);
else if (filename.EndsWith(".zip", StringComparison.InvariantCultureIgnoreCase)) else if (filename.EndsWith(".zip", StringComparison.InvariantCultureIgnoreCase))
return new ZipFile(filename, order); return new ZipFile(filename, order);
else if (filename.EndsWith(".oramap", StringComparison.InvariantCultureIgnoreCase)) else if (filename.EndsWith(".oramap", StringComparison.InvariantCultureIgnoreCase))
return new ZipFile(filename, order); return new ZipFile(filename, order);
else if (filename.EndsWith(".Z", StringComparison.InvariantCultureIgnoreCase)) else if (filename.EndsWith(".Z", StringComparison.InvariantCultureIgnoreCase))
return new InstallShieldPackage(filename, order); return new InstallShieldPackage(filename, order);
else else
return new Folder(filename, order); return new Folder(filename, order);
} }
public static void Mount(string name) public static void Mount(string name)
{ {
@@ -169,7 +169,7 @@ namespace OpenRA.FileFormats
{ {
foreach (var folder in mountedFolders) foreach (var folder in mountedFolders)
if (folder.Exists(filename)) if (folder.Exists(filename))
return true; return true;
return false; return false;
} }

View File

@@ -70,7 +70,7 @@ namespace OpenRA.FileFormats
foreach (var file in contents) foreach (var file in contents)
using (var dataStream = File.Create(Path.Combine(path, file.Key))) using (var dataStream = File.Create(Path.Combine(path, file.Key)))
using (var writer = new BinaryWriter(dataStream)) using (var writer = new BinaryWriter(dataStream))
writer.Write(file.Value); writer.Write(file.Value);
} }
} }
} }

View File

@@ -73,13 +73,13 @@ namespace OpenRA.FileFormats.Graphics
void SetData(byte[] colors, int width, int height); void SetData(byte[] colors, int width, int height);
} }
public enum PrimitiveType public enum PrimitiveType
{ {
PointList, PointList,
LineList, LineList,
TriangleList, TriangleList,
QuadList, QuadList,
} }
public struct Range<T> public struct Range<T>
{ {

View File

@@ -51,7 +51,7 @@ namespace OpenRA.FileFormats
LoadScreen = yaml["LoadScreen"]; LoadScreen = yaml["LoadScreen"];
Fonts = yaml["Fonts"].NodesDict.ToDictionary(x => x.Key, x => Pair.New(x.Value.NodesDict["Font"].Value, Fonts = yaml["Fonts"].NodesDict.ToDictionary(x => x.Key, x => Pair.New(x.Value.NodesDict["Font"].Value,
int.Parse(x.Value.NodesDict["Size"].Value))); int.Parse(x.Value.NodesDict["Size"].Value)));
if (yaml.ContainsKey("TileSize")) if (yaml.ContainsKey("TileSize"))
TileSize = int.Parse(yaml["TileSize"].Value); TileSize = int.Parse(yaml["TileSize"].Value);
} }

View File

@@ -28,7 +28,7 @@ namespace OpenRA.FileFormats
public string Race; public string Race;
public bool LockColor = false; public bool LockColor = false;
public ColorRamp ColorRamp = new ColorRamp(0,0,238,34); public ColorRamp ColorRamp = new ColorRamp(0,0,238,34);
public bool LockSpawn = false; public bool LockSpawn = false;
public int Spawn = 0; public int Spawn = 0;

View File

@@ -22,7 +22,7 @@ namespace OpenRA.FileFormats
public struct SourceLocation public struct SourceLocation
{ {
public string Filename; public int Line; public string Filename; public int Line;
public override string ToString() { return "{0}:{1}".F(Filename, Line); } public override string ToString() { return "{0}:{1}".F(Filename, Line); }
} }
public SourceLocation Location; public SourceLocation Location;
@@ -55,10 +55,10 @@ namespace OpenRA.FileFormats
{ {
} }
public override string ToString() public override string ToString()
{ {
return "{{YamlNode: {0} @ {1}}}".F(Key, Location); return "{{YamlNode: {0} @ {1}}}".F(Key, Location);
} }
} }
public class MiniYaml public class MiniYaml
@@ -177,15 +177,15 @@ namespace OpenRA.FileFormats
return FromLines(text.Split(new[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries), "<no filename available>"); return FromLines(text.Split(new[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries), "<no filename available>");
} }
public static List<MiniYamlNode> MergeLiberal(List<MiniYamlNode> a, List<MiniYamlNode> b) public static List<MiniYamlNode> MergeLiberal(List<MiniYamlNode> a, List<MiniYamlNode> b)
{ {
return Merge(a, b, false); return Merge(a, b, false);
} }
public static List<MiniYamlNode> MergeStrict(List<MiniYamlNode> a, List<MiniYamlNode> b) public static List<MiniYamlNode> MergeStrict(List<MiniYamlNode> a, List<MiniYamlNode> b)
{ {
return Merge(a, b, true); return Merge(a, b, true);
} }
static List<MiniYamlNode> Merge( List<MiniYamlNode> a, List<MiniYamlNode> b, bool throwErrors ) static List<MiniYamlNode> Merge( List<MiniYamlNode> a, List<MiniYamlNode> b, bool throwErrors )
{ {
@@ -200,8 +200,8 @@ namespace OpenRA.FileFormats
var bDict = b.ToDictionary( x => x.Key ); var bDict = b.ToDictionary( x => x.Key );
var keys = aDict.Keys.Union( bDict.Keys ).ToList(); var keys = aDict.Keys.Union( bDict.Keys ).ToList();
var noInherit = keys.Where(x => x.Length > 0 && x[0] == '-') var noInherit = keys.Where(x => x.Length > 0 && x[0] == '-')
.ToDictionary(x => x.Substring(1), x => false); .ToDictionary(x => x.Substring(1), x => false);
foreach( var key in keys ) foreach( var key in keys )
{ {
@@ -211,11 +211,11 @@ namespace OpenRA.FileFormats
if( noInherit.ContainsKey( key ) ) if( noInherit.ContainsKey( key ) )
{ {
if (!throwErrors) if (!throwErrors)
if (aa != null) if (aa != null)
ret.Add(aa); ret.Add(aa);
noInherit[key] = true; noInherit[key] = true;
} }
else else
{ {
@@ -225,23 +225,23 @@ namespace OpenRA.FileFormats
} }
} }
if (throwErrors) if (throwErrors)
if (noInherit.ContainsValue(false)) if (noInherit.ContainsValue(false))
throw new YamlException("Bogus yaml removals: {0}".F( throw new YamlException("Bogus yaml removals: {0}".F(
string.Join(", ", noInherit.Where(x => !x.Value).Select(x => x.Key).ToArray()))); string.Join(", ", noInherit.Where(x => !x.Value).Select(x => x.Key).ToArray())));
return ret; return ret;
} }
public static MiniYaml MergeLiberal(MiniYaml a, MiniYaml b) public static MiniYaml MergeLiberal(MiniYaml a, MiniYaml b)
{ {
return Merge(a, b, false); return Merge(a, b, false);
} }
public static MiniYaml MergeStrict(MiniYaml a, MiniYaml b) public static MiniYaml MergeStrict(MiniYaml a, MiniYaml b)
{ {
return Merge(a, b, true); return Merge(a, b, true);
} }
static MiniYaml Merge( MiniYaml a, MiniYaml b, bool throwErrors ) static MiniYaml Merge( MiniYaml a, MiniYaml b, bool throwErrors )
{ {
@@ -286,8 +286,8 @@ namespace OpenRA.FileFormats
} }
} }
public class YamlException : Exception public class YamlException : Exception
{ {
public YamlException(string s) : base(s) { } public YamlException(string s) : base(s) { }
} }
} }

View File

@@ -23,8 +23,8 @@ namespace OpenRA.FileFormats
public PlayerColorRemap(ColorRamp c, PaletteFormat fmt) public PlayerColorRemap(ColorRamp c, PaletteFormat fmt)
{ {
var c1 = c.GetColor(0); var c1 = c.GetColor(0);
var c2 = c.GetColor(1); /* temptemp: this can be expressed better */ var c2 = c.GetColor(1); /* temptemp: this can be expressed better */
var baseIndex = (fmt == PaletteFormat.cnc) ? 0xb0 : (fmt == PaletteFormat.d2k) ? 240 : 80; var baseIndex = (fmt == PaletteFormat.cnc) ? 0xb0 : (fmt == PaletteFormat.d2k) ? 240 : 80;
var ramp = (fmt == PaletteFormat.cnc) var ramp = (fmt == PaletteFormat.cnc)

View File

@@ -71,8 +71,8 @@ namespace OpenRA.FileFormats
public static IEqualityComparer<Pair<T, U>> EqualityComparer { get { return new PairEqualityComparer(); } } public static IEqualityComparer<Pair<T, U>> EqualityComparer { get { return new PairEqualityComparer(); } }
} }
public static class Pair public static class Pair
{ {
public static Pair<T, U> New<T, U>(T t, U u) { return new Pair<T, U>(t, u); } public static Pair<T, U> New<T, U>(T t, U u) { return new Pair<T, U>(t, u); }
static Pair() static Pair()
@@ -86,5 +86,5 @@ namespace OpenRA.FileFormats
public bool Equals(Color x, Color y) { return x.ToArgb() == y.ToArgb(); } public bool Equals(Color x, Color y) { return x.ToArgb() == y.ToArgb(); }
public int GetHashCode(Color obj) { return obj.GetHashCode(); } public int GetHashCode(Color obj) { return obj.GetHashCode(); }
} }
} }
} }

View File

@@ -62,23 +62,23 @@ namespace OpenRA
Constrain(Y, min.Y, max.Y)); Constrain(Y, min.Y, max.Y));
} }
public static float2 operator *(float a, float2 b) { return new float2(a * b.X, a * b.Y); } public static float2 operator *(float a, float2 b) { return new float2(a * b.X, a * b.Y); }
public static float2 operator *(float2 b, float a) { return new float2(a * b.X, a * b.Y); } public static float2 operator *(float2 b, float a) { return new float2(a * b.X, a * b.Y); }
public static float2 operator *( float2 a, float2 b ) { return new float2( a.X * b.X, a.Y * b.Y ); } public static float2 operator *( float2 a, float2 b ) { return new float2( a.X * b.X, a.Y * b.Y ); }
public static float2 operator /( float2 a, float2 b ) { return new float2( a.X / b.X, a.Y / b.Y ); } public static float2 operator /( float2 a, float2 b ) { return new float2( a.X / b.X, a.Y / b.Y ); }
public static bool operator ==(float2 me, float2 other) { return (me.X == other.X && me.Y == other.Y); } public static bool operator ==(float2 me, float2 other) { return (me.X == other.X && me.Y == other.Y); }
public static bool operator !=(float2 me, float2 other) { return !(me == other); } public static bool operator !=(float2 me, float2 other) { return !(me == other); }
public override int GetHashCode() { return X.GetHashCode() ^ Y.GetHashCode(); } public override int GetHashCode() { return X.GetHashCode() ^ Y.GetHashCode(); }
public override bool Equals(object obj) public override bool Equals(object obj)
{ {
if (obj == null) if (obj == null)
return false; return false;
float2 o = (float2)obj; float2 o = (float2)obj;
return o == this; return o == this;
} }
public static readonly float2 Zero = new float2(0, 0); public static readonly float2 Zero = new float2(0, 0);

View File

@@ -52,7 +52,7 @@ namespace OpenRA
public static readonly int2 Zero = new int2(0, 0); public static readonly int2 Zero = new int2(0, 0);
public Point ToPoint() { return new Point(X, Y); } public Point ToPoint() { return new Point(X, Y); }
public PointF ToPointF() { return new PointF(X, Y); } public PointF ToPointF() { return new PointF(X, Y); }
public float2 ToFloat2() { return new float2(X, Y); } public float2 ToFloat2() { return new float2(X, Y); }
public override string ToString() { return string.Format("{0},{1}", X, Y); } public override string ToString() { return string.Format("{0},{1}", X, Y); }
@@ -76,7 +76,7 @@ namespace OpenRA
public int2 Clamp(Rectangle r) public int2 Clamp(Rectangle r)
{ {
return new int2(Math.Min(r.Right, Math.Max(X, r.Left)), return new int2(Math.Min(r.Right, Math.Max(X, r.Left)),
Math.Min(r.Bottom, Math.Max(Y, r.Top))); Math.Min(r.Bottom, Math.Max(Y, r.Top)));
} }
public static int Dot(int2 a, int2 b) { return a.X * b.X + a.Y * b.Y; } public static int Dot(int2 a, int2 b) { return a.X * b.X + a.Y * b.Y; }

View File

@@ -38,34 +38,34 @@ namespace OpenRA
} }
} }
static IEnumerable<string> FilenamesForChannel(string channelName, string baseFilename) static IEnumerable<string> FilenamesForChannel(string channelName, string baseFilename)
{ {
for(var i = 0;; i++ ) for(var i = 0;; i++ )
yield return Path.Combine(LogPathPrefix, yield return Path.Combine(LogPathPrefix,
i > 0 ? "{0}.{1}".F(baseFilename, i) : baseFilename); i > 0 ? "{0}.{1}".F(baseFilename, i) : baseFilename);
} }
public static void AddChannel(string channelName, string baseFilename) public static void AddChannel(string channelName, string baseFilename)
{ {
if (channels.ContainsKey(channelName)) return; if (channels.ContainsKey(channelName)) return;
foreach (var filename in FilenamesForChannel(channelName, baseFilename)) foreach (var filename in FilenamesForChannel(channelName, baseFilename))
try try
{ {
var writer = File.CreateText(filename); var writer = File.CreateText(filename);
writer.AutoFlush = true; writer.AutoFlush = true;
channels.Add(channelName, channels.Add(channelName,
new ChannelInfo() new ChannelInfo()
{ {
Filename = filename, Filename = filename,
Writer = writer Writer = writer
}); });
return; return;
} }
catch (IOException) { } catch (IOException) { }
} }
public static void Write(string channel, string format, params object[] args) public static void Write(string channel, string format, params object[] args)
{ {

View File

@@ -82,7 +82,7 @@ namespace OpenRA
// auto size from render // auto size from render
var firstSprite = TraitsImplementing<IRender>().SelectMany(ApplyIRender).FirstOrDefault(); var firstSprite = TraitsImplementing<IRender>().SelectMany(ApplyIRender).FirstOrDefault();
if (firstSprite.Sprite == null) return int2.Zero; if (firstSprite.Sprite == null) return int2.Zero;
return (firstSprite.Sprite.size * firstSprite.Scale).ToInt2(); return (firstSprite.Sprite.size * firstSprite.Scale).ToInt2();
}); });
ApplyIRender = x => x.Render(this); ApplyIRender = x => x.Render(this);
@@ -105,7 +105,7 @@ namespace OpenRA
get { return currentActivity == null; } get { return currentActivity == null; }
} }
OpenRA.FileFormats.Lazy<int2> Size; OpenRA.FileFormats.Lazy<int2> Size;
// note: these delegates are cached to avoid massive allocation. // note: these delegates are cached to avoid massive allocation.
Func<IRender, IEnumerable<Renderable>> ApplyIRender; Func<IRender, IEnumerable<Renderable>> ApplyIRender;

View File

@@ -23,29 +23,29 @@ namespace OpenRA
public ActorInfo( string name, MiniYaml node, Dictionary<string, MiniYaml> allUnits ) public ActorInfo( string name, MiniYaml node, Dictionary<string, MiniYaml> allUnits )
{ {
try try
{ {
var mergedNode = MergeWithParent(node, allUnits).NodesDict; var mergedNode = MergeWithParent(node, allUnits).NodesDict;
Name = name; Name = name;
foreach (var t in mergedNode) foreach (var t in mergedNode)
if (t.Key != "Inherits" && !t.Key.StartsWith("-")) if (t.Key != "Inherits" && !t.Key.StartsWith("-"))
Traits.Add(LoadTraitInfo(t.Key.Split('@')[0], t.Value)); Traits.Add(LoadTraitInfo(t.Key.Split('@')[0], t.Value));
} }
catch (YamlException e) catch (YamlException e)
{ {
throw new YamlException("Actor type {0}: {1}".F(name, e.Message)); throw new YamlException("Actor type {0}: {1}".F(name, e.Message));
} }
} }
static IEnumerable<MiniYaml> GetInheritanceChain(MiniYaml node, Dictionary<string, MiniYaml> allUnits) static IEnumerable<MiniYaml> GetInheritanceChain(MiniYaml node, Dictionary<string, MiniYaml> allUnits)
{ {
while (node != null) while (node != null)
{ {
yield return node; yield return node;
node = GetParent(node, allUnits); node = GetParent(node, allUnits);
} }
} }
static MiniYaml GetParent( MiniYaml node, Dictionary<string, MiniYaml> allUnits ) static MiniYaml GetParent( MiniYaml node, Dictionary<string, MiniYaml> allUnits )
{ {
@@ -56,9 +56,9 @@ namespace OpenRA
MiniYaml parent; MiniYaml parent;
allUnits.TryGetValue( inherits.Value, out parent ); allUnits.TryGetValue( inherits.Value, out parent );
if (parent == null) if (parent == null)
throw new InvalidOperationException( throw new InvalidOperationException(
"Bogus inheritance -- actor type {0} does not exist".F(inherits.Value)); "Bogus inheritance -- actor type {0} does not exist".F(inherits.Value));
return parent; return parent;
} }
@@ -66,14 +66,14 @@ namespace OpenRA
static MiniYaml MergeWithParent( MiniYaml node, Dictionary<string, MiniYaml> allUnits ) static MiniYaml MergeWithParent( MiniYaml node, Dictionary<string, MiniYaml> allUnits )
{ {
var parent = GetParent( node, allUnits ); var parent = GetParent( node, allUnits );
if (parent != null) if (parent != null)
{ {
var result = MiniYaml.MergeStrict(node, MergeWithParent(parent, allUnits)); var result = MiniYaml.MergeStrict(node, MergeWithParent(parent, allUnits));
// strip the '-' // strip the '-'
result.Nodes.RemoveAll(a => a.Key.StartsWith("-")); result.Nodes.RemoveAll(a => a.Key.StartsWith("-"));
return result; return result;
} }
return node; return node;
} }

View File

@@ -49,7 +49,7 @@ namespace OpenRA.GameRules
public bool PerfText = false; public bool PerfText = false;
public bool PerfGraph = false; public bool PerfGraph = false;
public float LongTickThreshold = 0.001f; public float LongTickThreshold = 0.001f;
public bool SanityCheckUnsyncedCode = false; public bool SanityCheckUnsyncedCode = false;
public int Samples = 25; public int Samples = 25;
} }
@@ -79,7 +79,7 @@ namespace OpenRA.GameRules
public class PlayerSettings public class PlayerSettings
{ {
public string Name = "Newbie"; public string Name = "Newbie";
public ColorRamp ColorRamp = new ColorRamp(75, 255, 180, 25); public ColorRamp ColorRamp = new ColorRamp(75, 255, 180, 25);
public string LastServer = "localhost:1234"; public string LastServer = "localhost:1234";
} }
@@ -91,8 +91,8 @@ namespace OpenRA.GameRules
public bool TeamChatToggle = false; public bool TeamChatToggle = false;
public bool ViewportEdgeScroll = true; public bool ViewportEdgeScroll = true;
public MouseScrollType MouseScroll = MouseScrollType.Standard; public MouseScrollType MouseScroll = MouseScrollType.Standard;
public float ViewportEdgeScrollStep = 10f; public float ViewportEdgeScrollStep = 10f;
// Internal game settings // Internal game settings

View File

@@ -60,10 +60,10 @@ namespace OpenRA.Graphics
Game.Renderer.WorldSpriteRenderer.DrawSprite( this, location, paletteIndex, this.size ); Game.Renderer.WorldSpriteRenderer.DrawSprite( this, location, paletteIndex, this.size );
} }
public void DrawAt(float2 location, int paletteIndex, float scale) public void DrawAt(float2 location, int paletteIndex, float scale)
{ {
Game.Renderer.WorldSpriteRenderer.DrawSprite(this, location, paletteIndex, this.size * scale); Game.Renderer.WorldSpriteRenderer.DrawSprite(this, location, paletteIndex, this.size * scale);
} }
public void DrawAt( float2 location, int paletteIndex, float2 size ) public void DrawAt( float2 location, int paletteIndex, float2 size )
{ {

View File

@@ -70,18 +70,18 @@ namespace OpenRA.Graphics
} }
} }
public void DrawTextWithContrast(string text, float2 location, Color fg, Color bg, int offset) public void DrawTextWithContrast(string text, float2 location, Color fg, Color bg, int offset)
{ {
if (offset > 0) if (offset > 0)
{ {
DrawText(text, location + new float2(-offset, 0), bg); DrawText(text, location + new float2(-offset, 0), bg);
DrawText(text, location + new float2(offset, 0), bg); DrawText(text, location + new float2(offset, 0), bg);
DrawText(text, location + new float2(0, -offset), bg); DrawText(text, location + new float2(0, -offset), bg);
DrawText(text, location + new float2(0, offset), bg); DrawText(text, location + new float2(0, offset), bg);
} }
DrawText(text, location, fg); DrawText(text, location, fg);
} }
public int2 Measure(string text) public int2 Measure(string text)
{ {

View File

@@ -22,7 +22,7 @@ namespace OpenRA.Graphics
sprites = new Cache<string, Sprite[]>( LoadSprites ); sprites = new Cache<string, Sprite[]>( LoadSprites );
} }
readonly SheetBuilder SheetBuilder; readonly SheetBuilder SheetBuilder;
readonly Cache<string, Sprite[]> sprites; readonly Cache<string, Sprite[]> sprites;
readonly string[] exts; readonly string[] exts;

View File

@@ -44,9 +44,9 @@ namespace OpenRA.Graphics
get get
{ {
return new Rectangle(scrollPosition.X / Game.CellSize, return new Rectangle(scrollPosition.X / Game.CellSize,
scrollPosition.Y / Game.CellSize, scrollPosition.Y / Game.CellSize,
(int)(screenSize.X / Zoom / Game.CellSize), (int)(screenSize.X / Zoom / Game.CellSize),
(int)(screenSize.Y / Zoom / Game.CellSize)); (int)(screenSize.Y / Zoom / Game.CellSize));
} }
} }
@@ -70,9 +70,9 @@ namespace OpenRA.Graphics
var viewBR = (Game.CellSize*new float2(mapBounds.Right, mapBounds.Bottom)).ToInt2(); var viewBR = (Game.CellSize*new float2(mapBounds.Right, mapBounds.Bottom)).ToInt2();
var border = (.5f/Zoom * screenSize.ToFloat2()).ToInt2(); var border = (.5f/Zoom * screenSize.ToFloat2()).ToInt2();
scrollLimits = Rectangle.FromLTRB(viewTL.X - border.X, scrollLimits = Rectangle.FromLTRB(viewTL.X - border.X,
viewTL.Y - border.Y, viewTL.Y - border.Y,
viewBR.X - border.X, viewBR.X - border.X,
viewBR.Y - border.Y); viewBR.Y - border.Y);
// Re-center viewport // Re-center viewport
scrollPosition = NormalizeScrollPosition((oldCenter - 0.5f / Zoom * screenSize.ToFloat2()).ToInt2()); scrollPosition = NormalizeScrollPosition((oldCenter - 0.5f / Zoom * screenSize.ToFloat2()).ToInt2());
} }
@@ -135,13 +135,13 @@ namespace OpenRA.Graphics
{ {
Widget.DoDraw(); Widget.DoDraw();
var cursorName = Widget.RootWidget.GetCursorOuter(Viewport.LastMousePos) ?? "default"; var cursorName = Widget.RootWidget.GetCursorOuter(Viewport.LastMousePos) ?? "default";
var cursorSequence = CursorProvider.GetCursorSequence(cursorName); var cursorSequence = CursorProvider.GetCursorSequence(cursorName);
var cursorSprite = cursorSequence.GetSprite((int)cursorFrame); var cursorSprite = cursorSequence.GetSprite((int)cursorFrame);
renderer.SpriteRenderer.DrawSprite(cursorSprite, renderer.SpriteRenderer.DrawSprite(cursorSprite,
Viewport.LastMousePos - cursorSequence.Hotspot, Viewport.LastMousePos - cursorSequence.Hotspot,
Game.modData.Palette.GetPaletteIndex(cursorSequence.Palette), Game.modData.Palette.GetPaletteIndex(cursorSequence.Palette),
cursorSprite.size); cursorSprite.size);
} }
using( new PerfSample("render_flip") ) using( new PerfSample("render_flip") )

View File

@@ -29,7 +29,7 @@ namespace OpenRA
public string Uid { get; protected set; } public string Uid { get; protected set; }
public int MapFormat; public int MapFormat;
public bool Selectable; public bool Selectable;
public bool UseAsShellmap; public bool UseAsShellmap;
public string RequiresMod; public string RequiresMod;
public string Title; public string Title;
@@ -120,7 +120,7 @@ namespace OpenRA
var yaml = new MiniYaml( null, MiniYaml.FromStream(Container.GetContent("map.yaml")) ); var yaml = new MiniYaml( null, MiniYaml.FromStream(Container.GetContent("map.yaml")) );
FieldLoader.Load(this, yaml); FieldLoader.Load(this, yaml);
Uid = ComputeHash(); Uid = ComputeHash();
// 'Simple' metadata // 'Simple' metadata
FieldLoader.Load( this, yaml ); FieldLoader.Load( this, yaml );
@@ -394,16 +394,16 @@ namespace OpenRA
} }
string ComputeHash() string ComputeHash()
{ {
// UID is calculated by taking an SHA1 of the yaml and binary data // UID is calculated by taking an SHA1 of the yaml and binary data
// Read the relevant data into a buffer // Read the relevant data into a buffer
var data = Container.GetContent("map.yaml").ReadAllBytes() var data = Container.GetContent("map.yaml").ReadAllBytes()
.Concat(Container.GetContent("map.bin").ReadAllBytes()).ToArray(); .Concat(Container.GetContent("map.bin").ReadAllBytes()).ToArray();
// Take the SHA1 // Take the SHA1
using (var csp = SHA1.Create()) using (var csp = SHA1.Create())
return new string(csp.ComputeHash(data).SelectMany(a => a.ToString("x2")).ToArray()); return new string(csp.ComputeHash(data).SelectMany(a => a.ToString("x2")).ToArray());
} }
public void MakeDefaultPlayers() public void MakeDefaultPlayers()
{ {

View File

@@ -82,21 +82,21 @@ namespace OpenRA
return map; return map;
} }
public static IEnumerable<string> FindMapsIn(string dir) public static IEnumerable<string> FindMapsIn(string dir)
{ {
string[] NoMaps = { }; string[] NoMaps = { };
if (!Directory.Exists(dir)) if (!Directory.Exists(dir))
return NoMaps; return NoMaps;
return Directory.GetDirectories(dir) return Directory.GetDirectories(dir)
.Concat(Directory.GetFiles(dir, "*.zip")) .Concat(Directory.GetFiles(dir, "*.zip"))
.Concat(Directory.GetFiles(dir, "*.oramap")); .Concat(Directory.GetFiles(dir, "*.oramap"));
} }
Dictionary<string, Map> FindMaps(string[] mods) Dictionary<string, Map> FindMaps(string[] mods)
{ {
var paths = mods.SelectMany(p => FindMapsIn("mods{0}{1}{0}maps{0}".F(Path.DirectorySeparatorChar, p))) var paths = mods.SelectMany(p => FindMapsIn("mods{0}{1}{0}maps{0}".F(Path.DirectorySeparatorChar, p)))
.Concat(mods.SelectMany(p => FindMapsIn("{1}maps{0}{2}{0}".F(Path.DirectorySeparatorChar, Platform.SupportDir, p)))); .Concat(mods.SelectMany(p => FindMapsIn("{1}maps{0}{2}{0}".F(Path.DirectorySeparatorChar, Platform.SupportDir, p))));
var ret = new Dictionary<string, Map>(); var ret = new Dictionary<string, Map>();

View File

@@ -18,7 +18,7 @@ using OpenRA.Support;
namespace OpenRA.Network namespace OpenRA.Network
{ {
public enum ConnectionState public enum ConnectionState
{ {
PreConnecting, PreConnecting,
NotConnected, NotConnected,
@@ -26,7 +26,7 @@ namespace OpenRA.Network
Connected, Connected,
} }
public interface IConnection : IDisposable public interface IConnection : IDisposable
{ {
int LocalClientId { get; } int LocalClientId { get; }
ConnectionState ConnectionState { get; } ConnectionState ConnectionState { get; }

View File

@@ -44,17 +44,17 @@ namespace OpenRA.Network
frameData.Add( clientId, orders ); frameData.Add( clientId, orders );
} }
public bool IsReadyForFrame(int frame) public bool IsReadyForFrame(int frame)
{ {
return !ClientsNotReadyForFrame(frame).Any(); return !ClientsNotReadyForFrame(frame).Any();
} }
public IEnumerable<int> ClientsNotReadyForFrame(int frame) public IEnumerable<int> ClientsNotReadyForFrame(int frame)
{ {
var frameData = framePackets.GetOrAdd(frame); var frameData = framePackets.GetOrAdd(frame);
return ClientsPlayingInFrame(frame) return ClientsPlayingInFrame(frame)
.Where(client => !frameData.ContainsKey(client)); .Where(client => !frameData.ContainsKey(client));
} }
public IEnumerable<ClientOrder> OrdersForFrame( World world, int frame ) public IEnumerable<ClientOrder> OrdersForFrame( World world, int frame )
{ {

View File

@@ -67,7 +67,7 @@ namespace OpenRA
public Order(string orderstring, Order order) public Order(string orderstring, Order order)
: this(orderstring, order.Subject, order.TargetActor, order.TargetLocation, : this(orderstring, order.Subject, order.TargetActor, order.TargetLocation,
order.TargetString, order.Queued, order.ExtraLocation) {} order.TargetString, order.Queued, order.ExtraLocation) {}
public byte[] Serialize() public byte[] Serialize()
{ {
@@ -85,7 +85,7 @@ namespace OpenRA
{ {
// Format: // Format:
// u8 : orderID. // u8 : orderID.
// 0xFF: Full serialized order. // 0xFF: Full serialized order.
// varies: rest of order. // varies: rest of order.
default: default:
// TODO: specific serializers for specific orders. // TODO: specific serializers for specific orders.

View File

@@ -16,7 +16,7 @@ using OpenRA.FileFormats;
namespace OpenRA.Network namespace OpenRA.Network
{ {
public class OrderManager : IDisposable public class OrderManager : IDisposable
{ {
readonly SyncReport syncReport; readonly SyncReport syncReport;
readonly FrameData frameData = new FrameData(); readonly FrameData frameData = new FrameData();
@@ -157,17 +157,17 @@ namespace OpenRA.Network
get { return NetFrameNumber >= 1 && frameData.IsReadyForFrame( NetFrameNumber ); } get { return NetFrameNumber >= 1 && frameData.IsReadyForFrame( NetFrameNumber ); }
} }
static readonly IEnumerable<Session.Client> NoClients = new Session.Client[] {}; static readonly IEnumerable<Session.Client> NoClients = new Session.Client[] {};
public IEnumerable<Session.Client> GetClientsNotReadyForNextFrame public IEnumerable<Session.Client> GetClientsNotReadyForNextFrame
{ {
get get
{ {
return NetFrameNumber >= 1 return NetFrameNumber >= 1
? frameData.ClientsNotReadyForFrame(NetFrameNumber) ? frameData.ClientsNotReadyForFrame(NetFrameNumber)
.Select(a => LobbyInfo.ClientWithIndex(a)) .Select(a => LobbyInfo.ClientWithIndex(a))
: NoClients; : NoClients;
} }
} }
public void Tick() public void Tick()
{ {

View File

@@ -47,7 +47,7 @@ namespace OpenRA.Network
public class Client public class Client
{ {
public int Index; public int Index;
public ColorRamp ColorRamp; public ColorRamp ColorRamp;
public string Country; public string Country;
public int SpawnPoint; public int SpawnPoint;
public string Name; public string Name;

View File

@@ -65,8 +65,8 @@ namespace OpenRA.Network
a.ActorID, a.ActorID,
a.Type, a.Type,
a.Owner, a.Owner,
a.Trait, a.Trait,
a.Hash a.Hash
)); ));
return; return;
} }

View File

@@ -68,7 +68,7 @@ namespace OpenRA.Network
if (world == null) if (world == null)
{ {
if (client.Team == orderManager.LocalClient.Team) if (client.Team == orderManager.LocalClient.Team)
Game.AddChatLine(client.ColorRamp.GetColor(0), client.Name + " (Team)", Game.AddChatLine(client.ColorRamp.GetColor(0), client.Name + " (Team)",
order.TargetString); order.TargetString);
} }
else else
@@ -85,7 +85,7 @@ namespace OpenRA.Network
var suffix = (player != null && player.WinState == WinState.Lost) var suffix = (player != null && player.WinState == WinState.Lost)
? " (Dead)" ? " (Dead)"
: " (Team)"; : " (Team)";
Game.AddChatLine(client.ColorRamp.GetColor(0), client.Name + suffix, order.TargetString); Game.AddChatLine(client.ColorRamp.GetColor(0), client.Name + suffix, order.TargetString);
} }
} }
} }

View File

@@ -19,21 +19,21 @@ namespace OpenRA.Orders
{ {
public IEnumerable<Order> Order( World world, int2 xy, MouseInput mi ) public IEnumerable<Order> Order( World world, int2 xy, MouseInput mi )
{ {
var underCursor = world.FindUnitsAtMouse(mi.Location) var underCursor = world.FindUnitsAtMouse(mi.Location)
.Where(a => a.HasTrait<ITargetable>()) .Where(a => a.HasTrait<ITargetable>())
.OrderByDescending( .OrderByDescending(
a => a =>
a.Info.Traits.Contains<SelectableInfo>() a.Info.Traits.Contains<SelectableInfo>()
? a.Info.Traits.Get<SelectableInfo>().Priority ? a.Info.Traits.Get<SelectableInfo>().Priority
: int.MinValue) : int.MinValue)
.FirstOrDefault(); .FirstOrDefault();
var orders = world.Selection.Actors var orders = world.Selection.Actors
.Select(a => OrderForUnit(a, xy, mi, underCursor)) .Select(a => OrderForUnit(a, xy, mi, underCursor))
.Where(o => o != null) .Where(o => o != null)
.ToArray(); .ToArray();
var actorsInvolved = orders.Select(o => o.self).Distinct(); var actorsInvolved = orders.Select(o => o.self).Distinct();
if (actorsInvolved.Any()) if (actorsInvolved.Any())
yield return new Order("CreateGroup", actorsInvolved.First().Owner.PlayerActor, false) yield return new Order("CreateGroup", actorsInvolved.First().Owner.PlayerActor, false)
{ {
@@ -41,8 +41,8 @@ namespace OpenRA.Orders
}; };
foreach (var o in orders) foreach (var o in orders)
yield return CheckSameOrder(o.iot, o.trait.IssueOrder(o.self, o.iot, o.target, mi.Modifiers.HasModifier(Modifiers.Shift))); yield return CheckSameOrder(o.iot, o.trait.IssueOrder(o.self, o.iot, o.target, mi.Modifiers.HasModifier(Modifiers.Shift)));
} }
public void Tick( World world ) { } public void Tick( World world ) { }

View File

@@ -60,7 +60,7 @@ namespace OpenRA
if (client != null) if (client != null)
{ {
ClientIndex = client.Index; ClientIndex = client.Index;
ColorRamp = client.ColorRamp; ColorRamp = client.ColorRamp;
PlayerName = client.Name; PlayerName = client.Name;
botType = client.Bot; botType = client.Bot;
Country = ChooseCountry(world, client.Country); Country = ChooseCountry(world, client.Country);

View File

@@ -133,7 +133,7 @@ namespace OpenRA.Server
{ {
for (var i = 0; i < 256; i++) for (var i = 0; i < 256; i++)
if (conns.All(c => c.PlayerIndex != i) && preConns.All(c => c.PlayerIndex != i) if (conns.All(c => c.PlayerIndex != i) && preConns.All(c => c.PlayerIndex != i)
&& lobbyInfo.Clients.All(c => c.Index != i)) && lobbyInfo.Clients.All(c => c.Index != i))
return i; return i;
throw new InvalidOperationException("Already got 256 players"); throw new InvalidOperationException("Already got 256 players");
@@ -198,9 +198,9 @@ namespace OpenRA.Server
// Check that the client has compatable mods // Check that the client has compatable mods
var valid = mods.All( m => m.Contains('@')) && //valid format var valid = mods.All( m => m.Contains('@')) && //valid format
mods.Count() == Game.CurrentMods.Count() && //same number mods.Count() == Game.CurrentMods.Count() && //same number
mods.Select( m => Pair.New(m.Split('@')[0], m.Split('@')[1])).All(kv => Game.CurrentMods.ContainsKey(kv.First) && mods.Select( m => Pair.New(m.Split('@')[0], m.Split('@')[1])).All(kv => Game.CurrentMods.ContainsKey(kv.First) &&
(kv.Second == "{DEV_VERSION}" || Game.CurrentMods[kv.First].Version == "{DEV_VERSION}" || kv.Second == Game.CurrentMods[kv.First].Version)); (kv.Second == "{DEV_VERSION}" || Game.CurrentMods[kv.First].Version == "{DEV_VERSION}" || kv.Second == Game.CurrentMods[kv.First].Version));
if (!valid) if (!valid)
{ {
Log.Write("server", "Rejected connection from {0}; mods do not match.", Log.Write("server", "Rejected connection from {0}; mods do not match.",
@@ -241,7 +241,7 @@ namespace OpenRA.Server
if (pr == null) if (pr == null)
return; return;
if (pr.LockColor) if (pr.LockColor)
c.ColorRamp = pr.ColorRamp; c.ColorRamp = pr.ColorRamp;
if (pr.LockRace) if (pr.LockRace)
c.Country = pr.Race; c.Country = pr.Race;
if (pr.LockSpawn) if (pr.LockSpawn)
@@ -319,15 +319,15 @@ namespace OpenRA.Server
new ServerOrder(order, data).Serialize()); new ServerOrder(order, data).Serialize());
} }
public void SendChat(Connection asConn, string text) public void SendChat(Connection asConn, string text)
{ {
DispatchOrders(asConn, 0, new ServerOrder("Chat", text).Serialize()); DispatchOrders(asConn, 0, new ServerOrder("Chat", text).Serialize());
} }
public void SendDisconnected(Connection asConn) public void SendDisconnected(Connection asConn)
{ {
DispatchOrders(asConn, 0, new ServerOrder("Disconnected", "").Serialize()); DispatchOrders(asConn, 0, new ServerOrder("Disconnected", "").Serialize());
} }
void InterpretServerOrder(Connection conn, ServerOrder so) void InterpretServerOrder(Connection conn, ServerOrder so)
{ {
@@ -374,8 +374,8 @@ namespace OpenRA.Server
conns.Remove(toDrop); conns.Remove(toDrop);
SendChat(toDrop, "Connection Dropped"); SendChat(toDrop, "Connection Dropped");
if (GameStarted) if (GameStarted)
SendDisconnected(toDrop); /* Report disconnection */ SendDisconnected(toDrop); /* Report disconnection */
lobbyInfo.Clients.RemoveAll(c => c.Index == toDrop.PlayerIndex); lobbyInfo.Clients.RemoveAll(c => c.Index == toDrop.PlayerIndex);

View File

@@ -29,7 +29,7 @@ namespace OpenRA
static ISoundSource LoadSound(string filename) static ISoundSource LoadSound(string filename)
{ {
return LoadSoundRaw(AudLoader.LoadSound(FileSystem.Open(filename))); return LoadSoundRaw(AudLoader.LoadSound(FileSystem.Open(filename)));
} }
static ISoundSource LoadSoundRaw(byte[] rawData) static ISoundSource LoadSoundRaw(byte[] rawData)

View File

@@ -142,7 +142,7 @@ namespace OpenRA
public static T CheckSyncUnchanged<T>( World world, Func<T> fn ) public static T CheckSyncUnchanged<T>( World world, Func<T> fn )
{ {
if( world == null ) return fn(); if( world == null ) return fn();
var shouldCheckSync = Game.Settings.Debug.SanityCheckUnsyncedCode; var shouldCheckSync = Game.Settings.Debug.SanityCheckUnsyncedCode;
int sync = shouldCheckSync ? world.SyncHash() : 0; int sync = shouldCheckSync ? world.SyncHash() : 0;
bool prevInUnsyncedCode = inUnsyncedCode; bool prevInUnsyncedCode = inUnsyncedCode;
inUnsyncedCode = true; inUnsyncedCode = true;

View File

@@ -36,8 +36,8 @@ namespace OpenRA.Traits
Info = info; Info = info;
MaxHP = info.HP; MaxHP = info.HP;
hp = init.Contains<HealthInit>() ? (int)(init.Get<HealthInit, float>() * MaxHP) : MaxHP; hp = init.Contains<HealthInit>() ? (int)(init.Get<HealthInit, float>() * MaxHP) : MaxHP;
DisplayHp = hp; DisplayHp = hp;
} }
public int HP { get { return hp; } } public int HP { get { return hp; } }
@@ -75,7 +75,7 @@ namespace OpenRA.Traits
var oldState = this.DamageState; var oldState = this.DamageState;
/* apply the damage modifiers, if we have any. */ /* apply the damage modifiers, if we have any. */
var modifier = (float)self.TraitsImplementing<IDamageModifier>() var modifier = (float)self.TraitsImplementing<IDamageModifier>()
.Concat(self.Owner.PlayerActor.TraitsImplementing<IDamageModifier>()) .Concat(self.Owner.PlayerActor.TraitsImplementing<IDamageModifier>())
.Select(t => t.GetDamageModifier(attacker, warhead)).Product(); .Select(t => t.GetDamageModifier(attacker, warhead)).Product();
@@ -93,8 +93,8 @@ namespace OpenRA.Traits
Warhead = warhead, Warhead = warhead,
}; };
foreach (var nd in self.TraitsImplementing<INotifyDamage>() foreach (var nd in self.TraitsImplementing<INotifyDamage>()
.Concat(self.Owner.PlayerActor.TraitsImplementing<INotifyDamage>())) .Concat(self.Owner.PlayerActor.TraitsImplementing<INotifyDamage>()))
nd.Damaged(self, ai); nd.Damaged(self, ai);
if (DamageState != oldState) if (DamageState != oldState)
@@ -103,7 +103,7 @@ namespace OpenRA.Traits
if (attacker != null && attacker.IsInWorld && !attacker.IsDead()) if (attacker != null && attacker.IsInWorld && !attacker.IsDead())
foreach (var nd in attacker.TraitsImplementing<INotifyAppliedDamage>() foreach (var nd in attacker.TraitsImplementing<INotifyAppliedDamage>()
.Concat(attacker.Owner.PlayerActor.TraitsImplementing<INotifyAppliedDamage>())) .Concat(attacker.Owner.PlayerActor.TraitsImplementing<INotifyAppliedDamage>()))
nd.AppliedDamage(attacker, self, ai); nd.AppliedDamage(attacker, self, ai);
if (hp == 0) if (hp == 0)
@@ -112,7 +112,7 @@ namespace OpenRA.Traits
self.Owner.Deaths++; self.Owner.Deaths++;
foreach (var nd in self.TraitsImplementing<INotifyKilled>() foreach (var nd in self.TraitsImplementing<INotifyKilled>()
.Concat(self.Owner.PlayerActor.TraitsImplementing<INotifyKilled>())) .Concat(self.Owner.PlayerActor.TraitsImplementing<INotifyKilled>()))
nd.Killed(self, ai); nd.Killed(self, ai);
if( RemoveOnDeath ) if( RemoveOnDeath )

View File

@@ -20,7 +20,7 @@ namespace OpenRA.Traits
public bool DisableShroud = false; public bool DisableShroud = false;
public bool PathDebug = false; public bool PathDebug = false;
public bool UnlimitedPower; public bool UnlimitedPower;
public bool BuildAnywhere; public bool BuildAnywhere;
public object Create (ActorInitializer init) { return new DeveloperMode(this); } public object Create (ActorInitializer init) { return new DeveloperMode(this); }
} }
@@ -34,7 +34,7 @@ namespace OpenRA.Traits
[Sync] public bool DisableShroud; [Sync] public bool DisableShroud;
[Sync] public bool PathDebug; [Sync] public bool PathDebug;
[Sync] public bool UnlimitedPower; [Sync] public bool UnlimitedPower;
[Sync] public bool BuildAnywhere; [Sync] public bool BuildAnywhere;
public DeveloperMode(DeveloperModeInfo info) public DeveloperMode(DeveloperModeInfo info)
{ {
@@ -44,7 +44,7 @@ namespace OpenRA.Traits
DisableShroud = info.DisableShroud; DisableShroud = info.DisableShroud;
PathDebug = info.PathDebug; PathDebug = info.PathDebug;
UnlimitedPower = info.UnlimitedPower; UnlimitedPower = info.UnlimitedPower;
BuildAnywhere = info.BuildAnywhere; BuildAnywhere = info.BuildAnywhere;
} }
public void ResolveOrder (Actor self, Order order) public void ResolveOrder (Actor self, Order order)
@@ -96,11 +96,11 @@ namespace OpenRA.Traits
UnlimitedPower ^= true; UnlimitedPower ^= true;
break; break;
} }
case "DevBuildAnywhere": case "DevBuildAnywhere":
{ {
BuildAnywhere ^= true; BuildAnywhere ^= true;
break; break;
} }
default: default:
return; return;
} }

View File

@@ -136,7 +136,7 @@ namespace OpenRA.Traits
var eva = self.World.WorldActor.Info.Traits.Get<EvaAlertsInfo>(); var eva = self.World.WorldActor.Info.Traits.Get<EvaAlertsInfo>();
OreCapacity = self.World.ActorsWithTrait<IStoreOre>() OreCapacity = self.World.ActorsWithTrait<IStoreOre>()
.Where(a => a.Actor.Owner == Owner) .Where(a => a.Actor.Owner == Owner)
.Sum(a => a.Trait.Capacity); .Sum(a => a.Trait.Capacity);
if (Ore > OreCapacity) if (Ore > OreCapacity)

View File

@@ -18,117 +18,117 @@ using OpenRA.Network;
namespace OpenRA.Traits namespace OpenRA.Traits
{ {
// depends on the order of pips in WorldRenderer.cs! // depends on the order of pips in WorldRenderer.cs!
public enum PipType { Transparent, Green, Yellow, Red, Gray, Blue }; public enum PipType { Transparent, Green, Yellow, Red, Gray, Blue };
public enum TagType { None, Fake, Primary }; public enum TagType { None, Fake, Primary };
public enum Stance { Enemy, Neutral, Ally }; public enum Stance { Enemy, Neutral, Ally };
public class AttackInfo public class AttackInfo
{ {
public Actor Attacker; public Actor Attacker;
public WarheadInfo Warhead; public WarheadInfo Warhead;
public int Damage; public int Damage;
public DamageState DamageState; public DamageState DamageState;
public DamageState PreviousDamageState; public DamageState PreviousDamageState;
} }
public interface ITick { void Tick(Actor self); } public interface ITick { void Tick(Actor self); }
public interface IRender { IEnumerable<Renderable> Render(Actor self); } public interface IRender { IEnumerable<Renderable> Render(Actor self); }
public interface IIssueOrder public interface IIssueOrder
{ {
IEnumerable<IOrderTargeter> Orders { get; } IEnumerable<IOrderTargeter> Orders { get; }
Order IssueOrder(Actor self, IOrderTargeter order, Target target, bool queued); Order IssueOrder(Actor self, IOrderTargeter order, Target target, bool queued);
} }
public interface IOrderTargeter public interface IOrderTargeter
{ {
string OrderID { get; } string OrderID { get; }
int OrderPriority { get; } int OrderPriority { get; }
bool CanTargetActor(Actor self, Actor target, bool forceAttack, bool forceQueue, ref string cursor); bool CanTargetActor(Actor self, Actor target, bool forceAttack, bool forceQueue, ref string cursor);
bool CanTargetLocation(Actor self, int2 location, List<Actor> actorsAtLocation, bool forceAttack, bool forceQueue, ref string cursor); bool CanTargetLocation(Actor self, int2 location, List<Actor> actorsAtLocation, bool forceAttack, bool forceQueue, ref string cursor);
bool IsQueued { get; } bool IsQueued { get; }
} }
public interface IResolveOrder { void ResolveOrder(Actor self, Order order); } public interface IResolveOrder { void ResolveOrder(Actor self, Order order); }
public interface IValidateOrder { bool OrderValidation(OrderManager orderManager, World world, int clientId, Order order); } public interface IValidateOrder { bool OrderValidation(OrderManager orderManager, World world, int clientId, Order order); }
public interface IOrderVoice { string VoicePhraseForOrder(Actor self, Order order); } public interface IOrderVoice { string VoicePhraseForOrder(Actor self, Order order); }
public interface INotifySold { void Selling(Actor self); void Sold(Actor self); } public interface INotifySold { void Selling(Actor self); void Sold(Actor self); }
public interface INotifyDamage { void Damaged(Actor self, AttackInfo e); } public interface INotifyDamage { void Damaged(Actor self, AttackInfo e); }
public interface INotifyDamageStateChanged { void DamageStateChanged(Actor self, AttackInfo e); } public interface INotifyDamageStateChanged { void DamageStateChanged(Actor self, AttackInfo e); }
public interface INotifyKilled { void Killed(Actor self, AttackInfo e); } public interface INotifyKilled { void Killed(Actor self, AttackInfo e); }
public interface INotifyAppliedDamage { void AppliedDamage(Actor self, Actor damaged, AttackInfo e); } public interface INotifyAppliedDamage { void AppliedDamage(Actor self, Actor damaged, AttackInfo e); }
public interface INotifyBuildComplete { void BuildingComplete(Actor self); } public interface INotifyBuildComplete { void BuildingComplete(Actor self); }
public interface INotifyProduction { void UnitProduced(Actor self, Actor other, int2 exit); } public interface INotifyProduction { void UnitProduced(Actor self, Actor other, int2 exit); }
public interface INotifyCapture { void OnCapture(Actor self, Actor captor, Player oldOwner, Player newOwner); } public interface INotifyCapture { void OnCapture(Actor self, Actor captor, Player oldOwner, Player newOwner); }
public interface INotifyOtherCaptured { void OnActorCaptured(Actor self, Actor captured, Actor captor, Player oldOwner, Player newOwner); } public interface INotifyOtherCaptured { void OnActorCaptured(Actor self, Actor captured, Actor captor, Player oldOwner, Player newOwner); }
public interface IAcceptSpy { void OnInfiltrate(Actor self, Actor spy); } public interface IAcceptSpy { void OnInfiltrate(Actor self, Actor spy); }
public interface IStoreOre { int Capacity { get; } } public interface IStoreOre { int Capacity { get; } }
public interface IToolTip public interface IToolTip
{ {
string Name(); string Name();
Player Owner(); Player Owner();
Stance Stance(); Stance Stance();
} }
public interface IDisable { bool Disabled { get; } } public interface IDisable { bool Disabled { get; } }
public interface IExplodeModifier { bool ShouldExplode(Actor self); } public interface IExplodeModifier { bool ShouldExplode(Actor self); }
public interface IHuskModifier { string HuskActor(Actor self); } public interface IHuskModifier { string HuskActor(Actor self); }
public interface INudge { void OnNudge(Actor self, Actor nudger, bool force); } public interface INudge { void OnNudge(Actor self, Actor nudger, bool force); }
public interface IRadarSignature public interface IRadarSignature
{ {
IEnumerable<int2> RadarSignatureCells(Actor self); IEnumerable<int2> RadarSignatureCells(Actor self);
Color RadarSignatureColor(Actor self); Color RadarSignatureColor(Actor self);
} }
public interface IVisibilityModifier { bool IsVisible(Actor self); } public interface IVisibilityModifier { bool IsVisible(Actor self); }
public interface IRadarColorModifier { Color RadarColorOverride(Actor self); } public interface IRadarColorModifier { Color RadarColorOverride(Actor self); }
public interface IHasLocation { int2 PxPosition { get; } } public interface IHasLocation { int2 PxPosition { get; } }
public interface IOccupySpace : IHasLocation public interface IOccupySpace : IHasLocation
{ {
int2 TopLeft { get; } int2 TopLeft { get; }
IEnumerable<Pair<int2, SubCell>> OccupiedCells(); IEnumerable<Pair<int2, SubCell>> OccupiedCells();
} }
public static class IOccupySpaceExts public static class IOccupySpaceExts
{ {
public static int2 NearestCellTo(this IOccupySpace ios, int2 other) public static int2 NearestCellTo(this IOccupySpace ios, int2 other)
{ {
var nearest = ios.TopLeft; var nearest = ios.TopLeft;
var nearestDistance = int.MaxValue; var nearestDistance = int.MaxValue;
foreach (var cell in ios.OccupiedCells()) foreach (var cell in ios.OccupiedCells())
{ {
var dist = (other - cell.First).LengthSquared; var dist = (other - cell.First).LengthSquared;
if (dist < nearestDistance) if (dist < nearestDistance)
{ {
nearest = cell.First; nearest = cell.First;
nearestDistance = dist; nearestDistance = dist;
} }
} }
return nearest; return nearest;
} }
} }
public interface INotifyAttack { void Attacking(Actor self, Target target); } public interface INotifyAttack { void Attacking(Actor self, Target target); }
public interface IRenderModifier { IEnumerable<Renderable> ModifyRender(Actor self, IEnumerable<Renderable> r); } public interface IRenderModifier { IEnumerable<Renderable> ModifyRender(Actor self, IEnumerable<Renderable> r); }
public interface IDamageModifier { float GetDamageModifier(Actor attacker, WarheadInfo warhead); } public interface IDamageModifier { float GetDamageModifier(Actor attacker, WarheadInfo warhead); }
public interface ISpeedModifier { decimal GetSpeedModifier(); } public interface ISpeedModifier { decimal GetSpeedModifier(); }
public interface IFirepowerModifier { float GetFirepowerModifier(); } public interface IFirepowerModifier { float GetFirepowerModifier(); }
public interface IPalette { void InitPalette(WorldRenderer wr); } public interface IPalette { void InitPalette(WorldRenderer wr); }
public interface IPaletteModifier { void AdjustPalette(Dictionary<string, Palette> b); } public interface IPaletteModifier { void AdjustPalette(Dictionary<string, Palette> b); }
public interface IPips { IEnumerable<PipType> GetPips(Actor self); } public interface IPips { IEnumerable<PipType> GetPips(Actor self); }
public interface ITags { IEnumerable<TagType> GetTags(); } public interface ITags { IEnumerable<TagType> GetTags(); }
public interface ISelectionBar { float GetValue(); Color GetColor(); } public interface ISelectionBar { float GetValue(); Color GetColor(); }
public interface ITeleportable : IHasLocation /* crap name! */ public interface ITeleportable : IHasLocation /* crap name! */
{ {
bool CanEnterCell(int2 location); bool CanEnterCell(int2 location);
void SetPosition(Actor self, int2 cell); void SetPosition(Actor self, int2 cell);
void SetPxPosition(Actor self, int2 px); void SetPxPosition(Actor self, int2 px);
void AdjustPxPosition(Actor self, int2 px); /* works like SetPxPosition, but visual only */ void AdjustPxPosition(Actor self, int2 px); /* works like SetPxPosition, but visual only */
} }
public interface IMove : ITeleportable { int Altitude { get; set; } } public interface IMove : ITeleportable { int Altitude { get; set; } }
@@ -141,86 +141,86 @@ namespace OpenRA.Traits
public interface IFacingInfo {} /* tag interface for infoclasses whose corresponding trait has IFacing */ public interface IFacingInfo {} /* tag interface for infoclasses whose corresponding trait has IFacing */
public interface ICrushable public interface ICrushable
{ {
void OnCrush(Actor crusher); void OnCrush(Actor crusher);
void WarnCrush(Actor crusher); void WarnCrush(Actor crusher);
bool CrushableBy(string[] crushClasses, Player owner); bool CrushableBy(string[] crushClasses, Player owner);
} }
public struct Renderable public struct Renderable
{ {
public readonly Sprite Sprite; public readonly Sprite Sprite;
public readonly float2 Pos; public readonly float2 Pos;
public readonly string Palette; public readonly string Palette;
public readonly int Z; public readonly int Z;
public readonly int ZOffset; public readonly int ZOffset;
public float Scale; public float Scale;
public Renderable(Sprite sprite, float2 pos, string palette, int z, int zOffset, float scale) public Renderable(Sprite sprite, float2 pos, string palette, int z, int zOffset, float scale)
{ {
Sprite = sprite; Sprite = sprite;
Pos = pos; Pos = pos;
Palette = palette; Palette = palette;
Z = z; Z = z;
ZOffset = zOffset; ZOffset = zOffset;
Scale = scale; /* default */ Scale = scale; /* default */
} }
public Renderable(Sprite sprite, float2 pos, string palette, int z) public Renderable(Sprite sprite, float2 pos, string palette, int z)
: this(sprite, pos, palette, z, 0, 1f) { } : this(sprite, pos, palette, z, 0, 1f) { }
public Renderable(Sprite sprite, float2 pos, string palette, int z, float scale) public Renderable(Sprite sprite, float2 pos, string palette, int z, float scale)
: this(sprite, pos, palette, z, 0, scale) { } : this(sprite, pos, palette, z, 0, scale) { }
public Renderable WithScale(float newScale) { return new Renderable(Sprite, Pos, Palette, Z, ZOffset, newScale); } public Renderable WithScale(float newScale) { return new Renderable(Sprite, Pos, Palette, Z, ZOffset, newScale); }
public Renderable WithPalette(string newPalette) { return new Renderable(Sprite, Pos, newPalette, Z, ZOffset, Scale); } public Renderable WithPalette(string newPalette) { return new Renderable(Sprite, Pos, newPalette, Z, ZOffset, Scale); }
public Renderable WithZOffset(int newOffset) { return new Renderable(Sprite, Pos, Palette, Z, newOffset, Scale); } public Renderable WithZOffset(int newOffset) { return new Renderable(Sprite, Pos, Palette, Z, newOffset, Scale); }
public Renderable WithPos(float2 newPos) { return new Renderable(Sprite, newPos, Palette, Z, ZOffset, Scale); } public Renderable WithPos(float2 newPos) { return new Renderable(Sprite, newPos, Palette, Z, ZOffset, Scale); }
} }
public interface ITraitInfo { object Create(ActorInitializer init); } public interface ITraitInfo { object Create(ActorInitializer init); }
public class TraitInfo<T> : ITraitInfo where T : new() { public virtual object Create(ActorInitializer init) { return new T(); } } public class TraitInfo<T> : ITraitInfo where T : new() { public virtual object Create(ActorInitializer init) { return new T(); } }
public interface Requires<T> where T : class { } public interface Requires<T> where T : class { }
public interface INotifySelection { void SelectionChanged(); } public interface INotifySelection { void SelectionChanged(); }
public interface IWorldLoaded { void WorldLoaded(World w); } public interface IWorldLoaded { void WorldLoaded(World w); }
public interface ICreatePlayers { void CreatePlayers(World w); } public interface ICreatePlayers { void CreatePlayers(World w); }
public interface IBotInfo { string Name { get; } } public interface IBotInfo { string Name { get; } }
public interface IBot public interface IBot
{ {
void Activate(Player p); void Activate(Player p);
IBotInfo Info { get; } IBotInfo Info { get; }
} }
public interface IRenderOverlay { void Render(WorldRenderer wr); } public interface IRenderOverlay { void Render(WorldRenderer wr); }
public interface INotifyIdle { void TickIdle(Actor self); } public interface INotifyIdle { void TickIdle(Actor self); }
public interface IBlocksBullets { } public interface IBlocksBullets { }
public interface IPostRender { void RenderAfterWorld(WorldRenderer wr, Actor self); } public interface IPostRender { void RenderAfterWorld(WorldRenderer wr, Actor self); }
public interface IPostRenderSelection { void RenderAfterWorld(WorldRenderer wr, Actor self); } public interface IPostRenderSelection { void RenderAfterWorld(WorldRenderer wr, Actor self); }
public interface IPreRenderSelection { void RenderBeforeWorld(WorldRenderer wr, Actor self); } public interface IPreRenderSelection { void RenderBeforeWorld(WorldRenderer wr, Actor self); }
public interface IRenderAsTerrain { IEnumerable<Renderable> RenderAsTerrain(Actor self); } public interface IRenderAsTerrain { IEnumerable<Renderable> RenderAsTerrain(Actor self); }
public interface ITargetable public interface ITargetable
{ {
string[] TargetTypes { get; } string[] TargetTypes { get; }
IEnumerable<int2> TargetableCells(Actor self); IEnumerable<int2> TargetableCells(Actor self);
bool TargetableBy(Actor self, Actor byActor); bool TargetableBy(Actor self, Actor byActor);
} }
public interface INotifyStanceChanged public interface INotifyStanceChanged
{ {
void StanceChanged(Actor self, Player a, Player b, void StanceChanged(Actor self, Player a, Player b,
Stance oldStance, Stance newStance); Stance oldStance, Stance newStance);
} }
public interface ILintPass { void Run(Action<string> emitError, Action<string> emitWarning); } public interface ILintPass { void Run(Action<string> emitError, Action<string> emitWarning); }
public interface IObjectivesPanel { string ObjectivesPanel { get; } } public interface IObjectivesPanel { string ObjectivesPanel { get; } }
} }

View File

@@ -122,17 +122,17 @@ namespace OpenRA.Traits
public static int2 CellContaining(float2 pos) { return (1f / Game.CellSize * pos).ToInt2(); } public static int2 CellContaining(float2 pos) { return (1f / Game.CellSize * pos).ToInt2(); }
/* pretty crap */ /* pretty crap */
public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> ts, Thirdparty.Random random) public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> ts, Thirdparty.Random random)
{ {
var items = ts.ToList(); var items = ts.ToList();
while (items.Count > 0) while (items.Count > 0)
{ {
var t = items.Random(random); var t = items.Random(random);
yield return t; yield return t;
items.Remove(t); items.Remove(t);
} }
} }
static IEnumerable<int2> Neighbours(int2 c, bool allowDiagonal) static IEnumerable<int2> Neighbours(int2 c, bool allowDiagonal)
{ {

View File

@@ -15,10 +15,10 @@ namespace OpenRA.Traits
{ {
public class ValidateOrderInfo : TraitInfo<ValidateOrder> { } public class ValidateOrderInfo : TraitInfo<ValidateOrder> { }
public class ValidateOrder : IValidateOrder public class ValidateOrder : IValidateOrder
{ {
public bool OrderValidation(OrderManager orderManager, World world, int clientId, Order order) public bool OrderValidation(OrderManager orderManager, World world, int clientId, Order order)
{ {
if (order.Subject == null || order.Subject.Owner == null) if (order.Subject == null || order.Subject.Owner == null)
return true; return true;
@@ -36,12 +36,12 @@ namespace OpenRA.Traits
// Drop exploiting orders // Drop exploiting orders
if (subjectClientId != clientId && !isBotOrder) if (subjectClientId != clientId && !isBotOrder)
{ {
Game.Debug("Detected exploit order from client {0}: {1}", clientId, order.OrderString); Game.Debug("Detected exploit order from client {0}: {1}", clientId, order.OrderString);
return false; return false;
} }
return true; return true;
} }
} }
} }

View File

@@ -37,7 +37,7 @@ namespace OpenRA.Traits
{ {
var paletteName = "{0}{1}".F( info.BaseName, owner.InternalName ); var paletteName = "{0}{1}".F( info.BaseName, owner.InternalName );
var newpal = new Palette(wr.GetPalette(info.BasePalette), var newpal = new Palette(wr.GetPalette(info.BasePalette),
new PlayerColorRemap(owner.ColorRamp, info.PaletteFormat)); new PlayerColorRemap(owner.ColorRamp, info.PaletteFormat));
wr.AddPalette(paletteName, newpal); wr.AddPalette(paletteName, newpal);
} }
} }

View File

@@ -64,16 +64,16 @@ namespace OpenRA.Traits
for (int x = map.Bounds.Left; x < map.Bounds.Right; x++) for (int x = map.Bounds.Left; x < map.Bounds.Right; x++)
for (int y = map.Bounds.Top; y < map.Bounds.Bottom; y++) for (int y = map.Bounds.Top; y < map.Bounds.Bottom; y++)
{ {
var type = resourceTypes.FirstOrDefault( var type = resourceTypes.FirstOrDefault(
r => r.info.ResourceType == w.Map.MapResources.Value[x, y].type); r => r.info.ResourceType == w.Map.MapResources.Value[x, y].type);
if (type == null) if (type == null)
continue; continue;
if (!AllowResourceAt(type, new int2(x,y))) if (!AllowResourceAt(type, new int2(x,y)))
continue; continue;
content[x, y].type = type; content[x, y].type = type;
content[x, y].image = ChooseContent(type); content[x, y].image = ChooseContent(type);
} }
@@ -86,13 +86,13 @@ namespace OpenRA.Traits
} }
} }
public bool AllowResourceAt(ResourceType rt, int2 a) public bool AllowResourceAt(ResourceType rt, int2 a)
{ {
if (!world.Map.IsInMap(a.X, a.Y)) return false; if (!world.Map.IsInMap(a.X, a.Y)) return false;
if (!rt.info.AllowedTerrainTypes.Contains(world.GetTerrainInfo(a).Type)) return false; if (!rt.info.AllowedTerrainTypes.Contains(world.GetTerrainInfo(a).Type)) return false;
if (!rt.info.AllowUnderActors && world.ActorMap.AnyUnitsAt(a)) return false; if (!rt.info.AllowUnderActors && world.ActorMap.AnyUnitsAt(a)) return false;
return true; return true;
} }
Sprite[] ChooseContent(ResourceType t) Sprite[] ChooseContent(ResourceType t)
{ {

View File

@@ -22,8 +22,8 @@ namespace OpenRA.Traits
public readonly string Name = null; public readonly string Name = null;
public readonly string TerrainType = "Ore"; public readonly string TerrainType = "Ore";
public readonly string[] AllowedTerrainTypes = { }; public readonly string[] AllowedTerrainTypes = { };
public readonly bool AllowUnderActors = false; public readonly bool AllowUnderActors = false;
public Sprite[][] Sprites; public Sprite[][] Sprites;
public int PaletteIndex; public int PaletteIndex;

View File

@@ -19,7 +19,7 @@ namespace OpenRA.Traits
public class ScreenShaker : ITick public class ScreenShaker : ITick
{ {
int ticks = 0; int ticks = 0;
List<ShakeEffect> shakeEffects = new List<ShakeEffect>(); List<ShakeEffect> shakeEffects = new List<ShakeEffect>();
public void Tick (Actor self) public void Tick (Actor self)
{ {

View File

@@ -78,7 +78,7 @@ namespace OpenRA.Traits
return; return;
if (a.Owner == null || a.Owner.World.LocalPlayer == null if (a.Owner == null || a.Owner.World.LocalPlayer == null
|| a.Owner.Stances[a.Owner.World.LocalPlayer] != Stance.Ally) return; || a.Owner.Stances[a.Owner.World.LocalPlayer] != Stance.Ally) return;
if (vis.ContainsKey(a)) if (vis.ContainsKey(a))
{ {
@@ -160,7 +160,7 @@ namespace OpenRA.Traits
public void UpdateActor(Actor a) public void UpdateActor(Actor a)
{ {
if (a.Owner == null || a.Owner.World.LocalPlayer == null if (a.Owner == null || a.Owner.World.LocalPlayer == null
|| a.Owner.Stances[a.Owner.World.LocalPlayer] != Stance.Ally) return; || a.Owner.Stances[a.Owner.World.LocalPlayer] != Stance.Ally) return;
RemoveActor(a); AddActor(a); RemoveActor(a); AddActor(a);
} }

View File

@@ -27,7 +27,7 @@ namespace OpenRA.Widgets
public Func<string> GetText; public Func<string> GetText;
public Func<bool> IsDisabled = () => false; public Func<bool> IsDisabled = () => false;
public Action<MouseInput> OnMouseDown = _ => {}; public Action<MouseInput> OnMouseDown = _ => {};
public Action<MouseInput> OnMouseUp = _ => {}; public Action<MouseInput> OnMouseUp = _ => {};
// Equivalent to OnMouseUp, but without an input arg // Equivalent to OnMouseUp, but without an input arg
public Action OnClick = () => {}; public Action OnClick = () => {};
@@ -130,7 +130,7 @@ namespace OpenRA.Widgets
DrawBackground(rb, disabled, Depressed, Widget.MouseOverWidget == this); DrawBackground(rb, disabled, Depressed, Widget.MouseOverWidget == this);
font.DrawText(text, new int2(rb.X + (UsableWidth - s.X)/ 2, rb.Y + (Bounds.Height - s.Y) / 2) + stateOffset, font.DrawText(text, new int2(rb.X + (UsableWidth - s.X)/ 2, rb.Y + (Bounds.Height - s.Y) / 2) + stateOffset,
disabled ? Color.Gray : Color.White); disabled ? Color.Gray : Color.White);
} }
public override Widget Clone() { return new ButtonWidget(this); } public override Widget Clone() { return new ButtonWidget(this); }

View File

@@ -17,7 +17,7 @@ namespace OpenRA.Widgets
public class ChatDisplayWidget : Widget public class ChatDisplayWidget : Widget
{ {
public readonly int RemoveTime = 0; public readonly int RemoveTime = 0;
public readonly bool UseContrast = false; public readonly bool UseContrast = false;
const int logLength = 9; const int logLength = 9;
public string Notification = ""; public string Notification = "";
@@ -55,11 +55,11 @@ namespace OpenRA.Widgets
inset = font.Measure(owner).X + 10; inset = font.Measure(owner).X + 10;
font.DrawTextWithContrast(owner, chatpos, font.DrawTextWithContrast(owner, chatpos,
line.Color, Color.Black, UseContrast ? 1 : 0); line.Color, Color.Black, UseContrast ? 1 : 0);
} }
font.DrawTextWithContrast(line.Text, chatpos + new int2(inset, 0), font.DrawTextWithContrast(line.Text, chatpos + new int2(inset, 0),
Color.White, Color.Black, UseContrast ? 1 : 0); Color.White, Color.Black, UseContrast ? 1 : 0);
} }
Game.Renderer.DisableScissor(); Game.Renderer.DisableScissor();

View File

@@ -21,7 +21,7 @@ namespace OpenRA.Widgets
string content = ""; string content = "";
bool composing = false; bool composing = false;
bool teamChat = false; bool teamChat = false;
public readonly bool UseContrast = false; public readonly bool UseContrast = false;
readonly OrderManager orderManager; readonly OrderManager orderManager;

View File

@@ -104,27 +104,27 @@ namespace OpenRA.Widgets
} }
public class MaskWidget : Widget public class MaskWidget : Widget
{ {
public Action<MouseInput> OnMouseDown = _ => {}; public Action<MouseInput> OnMouseDown = _ => {};
public MaskWidget() : base() { } public MaskWidget() : base() { }
public MaskWidget(MaskWidget other) public MaskWidget(MaskWidget other)
: base(other) : base(other)
{ {
OnMouseDown = other.OnMouseDown; OnMouseDown = other.OnMouseDown;
} }
public override bool HandleMouseInput(MouseInput mi) public override bool HandleMouseInput(MouseInput mi)
{ {
if (mi.Event != MouseInputEvent.Down && mi.Event != MouseInputEvent.Up) if (mi.Event != MouseInputEvent.Down && mi.Event != MouseInputEvent.Up)
return false; return false;
if (mi.Event == MouseInputEvent.Down) if (mi.Event == MouseInputEvent.Down)
OnMouseDown(mi); OnMouseDown(mi);
return true; return true;
} }
public override string GetCursor(int2 pos) { return null; } public override string GetCursor(int2 pos) { return null; }
public override Widget Clone() { return new MaskWidget(this); } public override Widget Clone() { return new MaskWidget(this); }
} }
} }

View File

@@ -38,16 +38,16 @@ namespace OpenRA.Widgets
public override Widget Clone() { return new MapPreviewWidget(this); } public override Widget Clone() { return new MapPreviewWidget(this); }
public override bool HandleMouseInput(MouseInput mi) public override bool HandleMouseInput(MouseInput mi)
{ {
if (IgnoreMouseInput) if (IgnoreMouseInput)
return base.HandleMouseInput(mi); return base.HandleMouseInput(mi);
if (mi.Event != MouseInputEvent.Down) if (mi.Event != MouseInputEvent.Down)
return false; return false;
OnMouseDown(mi); OnMouseDown(mi);
return true; return true;
} }
public int2 ConvertToPreview(Map map, int2 point) public int2 ConvertToPreview(Map map, int2 point)
{ {

View File

@@ -27,7 +27,7 @@ namespace OpenRA.Widgets
Game.Renderer.LineRenderer.DrawLine(origin, origin + new float2(100, 0) * basis, Color.White, Color.White); Game.Renderer.LineRenderer.DrawLine(origin, origin + new float2(100, 0) * basis, Color.White, Color.White);
Game.Renderer.LineRenderer.DrawLine(origin + new float2(100, 0) * basis, origin + new float2(100, 100) * basis, Color.White, Color.White); Game.Renderer.LineRenderer.DrawLine(origin + new float2(100, 0) * basis, origin + new float2(100, 100) * basis, Color.White, Color.White);
int k = 0; int k = 0;
foreach (var item in PerfHistory.items.Values.ToArray()) foreach (var item in PerfHistory.items.Values.ToArray())
{ {
int n = 0; int n = 0;
@@ -41,19 +41,19 @@ namespace OpenRA.Widgets
return b; return b;
}); });
var u = new float2(rect.Left, rect.Top); var u = new float2(rect.Left, rect.Top);
Game.Renderer.LineRenderer.DrawLine( Game.Renderer.LineRenderer.DrawLine(
u + new float2(10, 10 * k + 5), u + new float2(10, 10 * k + 5),
u + new float2(12, 10 * k + 5), u + new float2(12, 10 * k + 5),
item.c, item.c); item.c, item.c);
Game.Renderer.LineRenderer.DrawLine( Game.Renderer.LineRenderer.DrawLine(
u + new float2(10, 10 * k + 4), u + new float2(10, 10 * k + 4),
u + new float2(12, 10 * k + 4), u + new float2(12, 10 * k + 4),
item.c, item.c); item.c, item.c);
++k; ++k;
} }
k = 0; k = 0;

View File

@@ -105,17 +105,17 @@ namespace OpenRA.Widgets
if(Keyboard != ScrollDirection.None || Edge != ScrollDirection.None) if(Keyboard != ScrollDirection.None || Edge != ScrollDirection.None)
{ {
var scroll = new float2(0, 0); var scroll = new float2(0, 0);
// Modified to use the ViewportEdgeScrollStep setting - Gecko // Modified to use the ViewportEdgeScrollStep setting - Gecko
if (Keyboard.Includes(ScrollDirection.Up) || Edge.Includes(ScrollDirection.Up)) if (Keyboard.Includes(ScrollDirection.Up) || Edge.Includes(ScrollDirection.Up))
scroll += new float2(0, -1); scroll += new float2(0, -1);
if (Keyboard.Includes(ScrollDirection.Right) || Edge.Includes(ScrollDirection.Right)) if (Keyboard.Includes(ScrollDirection.Right) || Edge.Includes(ScrollDirection.Right))
scroll += new float2(1, 0); scroll += new float2(1, 0);
if (Keyboard.Includes(ScrollDirection.Down) || Edge.Includes(ScrollDirection.Down)) if (Keyboard.Includes(ScrollDirection.Down) || Edge.Includes(ScrollDirection.Down))
scroll += new float2(0, 1); scroll += new float2(0, 1);
if (Keyboard.Includes(ScrollDirection.Left) || Edge.Includes(ScrollDirection.Left)) if (Keyboard.Includes(ScrollDirection.Left) || Edge.Includes(ScrollDirection.Left))
scroll += new float2(-1, 0); scroll += new float2(-1, 0);
float length = Math.Max(1, scroll.Length); float length = Math.Max(1, scroll.Length);
scroll.X = (scroll.X / length) * Game.Settings.Game.ViewportEdgeScrollStep; scroll.X = (scroll.X / length) * Game.Settings.Game.ViewportEdgeScrollStep;

View File

@@ -17,75 +17,75 @@ using OpenRA.Graphics;
namespace OpenRA.Widgets namespace OpenRA.Widgets
{ {
public abstract class Widget public abstract class Widget
{ {
public static Widget RootWidget public static Widget RootWidget
{ {
get { return rootWidget; } get { return rootWidget; }
set { rootWidget = value; } set { rootWidget = value; }
} }
static Widget rootWidget = new ContainerWidget(); static Widget rootWidget = new ContainerWidget();
static Stack<Widget> WindowList = new Stack<Widget>(); static Stack<Widget> WindowList = new Stack<Widget>();
public static Widget SelectedWidget; public static Widget SelectedWidget;
public static Widget MouseOverWidget; public static Widget MouseOverWidget;
public static void CloseWindow() public static void CloseWindow()
{ {
if (WindowList.Count > 0) if (WindowList.Count > 0)
RootWidget.RemoveChild(WindowList.Pop()); RootWidget.RemoveChild(WindowList.Pop());
if (WindowList.Count > 0) if (WindowList.Count > 0)
rootWidget.AddChild(WindowList.Peek()); rootWidget.AddChild(WindowList.Peek());
} }
public static Widget OpenWindow(string id) public static Widget OpenWindow(string id)
{ {
return OpenWindow(id, new WidgetArgs()); return OpenWindow(id, new WidgetArgs());
} }
public static Widget OpenWindow(string id, WidgetArgs args) public static Widget OpenWindow(string id, WidgetArgs args)
{ {
var window = Game.modData.WidgetLoader.LoadWidget(args, rootWidget, id); var window = Game.modData.WidgetLoader.LoadWidget(args, rootWidget, id);
if (WindowList.Count > 0) if (WindowList.Count > 0)
rootWidget.RemoveChild(WindowList.Peek()); rootWidget.RemoveChild(WindowList.Peek());
WindowList.Push(window); WindowList.Push(window);
return window; return window;
} }
public static Widget LoadWidget(string id, Widget parent, WidgetArgs args) public static Widget LoadWidget(string id, Widget parent, WidgetArgs args)
{ {
return Game.modData.WidgetLoader.LoadWidget(args, parent, id); return Game.modData.WidgetLoader.LoadWidget(args, parent, id);
} }
public static void DoTick() public static void DoTick()
{ {
RootWidget.TickOuter(); RootWidget.TickOuter();
} }
public static void DoDraw() public static void DoDraw()
{ {
RootWidget.DrawOuter(); RootWidget.DrawOuter();
} }
public static bool DoHandleInput(MouseInput mi) public static bool DoHandleInput(MouseInput mi)
{ {
var wasMouseOver = MouseOverWidget; var wasMouseOver = MouseOverWidget;
if (mi.Event == MouseInputEvent.Move) if (mi.Event == MouseInputEvent.Move)
MouseOverWidget = null; MouseOverWidget = null;
bool handled = false; bool handled = false;
if (SelectedWidget != null && SelectedWidget.HandleMouseInputOuter(mi)) if (SelectedWidget != null && SelectedWidget.HandleMouseInputOuter(mi))
handled = true; handled = true;
if (!handled && RootWidget.HandleMouseInputOuter(mi)) if (!handled && RootWidget.HandleMouseInputOuter(mi))
handled = true; handled = true;
if (mi.Event == MouseInputEvent.Move) if (mi.Event == MouseInputEvent.Move)
{ {
Viewport.LastMousePos = mi.Location; Viewport.LastMousePos = mi.Location;
Viewport.TicksSinceLastMove = 0; Viewport.TicksSinceLastMove = 0;
} }
if (wasMouseOver != MouseOverWidget) if (wasMouseOver != MouseOverWidget)
{ {
@@ -96,18 +96,18 @@ namespace OpenRA.Widgets
MouseOverWidget.MouseEntered(); MouseOverWidget.MouseEntered();
} }
return handled; return handled;
} }
public static bool DoHandleKeyPress(KeyInput e) public static bool DoHandleKeyPress(KeyInput e)
{ {
if (SelectedWidget != null) if (SelectedWidget != null)
return SelectedWidget.HandleKeyPressOuter(e); return SelectedWidget.HandleKeyPressOuter(e);
if (RootWidget.HandleKeyPressOuter(e)) if (RootWidget.HandleKeyPressOuter(e))
return true; return true;
return false; return false;
} }
public static void ResetAll() public static void ResetAll()
{ {
@@ -118,59 +118,59 @@ namespace OpenRA.Widgets
} }
// Info defined in YAML // Info defined in YAML
public string Id = null; public string Id = null;
public string X = "0"; public string X = "0";
public string Y = "0"; public string Y = "0";
public string Width = "0"; public string Width = "0";
public string Height = "0"; public string Height = "0";
public string Logic = null; public string Logic = null;
public object LogicObject { get; private set; } public object LogicObject { get; private set; }
public bool Visible = true; public bool Visible = true;
public bool IgnoreMouseOver; public bool IgnoreMouseOver;
public bool IgnoreChildMouseOver; public bool IgnoreChildMouseOver;
// Calculated internally // Calculated internally
public Rectangle Bounds; public Rectangle Bounds;
public Widget Parent = null; public Widget Parent = null;
public Func<bool> IsVisible; public Func<bool> IsVisible;
public Widget() { IsVisible = () => Visible; } public Widget() { IsVisible = () => Visible; }
public readonly List<Widget> Children = new List<Widget>(); public readonly List<Widget> Children = new List<Widget>();
public Widget(Widget widget) public Widget(Widget widget)
{ {
Id = widget.Id; Id = widget.Id;
X = widget.X; X = widget.X;
Y = widget.Y; Y = widget.Y;
Width = widget.Width; Width = widget.Width;
Height = widget.Height; Height = widget.Height;
Logic = widget.Logic; Logic = widget.Logic;
Visible = widget.Visible; Visible = widget.Visible;
Bounds = widget.Bounds; Bounds = widget.Bounds;
Parent = widget.Parent; Parent = widget.Parent;
IsVisible = widget.IsVisible; IsVisible = widget.IsVisible;
IgnoreChildMouseOver = widget.IgnoreChildMouseOver; IgnoreChildMouseOver = widget.IgnoreChildMouseOver;
foreach (var child in widget.Children) foreach (var child in widget.Children)
AddChild(child.Clone()); AddChild(child.Clone());
} }
public virtual Widget Clone() public virtual Widget Clone()
{ {
throw new InvalidOperationException("Widget type `{0}` is not cloneable.".F(GetType().Name)); throw new InvalidOperationException("Widget type `{0}` is not cloneable.".F(GetType().Name));
} }
public virtual int2 RenderOrigin public virtual int2 RenderOrigin
{ {
get get
{ {
var offset = (Parent == null) ? int2.Zero : Parent.ChildOrigin; var offset = (Parent == null) ? int2.Zero : Parent.ChildOrigin;
return new int2(Bounds.X, Bounds.Y) + offset; return new int2(Bounds.X, Bounds.Y) + offset;
} }
} }
public virtual int2 ChildOrigin { get { return RenderOrigin; } } public virtual int2 ChildOrigin { get { return RenderOrigin; } }
public virtual Rectangle RenderBounds public virtual Rectangle RenderBounds
{ {
@@ -181,120 +181,120 @@ namespace OpenRA.Widgets
} }
} }
public virtual void Initialize(WidgetArgs args) public virtual void Initialize(WidgetArgs args)
{ {
// Parse the YAML equations to find the widget bounds // Parse the YAML equations to find the widget bounds
var parentBounds = (Parent == null) var parentBounds = (Parent == null)
? new Rectangle(0, 0, Game.viewport.Width, Game.viewport.Height) ? new Rectangle(0, 0, Game.viewport.Width, Game.viewport.Height)
: Parent.Bounds; : Parent.Bounds;
var substitutions = args.ContainsKey("substitutions") ? var substitutions = args.ContainsKey("substitutions") ?
new Dictionary<string, int>((Dictionary<string, int>)args["substitutions"]) : new Dictionary<string, int>((Dictionary<string, int>)args["substitutions"]) :
new Dictionary<string, int>(); new Dictionary<string, int>();
substitutions.Add("WINDOW_RIGHT", Game.viewport.Width); substitutions.Add("WINDOW_RIGHT", Game.viewport.Width);
substitutions.Add("WINDOW_BOTTOM", Game.viewport.Height); substitutions.Add("WINDOW_BOTTOM", Game.viewport.Height);
substitutions.Add("PARENT_RIGHT", parentBounds.Width); substitutions.Add("PARENT_RIGHT", parentBounds.Width);
substitutions.Add("PARENT_LEFT", parentBounds.Left); substitutions.Add("PARENT_LEFT", parentBounds.Left);
substitutions.Add("PARENT_TOP", parentBounds.Top); substitutions.Add("PARENT_TOP", parentBounds.Top);
substitutions.Add("PARENT_BOTTOM", parentBounds.Height); substitutions.Add("PARENT_BOTTOM", parentBounds.Height);
int width = Evaluator.Evaluate(Width, substitutions); int width = Evaluator.Evaluate(Width, substitutions);
int height = Evaluator.Evaluate(Height, substitutions); int height = Evaluator.Evaluate(Height, substitutions);
substitutions.Add("WIDTH", width); substitutions.Add("WIDTH", width);
substitutions.Add("HEIGHT", height); substitutions.Add("HEIGHT", height);
Bounds = new Rectangle(Evaluator.Evaluate(X, substitutions), Bounds = new Rectangle(Evaluator.Evaluate(X, substitutions),
Evaluator.Evaluate(Y, substitutions), Evaluator.Evaluate(Y, substitutions),
width, width,
height); height);
} }
public void PostInit(WidgetArgs args) public void PostInit(WidgetArgs args)
{ {
if (Logic == null) if (Logic == null)
return; return;
args["widget"] = this; args["widget"] = this;
LogicObject = Game.modData.ObjectCreator.CreateObject<object>(Logic, args); LogicObject = Game.modData.ObjectCreator.CreateObject<object>(Logic, args);
var iwd = LogicObject as ILogicWithInit; var iwd = LogicObject as ILogicWithInit;
if (iwd != null) if (iwd != null)
iwd.Init(); iwd.Init();
args.Remove("widget"); args.Remove("widget");
} }
public virtual Rectangle EventBounds { get { return RenderBounds; } } public virtual Rectangle EventBounds { get { return RenderBounds; } }
public virtual Rectangle GetEventBounds() public virtual Rectangle GetEventBounds()
{ {
return Children return Children
.Where(c => c.IsVisible()) .Where(c => c.IsVisible())
.Select(c => c.GetEventBounds()) .Select(c => c.GetEventBounds())
.Aggregate(EventBounds, Rectangle.Union); .Aggregate(EventBounds, Rectangle.Union);
} }
public bool Focused { get { return SelectedWidget == this; } } public bool Focused { get { return SelectedWidget == this; } }
public virtual bool TakeFocus(MouseInput mi) public virtual bool TakeFocus(MouseInput mi)
{ {
if (Focused) if (Focused)
return true; return true;
if (SelectedWidget != null && !SelectedWidget.LoseFocus(mi)) if (SelectedWidget != null && !SelectedWidget.LoseFocus(mi))
return false; return false;
SelectedWidget = this; SelectedWidget = this;
return true; return true;
} }
// Remove focus from this widget; return false if you don't want to give it up // Remove focus from this widget; return false if you don't want to give it up
public virtual bool LoseFocus(MouseInput mi) public virtual bool LoseFocus(MouseInput mi)
{ {
// Some widgets may need to override focus depending on mouse click // Some widgets may need to override focus depending on mouse click
return LoseFocus(); return LoseFocus();
} }
public virtual bool LoseFocus() public virtual bool LoseFocus()
{ {
if (SelectedWidget == this) if (SelectedWidget == this)
SelectedWidget = null; SelectedWidget = null;
return true; return true;
} }
public virtual string GetCursor(int2 pos) { return "default"; } public virtual string GetCursor(int2 pos) { return "default"; }
public string GetCursorOuter(int2 pos) public string GetCursorOuter(int2 pos)
{ {
// Is the cursor on top of us? // Is the cursor on top of us?
if (!(IsVisible() && GetEventBounds().Contains(pos))) if (!(IsVisible() && GetEventBounds().Contains(pos)))
return null; return null;
// Do any of our children specify a cursor? // Do any of our children specify a cursor?
foreach (var child in Children.OfType<Widget>().Reverse()) foreach (var child in Children.OfType<Widget>().Reverse())
{ {
var cc = child.GetCursorOuter(pos); var cc = child.GetCursorOuter(pos);
if (cc != null) if (cc != null)
return cc; return cc;
} }
return EventBounds.Contains(pos) ? GetCursor(pos) : null; return EventBounds.Contains(pos) ? GetCursor(pos) : null;
} }
public virtual void MouseEntered() {} public virtual void MouseEntered() {}
public virtual void MouseExited() {} public virtual void MouseExited() {}
public virtual bool HandleMouseInput(MouseInput mi) { return false; } public virtual bool HandleMouseInput(MouseInput mi) { return false; }
public bool HandleMouseInputOuter(MouseInput mi) public bool HandleMouseInputOuter(MouseInput mi)
{ {
// Are we able to handle this event? // Are we able to handle this event?
if (!(Focused || (IsVisible() && GetEventBounds().Contains(mi.Location)))) if (!(Focused || (IsVisible() && GetEventBounds().Contains(mi.Location))))
return false; return false;
var oldMouseOver = MouseOverWidget; var oldMouseOver = MouseOverWidget;
// Send the event to the deepest children first and bubble up if unhandled // Send the event to the deepest children first and bubble up if unhandled
foreach (var child in Children.OfType<Widget>().Reverse()) foreach (var child in Children.OfType<Widget>().Reverse())
if (child.HandleMouseInputOuter(mi)) if (child.HandleMouseInputOuter(mi))
return true; return true;
if (IgnoreChildMouseOver) if (IgnoreChildMouseOver)
MouseOverWidget = oldMouseOver; MouseOverWidget = oldMouseOver;
@@ -302,58 +302,58 @@ namespace OpenRA.Widgets
if (mi.Event == MouseInputEvent.Move && MouseOverWidget == null && !IgnoreMouseOver) if (mi.Event == MouseInputEvent.Move && MouseOverWidget == null && !IgnoreMouseOver)
MouseOverWidget = this; MouseOverWidget = this;
return HandleMouseInput(mi); return HandleMouseInput(mi);
} }
public virtual bool HandleKeyPress(KeyInput e) { return false; } public virtual bool HandleKeyPress(KeyInput e) { return false; }
public virtual bool HandleKeyPressOuter(KeyInput e) public virtual bool HandleKeyPressOuter(KeyInput e)
{ {
if (!IsVisible()) if (!IsVisible())
return false; return false;
// Can any of our children handle this? // Can any of our children handle this?
foreach (var child in Children.OfType<Widget>().Reverse()) foreach (var child in Children.OfType<Widget>().Reverse())
if (child.HandleKeyPressOuter(e)) if (child.HandleKeyPressOuter(e))
return true; return true;
// Do any widgety behavior (enter text etc) // Do any widgety behavior (enter text etc)
var handled = HandleKeyPress(e); var handled = HandleKeyPress(e);
return handled; return handled;
} }
public virtual void Draw() {} public virtual void Draw() {}
public virtual void DrawOuter() public virtual void DrawOuter()
{ {
if (IsVisible()) if (IsVisible())
{ {
Draw(); Draw();
foreach (var child in Children) foreach (var child in Children)
child.DrawOuter(); child.DrawOuter();
} }
} }
public virtual void Tick() {} public virtual void Tick() {}
public virtual void TickOuter() public virtual void TickOuter()
{ {
if (IsVisible()) if (IsVisible())
{ {
Tick(); Tick();
foreach (var child in Children) foreach (var child in Children)
child.TickOuter(); child.TickOuter();
} }
} }
public virtual void AddChild(Widget child) public virtual void AddChild(Widget child)
{ {
child.Parent = this; child.Parent = this;
Children.Add(child); Children.Add(child);
} }
public virtual void RemoveChild(Widget child) public virtual void RemoveChild(Widget child)
{ {
Children.Remove(child); Children.Remove(child);
child.Removed(); child.Removed();
@@ -371,36 +371,36 @@ namespace OpenRA.Widgets
c.Removed(); c.Removed();
} }
public Widget GetWidget(string id) public Widget GetWidget(string id)
{ {
if (this.Id == id) if (this.Id == id)
return this; return this;
foreach (var child in Children) foreach (var child in Children)
{ {
var w = child.GetWidget(id); var w = child.GetWidget(id);
if (w != null) if (w != null)
return w; return w;
} }
return null; return null;
} }
public T GetWidget<T>(string id) where T : Widget public T GetWidget<T>(string id) where T : Widget
{ {
var widget = GetWidget(id); var widget = GetWidget(id);
return (widget != null) ? (T)widget : null; return (widget != null) ? (T)widget : null;
} }
} }
public class ContainerWidget : Widget public class ContainerWidget : Widget
{ {
public ContainerWidget() : base() { IgnoreMouseOver = true; } public ContainerWidget() : base() { IgnoreMouseOver = true; }
public ContainerWidget(ContainerWidget other) public ContainerWidget(ContainerWidget other)
: base(other) { IgnoreMouseOver = true; } : base(other) { IgnoreMouseOver = true; }
public override string GetCursor(int2 pos) { return null; } public override string GetCursor(int2 pos) { return null; }
public override Widget Clone() { return new ContainerWidget(this); } public override Widget Clone() { return new ContainerWidget(this); }
} }
public class WidgetArgs : Dictionary<string, object> public class WidgetArgs : Dictionary<string, object>
{ {
@@ -411,8 +411,8 @@ namespace OpenRA.Widgets
// TODO: you should use this anywhere you want to do // TODO: you should use this anywhere you want to do
// something in a logic ctor, but retain debuggability. // something in a logic ctor, but retain debuggability.
public interface ILogicWithInit public interface ILogicWithInit
{ {
void Init(); void Init();
} }
} }

View File

@@ -34,17 +34,17 @@ namespace OpenRA.Widgets
public override void Draw() public override void Draw()
{ {
var selbox = SelectionBox; var selbox = SelectionBox;
if (selbox == null) if (selbox == null)
{ {
foreach (var u in SelectActorsInBox(world, dragStart, dragStart)) foreach (var u in SelectActorsInBox(world, dragStart, dragStart))
worldRenderer.DrawRollover(u); worldRenderer.DrawRollover(u);
return; return;
} }
Game.Renderer.WorldLineRenderer.DrawRect( selbox.Value.First, selbox.Value.Second, Color.White ); Game.Renderer.WorldLineRenderer.DrawRect( selbox.Value.First, selbox.Value.Second, Color.White );
foreach (var u in SelectActorsInBox(world, selbox.Value.First, selbox.Value.Second)) foreach (var u in SelectActorsInBox(world, selbox.Value.First, selbox.Value.Second))
worldRenderer.DrawRollover(u); worldRenderer.DrawRollover(u);
} }
int2 dragStart, dragEnd; int2 dragStart, dragEnd;
@@ -159,7 +159,7 @@ namespace OpenRA.Widgets
return false; return false;
} }
static readonly Actor[] NoActors = {}; static readonly Actor[] NoActors = {};
IEnumerable<Actor> SelectActorsInBox(World world, int2 a, int2 b) IEnumerable<Actor> SelectActorsInBox(World world, int2 a, int2 b)
{ {
return world.FindUnits(a, b) return world.FindUnits(a, b)

View File

@@ -209,10 +209,10 @@ namespace OpenRA
} }
} }
public IEnumerable<TraitPair<T>> ActorsWithTrait<T>() public IEnumerable<TraitPair<T>> ActorsWithTrait<T>()
{ {
return traitDict.ActorsWithTraitMultiple<T>(this); return traitDict.ActorsWithTraitMultiple<T>(this);
} }
} }
public struct TraitPair<T> public struct TraitPair<T>

View File

@@ -35,7 +35,7 @@ namespace OpenRA.Mods.Cnc
Game.MoveViewport(new int2(b.Left + b.Width/2, b.Top + b.Height/2)); Game.MoveViewport(new int2(b.Left + b.Width/2, b.Top + b.Height/2));
Scripting.Media.PlayFMVFullscreen(w, "gdi1.vqa", Scripting.Media.PlayFMVFullscreen(w, "gdi1.vqa",
() => Scripting.Media.PlayFMVFullscreen(w, "landing.vqa", () => () => Scripting.Media.PlayFMVFullscreen(w, "landing.vqa", () =>
{ {
Sound.PlayMusic(Rules.Music["aoi"]); Sound.PlayMusic(Rules.Music["aoi"]);
started = true; started = true;
@@ -107,8 +107,8 @@ namespace OpenRA.Mods.Cnc
} }
// GoodGuy win conditions // GoodGuy win conditions
// BadGuy is dead // BadGuy is dead
var badcount = self.World.Actors.Count(a => a != a.Owner.PlayerActor && var badcount = self.World.Actors.Count(a => a != a.Owner.PlayerActor &&
a.Owner == Players["BadGuy"] && !a.IsDead()); a.Owner == Players["BadGuy"] && !a.IsDead());
if (badcount != lastBadCount) if (badcount != lastBadCount)
{ {
Game.Debug("{0} badguys remain".F(badcount)); Game.Debug("{0} badguys remain".F(badcount));
@@ -120,7 +120,7 @@ namespace OpenRA.Mods.Cnc
//GoodGuy lose conditions: MCV/cyard must survive //GoodGuy lose conditions: MCV/cyard must survive
var hasAnything = self.World.ActorsWithTrait<MustBeDestroyed>() var hasAnything = self.World.ActorsWithTrait<MustBeDestroyed>()
.Any( a => a.Actor.Owner == Players["GoodGuy"] ); .Any( a => a.Actor.Owner == Players["GoodGuy"] );
if (!hasAnything) if (!hasAnything)
OnLose(self.World); OnLose(self.World);
@@ -128,40 +128,40 @@ namespace OpenRA.Mods.Cnc
if (ticks == 25*5) if (ticks == 25*5)
{ {
ReinforceFromSea(self.World, ReinforceFromSea(self.World,
Actors["lstStart"].Location, Actors["lstStart"].Location,
Actors["lstEnd"].Location, Actors["lstEnd"].Location,
new int2(53,53), new int2(53,53),
new string[] {"e1","e1","e1"}, new string[] {"e1","e1","e1"},
Players["GoodGuy"]); Players["GoodGuy"]);
} }
if (ticks == 25*15) if (ticks == 25*15)
{ {
ReinforceFromSea(self.World, ReinforceFromSea(self.World,
Actors["lstStart"].Location, Actors["lstStart"].Location,
Actors["lstEnd"].Location, Actors["lstEnd"].Location,
new int2(53,53), new int2(53,53),
new string[] {"e1","e1","e1"}, new string[] {"e1","e1","e1"},
Players["GoodGuy"]); Players["GoodGuy"]);
} }
if (ticks == 25*30) if (ticks == 25*30)
{ {
ReinforceFromSea(self.World, ReinforceFromSea(self.World,
Actors["lstStart"].Location, Actors["lstStart"].Location,
Actors["lstEnd"].Location, Actors["lstEnd"].Location,
new int2(53,53), new int2(53,53),
new string[] {"jeep"}, new string[] {"jeep"},
Players["GoodGuy"]); Players["GoodGuy"]);
} }
if (ticks == 25*60) if (ticks == 25*60)
{ {
ReinforceFromSea(self.World, ReinforceFromSea(self.World,
Actors["lstStart"].Location, Actors["lstStart"].Location,
Actors["lstEnd"].Location, Actors["lstEnd"].Location,
new int2(53,53), new int2(53,53),
new string[] {"jeep"}, new string[] {"jeep"},
Players["GoodGuy"]); Players["GoodGuy"]);
} }

View File

@@ -39,8 +39,8 @@ namespace OpenRA.Mods.Cnc.Widgets
{ {
// Find an actor with a queue // Find an actor with a queue
var producer = world.Selection.Actors.FirstOrDefault(a => a.IsInWorld var producer = world.Selection.Actors.FirstOrDefault(a => a.IsInWorld
&& a.World.LocalPlayer == a.Owner && a.World.LocalPlayer == a.Owner
&& a.HasTrait<ProductionQueue>()); && a.HasTrait<ProductionQueue>());
if (producer != null) if (producer != null)
tabsWidget.Value.CurrentQueue = producer.TraitsImplementing<ProductionQueue>().First(); tabsWidget.Value.CurrentQueue = producer.TraitsImplementing<ProductionQueue>().First();
} }

View File

@@ -33,7 +33,7 @@ namespace OpenRA.Mods.Cnc.Widgets
[ObjectCreator.UseCtor] [ObjectCreator.UseCtor]
public CncWorldInteractionControllerWidget([ObjectCreator.Param] World world, public CncWorldInteractionControllerWidget([ObjectCreator.Param] World world,
[ObjectCreator.Param] WorldRenderer worldRenderer) [ObjectCreator.Param] WorldRenderer worldRenderer)
: base(world, worldRenderer) : base(world, worldRenderer)
{ {
tooltipContainer = new Lazy<TooltipContainerWidget>(() => tooltipContainer = new Lazy<TooltipContainerWidget>(() =>
@@ -86,8 +86,8 @@ namespace OpenRA.Mods.Cnc.Widgets
if (scrolltype != OpenRA.GameRules.MouseScrollType.Disabled && mi.Event == MouseInputEvent.Move && if (scrolltype != OpenRA.GameRules.MouseScrollType.Disabled && mi.Event == MouseInputEvent.Move &&
(mi.Button == MouseButton.Middle || mi.Button == (MouseButton.Left | MouseButton.Right))) (mi.Button == MouseButton.Middle || mi.Button == (MouseButton.Left | MouseButton.Right)))
{ {
var d = scrolltype == OpenRA.GameRules.MouseScrollType.Inverted ? -1 : 1; var d = scrolltype == OpenRA.GameRules.MouseScrollType.Inverted ? -1 : 1;
Game.viewport.Scroll((Viewport.LastMousePos - mi.Location) * d); Game.viewport.Scroll((Viewport.LastMousePos - mi.Location) * d);
} }
return base.HandleMouseInput(mi); return base.HandleMouseInput(mi);
@@ -187,17 +187,17 @@ namespace OpenRA.Mods.Cnc.Widgets
if(Keyboard != ScrollDirection.None || Edge != ScrollDirection.None) if(Keyboard != ScrollDirection.None || Edge != ScrollDirection.None)
{ {
var scroll = new float2(0, 0); var scroll = new float2(0, 0);
// Modified to use the ViewportEdgeScrollStep setting - Gecko // Modified to use the ViewportEdgeScrollStep setting - Gecko
if (Keyboard.Includes(ScrollDirection.Up) || Edge.Includes(ScrollDirection.Up)) if (Keyboard.Includes(ScrollDirection.Up) || Edge.Includes(ScrollDirection.Up))
scroll += new float2(0, -1); scroll += new float2(0, -1);
if (Keyboard.Includes(ScrollDirection.Right) || Edge.Includes(ScrollDirection.Right)) if (Keyboard.Includes(ScrollDirection.Right) || Edge.Includes(ScrollDirection.Right))
scroll += new float2(1, 0); scroll += new float2(1, 0);
if (Keyboard.Includes(ScrollDirection.Down) || Edge.Includes(ScrollDirection.Down)) if (Keyboard.Includes(ScrollDirection.Down) || Edge.Includes(ScrollDirection.Down))
scroll += new float2(0, 1); scroll += new float2(0, 1);
if (Keyboard.Includes(ScrollDirection.Left) || Edge.Includes(ScrollDirection.Left)) if (Keyboard.Includes(ScrollDirection.Left) || Edge.Includes(ScrollDirection.Left))
scroll += new float2(-1, 0); scroll += new float2(-1, 0);
float length = Math.Max(1, scroll.Length); float length = Math.Max(1, scroll.Length);
scroll.X = (scroll.X / length) * Game.Settings.Game.ViewportEdgeScrollStep; scroll.X = (scroll.X / length) * Game.Settings.Game.ViewportEdgeScrollStep;

View File

@@ -17,7 +17,7 @@ namespace OpenRA.Mods.Cnc.Widgets.Logic
{ {
[ObjectCreator.UseCtor] [ObjectCreator.UseCtor]
public ButtonTooltipLogic([ObjectCreator.Param] Widget widget, public ButtonTooltipLogic([ObjectCreator.Param] Widget widget,
[ObjectCreator.Param] ToggleButtonWidget button) [ObjectCreator.Param] ToggleButtonWidget button)
{ {
var label = widget.GetWidget<LabelWidget>("LABEL"); var label = widget.GetWidget<LabelWidget>("LABEL");
var hotkey = widget.GetWidget<LabelWidget>("HOTKEY"); var hotkey = widget.GetWidget<LabelWidget>("HOTKEY");

View File

@@ -28,8 +28,8 @@ namespace OpenRA.Mods.Cnc.Widgets.Logic
{ {
[ObjectCreator.UseCtor] [ObjectCreator.UseCtor]
public CncCheatsLogic([ObjectCreator.Param] Widget widget, public CncCheatsLogic([ObjectCreator.Param] Widget widget,
[ObjectCreator.Param] Action onExit, [ObjectCreator.Param] Action onExit,
[ObjectCreator.Param] World world) [ObjectCreator.Param] World world)
{ {
var panel = widget.GetWidget("CHEATS_PANEL"); var panel = widget.GetWidget("CHEATS_PANEL");

View File

@@ -20,10 +20,10 @@ namespace OpenRA.Mods.Cnc.Widgets.Logic
ColorRamp ramp; ColorRamp ramp;
[ObjectCreator.UseCtor] [ObjectCreator.UseCtor]
public CncColorPickerLogic([ObjectCreator.Param] Widget widget, public CncColorPickerLogic([ObjectCreator.Param] Widget widget,
[ObjectCreator.Param] ColorRamp initialRamp, [ObjectCreator.Param] ColorRamp initialRamp,
[ObjectCreator.Param] Action<ColorRamp> onChange, [ObjectCreator.Param] Action<ColorRamp> onChange,
[ObjectCreator.Param] Action<ColorRamp> onSelect, [ObjectCreator.Param] Action<ColorRamp> onSelect,
[ObjectCreator.Param] WorldRenderer worldRenderer) [ObjectCreator.Param] WorldRenderer worldRenderer)
{ {
var panel = widget.GetWidget("COLOR_CHOOSER"); var panel = widget.GetWidget("COLOR_CHOOSER");
ramp = initialRamp; ramp = initialRamp;
@@ -34,9 +34,9 @@ namespace OpenRA.Mods.Cnc.Widgets.Logic
Action sliderChanged = () => Action sliderChanged = () =>
{ {
ramp = new ColorRamp((byte)(255*hueSlider.Value), ramp = new ColorRamp((byte)(255*hueSlider.Value),
(byte)(255*satSlider.Value), (byte)(255*satSlider.Value),
(byte)(255*lumSlider.Value), (byte)(255*lumSlider.Value),
10); 10);
onChange(ramp); onChange(ramp);
}; };

View File

@@ -32,7 +32,7 @@ namespace OpenRA.Mods.Cnc.Widgets.Logic
// Show connection failed dialog // Show connection failed dialog
CloseWindow(); CloseWindow();
Widget.OpenWindow("CONNECTIONFAILED_PANEL", new WidgetArgs() Widget.OpenWindow("CONNECTIONFAILED_PANEL", new WidgetArgs()
{ {
{ "onAbort", onAbort }, { "onAbort", onAbort },
{ "onRetry", onRetry }, { "onRetry", onRetry },
{ "host", host }, { "host", host },
@@ -49,11 +49,11 @@ namespace OpenRA.Mods.Cnc.Widgets.Logic
[ObjectCreator.UseCtor] [ObjectCreator.UseCtor]
public CncConnectingLogic([ObjectCreator.Param] Widget widget, public CncConnectingLogic([ObjectCreator.Param] Widget widget,
[ObjectCreator.Param] string host, [ObjectCreator.Param] string host,
[ObjectCreator.Param] int port, [ObjectCreator.Param] int port,
[ObjectCreator.Param] Action onConnect, [ObjectCreator.Param] Action onConnect,
[ObjectCreator.Param] Action onRetry, [ObjectCreator.Param] Action onRetry,
[ObjectCreator.Param] Action onAbort) [ObjectCreator.Param] Action onAbort)
{ {
this.host = host; this.host = host;
this.port = port; this.port = port;
@@ -74,7 +74,7 @@ namespace OpenRA.Mods.Cnc.Widgets.Logic
{ {
Game.JoinServer(host, port); Game.JoinServer(host, port);
Widget.OpenWindow("CONNECTING_PANEL", new WidgetArgs() Widget.OpenWindow("CONNECTING_PANEL", new WidgetArgs()
{ {
{ "host", host }, { "host", host },
{ "port", port }, { "port", port },
{ "onConnect", onConnect }, { "onConnect", onConnect },
@@ -82,16 +82,16 @@ namespace OpenRA.Mods.Cnc.Widgets.Logic
{ "onRetry", () => Connect(host, port, onConnect, onAbort) } { "onRetry", () => Connect(host, port, onConnect, onAbort) }
}); });
} }
} }
public class CncConnectionFailedLogic public class CncConnectionFailedLogic
{ {
[ObjectCreator.UseCtor] [ObjectCreator.UseCtor]
public CncConnectionFailedLogic([ObjectCreator.Param] Widget widget, public CncConnectionFailedLogic([ObjectCreator.Param] Widget widget,
[ObjectCreator.Param] string host, [ObjectCreator.Param] string host,
[ObjectCreator.Param] int port, [ObjectCreator.Param] int port,
[ObjectCreator.Param] Action onRetry, [ObjectCreator.Param] Action onRetry,
[ObjectCreator.Param] Action onAbort) [ObjectCreator.Param] Action onAbort)
{ {
var panel = widget.GetWidget("CONNECTIONFAILED_PANEL"); var panel = widget.GetWidget("CONNECTIONFAILED_PANEL");
panel.GetWidget<ButtonWidget>("ABORT_BUTTON").OnClick = () => { Widget.CloseWindow(); onAbort(); }; panel.GetWidget<ButtonWidget>("ABORT_BUTTON").OnClick = () => { Widget.CloseWindow(); onAbort(); };
@@ -100,4 +100,4 @@ namespace OpenRA.Mods.Cnc.Widgets.Logic
widget.GetWidget<LabelWidget>("CONNECTING_DESC").GetText = () => widget.GetWidget<LabelWidget>("CONNECTING_DESC").GetText = () =>
"Could not connect to {0}:{1}".F(host, port); "Could not connect to {0}:{1}".F(host, port);
} }
}} }}

View File

@@ -20,7 +20,7 @@ namespace OpenRA.Mods.Cnc.Widgets.Logic
{ {
[ObjectCreator.UseCtor] [ObjectCreator.UseCtor]
public CncConquestObjectivesLogic([ObjectCreator.Param] Widget widget, public CncConquestObjectivesLogic([ObjectCreator.Param] Widget widget,
[ObjectCreator.Param] World world) [ObjectCreator.Param] World world)
{ {
var panel = widget.GetWidget("CONQUEST_OBJECTIVES"); var panel = widget.GetWidget("CONQUEST_OBJECTIVES");
panel.GetWidget<LabelWidget>("TITLE").GetText = () => "Conquest: " + world.Map.Title; panel.GetWidget<LabelWidget>("TITLE").GetText = () => "Conquest: " + world.Map.Title;

View File

@@ -18,8 +18,8 @@ namespace OpenRA.Mods.Cnc.Widgets.Logic
{ {
[ObjectCreator.UseCtor] [ObjectCreator.UseCtor]
public CncDirectConnectLogic([ObjectCreator.Param] Widget widget, public CncDirectConnectLogic([ObjectCreator.Param] Widget widget,
[ObjectCreator.Param] Action onExit, [ObjectCreator.Param] Action onExit,
[ObjectCreator.Param] Action openLobby) [ObjectCreator.Param] Action openLobby)
{ {
var panel = widget.GetWidget("DIRECTCONNECT_PANEL"); var panel = widget.GetWidget("DIRECTCONNECT_PANEL");
var ipField = panel.GetWidget<TextFieldWidget>("IP"); var ipField = panel.GetWidget<TextFieldWidget>("IP");

View File

@@ -29,8 +29,8 @@ namespace OpenRA.Mods.Cnc.Widgets.Logic
[ObjectCreator.UseCtor] [ObjectCreator.UseCtor]
public CncDownloadPackagesLogic([ObjectCreator.Param] Widget widget, public CncDownloadPackagesLogic([ObjectCreator.Param] Widget widget,
[ObjectCreator.Param] Dictionary<string,string> installData, [ObjectCreator.Param] Dictionary<string,string> installData,
[ObjectCreator.Param] Action afterInstall) [ObjectCreator.Param] Action afterInstall)
{ {
this.installData = installData; this.installData = installData;
this.afterInstall = afterInstall; this.afterInstall = afterInstall;

View File

@@ -66,7 +66,7 @@ namespace OpenRA.Mods.Cnc.Widgets.Logic
[ObjectCreator.UseCtor] [ObjectCreator.UseCtor]
public CncIngameChromeLogic([ObjectCreator.Param] Widget widget, public CncIngameChromeLogic([ObjectCreator.Param] Widget widget,
[ObjectCreator.Param] World world ) [ObjectCreator.Param] World world )
{ {
this.world = world; this.world = world;
world.WorldActor.Trait<CncMenuPaletteEffect>() world.WorldActor.Trait<CncMenuPaletteEffect>()

View File

@@ -21,8 +21,8 @@ namespace OpenRA.Mods.Cnc.Widgets.Logic
[ObjectCreator.UseCtor] [ObjectCreator.UseCtor]
public CncIngameMenuLogic([ObjectCreator.Param] Widget widget, public CncIngameMenuLogic([ObjectCreator.Param] Widget widget,
[ObjectCreator.Param] World world, [ObjectCreator.Param] World world,
[ObjectCreator.Param] Action onExit) [ObjectCreator.Param] Action onExit)
{ {
var resumeDisabled = false; var resumeDisabled = false;
menu = widget.GetWidget("INGAME_MENU"); menu = widget.GetWidget("INGAME_MENU");
@@ -63,7 +63,7 @@ namespace OpenRA.Mods.Cnc.Widgets.Logic
{ {
hideButtons = true; hideButtons = true;
Widget.OpenWindow("MUSIC_PANEL", new WidgetArgs() Widget.OpenWindow("MUSIC_PANEL", new WidgetArgs()
{ {
{ "onExit", () => hideButtons = false }, { "onExit", () => hideButtons = false },
}); });
}; };
@@ -72,7 +72,7 @@ namespace OpenRA.Mods.Cnc.Widgets.Logic
{ {
hideButtons = true; hideButtons = true;
Widget.OpenWindow("SETTINGS_PANEL", new WidgetArgs() Widget.OpenWindow("SETTINGS_PANEL", new WidgetArgs()
{ {
{ "world", world }, { "world", world },
{ "onExit", () => hideButtons = false }, { "onExit", () => hideButtons = false },
}); });

View File

@@ -112,7 +112,7 @@ namespace OpenRA.Mods.Cnc.Widgets.Logic
return; return;
if (!InstallUtils.ExtractFromPackage(source, extractPackage, filesToExtract, dest, onProgress, onError)) if (!InstallUtils.ExtractFromPackage(source, extractPackage, filesToExtract, dest, onProgress, onError))
return; return;
Game.RunAfterTick(() => Game.RunAfterTick(() =>
{ {

View File

@@ -18,12 +18,12 @@ namespace OpenRA.Mods.Cnc.Widgets.Logic
{ {
[ObjectCreator.UseCtor] [ObjectCreator.UseCtor]
public CncInstallLogic([ObjectCreator.Param] Widget widget, public CncInstallLogic([ObjectCreator.Param] Widget widget,
[ObjectCreator.Param] Dictionary<string,string> installData, [ObjectCreator.Param] Dictionary<string,string> installData,
[ObjectCreator.Param] Action continueLoading) [ObjectCreator.Param] Action continueLoading)
{ {
var panel = widget.GetWidget("INSTALL_PANEL"); var panel = widget.GetWidget("INSTALL_PANEL");
var args = new WidgetArgs() var args = new WidgetArgs()
{ {
{ "afterInstall", () => { Widget.CloseWindow(); continueLoading(); } }, { "afterInstall", () => { Widget.CloseWindow(); continueLoading(); } },
{ "installData", installData } { "installData", installData }
}; };
@@ -44,7 +44,7 @@ namespace OpenRA.Mods.Cnc.Widgets.Logic
panel.GetWidget<ButtonWidget>("MODS_BUTTON").OnClick = () => panel.GetWidget<ButtonWidget>("MODS_BUTTON").OnClick = () =>
{ {
Widget.OpenWindow("MODS_PANEL", new WidgetArgs() Widget.OpenWindow("MODS_PANEL", new WidgetArgs()
{ {
{ "onExit", () => {} }, { "onExit", () => {} },
// Close this panel // Close this panel
{ "onSwitch", Widget.CloseWindow }, { "onSwitch", Widget.CloseWindow },

View File

@@ -63,7 +63,7 @@ namespace OpenRA.Mods.Cnc.Widgets.Logic
}; };
Widget.OpenWindow("CONNECTIONFAILED_PANEL", new WidgetArgs() Widget.OpenWindow("CONNECTIONFAILED_PANEL", new WidgetArgs()
{ {
{ "onAbort", onExit }, { "onAbort", onExit },
{ "onRetry", onRetry }, { "onRetry", onRetry },
{ "host", om.Host }, { "host", om.Host },
@@ -85,11 +85,11 @@ namespace OpenRA.Mods.Cnc.Widgets.Logic
[ObjectCreator.UseCtor] [ObjectCreator.UseCtor]
internal CncLobbyLogic([ObjectCreator.Param( "widget" )] Widget lobby, internal CncLobbyLogic([ObjectCreator.Param( "widget" )] Widget lobby,
[ObjectCreator.Param] World world, // Shellmap world [ObjectCreator.Param] World world, // Shellmap world
[ObjectCreator.Param] OrderManager orderManager, [ObjectCreator.Param] OrderManager orderManager,
[ObjectCreator.Param] Action onExit, [ObjectCreator.Param] Action onExit,
[ObjectCreator.Param] Action onStart, [ObjectCreator.Param] Action onStart,
[ObjectCreator.Param] bool addBots) [ObjectCreator.Param] bool addBots)
{ {
this.orderManager = orderManager; this.orderManager = orderManager;
this.OnGameStart = () => { CloseWindow(); onStart(); }; this.OnGameStart = () => { CloseWindow(); onStart(); };
@@ -119,7 +119,7 @@ namespace OpenRA.Mods.Cnc.Widgets.Logic
{ {
var map = mapPreview.Map(); var map = mapPreview.Map();
if (map == null || mi.Button != MouseButton.Left if (map == null || mi.Button != MouseButton.Left
|| orderManager.LocalClient.State == Session.ClientState.Ready) || orderManager.LocalClient.State == Session.ClientState.Ready)
return; return;
var p = map.SpawnPoints var p = map.SpawnPoints
@@ -225,7 +225,7 @@ namespace OpenRA.Mods.Cnc.Widgets.Logic
lobby.GetWidget<ButtonWidget>("MUSIC_BUTTON").OnClick = () => lobby.GetWidget<ButtonWidget>("MUSIC_BUTTON").OnClick = () =>
{ {
Widget.OpenWindow("MUSIC_PANEL", new WidgetArgs() Widget.OpenWindow("MUSIC_PANEL", new WidgetArgs()
{ {
{ "onExit", () => {} }, { "onExit", () => {} },
}); });
}; };
@@ -290,8 +290,8 @@ namespace OpenRA.Mods.Cnc.Widgets.Logic
Func<int, ScrollItemWidget, ScrollItemWidget> setupItem = (ii, itemTemplate) => Func<int, ScrollItemWidget, ScrollItemWidget> setupItem = (ii, itemTemplate) =>
{ {
var item = ScrollItemWidget.Setup(itemTemplate, var item = ScrollItemWidget.Setup(itemTemplate,
() => client.SpawnPoint == ii, () => client.SpawnPoint == ii,
() => orderManager.IssueOrder(Order.Command("spawn {0} {1}".F(client.Index, ii)))); () => orderManager.IssueOrder(Order.Command("spawn {0} {1}".F(client.Index, ii))));
item.GetWidget<LabelWidget>("LABEL").GetText = () => ii == 0 ? "-" : ii.ToString(); item.GetWidget<LabelWidget>("LABEL").GetText = () => ii == 0 ? "-" : ii.ToString();
return item; return item;
}; };
@@ -372,11 +372,11 @@ namespace OpenRA.Mods.Cnc.Widgets.Logic
} }
// Editable player in slot // Editable player in slot
else if ((client.Index == orderManager.LocalClient.Index) || else if ((client.Index == orderManager.LocalClient.Index) ||
(client.Bot != null && Game.IsHost)) (client.Bot != null && Game.IsHost))
{ {
template = EditablePlayerTemplate.Clone(); template = EditablePlayerTemplate.Clone();
var botReady = (client.Bot != null && Game.IsHost var botReady = (client.Bot != null && Game.IsHost
&& orderManager.LocalClient.State == Session.ClientState.Ready); && orderManager.LocalClient.State == Session.ClientState.Ready);
var ready = botReady || client.State == Session.ClientState.Ready; var ready = botReady || client.State == Session.ClientState.Ready;
if (client.Bot != null) if (client.Bot != null)

View File

@@ -24,7 +24,7 @@ namespace OpenRA.Mods.Cnc.Widgets.Logic
[ObjectCreator.UseCtor] [ObjectCreator.UseCtor]
public CncMenuLogic([ObjectCreator.Param] Widget widget, public CncMenuLogic([ObjectCreator.Param] Widget widget,
[ObjectCreator.Param] World world) [ObjectCreator.Param] World world)
{ {
world.WorldActor.Trait<CncMenuPaletteEffect>() world.WorldActor.Trait<CncMenuPaletteEffect>()
.Fade(CncMenuPaletteEffect.EffectType.Desaturated); .Fade(CncMenuPaletteEffect.EffectType.Desaturated);
@@ -43,7 +43,7 @@ namespace OpenRA.Mods.Cnc.Widgets.Logic
{ {
Menu = MenuType.None; Menu = MenuType.None;
Widget.OpenWindow("MODS_PANEL", new WidgetArgs() Widget.OpenWindow("MODS_PANEL", new WidgetArgs()
{ {
{ "onExit", () => Menu = MenuType.Main }, { "onExit", () => Menu = MenuType.Main },
{ "onSwitch", RemoveShellmapUI } { "onSwitch", RemoveShellmapUI }
}); });
@@ -61,7 +61,7 @@ namespace OpenRA.Mods.Cnc.Widgets.Logic
{ {
Menu = MenuType.None; Menu = MenuType.None;
Widget.OpenWindow("SERVERBROWSER_PANEL", new WidgetArgs() Widget.OpenWindow("SERVERBROWSER_PANEL", new WidgetArgs()
{ {
{ "onExit", () => Menu = MenuType.Multiplayer }, { "onExit", () => Menu = MenuType.Multiplayer },
{ "openLobby", () => OpenLobbyPanel(MenuType.Multiplayer, false) } { "openLobby", () => OpenLobbyPanel(MenuType.Multiplayer, false) }
}); });
@@ -71,7 +71,7 @@ namespace OpenRA.Mods.Cnc.Widgets.Logic
{ {
Menu = MenuType.None; Menu = MenuType.None;
Widget.OpenWindow("CREATESERVER_PANEL", new WidgetArgs() Widget.OpenWindow("CREATESERVER_PANEL", new WidgetArgs()
{ {
{ "onExit", () => Menu = MenuType.Multiplayer }, { "onExit", () => Menu = MenuType.Multiplayer },
{ "openLobby", () => OpenLobbyPanel(MenuType.Multiplayer, false) } { "openLobby", () => OpenLobbyPanel(MenuType.Multiplayer, false) }
}); });
@@ -81,7 +81,7 @@ namespace OpenRA.Mods.Cnc.Widgets.Logic
{ {
Menu = MenuType.None; Menu = MenuType.None;
Widget.OpenWindow("DIRECTCONNECT_PANEL", new WidgetArgs() Widget.OpenWindow("DIRECTCONNECT_PANEL", new WidgetArgs()
{ {
{ "onExit", () => Menu = MenuType.Multiplayer }, { "onExit", () => Menu = MenuType.Multiplayer },
{ "openLobby", () => OpenLobbyPanel(MenuType.Multiplayer, false) } { "openLobby", () => OpenLobbyPanel(MenuType.Multiplayer, false) }
}); });
@@ -95,7 +95,7 @@ namespace OpenRA.Mods.Cnc.Widgets.Logic
{ {
Menu = MenuType.None; Menu = MenuType.None;
Widget.OpenWindow("REPLAYBROWSER_PANEL", new WidgetArgs() Widget.OpenWindow("REPLAYBROWSER_PANEL", new WidgetArgs()
{ {
{ "onExit", () => Menu = MenuType.Settings }, { "onExit", () => Menu = MenuType.Settings },
{ "onStart", RemoveShellmapUI } { "onStart", RemoveShellmapUI }
}); });
@@ -105,7 +105,7 @@ namespace OpenRA.Mods.Cnc.Widgets.Logic
{ {
Menu = MenuType.None; Menu = MenuType.None;
Widget.OpenWindow("MUSIC_PANEL", new WidgetArgs() Widget.OpenWindow("MUSIC_PANEL", new WidgetArgs()
{ {
{ "onExit", () => Menu = MenuType.Settings }, { "onExit", () => Menu = MenuType.Settings },
}); });
}; };
@@ -114,7 +114,7 @@ namespace OpenRA.Mods.Cnc.Widgets.Logic
{ {
Menu = MenuType.None; Menu = MenuType.None;
Widget.OpenWindow("SETTINGS_PANEL", new WidgetArgs() Widget.OpenWindow("SETTINGS_PANEL", new WidgetArgs()
{ {
{ "world", world }, { "world", world },
{ "onExit", () => Menu = MenuType.Settings }, { "onExit", () => Menu = MenuType.Settings },
}); });
@@ -146,9 +146,9 @@ namespace OpenRA.Mods.Cnc.Widgets.Logic
var map = WidgetUtils.ChooseInitialMap(Game.Settings.Server.Map); var map = WidgetUtils.ChooseInitialMap(Game.Settings.Server.Map);
CncConnectingLogic.Connect(IPAddress.Loopback.ToString(), CncConnectingLogic.Connect(IPAddress.Loopback.ToString(),
Game.CreateLocalServer(map), Game.CreateLocalServer(map),
() => OpenLobbyPanel(MenuType.Main, true), () => OpenLobbyPanel(MenuType.Main, true),
() => { Game.CloseServer(); Menu = MenuType.Main; }); () => { Game.CloseServer(); Menu = MenuType.Main; });
} }
} }
} }

View File

@@ -22,8 +22,8 @@ namespace OpenRA.Mods.Cnc.Widgets.Logic
[ObjectCreator.UseCtor] [ObjectCreator.UseCtor]
public CncModBrowserLogic([ObjectCreator.Param] Widget widget, public CncModBrowserLogic([ObjectCreator.Param] Widget widget,
[ObjectCreator.Param] Action onSwitch, [ObjectCreator.Param] Action onSwitch,
[ObjectCreator.Param] Action onExit) [ObjectCreator.Param] Action onExit)
{ {
var panel = widget.GetWidget("MODS_PANEL"); var panel = widget.GetWidget("MODS_PANEL");
var modList = panel.GetWidget<ScrollPanelWidget>("MOD_LIST"); var modList = panel.GetWidget<ScrollPanelWidget>("MOD_LIST");

View File

@@ -31,7 +31,7 @@ namespace OpenRA.Mods.Cnc.Widgets.Logic
[ObjectCreator.UseCtor] [ObjectCreator.UseCtor]
public CncMusicPlayerLogic([ObjectCreator.Param] Widget widget, public CncMusicPlayerLogic([ObjectCreator.Param] Widget widget,
[ObjectCreator.Param] Action onExit) [ObjectCreator.Param] Action onExit)
{ {
panel = widget.GetWidget("MUSIC_PANEL"); panel = widget.GetWidget("MUSIC_PANEL");
@@ -103,7 +103,7 @@ namespace OpenRA.Mods.Cnc.Widgets.Logic
panel.GetWidget<LabelWidget>("TIME_LABEL").GetText = () => (currentSong == null) ? "" : panel.GetWidget<LabelWidget>("TIME_LABEL").GetText = () => (currentSong == null) ? "" :
"{0:D2}:{1:D2} / {2:D2}:{3:D2}".F((int)Sound.MusicSeekPosition / 60, (int)Sound.MusicSeekPosition % 60, "{0:D2}:{1:D2} / {2:D2}:{3:D2}".F((int)Sound.MusicSeekPosition / 60, (int)Sound.MusicSeekPosition % 60,
currentSong.Length / 60, currentSong.Length % 60); currentSong.Length / 60, currentSong.Length % 60);
panel.GetWidget<LabelWidget>("TITLE_LABEL").GetText = () => (currentSong == null) ? "" : currentSong.Title; panel.GetWidget<LabelWidget>("TITLE_LABEL").GetText = () => (currentSong == null) ? "" : currentSong.Title;
var musicSlider = panel.GetWidget<SliderWidget>("MUSIC_SLIDER"); var musicSlider = panel.GetWidget<SliderWidget>("MUSIC_SLIDER");

View File

@@ -42,8 +42,8 @@ namespace OpenRA.Mods.Cnc.Widgets.Logic
[ObjectCreator.UseCtor] [ObjectCreator.UseCtor]
public CncServerBrowserLogic([ObjectCreator.Param] Widget widget, public CncServerBrowserLogic([ObjectCreator.Param] Widget widget,
[ObjectCreator.Param] Action openLobby, [ObjectCreator.Param] Action openLobby,
[ObjectCreator.Param] Action onExit) [ObjectCreator.Param] Action onExit)
{ {
var panel = widget.GetWidget("SERVERBROWSER_PANEL"); var panel = widget.GetWidget("SERVERBROWSER_PANEL");
var sl = panel.GetWidget<ScrollPanelWidget>("SERVER_LIST"); var sl = panel.GetWidget<ScrollPanelWidget>("SERVER_LIST");
@@ -127,9 +127,9 @@ namespace OpenRA.Mods.Cnc.Widgets.Logic
return; return;
} }
var gamesWaiting = games.Where(g => g.CanJoin()); var gamesWaiting = games.Where(g => g.CanJoin());
if (gamesWaiting.Count() == 0) if (gamesWaiting.Count() == 0)
{ {
searchStatus = SearchStatus.NoGames; searchStatus = SearchStatus.NoGames;
return; return;
@@ -138,7 +138,7 @@ namespace OpenRA.Mods.Cnc.Widgets.Logic
searchStatus = SearchStatus.Hidden; searchStatus = SearchStatus.Hidden;
currentServer = gamesWaiting.FirstOrDefault(); currentServer = gamesWaiting.FirstOrDefault();
foreach (var loop in gamesWaiting) foreach (var loop in gamesWaiting)
{ {
var game = loop; var game = loop;

View File

@@ -29,8 +29,8 @@ namespace OpenRA.Mods.Cnc.Widgets.Logic
[ObjectCreator.UseCtor] [ObjectCreator.UseCtor]
public CncSettingsLogic([ObjectCreator.Param] Widget widget, public CncSettingsLogic([ObjectCreator.Param] Widget widget,
[ObjectCreator.Param] World world, [ObjectCreator.Param] World world,
[ObjectCreator.Param] Action onExit) [ObjectCreator.Param] Action onExit)
{ {
this.world = world; this.world = world;
var panel = widget.GetWidget("SETTINGS_PANEL"); var panel = widget.GetWidget("SETTINGS_PANEL");

View File

@@ -23,8 +23,8 @@ namespace OpenRA.Mods.Cnc.Widgets.Logic
{ {
[ObjectCreator.UseCtor] [ObjectCreator.UseCtor]
public ProductionTooltipLogic([ObjectCreator.Param] Widget widget, public ProductionTooltipLogic([ObjectCreator.Param] Widget widget,
[ObjectCreator.Param] TooltipContainerWidget tooltipContainer, [ObjectCreator.Param] TooltipContainerWidget tooltipContainer,
[ObjectCreator.Param] ProductionPaletteWidget palette) [ObjectCreator.Param] ProductionPaletteWidget palette)
{ {
var pm = palette.world.LocalPlayer.PlayerActor.Trait<PowerManager>(); var pm = palette.world.LocalPlayer.PlayerActor.Trait<PowerManager>();
var pr = palette.world.LocalPlayer.PlayerActor.Trait<PlayerResources>(); var pr = palette.world.LocalPlayer.PlayerActor.Trait<PlayerResources>();
@@ -71,7 +71,7 @@ namespace OpenRA.Mods.Cnc.Widgets.Logic
var costString = "$: {0}".F(cost); var costString = "$: {0}".F(cost);
costLabel.GetText = () => costString; costLabel.GetText = () => costString;
costLabel.GetColor = () => pr.DisplayCash + pr.DisplayOre >= cost costLabel.GetColor = () => pr.DisplayCash + pr.DisplayOre >= cost
? Color.White : Color.Red; ? Color.White : Color.Red;
var leftWidth = Math.Max(font.Measure(tooltip.Name).X, requiresFont.Measure(requiresString).X); var leftWidth = Math.Max(font.Measure(tooltip.Name).X, requiresFont.Measure(requiresString).X);
var rightWidth = new [] {font.Measure(powerString).X, font.Measure(timeString).X, font.Measure(costString).X}.Aggregate(Math.Max); var rightWidth = new [] {font.Measure(powerString).X, font.Measure(timeString).X, font.Measure(costString).X}.Aggregate(Math.Max);

View File

@@ -18,8 +18,8 @@ namespace OpenRA.Mods.Cnc.Widgets.Logic
{ {
[ObjectCreator.UseCtor] [ObjectCreator.UseCtor]
public SimpleTooltipLogic([ObjectCreator.Param] Widget widget, public SimpleTooltipLogic([ObjectCreator.Param] Widget widget,
[ObjectCreator.Param] TooltipContainerWidget tooltipContainer, [ObjectCreator.Param] TooltipContainerWidget tooltipContainer,
[ObjectCreator.Param] Func<string> getText) [ObjectCreator.Param] Func<string> getText)
{ {
var label = widget.GetWidget<LabelWidget>("LABEL"); var label = widget.GetWidget<LabelWidget>("LABEL");

View File

@@ -19,8 +19,8 @@ namespace OpenRA.Mods.Cnc.Widgets.Logic
{ {
[ObjectCreator.UseCtor] [ObjectCreator.UseCtor]
public SupportPowerTooltipLogic([ObjectCreator.Param] Widget widget, public SupportPowerTooltipLogic([ObjectCreator.Param] Widget widget,
[ObjectCreator.Param] TooltipContainerWidget tooltipContainer, [ObjectCreator.Param] TooltipContainerWidget tooltipContainer,
[ObjectCreator.Param] SupportPowersWidget palette) [ObjectCreator.Param] SupportPowersWidget palette)
{ {
widget.IsVisible = () => palette.TooltipPower != null; widget.IsVisible = () => palette.TooltipPower != null;
var nameLabel = widget.GetWidget<LabelWidget>("NAME"); var nameLabel = widget.GetWidget<LabelWidget>("NAME");
@@ -43,7 +43,7 @@ namespace OpenRA.Mods.Cnc.Widgets.Logic
return; return;
time = "{0} / {1}".F(WidgetUtils.FormatTime(sp.RemainingTime), time = "{0} / {1}".F(WidgetUtils.FormatTime(sp.RemainingTime),
WidgetUtils.FormatTime(sp.Info.ChargeTime*25)); WidgetUtils.FormatTime(sp.Info.ChargeTime*25));
if (sp == lastPower) if (sp == lastPower)
return; return;

View File

@@ -20,8 +20,8 @@ namespace OpenRA.Mods.Cnc.Widgets.Logic
{ {
[ObjectCreator.UseCtor] [ObjectCreator.UseCtor]
public WorldTooltipLogic([ObjectCreator.Param] Widget widget, public WorldTooltipLogic([ObjectCreator.Param] Widget widget,
[ObjectCreator.Param] TooltipContainerWidget tooltipContainer, [ObjectCreator.Param] TooltipContainerWidget tooltipContainer,
[ObjectCreator.Param] CncWorldInteractionControllerWidget wic) [ObjectCreator.Param] CncWorldInteractionControllerWidget wic)
{ {
widget.IsVisible = () => wic.TooltipType != Type.None; widget.IsVisible = () => wic.TooltipType != Type.None;
var label = widget.GetWidget<LabelWidget>("LABEL"); var label = widget.GetWidget<LabelWidget>("LABEL");

View File

@@ -66,9 +66,9 @@ namespace OpenRA.Mods.Cnc.Widgets
var b = RenderBounds; var b = RenderBounds;
var rect = new RectangleF(b.X, var rect = new RectangleF(b.X,
b.Y + (1-providedFrac)*b.Height, b.Y + (1-providedFrac)*b.Height,
(float)b.Width, (float)b.Width,
providedFrac*b.Height); providedFrac*b.Height);
Game.Renderer.LineRenderer.FillRect(rect, color); Game.Renderer.LineRenderer.FillRect(rect, color);
var indicator = ChromeProvider.GetImage("sidebar-bits", "left-indicator"); var indicator = ChromeProvider.GetImage("sidebar-bits", "left-indicator");
@@ -77,7 +77,7 @@ namespace OpenRA.Mods.Cnc.Widgets
lastDrainedFrac = drainedFrac = float2.Lerp(lastDrainedFrac.GetValueOrDefault(drainedFrac), drainedFrac, .3f); lastDrainedFrac = drainedFrac = float2.Lerp(lastDrainedFrac.GetValueOrDefault(drainedFrac), drainedFrac, .3f);
float2 pos = new float2(b.X + b.Width - indicator.size.X, float2 pos = new float2(b.X + b.Width - indicator.size.X,
b.Y + (1-drainedFrac)*b.Height - indicator.size.Y / 2); b.Y + (1-drainedFrac)*b.Height - indicator.size.Y / 2);
Game.Renderer.RgbaSpriteRenderer.DrawSprite(indicator, pos); Game.Renderer.RgbaSpriteRenderer.DrawSprite(indicator, pos);
} }

View File

@@ -67,7 +67,7 @@ namespace OpenRA.Mods.Cnc.Widgets
[ObjectCreator.UseCtor] [ObjectCreator.UseCtor]
public ProductionPaletteWidget([ObjectCreator.Param] World world, public ProductionPaletteWidget([ObjectCreator.Param] World world,
[ObjectCreator.Param] WorldRenderer worldRenderer) [ObjectCreator.Param] WorldRenderer worldRenderer)
{ {
this.world = world; this.world = world;
this.worldRenderer = worldRenderer; this.worldRenderer = worldRenderer;
@@ -83,7 +83,7 @@ namespace OpenRA.Mods.Cnc.Widgets
.ToDictionary( .ToDictionary(
u => u.Name, u => u.Name,
u => Game.modData.SpriteLoader.LoadAllSprites( u => Game.modData.SpriteLoader.LoadAllSprites(
u.Traits.Get<TooltipInfo>().Icon ?? (u.Name + "icon"))[0]); u.Traits.Get<TooltipInfo>().Icon ?? (u.Name + "icon"))[0]);
overlayFont = Game.Renderer.Fonts["TinyBold"]; overlayFont = Game.Renderer.Fonts["TinyBold"];
holdOffset = new float2(32,24) - overlayFont.Measure("On Hold") / 2; holdOffset = new float2(32,24) - overlayFont.Measure("On Hold") / 2;
@@ -257,21 +257,21 @@ namespace OpenRA.Mods.Cnc.Widgets
var waiting = first != CurrentQueue.CurrentItem() && !first.Done; var waiting = first != CurrentQueue.CurrentItem() && !first.Done;
if (first.Done) if (first.Done)
overlayFont.DrawTextWithContrast("Ready", overlayFont.DrawTextWithContrast("Ready",
icon.Pos + readyOffset, icon.Pos + readyOffset,
Color.White, Color.Black, 1); Color.White, Color.Black, 1);
else if (first.Paused) else if (first.Paused)
overlayFont.DrawTextWithContrast("On Hold", overlayFont.DrawTextWithContrast("On Hold",
icon.Pos + holdOffset, icon.Pos + holdOffset,
Color.White, Color.Black, 1); Color.White, Color.Black, 1);
else if (!waiting) else if (!waiting)
overlayFont.DrawTextWithContrast(WidgetUtils.FormatTime(first.RemainingTimeActual), overlayFont.DrawTextWithContrast(WidgetUtils.FormatTime(first.RemainingTimeActual),
icon.Pos + timeOffset, icon.Pos + timeOffset,
Color.White, Color.Black, 1); Color.White, Color.Black, 1);
if (total > 1 || waiting) if (total > 1 || waiting)
overlayFont.DrawTextWithContrast(total.ToString(), overlayFont.DrawTextWithContrast(total.ToString(),
icon.Pos + queuedOffset, icon.Pos + queuedOffset,
Color.White, Color.Black, 1); Color.White, Color.Black, 1);
} }
} }
} }

View File

@@ -67,9 +67,9 @@ namespace OpenRA.Mods.Cnc.Widgets
var b = RenderBounds; var b = RenderBounds;
var rect = new RectangleF(b.X, var rect = new RectangleF(b.X,
b.Y + (1-capacityFrac)*b.Height, b.Y + (1-capacityFrac)*b.Height,
(float)b.Width, (float)b.Width,
capacityFrac*b.Height); capacityFrac*b.Height);
Game.Renderer.LineRenderer.FillRect(rect, color); Game.Renderer.LineRenderer.FillRect(rect, color);
var indicator = ChromeProvider.GetImage("sidebar-bits", "right-indicator"); var indicator = ChromeProvider.GetImage("sidebar-bits", "right-indicator");

View File

@@ -41,7 +41,7 @@ namespace OpenRA.Mods.Cnc.Widgets
[ObjectCreator.UseCtor] [ObjectCreator.UseCtor]
public SupportPowersWidget([ObjectCreator.Param] World world, public SupportPowersWidget([ObjectCreator.Param] World world,
[ObjectCreator.Param] WorldRenderer worldRenderer) [ObjectCreator.Param] WorldRenderer worldRenderer)
{ {
this.worldRenderer = worldRenderer; this.worldRenderer = worldRenderer;
spm = world.LocalPlayer.PlayerActor.Trait<SupportPowerManager>(); spm = world.LocalPlayer.PlayerActor.Trait<SupportPowerManager>();
@@ -117,16 +117,16 @@ namespace OpenRA.Mods.Cnc.Widgets
{ {
if (p.Power.Ready) if (p.Power.Ready)
overlayFont.DrawTextWithContrast("Ready", overlayFont.DrawTextWithContrast("Ready",
p.Pos + readyOffset, p.Pos + readyOffset,
Color.White, Color.Black, 1); Color.White, Color.Black, 1);
else if (!p.Power.Active) else if (!p.Power.Active)
overlayFont.DrawTextWithContrast("On Hold", overlayFont.DrawTextWithContrast("On Hold",
p.Pos + holdOffset, p.Pos + holdOffset,
Color.White, Color.Black, 1); Color.White, Color.Black, 1);
else else
overlayFont.DrawTextWithContrast(WidgetUtils.FormatTime(p.Power.RemainingTime), overlayFont.DrawTextWithContrast(WidgetUtils.FormatTime(p.Power.RemainingTime),
p.Pos + timeOffset, p.Pos + timeOffset,
Color.White, Color.Black, 1); Color.White, Color.Black, 1);
} }
} }

View File

@@ -61,7 +61,7 @@ namespace OpenRA.Mods.Cnc.Widgets
} }
} }
public override string GetCursor(int2 pos) { return null; } public override string GetCursor(int2 pos) { return null; }
public override Widget Clone() { throw new NotImplementedException(); } public override Widget Clone() { throw new NotImplementedException(); }
} }
} }

View File

@@ -12,7 +12,7 @@ using OpenRA.Traits;
namespace OpenRA.Mods.RA namespace OpenRA.Mods.RA
{ {
class AcceptsSuppliesInfo : TraitInfo<AcceptsSupplies> {} class AcceptsSuppliesInfo : TraitInfo<AcceptsSupplies> {}
class AcceptsSupplies {} class AcceptsSupplies {}
} }

Some files were not shown because too many files have changed in this diff Show More