This repository has been archived by the owner on Oct 19, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathFormBuilder.cs
487 lines (407 loc) · 13.9 KB
/
FormBuilder.cs
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
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
#region Copyright & License Information
/*
* Copyright 2007-2015 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you under the terms of the GNU General Public License
* as published by the Free Software Foundation. For more information,
* see COPYING.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using System.Xml;
using OpenRA.Graphics;
namespace OpenRA.TilesetBuilder
{
public partial class FormBuilder : Form
{
string srcfile;
int size;
TerrainTypeInfo[] terrainType;
Dictionary<ushort, TerrainTemplateInfo> templates;
void CreateNewTileset()
{
Show();
using (var formNew = new FormNew())
if (DialogResult.OK == formNew.ShowDialog())
{
srcfile = formNew.ImageFile;
size = formNew.TileSize;
var bitmap = new Bitmap(srcfile);
if (!formNew.PaletteFromImage)
{
var terrainPalette = new ImmutablePalette(formNew.PaletteFile, new int[0]);
ColorPalette pal;
using (var b = new Bitmap(1, 1, PixelFormat.Format8bppIndexed))
pal = b.Palette;
for (var i = 0; i < 256; i++)
pal.Entries[i] = Color.FromArgb(terrainPalette.GetColor(i).ToArgb());
bitmap.Palette = pal;
}
InitializeSurface(bitmap);
}
}
public FormBuilder(string src, string tsize, bool autoExport, string outputDir)
{
InitializeComponent();
LoadTerrainDefinitions();
size = int.Parse(tsize);
if (src.Length > 0)
{
srcfile = src;
var bitmap = new Bitmap(srcfile);
InitializeSurface(bitmap);
}
else
CreateNewTileset();
if (autoExport)
{
Export(outputDir);
Application.Exit();
}
}
void LoadTileset()
{
try
{
var doc = new XmlDocument();
doc.Load(Path.ChangeExtension(srcfile, "tsx"));
foreach (var e in doc.SelectNodes("//name").OfType<XmlElement>())
txtTilesetName.Text = e.GetAttribute("value");
foreach (var e in doc.SelectNodes("//terrain").OfType<XmlElement>())
surface1.TerrainTypes[int.Parse(e.GetAttribute("x")),
int.Parse(e.GetAttribute("y"))] = int.Parse(e.GetAttribute("t"));
foreach (var e in doc.SelectNodes("//template").OfType<XmlElement>())
surface1.Templates.Add(new Template
{
Cells = e.SelectNodes("./cell").OfType<XmlElement>()
.Select(f => new int2(int.Parse(f.GetAttribute("x")), int.Parse(f.GetAttribute("y"))))
.ToDictionary(a => a, a => true)
});
}
catch { }
}
void InitializeSurface(Bitmap bitmap)
{
surface1.TileSize = size;
surface1.Image = bitmap;
surface1.TilesPerRow = surface1.Image.Size.Width / surface1.TileSize;
surface1.Image.SetResolution(96, 96); // people keep being noobs about DPI, and GDI+ cares.
surface1.TerrainTypes = new int[surface1.Image.Width / size, surface1.Image.Height / size]; /* all passable by default */
surface1.Templates = new List<Template>();
surface1.Size = surface1.Image.Size;
surface1.Enabled = true;
LoadTileset();
}
void Save()
{
using (var w = XmlWriter.Create(Path.ChangeExtension(srcfile, "tsx"),
new XmlWriterSettings { Indent = true, IndentChars = " " }))
{
var tilesetName = txtTilesetName.Text;
if (tilesetName.Length < 1)
tilesetName = "Temperat";
w.WriteStartDocument();
w.WriteStartElement("tileset");
w.WriteStartElement("name");
w.WriteAttributeString("value", tilesetName);
w.WriteEndElement();
for (var i = 0; i <= surface1.TerrainTypes.GetUpperBound(0); i++)
for (var j = 0; j <= surface1.TerrainTypes.GetUpperBound(1); j++)
if (surface1.TerrainTypes[i, j] != 0)
{
w.WriteStartElement("terrain");
w.WriteAttributeString("x", i.ToString());
w.WriteAttributeString("y", j.ToString());
w.WriteAttributeString("t", surface1.TerrainTypes[i, j].ToString());
w.WriteEndElement();
}
foreach (var t in surface1.Templates)
{
w.WriteStartElement("template");
foreach (var c in t.Cells.Keys)
{
w.WriteStartElement("cell");
w.WriteAttributeString("x", c.X.ToString());
w.WriteAttributeString("y", c.Y.ToString());
w.WriteEndElement();
}
w.WriteEndElement();
}
w.WriteEndElement();
w.WriteEndDocument();
}
}
void LoadTerrainDefinitions()
{
var terrainDefinition = new Dictionary<string, TerrainTypeInfo>();
var yaml = MiniYaml.FromFile("defaults.yaml").FirstOrDefault(y => y.Key == "Terrain").Value.Nodes;
terrainDefinition = yaml.Select(n => new TerrainTypeInfo(n.Value)).ToDictionary(t => t.Type);
surface1.Icon = new Bitmap[terrainDefinition.Keys.Count];
terrainType = new TerrainTypeInfo[terrainDefinition.Keys.Count];
templates = new Dictionary<ushort, TerrainTemplateInfo>();
var title = this.Text;
surface1.UpdateMouseTilePosition +=
(x, y, tileNr) =>
{
Text = "{0} - {1} ({2,3}, {3,3}) tileNr: {4,3}".F(title, txtTilesetName.Text, x, y, tileNr);
};
surface1.Enabled = false;
var i = 0;
foreach (var deftype in terrainDefinition)
{
var icon = new Bitmap(16, 16);
// Loop through the images pixels to reset color.
for (var x = 0; x < icon.Width; x++)
{
for (var y = 0; y < icon.Height; y++)
{
var newColor = deftype.Value.Color;
icon.SetPixel(x, y, Color.FromArgb(newColor.ToArgb()));
}
}
surface1.Icon[i] = icon;
terrainType[i] = deftype.Value;
var terrainTypeButton = new ToolStripButton(deftype.Key, icon, TerrainTypeSelectorClicked);
terrainTypeButton.ToolTipText = deftype.Key;
terrainTypeButton.DisplayStyle = ToolStripItemDisplayStyle.ImageAndText;
terrainTypeButton.Tag = i.ToString();
terrainTypeButton.ImageAlign = ContentAlignment.MiddleLeft;
terrainTypes.Items.Add(terrainTypeButton);
i++;
}
}
void TerrainTypeSelectorClicked(object sender, EventArgs e)
{
var tsb = (ToolStripButton)sender;
surface1.InputMode = tsb.Tag as string;
foreach (var innerTsb in tsb.Owner.Items.OfType<ToolStripButton>())
innerTsb.Checked = false;
tsb.Checked = true;
}
void SaveClicked(object sender, EventArgs e) { Save(); }
void ShowOverlaysClicked(object sender, EventArgs e)
{
surface1.ShowTerrainTypes = ((ToolStripButton)sender).Checked;
surface1.Invalidate();
}
void ExportClicked(object sender, EventArgs e)
{
Export("Tilesets");
}
void DumpClicked(object sender, EventArgs e)
{
ExportTemplateToTileNumberMapping();
}
string ExportPalette(List<Color> p, string file)
{
while (p.Count < Palette.Size) p.Add(Color.Black); // pad the palette out with extra blacks
var paletteData = p.Take(Palette.Size).SelectMany(
c => new byte[] { (byte)(c.R >> 2), (byte)(c.G >> 2), (byte)(c.B >> 2) }).ToArray();
File.WriteAllBytes(file, paletteData);
return file;
}
string ExportTemplate(Template t, int n, string suffix, string dir)
{
var tileSize = size;
var filename = Path.Combine(dir, "{0}{1:00}{2}".F(txtTilesetName.Text, n, suffix));
var totalTiles = t.Width * t.Height;
var ms = new MemoryStream();
using (var bw = new BinaryWriter(ms))
{
bw.Write((ushort)tileSize);
bw.Write((ushort)tileSize);
bw.Write((uint)totalTiles);
bw.Write((ushort)t.Width);
bw.Write((ushort)t.Height);
bw.Write((uint)0); // filesize placeholder
bw.Flush();
bw.Write((uint)ms.Position + 24); // image start
bw.Write((uint)0); // 0 (32bits)
bw.Write((uint)0x2c730f8c); // magic?
bw.Write((uint)0); // flags start
bw.Write((uint)0); // walk start
bw.Write((uint)0); // index start
var src = surface1.Image.Clone(new Rectangle(0, 0, surface1.Image.Width, surface1.Image.Height),
surface1.Image.PixelFormat);
var data = src.LockBits(new Rectangle(0, 0, src.Width, src.Height),
ImageLockMode.ReadOnly, src.PixelFormat);
unsafe
{
var p = (byte*)data.Scan0;
for (var v = 0; v < t.Height; v++)
for (var u = 0; u < t.Width; u++)
{
if (t.Cells.ContainsKey(new int2(u + t.Left, v + t.Top)))
{
var q = p + data.Stride * tileSize * (v + t.Top) + tileSize * (u + t.Left);
for (var j = 0; j < tileSize; j++)
for (var i = 0; i < tileSize; i++)
bw.Write(q[i + j * data.Stride]);
}
else
for (var x = 0; x < tileSize * tileSize; x++)
bw.Write((byte)0); /* TODO: don't fill with air */
}
}
src.UnlockBits(data);
bw.Flush();
var indexStart = ms.Position;
for (var v = 0; v < t.Height; v++)
for (var u = 0; u < t.Width; u++)
bw.Write(t.Cells.ContainsKey(new int2(u + t.Left, v + t.Top))
? (byte)(u + t.Width * v)
: (byte)0xff);
bw.Flush();
var flagsStart = ms.Position;
for (var x = 0; x < totalTiles; x++)
bw.Write((byte)0);
bw.Flush();
var walkStart = ms.Position;
for (var x = 0; x < totalTiles; x++)
bw.Write((byte)0x8);
var bytes = ms.ToArray();
Array.Copy(BitConverter.GetBytes((uint)bytes.Length), 0, bytes, 12, 4);
Array.Copy(BitConverter.GetBytes(flagsStart), 0, bytes, 28, 4);
Array.Copy(BitConverter.GetBytes(walkStart), 0, bytes, 32, 4);
Array.Copy(BitConverter.GetBytes(indexStart), 0, bytes, 36, 4);
File.WriteAllBytes(filename, bytes);
}
return filename;
}
void Export(string outputDir)
{
var dir = Platform.ResolvePath("^", outputDir);
Directory.CreateDirectory(dir);
var tilesetName = txtTilesetName.Text;
var tilesetID = txtID.Text;
var tilesetExt = txtExt.Text;
if (tilesetName.Length < 1) tilesetName = "Temperat";
if (tilesetID.Length < 1) tilesetID = "TEMPERAT";
if (tilesetExt.Length < 1) tilesetExt = ".tem";
// Create a Tileset definition
// TODO: Pull this info from the GUI
var tilesetFile = tilesetName.ToLower();
if (tilesetFile.Length < 8)
tilesetFile = tilesetName.ToLower() + ".yaml";
else
tilesetFile = tilesetName.ToLower().Substring(0, 8) + ".yaml";
var tileset = new TileSet(
name: tilesetName,
id: tilesetID.ToUpper(),
terrainInfo: terrainType);
// List of files to add to the mix file
var fileList = new List<string>();
// Export tile artwork
foreach (var t in surface1.Templates)
fileList.Add(ExportTemplate(t, surface1.Templates.IndexOf(t), tilesetExt, dir));
// Add the templates
ushort cur = 0;
templates.Clear();
foreach (var tp in surface1.Templates)
{
var tiles = new byte[tp.Width * tp.Height];
foreach (var t in tp.Cells)
{
var ttype = terrainType[surface1.TerrainTypes[t.Key.X, t.Key.Y]].Type;
var idx = (t.Key.X - tp.Left) + tp.Width * (t.Key.Y - tp.Top);
tiles[idx] = tileset.GetTerrainIndex(ttype);
}
var template = new TerrainTemplateInfo(
id: cur,
images: new[] { "{0}{1:00}".F(txtTilesetName.Text, cur) },
size: new int2(tp.Width, tp.Height),
tiles: tiles);
// HACK: This part of the TileSet code is broken upstream
var field = template.GetType()
.GetField("tileInfo", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
field.SetValue(template, tiles.Select(t =>
{
var info = new TerrainTileInfo();
info.GetType().GetField("TerrainType").SetValue(info, t);
return info;
}).ToArray());
templates[cur] = template;
cur++;
}
SaveTileSet(tileset, Path.Combine(dir, tilesetFile));
Console.WriteLine("Finished export");
}
void ExportTemplateToTileNumberMapping()
{
Console.WriteLine("# start");
Console.WriteLine("# TemplateID CellID tilenr TemplateW TemplateH XinTilesPNG YinTilesPNG");
ushort cur = 0;
foreach (var tp in surface1.Templates)
{
foreach (var t in tp.Cells)
{
var idx = (t.Key.X - tp.Left) + tp.Width * (t.Key.Y - tp.Top);
// TemplateID CellID tilenr TemplateW TemplateH XinTilesPNG YinTilesPNG
Console.WriteLine("{0} {1} {2} {3} {4} {5} {6}",
cur,
idx,
t.Key.Y * surface1.TilesPerRow + t.Key.X,
tp.Width,
tp.Height,
t.Key.X,
t.Key.Y);
}
cur++;
}
Console.WriteLine("# end\n");
}
void TilesetNameChanged(object sender, EventArgs e)
{
var tilesetFile = txtTilesetName.Text;
if (tilesetFile.Length > 8)
tilesetFile = tilesetFile.ToLower().Substring(0, 8);
txtID.Text = tilesetFile.ToUpper();
txtPal.Text = tilesetFile.ToLower() + ".pal";
if (tilesetFile.Length < 3)
txtExt.Text = ".tem,.shp";
else
txtExt.Text = "." + tilesetFile.ToLower().Substring(0, 3) + ",.shp";
}
void NewTilesetClicked(object sender, EventArgs e)
{
CreateNewTileset();
}
void SaveTileSet(TileSet tileSet, string path)
{
var root = new List<MiniYamlNode>();
root.Add(new MiniYamlNode("Terrain", null,
tileSet.TerrainInfo.Select(t => new MiniYamlNode("TerrainType@{0}".F(t.Type), SaveTerrainInfo(t))).ToList()));
root.Add(new MiniYamlNode("Templates", null,
templates.Select(t => new MiniYamlNode("Template@{0}".F(t.Value.Id), SaveTemplate(t.Value, tileSet))).ToList()));
root.WriteToFile(path);
}
MiniYaml SaveTerrainInfo(TerrainTypeInfo t)
{
return FieldSaver.SaveDifferences(t, new TerrainTypeInfo(new MiniYaml("TerrainType")));
}
MiniYaml SaveTileInfo(TerrainTileInfo t, TileSet tileSet)
{
return new MiniYaml(tileSet.TerrainInfo[t.TerrainType].Type, new List<MiniYamlNode>());
}
MiniYaml SaveTemplate(TerrainTemplateInfo t, TileSet tileSet)
{
var defaultTemplate = new TerrainTemplateInfo(0, new string[] { null }, int2.Zero, null);
var root = FieldSaver.SaveDifferences(t, defaultTemplate);
var tileYaml = new List<MiniYamlNode>();
for (var i = 0; i < t.TilesCount; i++)
{
var tileInfo = t[i];
if (tileInfo != null)
tileYaml.Add(new MiniYamlNode(i.ToString(), SaveTileInfo(tileInfo, tileSet)));
}
root.Nodes.Add(new MiniYamlNode("Tiles", null, tileYaml));
return root;
}
}
}