Repository navigation
Expand file tree
/
Copy pathProgram.cs
More file actions
2826 lines (2768 loc) · 213 KB
/
Copy pathProgram.cs
File metadata and controls
2826 lines (2768 loc) · 213 KB
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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using MyAceEditor.PerfectWorld;
using MyAceEditor.Store;
using MyAceEditor.UI;
using System.Text;
namespace MyAceEditor;
internal static class Program
{
// Modos:
// (padrão) editor desktop nativo (WinForms)
// --mcp servidor MCP por stdio, para um agente de IA
// --inspect <elements.data> diagnóstico do parser do Perfect World
[STAThread]
private static void Main(string[] args)
{
if (args.Contains("--clean")) { MyAceEditor.UI.EditorForm.StartClean = true; args = args.Where(x => x != "--clean").ToArray(); }
if (args.Contains("--mcp")) { RunMcpMode(args).GetAwaiter().GetResult(); return; }
if (args.Length >= 2 && args[0] is "--cfg-audit" or "--cfg-match" or "--cfg-batch") { CfgDiagnostic(args); return; }
if (args.Length >= 2 && args[0] == "--inspect") { InspectElements(args[1]); return; }
if (args.Length >= 3 && args[0] == "--testcfg") { TestCfg(args[1], args[2]); return; }
if (args.Length >= 2 && args[0] == "--pck") { ListPck(args[1], args.Length >= 3 ? args[2] : ""); return; }
if (args.Length >= 3 && args[0] == "--client-plan") // <element destino> <element traduzido>: passos do tradutor sem aplicar + leitura dos domain*.data (client-plan-report.txt)
{
var sb = new StringBuilder();
foreach (var dir in new[] { args[1], args[2] })
foreach (var (name, d2) in DomainFile.Files)
{
var p = Path.Combine(dir, "data", name);
if (!File.Exists(p)) continue;
var b = File.ReadAllBytes(p);
var df = DomainFile.Parse(b, d2);
sb.AppendLine($"{dir} {name}: {(df is null ? "NÃO lido" : $"{df.NameAt.Count} territórios · ex.: {string.Join(", ", df.NameAt.Keys.Take(4).Select(id => $"{id} {df.Name(id)}"))}")}");
// prova: traduzido pelo outro, só os 32 bytes dos nomes mudam
var other = Path.Combine(dir == args[1] ? args[2] : args[1], "data", name);
if (dir == args[1] && df is not null && File.Exists(other) && DomainFile.Translate(b, File.ReadAllBytes(other), d2) is { } tr)
{
var names = df.NameAt.Values.ToList();
bool onlyNames = tr.Bytes.Length == b.Length && Enumerable.Range(0, b.Length).All(i => b[i] == tr.Bytes[i] || names.Any(at => i >= at && i < at + DomainFile.NameChars * 2));
var back = DomainFile.Parse(tr.Bytes, d2);
sb.AppendLine($" traduzido: {tr.Changed} nomes · só nomes mudaram: {onlyNames} · relido: {(back is null ? "NÃO" : string.Join(", ", back.NameAt.Keys.Take(4).Select(id => back.Name(id))))}");
}
}
foreach (var st in ClientTranslator.Plan(args[1], args[2]))
sb.AppendLine($"[{(st.Default ? "x" : " ")}{(st.Enabled ? "" : " desligado")}] {st.Title} — {st.Detail}");
File.WriteAllText("client-plan-report.txt", sb.ToString(), new UTF8Encoding(false));
return;
}
if (args.Length >= 2 && args[0] == "--path-edit-test") // <path.sev>: cria caminho e move ponto na memória (path-edit-test.txt)
{
File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "path-edit-test.txt"), MyAceEditor.UI.WorldView.PathSelfTest(File.ReadAllBytes(args[1])));
return;
}
if (args.Length >= 3 && args[0] == "--pck-split-test") // <pacote pequeno> <pasta de trabalho>: corta em t-001.pck + t.pkx, grava com PckWriter e confere (pck-split-test.txt)
{
var sb = new StringBuilder();
try
{
Directory.CreateDirectory(args[2]);
var src = File.ReadAllBytes(args[1]);
string p1 = Path.Combine(args[2], "t-001.pck"), p2 = Path.Combine(args[2], "t.pkx");
using (var orig = new MyAceEditor.PerfectWorld.PckArchive(args[1]))
{
long cut = orig.Entries.Min(e => e.Offset) + (orig.Entries.Max(e => e.Offset) - orig.Entries.Min(e => e.Offset)) / 2; // no meio dos dados
File.WriteAllBytes(p1, src[..(int)cut]); File.WriteAllBytes(p2, src[(int)cut..]);
var first = orig.Entries[0];
var changed = orig.Read(first).Concat("MYACE"u8.ToArray()).ToArray();
var files = new Dictionary<string, byte[]> { [first.Path] = changed, [@"myace\teste.txt"] = "ola"u8.ToArray() };
var bak = MyAceEditor.PerfectWorld.PckWriter.Write(Path.Combine(args[2], "t.pck"), files);
using var a = new MyAceEditor.PerfectWorld.PckArchive(Path.Combine(args[2], "t.pck"));
int same = 0, diff = 0;
foreach (var e in orig.Entries.Skip(1)) { if (a.Find(e.Path) is { } x && a.Read(x).AsSpan().SequenceEqual(orig.Read(e))) same++; else diff++; }
bool head = File.ReadAllBytes(p1).AsSpan(8).SequenceEqual(src.AsSpan(8, (int)cut - 8));
sb.AppendLine($"entradas {orig.Entries.Count} -> {a.Entries.Count}; mudada {(a.Read(a.Find(first.Path)!).AsSpan().SequenceEqual(changed) ? "ok" : "ERRO")}; nova {(a.Find(@"myace\teste.txt") is { } n && a.Read(n).Length == 3 ? "ok" : "ERRO")}; outras iguais {same}, diferentes {diff}; .pck igual fora do cabeçalho {head}; tamanho no cabeçalho {BitConverter.ToUInt32(File.ReadAllBytes(p1), 4)} = lógico {new FileInfo(p1).Length + new FileInfo(p2).Length}; backup {Path.GetFileName(bak)}");
}
}
catch (Exception ex) { sb.AppendLine("ERRO: " + ex); }
File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "pck-split-test.txt"), sb.ToString());
return;
}
if (args.Length >= 4 && args[0] == "--bmd-hulls") // <element> <mapa> <map.bht>: as cascas de cada .bmd batem com brushes do servidor? (bmd-hulls-report.txt)
{
var sb = new StringBuilder();
var bht = new MyAceEditor.PerfectWorld.BhtFile(File.ReadAllBytes(args[3]));
var boxes = Enumerable.Range(0, bht.Count).Select(bht.Box).ToList();
using var lit = new MyAceEditor.PerfectWorld.PckArchive(Path.Combine(args[1], "litmodels.pck"));
// os brushes do fim de cada .bmd (colisão do cliente) devem estar no map.bht com a mesma caixa
static string Key((float X0, float Y0, float Z0, float X1, float Y1, float Z1) b) => $"{b.X0:0.00} {b.Y0:0.00} {b.Z0:0.00} {b.X1:0.00} {b.Y1:0.00} {b.Z1:0.00}";
var keys = new HashSet<string>(Enumerable.Range(0, bht.Count).Select(i => Key(bht.Box(i))));
int files = 0, found = 0, none = 0, empty = 0, brushes = 0, hit = 0;
foreach (var e in lit.Entries.Where(e => e.Path.StartsWith($@"litmodels\{args[2]}\", StringComparison.OrdinalIgnoreCase) && e.Path.EndsWith(".bmd", StringComparison.OrdinalIgnoreCase)))
{
var d = lit.Read(e); files++;
var at = MyAceEditor.PerfectWorld.BmdModel.CdBrushes(d);
if (at is null) { none++; if (none <= 4) sb.AppendLine($"sem brushes achados: {e.Path} ({d.Length} B)"); continue; }
if (at.Count == 0) { empty++; continue; }
found++;
foreach (int o in at)
{
brushes++;
float F(int k) => BitConverter.ToSingle(d, o + k);
if (keys.Contains(Key((F(24), F(28), F(32), F(36), F(40), F(44))))) hit++;
else if (brushes - hit <= 4) sb.AppendLine($"brush do {e.Path} fora do map.bht: {F(24):0.00},{F(28):0.00},{F(32):0.00}");
}
}
sb.Insert(0, $"{files} .bmd: com brushes {found}, sem colisão {empty}, não achados {none} | brushes {brushes}, no map.bht {hit} (map.bht tem {bht.Count})\n");
File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "bmd-hulls-report.txt"), sb.ToString());
return;
}
if (args.Length >= 2 && args[0] == "--bht-check") // <pasta config do servidor>: lê todo */map.bht, confere a volta byte a byte e o deslocar de brushes
{
var sb = new StringBuilder();
foreach (var f in Directory.GetFiles(args[1], "map.bht", SearchOption.AllDirectories).OrderBy(x => x))
{
try
{
var raw = File.ReadAllBytes(f); var b = new MyAceEditor.PerfectWorld.BhtFile(raw);
bool same = b.Write().AsSpan().SequenceEqual(raw);
string move = "";
if (b.Count > 0)
{
// desloca os brushes dentro da caixa do 1º (+ 2 m de folga) e confere a caixa e um plano relidos
var c = b.Box(0); var sel = b.Inside(c.X0 - 2, c.Y0 - 2, c.Z0 - 2, c.X1 + 2, c.Y1 + 2, c.Z1 + 2);
b.Move(sel, 3, 0.5f, -2);
var m = new MyAceEditor.PerfectWorld.BhtFile(b.Write()); var c2 = m.Box(0);
bool ok = Math.Abs(c2.X0 - c.X0 - 3) < 1e-3 && Math.Abs(c2.Y1 - c.Y1 - 0.5f) < 1e-3 && Math.Abs(c2.Z0 - c.Z0 + 2) < 1e-3 && m.Count == b.Count;
move = $" · mover {sel.Count} brush(es): {(ok ? "ok" : "ERRO")}";
}
sb.AppendLine($"{Path.GetFileName(Path.GetDirectoryName(f))}: {b.Count} brushes, volta {(same ? "igual" : "DIFERENTE")}{move}");
}
catch (Exception ex) when (ex is InvalidDataException or IOException) { sb.AppendLine($"{f}: {ex.Message}"); }
}
File.WriteAllText(Path.Combine(AppContext.BaseDirectory, "bht-check-report.txt"), sb.ToString());
return;
}
if (args.Length >= 2 && args[0] == "--ecwld-check") // <pasta element\maps>: lê todos os .ecwld e confere se cada bloco termina onde o próximo começa (ecwld-check-report.txt)
{
var sb = new StringBuilder(); int maps = 0, exactMaps = 0, sameMaps = 0, editOk = 0, editTried = 0;
foreach (var file in Directory.GetFiles(args[1], "*.ecwld", SearchOption.AllDirectories).OrderBy(x => x))
{
try
{
var raw = File.ReadAllBytes(file);
var sc = new WorldScene(raw); maps++;
if (sc.BlocksExact == sc.BlocksTotal) exactMaps++;
// gravador de edição (EcwldFile): sem mudança = idêntico; mover/clonar/apagar e conferir relendo
string rt;
try
{
var ef = new EcwldFile(raw);
bool same = ef.Write().AsSpan().SequenceEqual(raw);
if (same) sameMaps++;
rt = same ? "regrava IDÊNTICO" : "regrava DIFERENTE";
if (same && sc.Effects.Count > 0)
{
editTried++;
var fx = sc.Effects[0];
uint nid = ef.Clone(EcwldFile.Kind.Effect, fx.Id, 5, 5);
ef.Move(EcwldFile.Kind.Effect, nid, fx.X + 1, fx.Y, fx.Z);
var back = new WorldScene(ef.Write());
var moved = back.Effects.FirstOrDefault(e => e.Id == nid);
bool ok1 = back.Effects.Count > sc.Effects.Count && moved is not null && Math.Abs(moved.X - (fx.X + 1)) < 1e-3 && moved.Gfx == fx.Gfx && back.BlocksExact == back.BlocksTotal;
ef.Delete(EcwldFile.Kind.Effect, nid);
bool ok2 = ef.Write().AsSpan().SequenceEqual(raw);
if (ok1 && ok2) editOk++;
rt += $" · editar efeito: clone+mover {(ok1 ? "OK" : "FALHOU")}, apagar o clone volta ao original {(ok2 ? "OK" : "FALHOU")}";
}
}
catch (InvalidDataException ex) { rt = "sem edição: " + ex.Message; }
sb.AppendLine($"{Path.GetFileName(Path.GetDirectoryName(file))}: v{sc.Version} blocos {sc.BlocksExact}/{sc.BlocksTotal} · {rt} · árvores {sc.Trees.Count} · efeitos {sc.Effects.Count} · modelos {sc.Models.Count} · sons {sc.Sounds.Count} · bichos {sc.CritterRefs.Count} · curvas {sc.BezierRefs.Count}");
}
catch (Exception ex) { sb.AppendLine($"{file}: ERRO {ex.Message}"); }
}
File.WriteAllText("ecwld-check-report.txt", $"# {exactMaps}/{maps} mapas com todos os blocos exatos · {sameMaps}/{maps} regravam idênticos · edição {editOk}/{editTried}\n" + sb, new UTF8Encoding(false));
return;
}
if (args.Length >= 2 && args[0] == "--pathsev") // <pasta ou arquivo>: lê e regrava todos os path.sev (pathsev-report.txt)
{
var files = Directory.Exists(args[1]) ? Directory.GetFiles(args[1], "path.sev", SearchOption.AllDirectories) : new[] { args[1] };
var sb = new StringBuilder();
int ok = 0;
foreach (var file in files)
{
try
{
var b = File.ReadAllBytes(file); var pf = PathFile.Read(b); bool same = pf.Write().AsSpan().SequenceEqual(b);
if (same) ok++;
sb.AppendLine($"{file}: v{pf.Version} · {pf.Paths.Count} caminhos · versões {string.Join(",", pf.Paths.Select(x => x.Version).Distinct())} · {(same ? "IDÊNTICO" : "DIFERENTE")}");
}
catch (Exception ex) { sb.AppendLine($"{file}: ERRO {ex.Message}"); }
}
File.WriteAllText("pathsev-report.txt", $"# {ok}/{files.Length} idênticos\n" + sb, new UTF8Encoding(false));
return;
}
if (args.Length >= 3 && args[0] == "--pck-diff") // <pck A> <pck B> [prefixo]: arquivos presentes nos dois com conteúdo diferente (pck-diff-report.txt)
{
using var a = new PckArchive(args[1]); using var b = new PckArchive(args[2]);
var pre = args.Length >= 4 ? args[3] : "";
var sb = new StringBuilder();
int same = 0, onlyA = 0;
foreach (var ea in a.Entries.Where(e => e.Path.StartsWith(pre, StringComparison.OrdinalIgnoreCase)).OrderBy(e => e.Path, StringComparer.OrdinalIgnoreCase))
{
if (b.Find(ea.Path) is not { } eb) { onlyA++; continue; }
byte[] da = a.Read(ea), db = b.Read(eb);
if (da.AsSpan().SequenceEqual(db)) same++; else sb.AppendLine($"{ea.Path}\t{da.Length}\t{db.Length}");
}
File.WriteAllText("pck-diff-report.txt", $"# iguais {same} · só em A {onlyA}\n" + sb, new UTF8Encoding(false));
return;
}
if (args.Length >= 3 && args[0] == "--uid-check") // --uid-check <interfaces.pck> <janela.xml>: em branco -> conferir -> trazer -> conferir (Criar interface)
{
using var pck = new PckArchive(args[1]);
var e = pck.Find(args[2]) ?? throw new FileNotFoundException(args[2]);
var orig = UiDesign.FromBytes(pck.Read(e));
var design = UiDesign.NewXml("Win_Teste", new System.Drawing.Size(300, 200), null);
design = UiDesign.Insert(design, UiDesign.LabelBlock("Txt", "oi", 80, 20, 10, false, System.Drawing.Color.White, false));
var c1 = UiDesign.Compare(orig, design);
design = UiDesign.BringMissing(orig, design, c1);
var c2 = UiDesign.Compare(orig, design);
design = UiDesign.SetDialog(design, name: c2.WindowWanted, size: new System.Drawing.Size(471, 400), frame: @"x\y.tga");
var d = GameDialog.Parse(design);
File.WriteAllLines("uid-check.txt", new[]
{
$"antes: faltam {c1.Missing.Count}, comandos {c1.MissingCommands.Count}",
$"depois: ok={c2.Ok} faltam {c2.Missing.Count}",
$"janela {d.Name} {d.Size} moldura {d.Frame} controles {d.Controls.Count} (original {GameDialog.Parse(orig).Controls.Count})",
$"reordenar: {string.Join(",", UiDesign.Pieces(UiDesign.Reorder(design, "Txt", 0)).Take(3).Select(p => p.Name))}",
"", design,
});
return;
}
if (args.Length >= 4 && args[0] == "--pck-extract") // --pck-extract <pck> <filtro> <pasta>
{
using var pck = new PckArchive(args[1]);
var list = pck.Entries.Where(e => e.Path.Contains(args[2], StringComparison.OrdinalIgnoreCase)).ToList();
var (done, failed) = MyAceEditor.UI.PckView.ExtractTo(pck, args[3], list, CancellationToken.None);
File.WriteAllText("pck-extract.txt", $"{done - failed} extraídos, {failed} falhas");
return;
}
if (args.Length >= 4 && args[0] == "--icon-add") // --icon-add <cópia do surfaces.pck> <imagem> <nome>: grava e recorta de volta em <imagem>.out.png
{
try { using var img = new System.Drawing.Bitmap(args[2]); MyAceEditor.PerfectWorld.IconAtlas.AddIcon(args[1], args[3], img); }
catch (Exception ex) { File.WriteAllText("pck-extract.txt", ex.ToString()); return; }
var at = MyAceEditor.PerfectWorld.IconAtlas.Load(args[1])!;
using var back = at.Get(args[3] + ".dds");
back?.Save(args[2] + ".out.png");
File.WriteAllText("pck-extract.txt", $"ícones: {at.Count}, achou o novo: {at.Has(args[3] + ".dds")}");
return;
}
if (args.Length >= 2 && args[0] == "--icons") { TestIcons(args[1]); return; }
if (args.Length >= 2 && args[0] == "--roundtrip") { RoundTrip(args[1]); return; }
if (args.Length >= 3 && args[0] == "--check") { CheckPair(args[1], args[2]); return; }
if (args.Length >= 4 && args[0] == "--local-send") { LocalSend(args[1], args[2], args[3]); return; }
if (args.Length >= 2 && args[0] == "--tasks-fixdiff") { TaskFixDiff(args[1]); return; } // <tasks.data>: bloco fixo × início dos textos (tasks-fixdiff.txt)
if (args.Length >= 2 && args[0] == "--tasks-layout") { TestTaskLayout(args.Skip(1).ToArray()); return; } // <tasks.data>...: lê e regrava cada quest (tasks-layout.txt)
if (args.Length >= 2 && args[0] == "--tasks-texts") { TestTaskTexts(args[1]); return; } // <tasks.data>: textos em qualquer versão
if (args.Length >= 4 && args[0] == "--tasks-translate") { TasksTranslate(args[1], args[2], args[3]); return; } // <destino> <traduzido> <saída>
if (args.Length >= 4 && args[0] == "--pck-texts") // <pck destino> <pck traduzido> <cópia de saída>: textos por ID (pck-texts.txt)
{
File.Copy(args[1], args[3], true);
var (n, files) = PackTextTranslator.Plan(args[3], args[2], dryRun: false);
if (files.Count > 0) PckWriter.Write(args[3], files);
File.WriteAllText("pck-texts.txt", $"{n:N0} textos em {files.Count} arquivo(s)\n" + string.Join("\n", files.Keys.Order().Take(40)), new UTF8Encoding(false));
return;
}
if (args.Length >= 2 && args[0] == "--icon-check") // <surfaces.pck>: ícones do atlas comprimido = recorte do atlas inteiro (icon-check.txt)
{
var at = MyAceEditor.PerfectWorld.IconAtlas.Load(args[1])!;
var (n, bad) = at.VerifyAgainstFullDecode();
File.WriteAllText("icon-check.txt", $"{n:N0} icones conferidos · {bad:N0} diferentes", new UTF8Encoding(false));
return;
}
if (args.Length >= 2 && args[0] == "--decode-check") // <elements.data>: valores lidos = os do decodificador antigo, campo a campo (decode-check.txt)
{
var m = CfgCatalog.Load(args[1]).Module;
var inv = System.Globalization.CultureInfo.InvariantCulture;
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
var gbk = System.Text.Encoding.GetEncoding(936);
string Old(CfgField f, byte[] raw, int p) // cópia do decodificador de antes da otimização
{
string t = f.Type.ToLowerInvariant();
if (t.StartsWith("wstring:") || t.StartsWith("string:"))
{
string text = t.StartsWith("wstring:") ? System.Text.Encoding.Unicode.GetString(raw, p, f.Size) : gbk.GetString(raw, p, f.Size);
int nul = text.IndexOf('\0'); return nul < 0 ? text : text[..nul];
}
if (t.StartsWith("byte:") || t.StartsWith("bytes:")) return Convert.ToHexString(raw.AsSpan(p, f.Size));
return t switch
{
"float" => BitConverter.ToSingle(raw, p).ToString("R", inv), "double" => BitConverter.ToDouble(raw, p).ToString("R", inv),
"int64" or "long" => BitConverter.ToInt64(raw, p).ToString(inv), "uint64" or "ulong" => BitConverter.ToUInt64(raw, p).ToString(inv),
"int16" or "short" => BitConverter.ToInt16(raw, p).ToString(inv), "uint16" or "word" or "ushort" => BitConverter.ToUInt16(raw, p).ToString(inv),
"int8" or "sbyte" => unchecked((sbyte)raw[p]).ToString(inv), "uint8" or "byte" or "char" or "bool" => raw[p].ToString(inv),
"uint32" or "uint" or "dword" => BitConverter.ToUInt32(raw, p).ToString(inv), "int32" or "int" => BitConverter.ToInt32(raw, p).ToString(inv),
_ => "?",
};
}
long n = 0, bad = 0; var first = new StringBuilder();
if (m.Source is ElementsLayout lay)
foreach (var span in lay.Blocks)
{
var l = span.List; var blk = span.Block;
foreach (var it in l.Items)
{
if (it.Raw is not { } raw) continue;
int p = 0;
foreach (var f in blk.Fields)
{
n++;
if (it.Fields.TryGetValue(f.Name, out var fv) && fv.Value != Old(f, raw, p) && bad++ < 10) first.AppendLine($"{l.Name} {it.Id} {f.Name}: novo '{fv.Value}' antigo '{Old(f, raw, p)}'");
p += f.Size;
}
}
}
File.WriteAllText("decode-check.txt", $"{n:N0} campos conferidos · {bad:N0} diferentes\n{first}", new UTF8Encoding(false));
return;
}
if (args.Length >= 2 && args[0] == "--load-bench") // <elements.data>: abre como o programa, sem janela; tempo por etapa e memória (load-bench.txt)
{
MyAceEditor.UI.ElementsLoadBundle.MemTrace = args.Length >= 3 && args[2] == "mem";
var total = System.Diagnostics.Stopwatch.StartNew();
var b = MyAceEditor.UI.ElementsLoadBundle.Read(args[1], null, new LoadContext(), null, null, null, null, null);
total.Stop();
long managed = GC.GetTotalMemory(forceFullCollection: true);
var proc = System.Diagnostics.Process.GetCurrentProcess();
File.WriteAllText("load-bench.txt", $"total {total.ElapsedMilliseconds} ms\n{MyAceEditor.UI.ElementsLoadBundle.LastTimes}\n"
+ $"memoria gerenciada {managed / 1048576} MB · privada {proc.PrivateMemorySize64 / 1048576} MB · pico {proc.PeakWorkingSet64 / 1048576} MB\n"
+ $"registros {b.Owners.Count:N0} · quests {b.TaskCount:N0} · icones {b.Atlas?.Count ?? 0:N0}" + $"\ntasks: {b.Tasks?.LoadTimes} · regravacao identica: {b.Tasks?.RoundTripVerified} · {b.Tasks?.ReadOnlyReason ?? b.Tasks?.SchemaError ?? "ok"}", new UTF8Encoding(false));
return;
}
if (args.Length >= 2 && args[0] == "--creature-shot") // <png>: painel da criatura do Mundo 3D com dados de exemplo
{
var cf = MyAceEditor.UI.WorldCreaturePanel.ShotForm();
cf.Show();
var until2 = DateTime.Now.AddSeconds(2);
while (DateTime.Now < until2) { Application.DoEvents(); Thread.Sleep(20); }
using var cb = new System.Drawing.Bitmap(cf.Width, cf.Height);
cf.DrawToBitmap(cb, new System.Drawing.Rectangle(0, 0, cf.Width, cf.Height));
cb.Save(args[1], System.Drawing.Imaging.ImageFormat.Png);
return;
}
if (args.Length >= 2 && args[0] == "--prefs-shot") // <png>: tela de Preferências com 2 opções de exemplo
{
var w = new MyAceEditor.UI.PreferencesWindow(new MyAceEditor.UI.PreferencesWindow.Pref[]
{
new("MyAce (editor)", "", () => "Perguntar se quer enviar ao servidor", () => "Ligado: pergunta ao abrir e ao salvar.", () => (false, null), _ => null),
new("Servidor local", "", () => "Velocidade de movimento sem a trava de 3 / 5 m/s", () => "Ligado: os bônus fixos de movimento somam sem limite (até 15 m/s). Desligado: regra original. Reinicia os mapas.", () => (false, null), _ => null),
new("Servidor local", "", () => "Exemplo indisponível", () => "Uma opção que depende de algo que não está pronto.", () => (null, "Servidor local ainda não instalado."), _ => null),
}, new Dictionary<string, string> { ["MyAce (editor)"] = MyAceEditor.UI.UiKit.Settings, ["Servidor local"] = MyAceEditor.UI.UiKit.Server },
[(MyAceEditor.UI.Loc.T("prefs.secPck", "PCK Key"), "", new MyAceEditor.UI.PckKeysPage(args.Length >= 4 ? args[3] : null))], "MyAce (editor)") { StartPosition = FormStartPosition.Manual, Location = new System.Drawing.Point(-20000, -20000) };
MyAceEditor.UI.PreferencesWindow.Quiet = true;
w.Show();
var until = DateTime.Now.AddSeconds(3);
while (DateTime.Now < until) { Application.DoEvents(); Thread.Sleep(20); }
// "pck": página PCK Key escolhida, teste de edição/desfazer e conferência de texto cortado (prefs-shot.txt ao lado da foto)
if (args.Length >= 3 && args[2] == "pck" && w.Controls.OfType<TabControl>().FirstOrDefault() is { } ptc)
{
var pagePck = ptc.TabPages.Cast<TabPage>().First(tp => tp.Controls.OfType<MyAceEditor.UI.PckKeysPage>().Any());
ptc.SelectedTab = pagePck;
var pk = pagePck.Controls.OfType<MyAceEditor.UI.PckKeysPage>().First();
var log = new StringBuilder();
log.AppendLine("pck: " + pk.SelfTest());
// texto cortado: rótulos e botões da página (a largura tem de caber no texto, considerando o ícone)
var cut = new List<string>();
void Walk(Control c)
{
foreach (Control k in c.Controls) Walk(k);
if (c is not (Label or Button) || !c.Visible || string.IsNullOrEmpty(c.Text) || c.Width <= 0) return;
if (c is Label { AutoSize: true }) return;
int extra = c is Button bb ? (bb.Image?.Width ?? 0) + bb.Padding.Horizontal + 14 : c.Padding.Horizontal;
var flags = c is Label { Height: > 26 } ? TextFormatFlags.WordBreak : TextFormatFlags.SingleLine;
var need = TextRenderer.MeasureText(c.Text.Trim(), c.Font, new System.Drawing.Size(c.Width - extra, 0), flags);
if (need.Width > c.Width - extra + 1 || need.Height > c.Height) cut.Add($"{c.GetType().Name} \"{c.Text.Trim()}\" {need.Width}x{need.Height} > {c.Width - extra}x{c.Height}");
}
Application.DoEvents(); Walk(pk);
log.AppendLine($"pck layout {MyAceEditor.PerfectWorld.AppLang.Current}: {cut.Count} com texto cortado" + (cut.Count > 0 ? Environment.NewLine + " " + string.Join(Environment.NewLine + " ", cut) : ""));
File.WriteAllText(Path.ChangeExtension(args[1], ".txt"), log.ToString());
var u2 = DateTime.Now.AddSeconds(1); while (DateTime.Now < u2) { Application.DoEvents(); Thread.Sleep(20); }
}
using var bmp = new System.Drawing.Bitmap(w.Width, w.Height);
w.DrawToBitmap(bmp, new System.Drawing.Rectangle(0, 0, w.Width, w.Height));
bmp.Save(args[1], System.Drawing.Imaging.ImageFormat.Png);
return;
}
if (args.Length >= 3 && args[0] == "--ss-shot") // <png> <pasta element> [página]: janela "Servidor e pastas" fora da tela
{
var w = new MyAceEditor.UI.ServerSetupWindow(args[2], System.Drawing.Color.FromArgb(231, 236, 242), System.Drawing.Color.FromArgb(30, 39, 51)) { StartPosition = FormStartPosition.Manual, Location = new System.Drawing.Point(-20000, -20000) };
w.Show();
if (args.Length >= 4 && w.Controls.OfType<TabControl>().FirstOrDefault() is { } tc && int.Parse(args[3]) < tc.TabCount) tc.SelectedIndex = int.Parse(args[3]);
var until = DateTime.Now.AddSeconds(4);
while (DateTime.Now < until) { Application.DoEvents(); Thread.Sleep(20); }
using var bmp = new System.Drawing.Bitmap(w.Width, w.Height);
w.DrawToBitmap(bmp, new System.Drawing.Rectangle(0, 0, w.Width, w.Height));
bmp.Save(args[1], System.Drawing.Imaging.ImageFormat.Png);
return;
}
if (args.Length >= 2 && args[0] == "--wq-shot") { MyAceEditor.UI.QuestShotTest.Run(args[1], args.Length >= 3 ? int.Parse(args[2]) : 0); return; } // <png>: painel e editor de quest do 3D com dados de exemplo
if (args.Length >= 3 && args[0] == "--quest-keep-test") // <tasks.data> <saída>: abrir qualquer quest no assistente e mudar só o que a tela mostra
{
var tf = new TasksFile(args[1]);
int total = 0, strict = 0, opened = 0, noChange = 0, onlyGold = 0, back = 0;
string first = "";
foreach (var q in tf.Roots!.ToList())
{
total++;
if (QuestBuilder.FromQuest(tf, q, out _) is not null) strict++;
var d = QuestBuilder.FromQuestKeep(tf, q);
if (d.Keep) opened++;
var was = q.Fixed;
var state = QuestBuilder.Capture(q);
var err = QuestBuilder.Patch(tf, q, d);
if (err is null && q.Fixed.AsSpan().SequenceEqual(was)) noChange++; else if (first.Length == 0) first = $"nada mudou {q.Id}: {err}";
d.Gold += 1;
err = QuestBuilder.Patch(tf, q, d);
var diff = QuestBuilder.Diff(tf, was, q);
if (err is null && diff.Count == 1 && diff[0] == "m_Award_S.m_ulGoldNum") onlyGold++; else if (first.Length == 0) first = $"ouro {q.Id}: {err} {string.Join(",", diff.Take(4))}";
QuestBuilder.Restore(tf, q, state);
if (q.Fixed.AsSpan().SequenceEqual(was)) back++;
}
File.WriteAllText(args[2], $"quests {total}, assistente completo {strict}, abrem agora {opened}, sem mudar nada igual {noChange}, só o ouro muda {onlyGold}, volta igual {back}\n{first}\n");
return;
}
if (args.Length >= 3 && args[0] == "--pck-keys-test") { MyAceEditor.PerfectWorld.PckKeysSelfTest.Run(args[1], args[2]); Environment.Exit(0); } // <element> <saída>: perfis de chaves do .pck (cópias)
if (args.Length >= 4 && args[0] == "--bridge-test") { MyAceEditor.PerfectWorld.WorldEdit.ObjectsSelfTest.RunBridge(args[1], args[2], args[3]); Environment.Exit(0); } // <element> <config> <saída>: pontes copiadas, metro a metro
if (args.Length >= 4 && args[0] == "--copy-block-test") { MyAceEditor.PerfectWorld.WorldEdit.ObjectsSelfTest.RunCopyBlocks(args[1], args[2], args[3]); Environment.Exit(0); } // <element> <config> <saída>: construção copiada fecha o .rmap embaixo?
if (args.Length >= 4 && args[0] == "--objects-test") { MyAceEditor.PerfectWorld.WorldEdit.ObjectsSelfTest.Run(args[1], args[2], args[3]); Environment.Exit(Environment.ExitCode); } // <element> <config> <saída>: objetos do mundo sem janela
if (args.Length >= 4 && args[0] == "--zone-test") { ZoneSelfTest.Run(args[1], args[2], args[3]); return; } // <maps> <config> <saída>: editor de zonas sem janela
if (args.Length >= 3 && args[0] == "--quest-preview-shot") // <png> <pasta element>: janela de quests do jogo com dados de exemplo
{
using var w = new Form { Width = 620, Height = 480, StartPosition = FormStartPosition.Manual, Location = new System.Drawing.Point(-20000, -20000), ShowInTaskbar = false };
var pv = MyAceEditor.UI.QuestPreview.Create(args[2]);
if (pv is null) { File.WriteAllText("quest-preview.txt", "sem janela"); return; }
pv.Set(new("Carta para o ferreiro", "Leve a carta do guarda até o ferreiro da vila.", "Falar com Guarda Li", new MyAceEditor.UI.QuestPreview.Step[] { new("Falar com o guarda", "", "Falar com Guarda Li"), new("Entregar a carta", "", "Falar com Ferreiro Wang") }, 5000, 1200, 0, Array.Empty<System.Drawing.Image?>()));
w.Controls.Add(pv); w.Show();
var stop = DateTime.Now.AddSeconds(2);
while (DateTime.Now < stop) { Application.DoEvents(); Thread.Sleep(30); }
using var img = new System.Drawing.Bitmap(w.Width, w.Height);
w.DrawToBitmap(img, new System.Drawing.Rectangle(0, 0, w.Width, w.Height));
img.Save(args[1], System.Drawing.Imaging.ImageFormat.Png);
return;
}
if (args.Length >= 2 && args[0] == "--server-delete-test") // <pasta MyAceDelTest...>: só para um servidor descartável de teste
{
if (!Path.GetFileName(args[1].TrimEnd('\\', '/')).StartsWith("MyAceDelTest")) return;
var test = new LocalServer(args[1]);
bool before = test.Exists();
test.Delete();
File.WriteAllText("server-delete-test.txt", $"antes={before} depois={test.Exists()} distro={test.Distro}");
return;
}
if (args.Length >= 3 && args[0] == "--fav-test") // <elements.data> <arquivo de chaves>: conta quantas chaves existem; resultado em fav-test.txt
{
var keys = File.ReadAllLines(args[2]);
var found = MyAceEditor.UI.EditorForm.ExistingFavorites(keys, CfgCatalog.Load(args[1]).Module).ToList();
File.WriteAllText("fav-test.txt", $"{found.Count} de {keys.Length}: {string.Join(" ", found)}");
return;
}
if (args.Length >= 3 && args[0] == "--map-names-dump") // <saída tsv> <pasta element>...: pasta do mapa e nome em cada cliente
{
var all = args.Skip(2).Select(MapTags.ClientMapNames).ToList();
File.WriteAllLines(args[1], all.SelectMany(d => d.Keys).Distinct(StringComparer.OrdinalIgnoreCase).OrderBy(k => k)
.Select(k => k + "\t" + string.Join("\t", all.Select(d => d.GetValueOrDefault(k, "")))));
return;
}
if (args.Length >= 3 && args[0] == "--path-orphans") // <saída> <pasta config do servidor>: pontos do npcgen que citam caminho que o path.sev não tem
{
var sb = new StringBuilder();
foreach (var dir in Directory.GetDirectories(args[2]))
{
string gen = Path.Combine(dir, "npcgen.data"), sev = Path.Combine(dir, "path.sev");
if (!File.Exists(gen) || !File.Exists(sev)) continue;
var ids = PathFile.Read(File.ReadAllBytes(sev)).Paths.Select(x => x.Id).ToHashSet();
var used = NpcGenFile.Read(File.ReadAllBytes(gen)).Spawns.SelectMany(x => x.Creatures).Select(c => c.PathId).Where(i => i > 0).ToList();
var orphans = used.Where(i => !ids.Contains(i)).ToList();
sb.AppendLine($"{Path.GetFileName(dir)} caminhos={ids.Count} max={(ids.Count > 0 ? ids.Max() : 0)} usados={used.Count} orfaos={orphans.Count} maxOrfao={(orphans.Count > 0 ? orphans.Max() : 0)}");
}
File.WriteAllText(args[1], sb.ToString());
return;
}
if (args.Length >= 2 && args[0] == "--path-who-shot") // <png>: janela de quem anda no caminho, com dados de exemplo
{
var sp = new NpcGenSpawn();
sp.Creatures.Add(new NpcGenCreature { Id = 1698, Amount = 20 }); sp.Creatures.Add(new NpcGenCreature { Id = 1704, Amount = 20 });
using var d = new MyAceEditor.UI.PathWhoDialog(sp, n => "Vespa Sangrenta (" + n + ")");
d.Show(); Application.DoEvents();
using var bmp = new System.Drawing.Bitmap(d.Width, d.Height);
d.DrawToBitmap(bmp, new System.Drawing.Rectangle(0, 0, d.Width, d.Height));
bmp.Save(args[1], System.Drawing.Imaging.ImageFormat.Png);
return;
}
if (args.Length >= 4 && args[0] == "--item-fields") // <elements.data> <bloco> <id ou 0 = 1º com serviço> [saída]: campos preenchidos de um registro
{
var mod = CfgCatalog.Load(args[1]).Module;
var list = mod.FindListByName(args[2]);
var it = list?.Items.FirstOrDefault(i => i.Id == args[3]) ?? list?.Items.FirstOrDefault(i => args[3].Contains('=') ? i.Fields.TryGetValue(args[3].Split('=')[0], out var ff) && ff.Value is not ("0" or "") : true);
var sbf = new StringBuilder($"{args[2]}: {list?.Items.Count} registros, campos {it?.Fields.Count}\n");
if (it is not null) foreach (var (k, f) in it.Fields) sbf.AppendLine($"{k} [{f.Type}] = {f.Value}");
File.WriteAllText(args.Length > 4 ? args[4] : "item-fields.txt", sbf.ToString());
return;
}
if (args.Length >= 3 && args[0] == "--npc-builder-test") // <elements.data> <saída>: cria vendedor e fornalha na memória e confere as regras
{
var mod = CfgCatalog.Load(args[1]).Module;
var sb = new StringBuilder();
var before = ItemRules.Check(mod).Select(x => x.Key).ToHashSet();
var items = mod.FindListByName("WEAPON_ESSENCE")!.Items.Take(3).Select(i => int.Parse(i.Id)).ToList();
var known = mod.Lists.Where(l => l.Name.EndsWith("_ESSENCE")).SelectMany(l => l.Items).Select(i => i.Id).ToHashSet();
bool IsItem(int id) => known.Contains(id.ToString());
Model.Item Blank(Model.ItemList l) { var it = new Model.Item(); foreach (var (k, f) in l.Items[0].Fields) it.Fields[k] = Model.Field.Of(f.Type, f.Type == Model.FieldType.String ? "" : "0"); return it; }
void Insert(Model.ItemList l, Model.Item it) => l.Items.Add(it);
int baseNpc = int.Parse(mod.FindListByName("NPC_ESSENCE")!.Items[0].Id);
var shop = new ShopDraft(); shop.Goods[0][0] = items[0]; shop.Goods[0][5] = items[1]; shop.Titles[0] = "Armas";
var seller = new NpcDraft { Kind = NpcKind.Seller, BaseId = baseNpc, Name = "Vendedor de teste", Shop = shop };
sb.AppendLine("loja vazia acusa: " + NpcBuilder.Validate(mod, new NpcDraft { Kind = NpcKind.Seller, BaseId = baseNpc, Name = "x", Shop = new ShopDraft() }, IsItem).Count);
sb.AppendLine("vendedor erros: " + string.Join("; ", NpcBuilder.Validate(mod, seller, IsItem)));
int sid = NpcBuilder.Build(mod, seller, Blank, Insert, n => "Item " + n);
var sn = mod.FindListByName("NPC_ESSENCE")!.Items.First(i => i.Id == sid.ToString());
var sv = mod.FindListByName("NPC_SELL_SERVICE")!.Items.First(i => i.Id == sn.Fields["id_sell_service"].Value);
sb.AppendLine($"vendedor {sid} loja {sv.Id} item1 {sv.Fields["pages_1_goods_1_id"].Value} item6 {sv.Fields["pages_1_goods_6_id"].Value} titulo {sv.Fields["pages_1_page_title"].Value} compra {sn.Fields["id_buy_service"].Value}");
var make = new MakeDraft(); make.Goods[0][0] = new RecipeDraft { Product = items[2], Count = 2, Price = 100, Materials = [(items[0], 3), (items[1], 1)] };
make.Goods[0][1] = new RecipeDraft { RecipeId = int.Parse(mod.FindListByName("RECIPE_ESSENCE")!.Items.First(r => r.Fields["id_skill"].Value == "0").Id) };
var forge = new NpcDraft { Kind = NpcKind.Forge, BaseId = baseNpc, Name = "Fornalha de teste", Make = make };
sb.AppendLine("fornalha erros: " + string.Join("; ", NpcBuilder.Validate(mod, forge, IsItem)));
var bad = make.Copy(); bad.Goods[0][0]!.Materials = [(items[0], 0)];
sb.AppendLine("material 0 acusa: " + NpcBuilder.Validate(mod, new NpcDraft { Kind = NpcKind.Forge, BaseId = baseNpc, Name = "x", Make = bad }, IsItem).Count);
int fid = NpcBuilder.Build(mod, forge, Blank, Insert, n => "Item " + n);
var fn = mod.FindListByName("NPC_ESSENCE")!.Items.First(i => i.Id == fid.ToString());
var ms = mod.FindListByName("NPC_MAKE_SERVICE")!.Items.First(i => i.Id == fn.Fields["id_make_service"].Value);
var rc = mod.FindListByName("RECIPE_ESSENCE")!.Items.First(i => i.Id == ms.Fields["pages_1_id_goods_1"].Value);
sb.AppendLine($"fornalha {fid} servico {ms.Id} receita {rc.Id} produto {rc.Fields["targets_1_id_to_make"].Value} chance {rc.Fields["targets_1_probability"].Value} qtd {rc.Fields["num_to_make"].Value} material {rc.Fields["materials_1_id"].Value}x{rc.Fields["materials_1_num"].Value}");
sb.AppendLine("teleportador sem destino acusa: " + NpcBuilder.Validate(mod, new NpcDraft { Kind = NpcKind.Teleporter, BaseId = baseNpc, Name = "x" }, IsItem).Count);
var tele = new NpcDraft { Kind = NpcKind.Teleporter, BaseId = baseNpc, Name = "Teleportador de teste", Stops = [new TeleportStop(3101, 500, 10), new TeleportStop(1901, 0, 0)], Discover = 3101 };
sb.AppendLine("teleportador erros: " + string.Join("; ", NpcBuilder.Validate(mod, tele, IsItem)));
int tid = NpcBuilder.Build(mod, tele, Blank, Insert, n => "Item " + n);
var tn = mod.FindListByName("NPC_ESSENCE")!.Items.First(i => i.Id == tid.ToString());
var ts = mod.FindListByName("NPC_TRANSMIT_SERVICE")!.Items.First(i => i.Id == tn.Fields["id_transmit_service"].Value);
sb.AppendLine($"teleportador {tid} servico {ts.Id} destinos {ts.Fields["num_targets"].Value}: {string.Join(", ", NpcBuilder.StopsOf(ts))} descobre {tn.Fields["id_to_discover"].Value}");
var ids = mod.Lists.Where(l => l.Name is "NPC_ESSENCE" or "NPC_SELL_SERVICE" or "NPC_MAKE_SERVICE").SelectMany(l => l.Items).Where(i => i.Id == sid.ToString() || i.Id == fid.ToString() || i.Id == sv.Id || i.Id == ms.Id).Count();
sb.AppendLine("ids sem repetir: " + (ids == 4));
var novos = ItemRules.Check(mod).Where(x => !before.Contains(x.Key)).ToList();
sb.AppendLine("problemas novos: " + novos.Count + " " + string.Join(" | ", novos.Take(5).Select(x => x.Rule + " " + x.Id + " " + x.Detail)));
File.WriteAllText(args[2], sb.ToString());
return;
}
if (args.Length >= 5 && args[0] == "--teleport-test") // <element> <world_targets.sev> <element de outro cliente> <saída>: leitura e escrita dos pontos, domínio, regiões e ajuda; não grava no jogo
{
var o = new List<string>();
var dir = Path.Combine(Path.GetTempPath(), "myace-tp-" + Environment.ProcessId);
Directory.CreateDirectory(Path.Combine(dir, "maps", "world"));
var txt = Path.Combine(dir, "maps", "world", "world_targets.txt");
File.Copy(Path.Combine(args[1], "maps", "world", "world_targets.txt"), txt);
File.Copy(args[2], Path.Combine(dir, "world_targets.sev"));
var t = WorldTargets.Open(dir, dir)!;
var txtBytes = File.ReadAllBytes(txt); var sevBytes = File.ReadAllBytes(Path.Combine(dir, "world_targets.sev"));
o.Add($"cliente {t.Client.Count} pontos, servidor {t.Server.Count}, proximo ID {t.NextId()}");
o.Add($"txt igual ao regravar: {t.ClientBytes().AsSpan().SequenceEqual(txtBytes)} ({t.ClientBytes().Length} x {txtBytes.Length})");
o.Add($"sev igual ao regravar: {WorldTargets.WriteServer(t.Server).AsSpan().SequenceEqual(sevBytes)}");
var (oc, os) = t.Differences();
o.Add($"so no cliente {oc.Count}: {string.Join(",", oc.Take(12))}; so no servidor {os.Count}: {string.Join(",", os.Take(12))}");
var p = t.Add("Ponto de teste", 1, 100.5f, 220.25f, -300.75f, -1);
t.Save();
var r = WorldTargets.Open(dir, dir)!;
o.Add($"depois de gravar: {r.Client.Count}/{r.Server.Count}, volta {r.Client.Find(x => x.Id == p.Id)} / {r.Server.Find(x => x.Id == p.Id)}");
var prec = PrecinctFile.Read(Path.Combine(args[1], "maps", "world", "precinct.clt"));
int same = 0, diff = 0;
foreach (var w in t.Client.Where(x => x.Tag == 1 && x.Id != p.Id))
{
int d = prec?.At(w.X, w.Z, prec.MainInstance)?.Domain ?? 0;
if ((d > 0 ? d : -1) == w.Domain) same++; else { diff++; if (diff <= 12) o.Add($" dominio difere: {w.Id} {w.Name}: arquivo {w.Domain}, precinct {d}"); }
}
o.Add($"dominio pelo precinct, mapa 1: {same} iguais, {diff} diferentes; areas com dominio {prec?.Areas.Count(a => a.Domain > 0)} de {prec?.Areas.Count}");
foreach (var map in Directory.GetDirectories(Path.Combine(args[1], "maps")))
{
var mine = Path.Combine(map, "precinct.clt"); var other = Path.Combine(args[3], "maps", Path.GetFileName(map), "precinct.clt");
if (!File.Exists(mine) || !File.Exists(other)) continue;
var b = PrecinctFile.Translate(File.ReadAllBytes(mine), File.ReadAllBytes(other), out int n);
if (b is null) continue;
var f = Path.Combine(dir, "precinct.clt"); File.WriteAllBytes(f, b);
var was = PrecinctFile.Read(mine)!; var now = PrecinctFile.Read(f)!;
bool keep = was.Areas.Count == now.Areas.Count && was.Areas.Zip(now.Areas).All(z => z.First.Points.SequenceEqual(z.Second.Points) && z.First.Music.SequenceEqual(z.Second.Music) && z.First.Sound == z.Second.Sound && z.First.Domain == z.Second.Domain);
o.Add($"precinct {Path.GetFileName(map)}: {n} nomes, resto igual {keep}, ex.: {was.Areas.Zip(now.Areas).Where(z => z.First.Name != z.Second.Name).Select(z => z.First.Name + " -> " + z.Second.Name).FirstOrDefault()}");
}
var (texts, files) = HelpScripts.Plan(Path.Combine(args[1], "help", "script.pck"), Path.Combine(args[3], "help", "script.pck"));
o.Add($"ajuda: {texts} textos em {files.Count} arquivos");
if (files.Count > 0) { var e = files.First(); o.Add($" ex.: {e.Key}: {string.Join(" | ", Encoding.UTF8.GetString(e.Value).Split('\n').Where(l => l.StartsWith("#name") || l.StartsWith("#steps")).Take(2))}"); }
Directory.Delete(dir, true);
File.WriteAllLines(args[4], o);
return;
}
if (args.Length >= 5 && args[0] == "--domain-test") // <element> <domain.sev> <saída> <png>: leitura e escrita dos territórios, triângulos e fronteiras
{
var o = new List<string>();
var bytes = File.ReadAllBytes(Path.Combine(args[1], "data", "domain.data"));
var dm = DomainMap.Parse(bytes);
o.Add($"cliente {dm.Areas.Count} territórios, regravar igual: {dm.Build().AsSpan().SequenceEqual(bytes)}");
var sb2 = File.ReadAllBytes(args[2]);
var ds = DomainServer.Parse(sb2);
o.Add($"servidor {ds.Entries.Count}, regravar igual: {ds.Build().AsSpan().SequenceEqual(sb2)}");
int fine = dm.Areas.Count(a => DomainMap.Triangulate(a.Vertices).Count == a.Faces.Count);
o.Add($"triângulos com a mesma contagem do arquivo: {fine} de {dm.Areas.Count}");
var old = dm.Areas.ToDictionary(a => a.Id, a => a.Neighbors.OrderBy(x => x).ToList());
dm.ComputeNeighbors();
int same = dm.Areas.Count(a => a.Neighbors.OrderBy(x => x).SequenceEqual(old[a.Id]));
o.Add($"fronteiras calculadas iguais às do arquivo: {same} de {dm.Areas.Count}");
var m2 = DomainMap.Parse(bytes);
ds.Match(m2);
o.Add($"par igual depois de Match: {ds.Build().AsSpan().SequenceEqual(sb2)}");
File.WriteAllLines(args[3], o);
MyAceEditor.UI.DomainEditorWindow.Shot(args[1], args[4]);
return;
}
if (args.Length >= 4 && args[0] == "--teleport-check") // <elements.data> <world_targets.sev> <saída>: destinos e pontos dos NPCs contra o servidor
{
var mod = CfgCatalog.Load(args[1]).Module;
var bad = ItemRules.CheckTeleports(mod, WorldTargets.ReadServer(File.ReadAllBytes(args[2])).Select(t => t.Id).ToHashSet());
File.WriteAllLines(args[3], bad.GroupBy(p => p.Rule).Select(g => $"{g.Key}: {g.Count()}").Concat(bad.Take(30).Select(p => p.ToString())));
return;
}
if (args.Length >= 3 && args[0] == "--atlas-test") // <tasks.data> <saída>: põe e tira um ponto do Atlas Geográfico na memória e relê
{
var o = new List<string>();
var tf = new TasksFile(args[1]);
var group = ((QuestNode)tf.Index.Find(6940)!).Children[^1];
int before = group.Children.Count;
var made = TeleportAtlas.Add(tf, 6940, "Vila de Teste", 9100)!;
o.Add($"nova subquest {made.Id} {made.Name}, grupo {group.Children.Count - before} a mais; acha pelo ponto: {TeleportAtlas.Find(tf, 6940, 9100)?.Id}");
var saved = tf.Build();
var again = new TasksFile(saved);
var back = TeleportAtlas.Find(again, 6940, 9100);
o.Add($"depois de gravar e reler: {back?.Id} {back?.Name}, pai {back?.Parent?.Id}, quests {again.Index.Nodes.Count} contra {tf.Index.Nodes.Count}");
TeleportAtlas.Remove(tf, made);
var bytes = new TasksFile(args[1]).Build();
o.Add($"tirar volta ao original: {tf.Build().AsSpan().SequenceEqual(bytes)}");
File.WriteAllLines(args[2], o);
return;
}
if (args.Length >= 4 && args[0] == "--quest-tree") // <tasks.data> <id> <saída>: nó, filhos e campos com valor
{
var tf = new TasksFile(args[1]);
var sb = new StringBuilder();
void Walk(QuestNode n, int depth)
{
sb.AppendLine(new string(' ', depth * 2) + $"{n.Id} {n.Name} filhos {n.Children.Count} fixed {n.Fixed.Length}");
if (depth <= 1) foreach (var f in n.Fields) { var raw = f.Offset + 4 <= n.Fixed.Length ? BitConverter.ToInt32(n.Fixed, f.Offset) : 0; if (raw != 0) sb.AppendLine(new string(' ', depth * 2 + 2) + $"{f.Group}/{f.Name}@{f.Offset} = {raw}"); }
foreach (var c in n.Children) Walk(c, depth + 1);
}
Walk((QuestNode)tf.Index.Find(int.Parse(args[2]))!, 0);
File.WriteAllText(args[3], sb.ToString());
return;
}
if (args.Length >= 3 && args[0] == "--teleport-report") // <pasta element> <saída>: qual NPC leva aonde, por quanto, e quem descobre cada ponto
{
var mod = CfgCatalog.Load(Path.Combine(args[1], "data", "elements.data")).Module;
var names = new Dictionary<string, string>();
foreach (var line in File.ReadAllText(Path.Combine(args[1], "maps", "world", "world_targets.txt"), Encoding.Unicode).Split('\n'))
if (System.Text.RegularExpressions.Regex.Match(line, "^(\\d+)\\s+\"([^\"]*)\"\\s+(\\d+)\\s+\"([^\"]*)\"") is { Success: true } m) names[m.Groups[1].Value] = $"{m.Groups[2].Value} (mapa {m.Groups[3].Value})";
var svc = mod.FindListByName("NPC_TRANSMIT_SERVICE")!.Items.ToDictionary(i => i.Id);
var sb = new StringBuilder("NPC\tServiço\tDestino\tTaxa\tNível\n");
var discover = new Dictionary<string, List<string>>();
int npcs = 0, links = 0; long maxFee = 0;
foreach (var n in mod.FindListByName("NPC_ESSENCE")!.Items)
{
string nm = MyAceEditor.PerfectWorld.TasksFile.SplitColor(n.Name).Text;
if (n.Fields.TryGetValue("id_to_discover", out var d) && d.Value is not ("0" or ""))
{ if (!discover.TryGetValue(d.Value, out var l)) discover[d.Value] = l = new(); l.Add(nm); }
if (!n.Fields.TryGetValue("id_transmit_service", out var t) || !svc.TryGetValue(t.Value, out var s)) continue;
npcs++;
int count = int.Parse(s.Fields["num_targets"].Value);
for (int i = 1; i <= count; i++)
{
var id = s.Fields[$"targets_{i}_idTarget"].Value; long fee = long.Parse(s.Fields[$"targets_{i}_fee"].Value);
maxFee = Math.Max(maxFee, fee); links++;
sb.AppendLine($"{nm} ({n.Id})\t{s.Id}\t{names.GetValueOrDefault(id, id)}\t{fee}\t{s.Fields[$"targets_{i}_required_level"].Value}");
}
}
sb.Insert(0, $"# {npcs} NPCs teleportadores, {links} ligações, {svc.Count} serviços, {names.Count} pontos, taxa máxima {maxFee}, pontos com NPC que descobre {discover.Count}\n");
sb.AppendLine("\n# Quem descobre cada ponto (id_to_discover)");
foreach (var (id, l) in discover.OrderBy(x => x.Key)) sb.AppendLine($"{names.GetValueOrDefault(id, id)}\t{string.Join(", ", l.Distinct().Take(4))}");
File.WriteAllText(args[2], sb.ToString());
return;
}
if (args.Length >= 5 && args[0] == "--path-near") // <saída> <pasta do mapa> <x> <z>: caminhos perto do ponto e quem anda neles (teste 24)
{
float px = float.Parse(args[3], System.Globalization.CultureInfo.InvariantCulture), pz = float.Parse(args[4], System.Globalization.CultureInfo.InvariantCulture);
var paths = PathFile.Read(File.ReadAllBytes(Path.Combine(args[2], "path.sev"))).Paths;
var gen = NpcGenFile.Read(File.ReadAllBytes(Path.Combine(args[2], "npcgen.data")));
var sb = new StringBuilder($"caminhos {paths.Count}, max {paths.Max(x => x.Id)}, pontos {gen.Spawns.Count}\n");
foreach (var pa in paths)
{
if (!pa.Points.Any(q => MathF.Abs(q.Pos.X - px) < 200 && MathF.Abs(q.Pos.Z - pz) < 200)) continue;
sb.AppendLine(FormattableString.Invariant($"caminho {pa.Id} v{pa.Version} pontos {pa.Points.Count} de ({pa.Points[0].Pos.X:0},{pa.Points[0].Pos.Y:0},{pa.Points[0].Pos.Z:0}) a ({pa.Points[^1].Pos.X:0},{pa.Points[^1].Pos.Y:0},{pa.Points[^1].Pos.Z:0})"));
foreach (var sp in gen.Spawns)
foreach (var c in sp.Creatures.Where(c => c.PathId == pa.Id))
sb.AppendLine(FormattableString.Invariant($" ponto #{gen.Spawns.IndexOf(sp)} em ({sp.Position.X:0},{sp.Position.Y:0},{sp.Position.Z:0}) raio {sp.Spread.X:0} tipo {sp.Type} grupo {sp.GroupType} criaturas {sp.Creatures.Count}: id {c.Id} qtd {c.Amount} laco {c.PathLoop}"));
}
sb.AppendLine("--- caminhos no ar (ponto a mais de 25 m acima do primeiro) ---");
foreach (var pa in paths.Where(x => x.Points.Max(q => q.Pos.Y) - x.Points.Min(q => q.Pos.Y) > 25 || x.Id > 1000000000))
{
int users = gen.Spawns.Sum(sp => sp.Creatures.Count(c => c.PathId == pa.Id));
sb.AppendLine(FormattableString.Invariant($"caminho {pa.Id} pontos {pa.Points.Count} usuarios {users} y {pa.Points.Min(q => q.Pos.Y):0}-{pa.Points.Max(q => q.Pos.Y):0} de ({pa.Points[0].Pos.X:0},{pa.Points[0].Pos.Z:0}) a ({pa.Points[^1].Pos.X:0},{pa.Points[^1].Pos.Z:0})"));
}
var byId = gen.Spawns.SelectMany(sp => sp.Creatures).Where(c => c.PathId > 1000000000).GroupBy(c => c.PathId);
foreach (var g in byId) sb.AppendLine($"usado {g.Key}: {g.Count()} criaturas, ids {string.Join(',', g.Select(c => c.Id).Distinct().Take(12))}");
foreach (var sp in gen.Spawns.Where(x => x.Creatures.Any(c => c.PathId > 1358957000))) sb.AppendLine(FormattableString.Invariant($"ponto #{gen.Spawns.IndexOf(sp)} em ({sp.Position.X:0},{sp.Position.Y:0},{sp.Position.Z:0}) raio {sp.Spread.X:0} criaturas {sp.Creatures.Count}: {string.Join(" ", sp.Creatures.Select(c => $"{c.Id}x{c.Amount}/caminho {c.PathId}/laco {c.PathLoop}"))}"));
File.WriteAllText(args[1], sb.ToString());
return;
}
if (args.Length >= 3 && args[0] == "--spt-all") // <pasta com .spt> <saída tsv>: nome, vértices de galho e de fronde, altura (compara com Tests/SptOracle)
{
using var o = new StreamWriter(args[2]);
foreach (var p in Directory.GetFiles(args[1], "*.spt", SearchOption.AllDirectories))
try { var m = SptGrower.Build(new SptFile(File.ReadAllBytes(p))); o.WriteLine(FormattableString.Invariant($"{Path.GetFileName(p).ToLowerInvariant()} {m.Pos.Count} {m.FrondPos.Count} {m.Height:0.0}")); }
catch (Exception ex) { o.WriteLine(Path.GetFileName(p) + " ERRO " + ex.Message); }
return;
}
if (args.Length >= 3 && args[0] == "--spt-stats") // <pasta com .spt> <saída tsv>: nome, Z mínimo, mediano e máximo, raio mediano e máximo (o par do --stats do Tests/SptOracle)
{
using var o = new StreamWriter(args[2]);
foreach (var p in Directory.GetFiles(args[1], "*.spt", SearchOption.AllDirectories))
{
var m = SptGrower.Build(new SptFile(File.ReadAllBytes(p)));
var pts = m.Pos.Concat(m.FrondPos).ToList();
if (pts.Count == 0) continue;
var z = pts.Select(v => v.Y).OrderBy(v => v).ToList();
var r = pts.Select(v => MathF.Sqrt(v.X * v.X + v.Z * v.Z)).OrderBy(v => v).ToList();
o.WriteLine(FormattableString.Invariant($"{Path.GetFileName(p).ToLowerInvariant()}\t{z[0]:0.00}\t{z[z.Count / 2]:0.00}\t{z[^1]:0.00}\t{r[r.Count / 2]:0.00}\t{r[^1]:0.00}"));
}
return;
}
if (args.Length >= 3 && args[0] == "--spt-obj") // <.spt ou pasta> <saída>: vértices de galho e fronde em eixos do SpeedTree (compara com Tests/SptOracle)
{
static void Obj(string spt, string to)
{
var m = SptGrower.Build(new SptFile(File.ReadAllBytes(spt)));
File.WriteAllLines(to, m.Pos.Select(p => FormattableString.Invariant($"v B {p.X} {-p.Z} {p.Y}"))
.Concat(m.FrondPos.Select(p => FormattableString.Invariant($"v F {p.X} {-p.Z} {p.Y}")))
.Concat(m.Leaves.Select(l => FormattableString.Invariant($"v L {l.Pos.X} {-l.Pos.Z} {l.Pos.Y}"))));
}
if (File.Exists(args[1])) { Obj(args[1], args[2]); return; }
Directory.CreateDirectory(args[2]);
foreach (var p in Directory.GetFiles(args[1], "*.spt", SearchOption.AllDirectories))
Obj(p, Path.Combine(args[2], Path.GetFileName(p).ToLowerInvariant() + ".txt"));
return;
}
if (args.Length >= 2 && args[0] == "--item-pick-shot") // <png>: janela de escolher item com dados de exemplo
{
var rows = Enumerable.Range(1, 40).Select(i => (Id: 1000 + i, Name: $"Item de exemplo {i}", Block: i % 3 == 0 ? "Armas" : i % 3 == 1 ? "Armaduras" : "Itens de quest")).ToList();
using var w = new MyAceEditor.UI.ItemSearchWindow(rows, favorites: [1003, 1006], recent: [1009, 1001]) { StartPosition = FormStartPosition.Manual, Location = new System.Drawing.Point(-20000, -20000) };
w.Show();
var stop = DateTime.Now.AddSeconds(2);
while (DateTime.Now < stop) { Application.DoEvents(); Thread.Sleep(30); }
using var img = new System.Drawing.Bitmap(w.Width, w.Height);
w.DrawToBitmap(img, new System.Drawing.Rectangle(0, 0, w.Width, w.Height));
img.Save(args[1], System.Drawing.Imaging.ImageFormat.Png);
return;
}
if (args.Length >= 2 && args[0] == "--xdrop-test") // <arquivos .sev...>: regrava cada um e confere byte a byte; relatório em xdrop-test.txt
{
var sb = new StringBuilder();
foreach (var f in args.Skip(1))
{
var bytes = File.ReadAllBytes(f);
var x = ExtraDropsFile.Parse(bytes);
sb.AppendLine($"{(x.ToBytes().AsSpan().SequenceEqual(bytes) ? "IDENTICO" : "DIFERENTE")} {x.Tables.Count} tabelas {f}");
}
File.WriteAllText("xdrop-test.txt", sb.ToString());
return;
}
if (args.Length >= 3 && args[0] == "--xdrop-shot") // <png> <extra_drops.sev>: print da aba Drops extras
{
using var w = new Form { Width = 1000, Height = 640, StartPosition = FormStartPosition.Manual, Location = new System.Drawing.Point(-20000, -20000), ShowInTaskbar = false };
var panel = new MyAceEditor.UI.ExtraDropsPanel { Dock = DockStyle.Fill };
w.Controls.Add(panel); w.Show(); panel.Open(args[2]);
var until = DateTime.Now.AddSeconds(2);
while (DateTime.Now < until) { Application.DoEvents(); Thread.Sleep(30); }
using var bmp = new System.Drawing.Bitmap(w.Width, w.Height);
w.DrawToBitmap(bmp, new System.Drawing.Rectangle(0, 0, w.Width, w.Height));
bmp.Save(args[1], System.Drawing.Imaging.ImageFormat.Png);
return;
}
if (args.Length >= 3 && args[0] is "--gm-shot" or "--adm-shot") // <png> <pasta element | pasta do servidor local>: print da janela fora da tela
{
Form w = args[0] == "--gm-shot" ? new MyAceEditor.UI.GmPanel(args[2])
: new MyAceEditor.UI.ServerAdminWindow(new LocalServer(args.Length >= 5 ? args[4] : ""), args[2], args.Length >= 4 ? args[3] : "", System.Drawing.Color.FromArgb(231, 236, 242), System.Drawing.Color.FromArgb(30, 39, 51), System.Drawing.Color.FromArgb(37, 99, 235));
w.StartPosition = FormStartPosition.Manual; w.Location = new System.Drawing.Point(-20000, -20000); w.ShowInTaskbar = false;
if (args[0] == "--gm-shot" && args.Length >= 4) { w.Width = int.Parse(args[3]); w.Height = 1000; } // [largura] [aba]: painel estreito ao lado do jogo
w.Show();
if (args[0] == "--gm-shot" && args.Length >= 5 && w.Controls.OfType<TabControl>().FirstOrDefault() is { } gmTabs) gmTabs.SelectedIndex = int.Parse(args[4]);
var until = DateTime.Now.AddSeconds(8);
while (DateTime.Now < until) { Application.DoEvents(); Thread.Sleep(30); }
using var bmp = new System.Drawing.Bitmap(w.Width, w.Height);
w.DrawToBitmap(bmp, new System.Drawing.Rectangle(0, 0, w.Width, w.Height));
bmp.Save(args[1], System.Drawing.Imaging.ImageFormat.Png);
w.Close();
return;
}
if (args.Length >= 4 && args[0] == "--adm") // <pasta do servidor local> deleterole|deleteaccount <id>: o mesmo do painel (adm.txt)
{
var adm = new ServerAdmin(new LocalServer(args[1]));
string? err = args[2] == "deleterole" ? adm.DeleteRole(int.Parse(args[3])) : args[2] == "deleteaccount" ? adm.DeleteAccount(int.Parse(args[3]))
: args[2] == "role" ? adm.RoleDetails(int.Parse(args[3]))?.ToString() ?? "não achei"
: args[2] == "broadcast" ? Run(() => adm.Broadcast(args[3]))
: args[2] == "start" ? new LocalServer(args[1]).Start().Output : "comando?";
static string? Run(Action a) { a(); return null; }
File.WriteAllText("adm.txt", err ?? "OK", new UTF8Encoding(false));
return;
}
if (args.Length >= 3 && args[0] == "--el-translate") // <elements destino> <elements traduzido>: quantos textos o plano troca (el-translate.txt)
{
var cur = CfgCatalog.Load(args[1]); var oth = CfgCatalog.Load(args[2]).Module;
var plan = ElementsTranslator.Plan(cur.Module, ElementsCfg.Load(cur.ConfigPath), oth);
File.WriteAllText("el-translate.txt", $"{plan.Count:N0} textos\n" + string.Join("\n", plan.Take(8).Select(c => $"{c.Block.Name} {c.Item.Id} {c.Field}: {c.Item.Fields[c.Field].Value} -> {c.Value}")), new UTF8Encoding(false));
return;
}
if (args.Length >= 3 && args[0] == "--shop-translate") // <gshop destino> <gshop traduzido>: quantos textos (shop-translate.txt)
{
var dst = GShopFile.ReadClient(File.ReadAllBytes(args[1])); var src = GShopFile.ReadClient(File.ReadAllBytes(args[2]));
int n = ClientTranslator.TranslateShop(dst, src, dryRun: false);
var back = GShopFile.ReadClient(dst.WriteClient());
File.WriteAllText("shop-translate.txt", $"{n:N0} textos · relido {back.Items.Count:N0} itens\n" + string.Join("\n", back.Items.Take(3).Select(i => $"{i.ItemId} {i.Name}: {i.Description[..Math.Min(80, i.Description.Length)]}")), new UTF8Encoding(false));
return;
}
if (args.Length >= 3 && args[0] == "--world-test") // <pasta element> <mapa>: terreno, construções e modelos (world-test.txt)
{
var sb = new StringBuilder();
var t = TerrainFile.Open(Path.Combine(args[1], "maps", args[2]));
sb.AppendLine(t is null ? "terreno: NÃO ABRIU" : $"terreno: {t.Width}×{t.Height} m · {t.Rows}×{t.Cols} pedaços · altura em (0,0) = {t.HeightAt(0, 0)}");
if (t is not null)
using (var tp = new PckArchive(Path.Combine(args[1], "textures.pck")))
{
// camadas do chão das primeiras áreas e se cada textura existe no textures.pck
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
for (int ar = 0; ar < 4; ar++)
for (int ac = 0; ac < 4; ac++)
{
TerrainFile.GroundLayer[]? ls = null;
try { ls = t.Ground(ar, ac); } catch (Exception ex) { sb.AppendLine($"área {ar},{ac}: ERRO {ex.Message}"); }
if (ls is null) continue;
sb.AppendLine($"área {ar},{ac}: {ls.Length} camadas");
foreach (var l in ls)
if (seen.Add(l.Texture)) sb.AppendLine($" {l.Texture} ×{l.UScale}/{l.VScale} máscara {(l.Mask is null ? "-" : l.MaskSide.ToString())} · {(tp.Find(l.Texture.ToLowerInvariant()) is null ? "NÃO EXISTE" : "ok")}");
}
}
using (var lit = new PckArchive(Path.Combine(args[1], "litmodels.pck")))
{
var bmds = lit.Entries.Where(e => e.Path.StartsWith($@"litmodels\{args[2]}\", StringComparison.OrdinalIgnoreCase) && e.Path.EndsWith(".bmd", StringComparison.OrdinalIgnoreCase)).ToList();
int ok = 0, bad = 0; string? firstBad = null;
var texNames = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
foreach (var e in bmds)
{
if (BmdModel.Read(lit.Read(e)) is { } bm) { ok++; foreach (var mesh in bm.Meshes) texNames[mesh.Texture] = texNames.GetValueOrDefault(mesh.Texture) + 1; }
else { bad++; firstBad ??= e.Path; }
}
sb.AppendLine($"construções: {bmds.Count:N0} .bmd · lidas {ok} de {Math.Min(400, bmds.Count)} · falharam {bad}" + (firstBad is null ? "" : $" (ex.: {firstBad})"));
// texturas das construções que não estão no building.pck (saem só com a cor do vértice)
using var bp = new PckArchive(Path.Combine(args[1], "building.pck"));
var others = new[] { "textures", "gfx", "models", "surfaces", "grasses", "trees" }
.Where(n => PckArchive.Exists(Path.Combine(args[1], n + ".pck"))).Select(n => (n, p: new PckArchive(Path.Combine(args[1], n + ".pck")))).ToList();
foreach (var (tn, cnt) in texNames.OrderByDescending(k => k.Value))
{
if (bp.Find(tn.ToLowerInvariant()) is not null) continue;
var where = others.Where(o => o.p.Find(tn.ToLowerInvariant()) is not null).Select(o => o.n).ToList();
sb.AppendLine($" sem textura no building.pck: {tn} ({cnt} malhas){(where.Count > 0 ? " · está em " + string.Join(", ", where) : "")}");
}
foreach (var o in others) o.p.Dispose();
}
File.WriteAllText("world-test.txt", sb.ToString(), new UTF8Encoding(false));
return;
}
if (args.Length >= 2 && args[0] == "--npcgen") // <npcgen.data>: lê e regrava (npcgen.txt)
{
string rep;
try
{
var d = File.ReadAllBytes(args[1]); var f = NpcGenFile.Read(d);
rep = $"v{f.Version} · {f.Spawns.Count:N0} pontos · {f.Resources.Count:N0} recursos · regrava {(f.Write().AsSpan().SequenceEqual(d) ? "IDÊNTICO" : "DIFERENTE")}";
// controladores (gatilhos): ID do jogo, nome, ligado ao abrir, quantos pontos usam (para testar plugins)
if (args.Length >= 3 && int.TryParse(args[2], out var cid)) // --npcgen <arquivo> <id da criatura>: pontos dela
foreach (var (sp, k) in f.Spawns.Select((sp, k) => (sp, k)).Where(x => x.sp.Creatures.Any(c => c.Id == cid)))
rep += $"\nponto {k}: pos {sp.Position.X:0},{sp.Position.Y:0},{sp.Position.Z:0} gatilho {sp.Trigger} autoRevive {sp.AutoRevive} initGen {sp.InitGen} renascer {string.Join("/", sp.Creatures.Select(c => c.Respawn))}";
foreach (var t in f.Triggers)
rep += $"\ncontrolador {t.GmId} (id {t.Id}) '{t.Name}' auto={t.AutoStart} pontos={f.Spawns.Count(x => x.Trigger == t.Id)}";
}
catch (Exception ex) { rep = "FALHOU: " + ex.Message; }
File.WriteAllText("npcgen.txt", rep, new UTF8Encoding(false));
return;
}
if (args.Length >= 3 && args[0] == "--model") // <pasta element> <.ecm>: acha o .ski do modelo (model.txt)
{
using var packs = new MyAceEditor.UI.ModelPacks(args[1]);
var r = packs.For(args[2]) is { } mp ? MyAceEditor.UI.WorldModels.ResolveSki(mp, args[2]) : null;
File.WriteAllText("model.txt", r is { } x ? $"OK {x.Dir}\ntexturas: {string.Join(", ", x.Ski.Textures)}" : "NÃO ACHEI", new UTF8Encoding(false));
return;
}
if (args.Length >= 4 && args[0] == "--field") // <elements.data> <bloco> <campo>: valor nos 8 primeiros itens (field.txt)
{
var list = CfgCatalog.Load(args[1]).Module.FindListByName(args[2]);
File.WriteAllText("field.txt", string.Join("\n", (list?.Items ?? new()).Where(i => args.Length < 5 || i.Id == args[4]).Take(8).Select(i => $"{i.Id}\t{i.Name}\t{(i.Fields.TryGetValue(args[3], out var f) ? $"{f.Type}: {f.Value}" : "(sem o campo)")}")), new UTF8Encoding(false));
return;
}
if (args.Length >= 2 && args[0] == "--drops") // <elements.data> [elements antigo]: drop dos monstros novos/mudados (ou com item a 100%) (drops.txt)
{
var mon = CfgCatalog.Load(args[1]).Module.FindListByName("MONSTER_ESSENCE");
var old = args.Length >= 3 ? CfgCatalog.Load(args[2]).Module.FindListByName("MONSTER_ESSENCE")?.Items.ToDictionary(i => i.Id, i => i) : null;
string V(Model.Item it, string k) => it.Fields.TryGetValue(k, out var f) ? f.Value : "?";
var sb = new StringBuilder();
foreach (var it in mon?.Items ?? new())
{
var drops = Enumerable.Range(1, 32).Select(i => (Id: V(it, $"drop_matters_{i}_id"), P: V(it, $"drop_matters_{i}_probability"))).Where(d => d.Id is not ("0" or "?")).ToList();
bool changed = old is not null && (!old.TryGetValue(it.Id, out var o) || it.Fields.Any(f => V(o, f.Key) != f.Value.Value));
if (old is not null ? !changed : !drops.Any(d => float.TryParse(d.P, System.Globalization.CultureInfo.InvariantCulture, out var p) && p >= 0.99f)) continue;
sb.AppendLine($"{it.Id}\t{it.Name}\tnum0..3 = {V(it, "probability_drop_num0")} {V(it, "probability_drop_num1")} {V(it, "probability_drop_num2")} {V(it, "probability_drop_num3")}\tdrop_times = {V(it, "drop_times")}\tdinheiro = {V(it, "money_average")}±{V(it, "money_var")}\tnível = {V(it, "level")}");
sb.AppendLine("\titens: " + string.Join(", ", drops.Select(d => $"{d.Id} ({d.P})")));
}
File.WriteAllText("drops.txt", sb.ToString(), new UTF8Encoding(false));
return;
}
if (args.Length >= 3 && args[0] == "--new-items") // <elements novo> <elements antigo>: registros que só existem no novo (new-items.txt)
{
var a = CfgCatalog.Load(args[1]).Module; var b = CfgCatalog.Load(args[2]).Module;
var sb = new StringBuilder();
foreach (var l in a.Lists)
{
var old = b.FindListByName(l.Name)?.Items.Select(i => i.Id).ToHashSet() ?? new();
foreach (var it in l.Items.Where(i => !old.Contains(i.Id)))
sb.AppendLine($"{l.Name}\t{it.Id}\t{it.Name}\t" + string.Join(" ", it.Fields.Where(f => f.Key is "proc_type" or "id_major_type" or "id_sub_type" or "pile_num_max" or "file_matter" or "level").Select(f => $"{f.Key}={f.Value.Value}")));
}
File.WriteAllText("new-items.txt", sb.ToString(), new UTF8Encoding(false));
return;
}
if (args.Length >= 5 && args[0] == "--item-set") // <elements.data> <bloco> <id> <campo=valor,...>: muda e grava com backup (item-set.txt)
{
var mod = CfgCatalog.Load(args[1]).Module;
var it = mod.FindListByName(args[2])?.FindById(args[3]);
var log = new StringBuilder();
if (it is null) log.Append("item não encontrado");
else
{
foreach (var kv in args[4].Split(','))
{
var p = kv.Split('=', 2);
if (p.Length == 2 && it.Fields.TryGetValue(p[0], out var f)) { log.AppendLine($"{p[0]}: {f.Value} -> {p[1]}"); it.Fields[p[0]] = MyAceEditor.Model.Field.Of(f.Type, p[1]); }
else log.AppendLine($"{kv}: campo não existe");
}
var bk = ElementsWriter.Save(mod, args[1]);
log.AppendLine("gravado; backup " + bk);
}
File.WriteAllText("item-set.txt", log.ToString());
return;
}
if (args.Length >= 5 && args[0] == "--item-field") // <elements.data> <bloco> <id> <campo,...>: valores dos campos do item (item-field.txt)
{
var mod = CfgCatalog.Load(args[1]).Module;
var it = mod.FindListByName(args[2])?.FindById(args[3]);
File.WriteAllText("item-field.txt", it is null ? "item não encontrado" : string.Join("\n", args[4].Split(',').Select(k => $"{k} = {it.Fields.GetValueOrDefault(k)?.Value ?? "(sem campo)"}")));
return;
}
if (args.Length >= 4 && args[0] == "--item-diff") // <elements.data> <id> <id>: campos que diferem entre os dois itens (item-diff.txt)
{
var m = CfgCatalog.Load(args[1]).Module;
(Model.Item It, string List)? Find(string id) => m.Lists.SelectMany(l => l.Items.Select(i => (i, l.Name))).FirstOrDefault(x => x.i.Id == id) is var r && r.i is not null ? r : null;
var (a, b) = (Find(args[2]), Find(args[3]));
var sb = new StringBuilder($"{args[2]}: {a?.List ?? "não existe"}\n{args[3]}: {b?.List ?? "não existe"}\n");
foreach (var id in new[] { args[2], args[3] }) // o mesmo ID em mais de uma lista (o gs acha pelo ID em todas)
sb.AppendLine($"{id} em: " + string.Join(", ", m.Lists.Where(l => l.Items.Any(i => i.Id == id)).Select(l => $"{l.Name} ({string.Join(" / ", l.Items.Where(i => i.Id == id).Select(i => i.Name))})")));
if (a is { } x && b is { } y)
foreach (var k in x.It.Fields.Keys.Union(y.It.Fields.Keys))
if (x.It.Fields.GetValueOrDefault(k)?.Value != y.It.Fields.GetValueOrDefault(k)?.Value)
sb.AppendLine($"{k}: {x.It.Fields.GetValueOrDefault(k)?.Value} | {y.It.Fields.GetValueOrDefault(k)?.Value}");
File.WriteAllText("item-diff.txt", sb.ToString(), new UTF8Encoding(false));
return;
}
if (args.Length >= 3 && args[0] == "--item-texts") // <configs.pck> <pasta de teste>: round-trip + editar cor/descrição numa CÓPIA e conferir (item-texts.txt)
{
var sb = new StringBuilder();
var copy = Path.Combine(args[2], "configs.pck");
Directory.CreateDirectory(args[2]); File.Copy(args[1], copy, true);
using (var p = new PckArchive(copy))
foreach (var f in new[] { ItemTexts.ColorFile, ItemTexts.DescFile })
sb.AppendLine($"{f}: round-trip {(p.Find(f) is { } e && ItemTexts.Decode(p.Read(e)) is not null ? "OK" : "FALHOU")}");
var before = GameConfigs.Load(copy)!;
int multi = before.ItemDescs.Keys.FirstOrDefault(k => before.ItemDescs[k].Contains("Dexterity +10-11"));
int anyId = before.ItemDescs.Keys.First(), newId = 999_001;
sb.AppendLine($"descrições: {before.ItemDescs.Count} cores: {before.ItemColors.Count} (2 linhas, ex.: {multi})");
ItemTexts.Save(copy, new Dictionary<int, int?> { [anyId] = 8, [newId] = 3 },
new Dictionary<int, string?> { [anyId] = "^ff0000Teste\n^ffffffLinha 2", [newId] = "^aa32ffNovo", [multi] = null });
var after = GameConfigs.Load(copy)!;
sb.AppendLine($"cor {anyId}: {after.ItemColors.GetValueOrDefault(anyId)} (8) cor {newId}: {after.ItemColors.GetValueOrDefault(newId)} (3)");
sb.AppendLine($"desc {anyId}: {after.ItemDescs.GetValueOrDefault(anyId)}");
sb.AppendLine($"desc {newId}: {after.ItemDescs.GetValueOrDefault(newId)} desc {multi} tirada: {!after.ItemDescs.ContainsKey(multi)}");
int changed = before.ItemDescs.Count(kv => kv.Key != anyId && kv.Key != multi && after.ItemDescs.GetValueOrDefault(kv.Key) != kv.Value);
sb.AppendLine($"outras descrições alteradas: {changed}; total {after.ItemDescs.Count} (esperado {before.ItemDescs.Count})");
using (var a = new PckArchive(args[1])) using (var b = new PckArchive(copy)) // os outros arquivos do pacote seguem iguais
{
int diff = a.Entries.Count(e => e.Path != ItemTexts.ColorFile && e.Path != ItemTexts.DescFile && (b.Find(e.Path) is not { } be || !a.Read(e).AsSpan().SequenceEqual(b.Read(be))));
sb.AppendLine($"outros arquivos do pacote diferentes: {diff} de {a.Entries.Count - 2}");
}