-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
1466 lines (1374 loc) · 67 KB
/
Program.cs
File metadata and controls
1466 lines (1374 loc) · 67 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
// "FBX ASCII Rebake Tool"
// ASCII FBX Transform Baker + Unity Prefab Transform Resetter
// by: vector_cmdr (https://github.com/vectorcmdr)
//
// This tool processes ASCII FBX files in the current directory,
// and bakes original local rotation, scale etc. (Properties70)
// into geometry properties (Geometry) and resets the properties.
// It also processes Unity prefab files that correspond to the
// FBX files and resets m_LocalRotation to identity quaternion,
// m_LocalScale to (1,1,1), m_LocalEulerAnglesHint to (0,0,0).
//
// It then writes the modified files to a subdirectory named "baked".
//
// License: MIT License (https://opensource.org/licenses/MIT)
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
namespace RebaseFBX
{
class Program
{
const double NZT = 1e-6;
static int Main(string[] args)
{
string dir = args.Length > 0 ? args[0] : Directory.GetCurrentDirectory();
if (!Directory.Exists(dir)) { Console.Error.WriteLine($"Directory not found: {dir}"); return 1; }
string outDir = Path.Combine(dir, "baked");
Directory.CreateDirectory(outDir);
int ok = 0, fail = 0;
// Process FBX files
string[] fbxFiles = Directory.GetFiles(dir, "*.fbx", SearchOption.TopDirectoryOnly);
foreach (string path in fbxFiles)
{
string fname = Path.GetFileName(path);
Console.WriteLine($"\n--- {fname} ---");
try
{
if (IsBinary(path)) { Console.WriteLine(" SKIPPED (binary)."); continue; }
string[] lines = File.ReadAllLines(path);
int n = ProcessFbx(lines);
Console.WriteLine(n > 0 ? $" Baked {n} submesh(es)." : " Nothing to bake.");
File.WriteAllLines(Path.Combine(outDir, fname), lines);
Console.WriteLine($" -> {Path.Combine(outDir, fname)}"); ok++;
}
catch (Exception ex) { Console.Error.WriteLine($" FAILED: {ex.Message}\n{ex.StackTrace}"); fail++; }
}
// Process Unity .prefab files
string[] prefabFiles = Directory.GetFiles(dir, "*.prefab", SearchOption.TopDirectoryOnly);
foreach (string path in prefabFiles)
{
string fname = Path.GetFileName(path);
Console.WriteLine($"\n--- {fname} ---");
try
{
string[] lines = File.ReadAllLines(path);
int n = ProcessPrefab(lines);
Console.WriteLine(n > 0 ? $" Reset {n} Transform(s)." : " Nothing to reset.");
File.WriteAllLines(Path.Combine(outDir, fname), lines);
Console.WriteLine($" -> {Path.Combine(outDir, fname)}"); ok++;
}
catch (Exception ex) { Console.Error.WriteLine($" FAILED: {ex.Message}\n{ex.StackTrace}"); fail++; }
}
if (fbxFiles.Length == 0 && prefabFiles.Length == 0)
Console.WriteLine("No .fbx or .prefab files found.");
Console.WriteLine($"\nDone. OK={ok} FAIL={fail}");
return fail > 0 ? 1 : 0;
}
/// <summary>
/// Determines if the specified FBX file is in binary format.
/// Reads the first 20 bytes of the file and checks for the "Kaydara FBX Binary" signature.
/// Returns true if the file is binary, otherwise false.
/// </summary>
/// <param name="p">Path to the FBX file.</param>
/// <returns>True if the file is binary; false if ASCII or unreadable.</returns>
static bool IsBinary(string p)
{
try
{
byte[] h = new byte[20];
using var f = File.OpenRead(p);
f.Read(h, 0, 20);
return Encoding.ASCII.GetString(h).StartsWith("Kaydara FBX Binary");
}
catch{ return false; }
}
/// <summary>
/// Matches inline: m_LocalRotation: {x: 0.123, y: 0, z: 0, w: 1}
/// </summary>
static readonly Regex RxRotInline = new Regex(
@"^(\s*m_LocalRotation:\s*)\{x:\s*[^,]+,\s*y:\s*[^,]+,\s*z:\s*[^,]+,\s*w:\s*[^\}]+\}",
RegexOptions.Compiled);
/// <summary>
/// Matches inline: m_LocalScale: {x: 1, y: 1, z: 1}
/// </summary>
static readonly Regex RxScaleInline = new Regex(
@"^(\s*m_LocalScale:\s*)\{x:\s*[^,]+,\s*y:\s*[^,]+,\s*z:\s*[^\}]+\}",
RegexOptions.Compiled);
/// <summary>
/// Matches inline: m_LocalEulerAnglesHint: {x: 0, y: 90, z: 0}
/// </summary>
static readonly Regex RxEulerInline = new Regex(
@"^(\s*m_LocalEulerAnglesHint:\s*)\{x:\s*[^,]+,\s*y:\s*[^,]+,\s*z:\s*[^\}]+\}",
RegexOptions.Compiled);
/// <summary>
/// Processes a Unity .prefab YAML file for a rebaked rebased FBX.
/// Finds all Transform / RectTransform components and resets
/// m_LocalRotation, m_LocalScale, and m_LocalEulerAnglesHint.
/// Preserves all other content byte-for-byte.
/// </summary>
static int ProcessPrefab(string[] L)
{
int resetCount = 0;
for (int i = 0; i < L.Length; i++)
{
string trimmed = L[i].TrimStart();
// m_LocalRotation
// Inline form: m_LocalRotation: {x: .., y: .., z: .., w: ..}
if (trimmed.StartsWith("m_LocalRotation:"))
{
var m = RxRotInline.Match(L[i]);
if (m.Success)
{
string prefix = m.Groups[1].Value;
string newVal = "{x: 0, y: 0, z: 0, w: 1}";
L[i] = prefix + newVal;
resetCount++;
}
else if (trimmed == "m_LocalRotation:")
{
// Multi-line form:
// m_LocalRotation:
// x: 0
// y: 0
// z: 0
// w: 1
ResetMultiLineQuat(L, i + 1);
resetCount++;
}
}
// m_LocalScale
else if (trimmed.StartsWith("m_LocalScale:"))
{
var m = RxScaleInline.Match(L[i]);
if (m.Success)
{
string prefix = m.Groups[1].Value;
L[i] = prefix + "{x: 1, y: 1, z: 1}";
}
else if (trimmed == "m_LocalScale:")
{
ResetMultiLineVec3(L, i + 1, 1, 1, 1);
}
}
// m_LocalEulerAnglesHint
else if (trimmed.StartsWith("m_LocalEulerAnglesHint:"))
{
var m = RxEulerInline.Match(L[i]);
if (m.Success)
{
string prefix = m.Groups[1].Value;
L[i] = prefix + "{x: 0, y: 0, z: 0}";
}
else if (trimmed == "m_LocalEulerAnglesHint:")
{
ResetMultiLineVec3(L, i + 1, 0, 0, 0);
}
}
}
return resetCount;
}
/// <summary>
/// Resets multi-line quaternion (x, y, z, w) starting at line 'start'.
/// </summary>
static void ResetMultiLineQuat(string[] L, int start)
{
var map = new Dictionary<string, string>
{ { "x", "0" }, { "y", "0" }, { "z", "0" }, { "w", "1" } };
for (int i = start; i < Math.Min(start + 6, L.Length); i++)
{
string t = L[i].TrimStart();
foreach (var kv in map)
{
if (t.StartsWith(kv.Key + ":"))
{
int colon = L[i].IndexOf(':');
L[i] = L[i].Substring(0, colon + 1) + " " + kv.Value;
break;
}
}
}
}
/// <summary>
/// Resets multi-line vector3 (x, y, z) starting at line 'start'.
/// </summary>
static void ResetMultiLineVec3(string[] L, int start, double x, double y, double z)
{
var map = new Dictionary<string, string>
{ { "x", Fmt(x) }, { "y", Fmt(y) }, { "z", Fmt(z) } };
for (int i = start; i < Math.Min(start + 5, L.Length); i++)
{
string t = L[i].TrimStart();
foreach (var kv in map)
{
if (t.StartsWith(kv.Key + ":"))
{
int colon = L[i].IndexOf(':');
L[i] = L[i].Substring(0, colon + 1) + " " + kv.Value;
break;
}
}
}
}
/// <summary>
/// Represents a model entry in the FBX file.
/// </summary>
/// <remarks>
/// This struct is used to store information about a model node parsed from the FBX "Objects" section.
/// <list type="bullet">
/// <item>
/// <description><see cref="Id"/>: The unique identifier of the model node.</description>
/// </item>
/// <item>
/// <description><see cref="Name"/>: The name of the model node (as parsed from the FBX).</description>
/// </item>
/// <item>
/// <description><see cref="Ps"/>: The start line index of the Properties section for this model in the FBX file, or -1 if not found.</description>
/// </item>
/// <item>
/// <description><see cref="Pe"/>: The end line index of the Properties section for this model in the FBX file, or -1 if not found.</description>
/// </item>
/// </list>
/// </remarks>
struct MdlE { public long Id; public string Name; public int Ps, Pe; }
/// <summary>
/// Represents a geometry entry in the FBX file.
/// </summary>
/// <remarks>
/// This struct is used to store information about a geometry node parsed from the FBX "Objects" section.
/// <list type="bullet">
/// <item>
/// <description><see cref="Id"/>: The unique identifier of the geometry node.</description>
/// </item>
/// <item>
/// <description><see cref="Bs"/>: The start line index of the geometry block in the FBX file (inclusive).</description>
/// </item>
/// <item>
/// <description><see cref="Be"/>: The end line index of the geometry block in the FBX file (inclusive).</description>
/// </item>
/// </list>
/// </remarks>
struct GeoE { public long Id; public int Bs, Be; }
/// <summary>
/// Processes an ASCII FBX file's contents, baking transform properties into geometry and resetting transform properties.
/// </summary>
/// <param name="L">The lines of the FBX file to process.</param>
/// <remarks>
/// <para>
/// This method parses the "Objects" and "Connections" sections of the FBX file to identify model and geometry nodes,
/// and maps geometry nodes to their parent model nodes. For each geometry-model pair, it:
/// </para>
/// <para>
/// The method preserves the original file structure and formatting as much as possible, only modifying the relevant transform and geometry data in-place.
/// </para>
/// <para>
/// If no eligible geometry is found or no transforms need baking, returns 0.
/// </para>
/// <returns>
/// The number of geometry submeshes that were baked (i.e. had transforms applied and reset).
/// </returns>
/// </remarks>
static int ProcessFbx(string[] L)
{
FindSec(L, "Objects", out int oS, out int oE); if (oS < 0) return 0;
FindSec(L, "Connections", out int cS, out int cE);
var mdls = new Dictionary<long, MdlE>();
for (int i = oS; i <= oE; i++)
{
string t = L[i].TrimStart(); if (!t.StartsWith("Model:")) continue;
long id = PId(t); if (id == 0) continue;
int bo = FB(L, i, oE); if (bo < 0) continue;
int bc = FC(L, bo); if (bc < 0) continue;
var me = new MdlE { Id = id, Name = EName(t), Ps = -1, Pe = -1 };
for (int j = bo + 1; j < bc; j++)
{
string pt = L[j].TrimStart();
if (pt.StartsWith("Properties70:") || pt.StartsWith("Properties60:"))
{
int po = FB(L, j, bc);
if (po >= 0)
{
int pc = FC(L, po);
if (pc >= 0) { me.Ps = po; me.Pe = pc; }
}
break;
}
}
mdls[id] = me; i = bc;
}
var geos = new Dictionary<long, GeoE>();
for (int i = oS; i <= oE; i++)
{
string t = L[i].TrimStart(); if (!t.StartsWith("Geometry:") || !t.Contains("\"Mesh\"")) continue;
long gid = PId(t); if (gid == 0) continue;
int bo = FB(L, i, oE); if (bo < 0) continue;
int bc = FC(L, bo); if (bc < 0) continue;
geos[gid] = new GeoE { Id = gid, Bs = bo + 1, Be = bc - 1 }; i = bc;
}
var g2m = new Dictionary<long, long>();
if (cS >= 0) for (int i = cS; i <= cE; i++)
{
string t = L[i].TrimStart(); int ci = t.IndexOf("C:", StringComparison.Ordinal); if (ci < 0) continue;
string[] p = CSV(t.Substring(ci + 2)); if (p.Length < 3 || UQ(p[0]) != "OO") continue;
long ch = PL(p[1]), pa = PL(p[2]);
if (ch != 0 && pa != 0 && geos.ContainsKey(ch) && mdls.ContainsKey(pa)) g2m[ch] = pa;
}
int baked = 0;
foreach (var kvp in g2m)
{
long gid = kvp.Key, mid = kvp.Value;
var mdl = mdls[mid]; var geo = geos[gid];
if (mdl.Ps < 0) continue;
int ps = mdl.Ps, pe = mdl.Pe;
Vec3 rot = RV3(L, ps, pe, "Lcl Rotation", V0);
Vec3 scl = RV3(L, ps, pe, "Lcl Scaling", V1);
Vec3 tr = RV3(L, ps, pe, "Lcl Translation", V0);
Vec3 pre = RV3(L, ps, pe, "PreRotation", V0);
Vec3 pst = RV3(L, ps, pe, "PostRotation", V0);
Vec3 rof = RV3(L, ps, pe, "RotationOffset", V0);
Vec3 rpv = RV3(L, ps, pe, "RotationPivot", V0);
Vec3 sof = RV3(L, ps, pe, "ScalingOffset", V0);
Vec3 spv = RV3(L, ps, pe, "ScalingPivot", V0);
Vec3 gT = RV3(L, ps, pe, "GeometricTranslation", V0);
Vec3 gR = RV3(L, ps, pe, "GeometricRotation", V0);
Vec3 gS = RV3(L, ps, pe, "GeometricScaling", V1);
int ro = 0;
int roLn = FPL(L, ps, pe, "RotationOrder");
if (roLn >= 0)
{
var rp = CSV(L[roLn].Substring(L[roLn].IndexOf(':') + 1));
if (rp.Length >= 1) int.TryParse(rp[rp.Length - 1].Trim(), out ro);
}
bool any = !IsZ(rot) || !Is1(scl) || !IsZ(pre) || !IsZ(pst) || !IsZ(gT) || !IsZ(gR) || !Is1(gS);
if (!any) continue;
Console.Write($" [{mdl.Name}] o={RN(ro)}");
if (!IsZ(rot)) Console.Write($" r=({rot.X:G5},{rot.Y:G5},{rot.Z:G5})");
if (!Is1(scl)) Console.Write($" s=({scl.X:G5},{scl.Y:G5},{scl.Z:G5})");
if (!IsZ(pre)) Console.Write($" pre=({pre.X:G5},{pre.Y:G5},{pre.Z:G5})");
if (!IsZ(pst)) Console.Write($" pst=({pst.X:G5},{pst.Y:G5},{pst.Z:G5})");
if (!IsZ(gR)) Console.Write($" gR=({gR.X:G5},{gR.Y:G5},{gR.Z:G5})");
if (!Is1(gS)) Console.Write($" gS=({gS.X:G5},{gS.Y:G5},{gS.Z:G5})");
Mat4 mNode = Mat4.Tr(tr) * Mat4.Tr(rof) * Mat4.Tr(rpv)
* Mat4.Euler(pre, 0) * Mat4.Euler(rot, ro) * Mat4.Invert(Mat4.Euler(pst, 0))
* Mat4.Tr(Neg(rpv)) * Mat4.Tr(sof) * Mat4.Tr(spv) * Mat4.Scale(scl) * Mat4.Tr(Neg(spv));
Mat4 mGeo = Mat4.Tr(gT) * Mat4.Euler(gR, 0) * Mat4.Scale(gS);
Mat4 mClean = Mat4.Tr(tr) * Mat4.Tr(rof) * Mat4.Tr(sof);
Mat4 mBake = Mat4.Invert(mClean) * mNode * mGeo;
double det3 = Det3(mBake);
bool mirr = det3 < 0;
if (mirr) Console.Write(" [MIRROR]");
Console.WriteLine();
Mat4 nBake = NormalMat(mBake);
XfArr(L, geo.Bs, geo.Be, "Vertices", mBake, false);
List<int[]> polys = mirr ? ParsePolys(L, geo.Bs, geo.Be) : null;
ProcLE(L, geo.Bs, geo.Be, "LayerElementNormal", "Normals", nBake, mirr, polys);
ProcLE(L, geo.Bs, geo.Be, "LayerElementTangent", "Tangents", nBake, mirr, polys);
ProcLE(L, geo.Bs, geo.Be, "LayerElementBinormal", "Binormals", nBake, mirr, polys);
if (mirr)
{
ReordLE(L, geo.Bs, geo.Be, "LayerElementUV", "UV", polys, 2);
ReordLE(L, geo.Bs, geo.Be, "LayerElementColor", "Colors", polys, 4);
ReverseWind(L, geo.Bs, geo.Be);
}
int nzf = FixNZ(L, geo.Bs, geo.Be);
if (nzf > 0) Console.WriteLine($" -> Fixed {nzf} near-zero normal(s)");
WV3(L, ps, pe, "Lcl Rotation", 0, 0, 0);
WV3(L, ps, pe, "Lcl Scaling", 1, 1, 1);
WV3(L, ps, pe, "PreRotation", 0, 0, 0);
WV3(L, ps, pe, "PostRotation", 0, 0, 0);
WV3(L, ps, pe, "GeometricTranslation", 0, 0, 0);
WV3(L, ps, pe, "GeometricRotation", 0, 0, 0);
WV3(L, ps, pe, "GeometricScaling", 1, 1, 1);
baked++;
}
return baked;
}
/// <summary>
/// Processes LayerElement arrays in FBX geometry, applies transformation matrix
/// and optionally reorders elements for mirrored meshes.
/// </summary>
static void ProcLE(string[] L, int rs, int re,
string leName, string arrName, Mat4 nm, bool reord, List<int[]> polys)
{
for (int i = rs; i <= re; i++)
{
string t = L[i].TrimStart();
if (!t.StartsWith(leName)) continue;
int bo = FB(L, i, re); if (bo < 0) continue;
int bc = FC(L, bo); if (bc < 0) continue;
XfArr(L, bo + 1, bc - 1, arrName, nm, true);
if (reord && polys != null)
{
string map = RSt(L, bo + 1, bc - 1, "MappingInformationType");
if (map.IndexOf("ByPolygonVertex", StringComparison.OrdinalIgnoreCase) >= 0)
{
string reft = RSt(L, bo + 1, bc - 1, "ReferenceInformationType");
if (reft.IndexOf("IndexToDirect", StringComparison.OrdinalIgnoreCase) >= 0)
ReordI(L, bo + 1, bc - 1, arrName + "Index", polys, 1);
else
ReordD(L, bo + 1, bc - 1, arrName, polys, 3);
}
}
i = bc;
}
}
/// <summary>
/// Reorders LayerElement arrays in FBX geometry for mirrored meshes, based on polygon winding and stride.
/// </summary>
static void ReordLE(string[] L, int rs, int re,
string leName, string arrName, List<int[]> polys, int stride)
{
if (polys == null) return;
for (int i = rs; i <= re; i++)
{
string t = L[i].TrimStart();
if (!t.StartsWith(leName)) continue;
int bo = FB(L, i, re); if (bo < 0) continue;
int bc = FC(L, bo); if (bc < 0) continue;
string map = RSt(L, bo + 1, bc - 1, "MappingInformationType");
if (map.IndexOf("ByPolygonVertex", StringComparison.OrdinalIgnoreCase) < 0)
{
i = bc;
continue;
}
string reft = RSt(L, bo + 1, bc - 1, "ReferenceInformationType");
if (reft.IndexOf("IndexToDirect", StringComparison.OrdinalIgnoreCase) >= 0)
ReordI(L, bo + 1, bc - 1, arrName + "Index", polys, 1);
else
ReordD(L, bo + 1, bc - 1, arrName, polys, stride);
i = bc;
}
}
/// <summary>
/// Parses the PolygonVertexIndex array in FBX geometry and returns a list of polygon index arrays.
/// </summary>
static List<int[]> ParsePolys(string[] L, int rs, int re)
{
int[] raw = RdI(L, rs, re, "PolygonVertexIndex"); if (raw == null) return null;
var polys = new List<int[]>(); int ps = 0;
for (int i = 0; i < raw.Length; i++)
{
if (raw[i] < 0)
{
int len = i - ps + 1;
int[] p = new int[len];
for (int j = 0; j < len; j++) p[j] = ps + j;
polys.Add(p); ps = i + 1;
}
}
return polys;
}
/// <summary>
/// Reverses the winding order of polygons in the PolygonVertexIndex array for mirrored meshes.
/// </summary>
static void ReverseWind(string[] L, int rs, int re)
{
int[] v = RdI(L, rs, re, "PolygonVertexIndex", out var li); if (v == null) return;
int ps = 0, pc = 0;
for (int i = 0; i < v.Length; i++)
if (v[i] < 0)
{
int lr = -(v[i] + 1); int len = i - ps + 1;
int[] pv = new int[len];
for (int j = 0; j < len - 1; j++) pv[j] = v[ps + j];
pv[len - 1] = lr; Array.Reverse(pv);
for (int j = 0; j < len - 1; j++) v[ps + j] = pv[j];
v[i] = -(pv[len - 1] + 1); ps = i + 1; pc++;
}
WrI(L, v, li); Console.WriteLine($" -> Reversed winding on {pc} polygon(s)");
}
/// <summary>
/// Reorders direct-mapped LayerElement arrays for mirrored meshes, swapping elements within each polygon.
/// </summary>
static void ReordD(string[] L, int rs, int re, string name, List<int[]> polys, int stride)
{
double[] v = RdD(L, rs, re, name, out var li); if (v == null) return;
foreach (var poly in polys)
{
for (int a = 0, b = poly.Length - 1; a < b; a++, b--)
{
int ai = poly[a] * stride, bi = poly[b] * stride;
for (int s = 0; s < stride; s++)
{
double tmp = v[ai + s];
v[ai + s] = v[bi + s];
v[bi + s] = tmp;
}
}
}
WrD(L, v, li);
}
/// <summary>
/// Reorders index-mapped LayerElement arrays for mirrored meshes, swapping indices within each polygon.
/// </summary>
static void ReordI(string[] L, int rs, int re, string name, List<int[]> polys, int stride)
{
int[] v = RdI(L, rs, re, name, out var li); if (v == null) return;
foreach (var poly in polys)
{
for (int a = 0, b = poly.Length - 1; a < b; a++, b--)
{
int ai = poly[a] * stride, bi = poly[b] * stride;
for (int s = 0; s < stride; s++)
{
int tmp = v[ai + s];
v[ai + s] = v[bi + s];
v[bi + s] = tmp;
}
}
}
WrI(L, v, li);
}
/// <summary>
/// Fixes near-zero normals in LayerElementNormal arrays, normalizes them, and replaces invalid normals.
/// </summary>
static int FixNZ(string[] L, int rs, int re)
{
int total = 0;
for (int i = rs; i <= re; i++)
{
string t = L[i].TrimStart();
if (!t.StartsWith("LayerElementNormal")) continue;
int bo = FB(L, i, re); if (bo < 0) continue;
int bc = FC(L, bo); if (bc < 0) continue;
total += FixNZArr(L, bo + 1, bc - 1, "Normals"); i = bc;
}
return total;
}
/// <summary>
/// Fixes near-zero values in a specific normal array, normalizes, and replaces invalid normals.
/// </summary>
static int FixNZArr(string[] L, int rs, int re, string name)
{
double[] v = RdD(L, rs, re, name, out var li); if (v == null) return 0;
int fc = 0;
for (int i = 0; i + 2 < v.Length; i += 3)
{
double x = v[i], y = v[i + 1], z = v[i + 2];
if (Math.Abs(x) < NZT) x = 0;
if (Math.Abs(y) < NZT) y = 0;
if (Math.Abs(z) < NZT) z = 0;
double len = Math.Sqrt(x * x + y * y + z * z);
if (len < NZT) { v[i] = 0; v[i + 1] = 1; v[i + 2] = 0; fc++; }
else if (Math.Abs(len - 1.0) > 0.001) { v[i] = x / len; v[i + 1] = y / len; v[i + 2] = z / len; fc++; }
else { v[i] = x; v[i + 1] = y; v[i + 2] = z; }
}
if (fc > 0) WrD(L, v, li);
return fc;
}
/// <summary>
/// Represents line information for array data in FBX geometry.
/// </summary>
/// <remarks>
/// The <c>LI</c> struct is used to track the location and formatting of array data (such as vertices or normals)
/// within the lines of an FBX ASCII file. This information is necessary for reading, transforming, and writing
/// back the array data while preserving the original file's formatting.
/// </remarks>
/// <param name="Ln">The line number in the file where this array segment is located.</param>
/// <param name="Pfx">The prefix string (indentation and any leading tokens) for the line.</param>
/// <param name="Cnt">The number of values on this line segment.</param>
/// <param name="TC">True if the line ends with a trailing comma, otherwise false.</param>
struct LI
{
public int Ln; // Line number in the file
public string Pfx; // Prefix (indentation, etc.)
public int Cnt; // Number of values on this line
public bool TC; // Trailing comma present
}
/// <summary>
/// Applies a transformation matrix to an array of FBX geometry elements (vertices or normals).
/// </summary>
static void XfArr(string[] L, int rs, int re, string name, Mat4 m, bool isN)
{
double[] v = RdD(L, rs, re, name, out var li); if (v == null) return;
for (int i = 0; i + 2 < v.Length; i += 3)
{
double x = v[i], y = v[i + 1], z = v[i + 2];
if (isN)
{
double tx = m.M00 * x + m.M01 * y + m.M02 * z;
double ty = m.M10 * x + m.M11 * y + m.M12 * z;
double tz = m.M20 * x + m.M21 * y + m.M22 * z;
double len = Math.Sqrt(tx * tx + ty * ty + tz * tz);
if (len > 1e-14) { tx /= len; ty /= len; tz /= len; }
v[i] = tx; v[i + 1] = ty; v[i + 2] = tz;
}
else
{
v[i] = m.M00 * x + m.M01 * y + m.M02 * z + m.M03;
v[i + 1] = m.M10 * x + m.M11 * y + m.M12 * z + m.M13;
v[i + 2] = m.M20 * x + m.M21 * y + m.M22 * z + m.M23;
}
}
WrD(L, v, li);
}
/// <summary>
/// Reads a double array from FBX geometry, returning the values and line info for writing back.
/// </summary>
static double[] RdD(string[] L, int rs, int re, string name, out List<LI> lis)
{
lis = null; int hl = -1;
for (int i = rs; i <= re; i++)
{
string t = L[i].TrimStart();
if (t.StartsWith(name + ":") && t.Contains("*")) { hl = i; break; }
}
if (hl < 0) return null;
int ob = FB(L, hl, re + 1); if (ob < 0) return null;
int cb = FC(L, ob); if (cb < 0) return null;
int al = -1;
for (int i = ob + 1; i < cb; i++)
{
if (L[i].TrimStart().StartsWith("a:")) { al = i; break; }
}
if (al < 0) return null;
var all = new List<double>(); lis = new List<LI>();
for (int i = al; i <= cb - 1; i++)
{
string raw = L[i]; string pfx, cnt;
if (i == al)
{
int ap = raw.IndexOf("a:", StringComparison.Ordinal);
pfx = raw.Substring(0, ap + 2);
cnt = raw.Substring(ap + 2);
}
else
{
int ind = 0;
while (ind < raw.Length && (raw[ind] == ' ' || raw[ind] == '\t')) ind++;
pfx = raw.Substring(0, ind);
cnt = raw.Substring(ind);
}
bool tc = cnt.TrimEnd().EndsWith(","); int c = 0;
foreach (string n in cnt.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
{
string s = n.Trim();
if (s.Length > 0 && double.TryParse(s, NumberStyles.Float | NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out double val))
{
all.Add(val); c++;
}
}
lis.Add(new LI { Ln = i, Pfx = pfx, Cnt = c, TC = tc });
}
return all.ToArray();
}
/// <summary>
/// Writes a double array back to FBX geometry using the provided line info.
/// </summary>
static void WrD(string[] L, double[] v, List<LI> lis)
{
int vi = 0;
for (int i = 0; i < lis.Count; i++)
{
var inf = lis[i]; var sb = new StringBuilder();
sb.Append(inf.Pfx); if (i == 0) sb.Append(' ');
for (int j = 0; j < inf.Cnt; j++) { if (j > 0) sb.Append(','); sb.Append(Fmt(v[vi++])); }
if (inf.TC) sb.Append(',');
L[inf.Ln] = sb.ToString();
}
}
/// <summary>
/// Reads an integer array from FBX geometry, returning the values and line info for writing back.
/// </summary>
static int[] RdI(string[] L, int rs, int re, string name) => RdI(L, rs, re, name, out _);
static int[] RdI(string[] L, int rs, int re, string name, out List<LI> lis)
{
lis = null; int hl = -1;
for (int i = rs; i <= re; i++)
{
string t = L[i].TrimStart();
if (t.StartsWith(name + ":") && t.Contains("*")) { hl = i; break; }
}
if (hl < 0) return null;
int ob = FB(L, hl, re + 1); if (ob < 0) return null;
int cb = FC(L, ob);
if (cb < 0) return null;
int al = -1;
for (int i = ob + 1; i < cb; i++)
{
if (L[i].TrimStart().StartsWith("a:")) { al = i; break; }
}
if (al < 0) return null;
var all = new List<int>(); lis = new List<LI>();
for (int i = al; i <= cb - 1; i++)
{
string raw = L[i];
string pfx, cnt;
if (i == al)
{
int ap = raw.IndexOf("a:", StringComparison.Ordinal);
pfx = raw.Substring(0, ap + 2);
cnt = raw.Substring(ap + 2);
}
else
{
int ind = 0;
while (ind < raw.Length && (raw[ind] == ' ' || raw[ind] == '\t')) ind++;
pfx = raw.Substring(0, ind);
cnt = raw.Substring(ind);
}
bool tc = cnt.TrimEnd().EndsWith(","); int c = 0;
foreach (string n in cnt.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
{
string s = n.Trim();
if (s.Length > 0 && int.TryParse(s, NumberStyles.Integer | NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out int val))
{
all.Add(val); c++;
}
}
lis.Add(new LI { Ln = i, Pfx = pfx, Cnt = c, TC = tc });
}
return all.ToArray();
}
/// <summary>
/// Writes an integer array back to FBX geometry using the provided line info.
/// </summary>
static void WrI(string[] L, int[] v, List<LI> lis)
{
int vi = 0;
for (int i = 0; i < lis.Count; i++)
{
var inf = lis[i]; var sb = new StringBuilder();
sb.Append(inf.Pfx); if (i == 0) sb.Append(' ');
for (int j = 0; j < inf.Cnt; j++)
{
if (j > 0) sb.Append(','); sb.Append(v[vi++].ToString(CultureInfo.InvariantCulture));
}
if (inf.TC) sb.Append(',');
L[inf.Ln] = sb.ToString();
}
}
/// <summary>
/// Reads a string property value from FBX geometry between specified lines.
/// </summary>
static string RSt(string[] L, int s, int e, string pn)
{
for (int i = s; i <= e; i++)
{
string t = L[i].TrimStart();
if (t.StartsWith(pn + ":"))
{
int q1 = t.IndexOf('"');
if (q1 >= 0)
{
int q2 = t.IndexOf('"', q1 + 1);
if (q2 > q1) return t.Substring(q1 + 1, q2 - q1 - 1);
}
return t.Substring(t.IndexOf(':') + 1).Trim();
}
}
return "";
}
// ==============
// Shared Helpers
// ==============
/// <summary>
/// Provides commonly used constant vectors for FBX transform operations.
/// </summary>
/// <remarks>
/// <para>
/// <see cref="V0"/> is a zero vector (0, 0, 0), typically used as a default for translation or rotation.
/// <see cref="V1"/> is a unit vector (1, 1, 1), typically used as a default for scaling.
/// </para>
/// These constants are used throughout the FBX processing logic to represent default or identity values
/// for vector-based FBX properties.
/// </remarks>
static readonly Vec3 V0 = new Vec3(0, 0, 0), V1 = new Vec3(1, 1, 1);
/// <summary>
/// Determines whether the given <see cref="Vec3"/> is effectively a zero vector.
/// </summary>
/// <param name="v">The vector to check.</param>
/// <returns>
/// True if all components (X, Y, Z) are within 1e-10 of zero; otherwise, false.
/// </returns>
/// <remarks>
/// This method is used to test if a vector is close enough to zero to be considered as such
/// for the purposes of FBX transform property comparisons and resets.
/// </remarks>
static bool IsZ(Vec3 v) => Math.Abs(v.X) < 1e-10 && Math.Abs(v.Y) < 1e-10 && Math.Abs(v.Z) < 1e-10;
/// <summary>
/// Determines whether the given <see cref="Vec3"/> is effectively a unit vector (1, 1, 1).
/// </summary>
/// <param name="v">The vector to check.</param>
/// <returns>
/// True if all components (X, Y, Z) are within 1e-10 of 1; otherwise, false.
/// </returns>
/// <remarks>
/// This method is used to test if a vector is close enough to (1, 1, 1) to be considered as such
/// for the purposes of FBX scaling property comparisons and resets.
/// </remarks>
static bool Is1(Vec3 v) => Math.Abs(v.X - 1) < 1e-10 && Math.Abs(v.Y - 1) < 1e-10 && Math.Abs(v.Z - 1) < 1e-10;
/// <summary>
/// Returns the negation of a <see cref="Vec3"/> vector.
/// </summary>
/// <param name="v">The vector to negate.</param>
/// <returns>
/// A new <see cref="Vec3"/> whose components are the negated values of the input vector.
/// </returns>
/// <remarks>
/// This helper is used to invert the direction of a vector, commonly for pivot or offset calculations
/// in FBX transform operations.
/// </remarks>
static Vec3 Neg(Vec3 v) => new Vec3(-v.X, -v.Y, -v.Z);
/// <summary>
/// Returns the string representation of an FBX rotation order code.
/// </summary>
/// <param name="o">The integer rotation order code (0-5).</param>
/// <returns>
/// A string representing the rotation order, such as "XYZ", "XZY", etc.
/// If the code is not recognized, returns "?({o})".
/// </returns>
/// <remarks>
/// FBX files encode rotation order as an integer (0-5), which determines the order in which Euler rotations are applied.
/// This helper method maps those codes to their corresponding string representations for display or debugging purposes.
/// </remarks>
static string RN(int o) => o switch { 0 => "XYZ", 1 => "XZY", 2 => "YZX", 3 => "YXZ", 4 => "ZXY", 5 => "ZYX", _ => $"?({o})" };
/// <summary>
/// Formats a double-precision floating-point value as a string for FBX output.
/// </summary>
/// <param name="v">The double value to format.</param>
/// <returns>
/// A string representation of the value, using up to 10 decimal places for typical values,
/// or scientific notation for very large or very small values. Trailing zeros and decimal points
/// are trimmed for compactness. Zero is always returned as "0".
/// </returns>
/// <remarks>
/// This method ensures that numbers are formatted in a way that is compatible with FBX ASCII files,
/// preserving precision while minimizing unnecessary characters.
/// </remarks>
static string Fmt(double v)
{
if (v == 0) return "0";
double a = Math.Abs(v);
if (a >= 0.0001 && a < 1e15)
{
string s = v.ToString("F10", CultureInfo.InvariantCulture);
if (s.Contains('.')) s = s.TrimEnd('0').TrimEnd('.'); return s;
}
return v.ToString("G15", CultureInfo.InvariantCulture);
}
/// <summary>
/// Computes the determinant of the upper-left 3x3 submatrix of a 4x4 matrix.
/// </summary>
/// <param name="m">The <see cref="Mat4"/> matrix whose determinant is to be calculated.</param>
/// <returns>
/// The determinant of the 3x3 submatrix formed by the first three rows and columns of <paramref name="m"/>.
/// </returns>
/// <remarks>
/// This function is typically used to determine if a transformation matrix includes a mirroring operation
/// (i.e., a negative determinant indicates a mirrored transformation).
/// </remarks>
static double Det3(Mat4 m) =>
m.M00 * (m.M11 * m.M22 - m.M12 * m.M21) -
m.M01 * (m.M10 * m.M22 - m.M12 * m.M20) +
m.M02 * (m.M10 * m.M21 - m.M11 * m.M20);
/// <summary>
/// Computes the inverse transpose of the upper-left 3x3 submatrix of a 4x4 matrix,
/// which is commonly used as the normal transformation matrix in 3D graphics.
/// </summary>
/// <param name="m">The <see cref="Mat4"/> matrix whose normal matrix is to be calculated.</param>
/// <returns>
/// A <see cref="Mat4"/> representing the inverse transpose of the 3x3 rotation/scaling part of <paramref name="m"/>.
/// The translation components are set to zero.
/// </returns>
/// <remarks>
/// This function is typically used to correctly transform normal vectors when non-uniform scaling or mirroring
/// is present in the transformation matrix. The resulting matrix is suitable for transforming normals in FBX geometry processing.
/// </remarks>
static Mat4 NormalMat(Mat4 m)
{
double a = m.M00, b = m.M01, c = m.M02;
double d = m.M10, e = m.M11, f = m.M12;
double g = m.M20, h = m.M21, k = m.M22;
double det = a * (e * k - f * h) - b * (d * k - f * g) + c * (d * h - e * g);
double id = 1.0 / det;
var r = Mat4.Identity;
r.M00 = (e * k - f * h) * id; r.M01 = -(d * k - f * g) * id; r.M02 = (d * h - e * g) * id;
r.M10 = -(b * k - c * h) * id; r.M11 = (a * k - c * g) * id; r.M12 = -(a * h - b * g) * id;
r.M20 = (b * f - c * e) * id; r.M21 = -(a * f - c * d) * id; r.M22 = (a * e - b * d) * id;
r.M03 = 0; r.M13 = 0; r.M23 = 0;
return r;
}
/// <summary>
/// Finds the line index of a property in an FBX ASCII file's Properties section.
/// </summary>
/// <param name="L">The array of lines representing the FBX file.</param>
/// <param name="s">The start line index (inclusive) to search from.</param>
/// <param name="e">The end line index (inclusive) to search to.</param>
/// <param name="pn">The property name to search for (e.g., "Lcl Rotation").</param>
/// <returns>
/// The index of the line containing the property definition (either "P:" or "Property:") with the specified property name in quotes,
/// or -1 if not found within the specified range.
/// </returns>
/// <remarks>
/// This helper is used to locate the line number of a specific property in the FBX Properties70/Properties60 block,
/// enabling further reading or writing of property values.
/// </remarks>
static int FPL(string[] L, int s, int e, string pn)
{
string q = "\"" + pn + "\"";
for (int i = s; i <= e; i++)
{
string t = L[i].TrimStart();
if ((t.StartsWith("P:") || t.StartsWith("Property:")) && t.Contains(q))
return i;
}
return -1;
}
/// <summary>
/// Reads a 3-component vector (Vec3) property from a specified range of lines in an FBX ASCII file.
/// </summary>
/// <param name="L">The array of lines representing the FBX file.</param>
/// <param name="ps">The start line index (inclusive) of the search range.</param>
/// <param name="pe">The end line index (inclusive) of the search range.</param>
/// <param name="pn">The property name to search for (e.g., "Lcl Rotation").</param>
/// <param name="def">The default <see cref="Vec3"/> value to return if the property is not found or cannot be parsed.</param>
/// <returns>
/// A <see cref="Vec3"/> containing the parsed property values if found and valid; otherwise, returns <paramref name="def"/>.
/// </returns>
/// <remarks>
/// This method locates the line containing the specified property name within the given range,
/// parses the last three comma-separated values on that line as doubles, and constructs a <see cref="Vec3"/>.