-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathObjFile.cs
More file actions
1934 lines (1524 loc) · 76 KB
/
ObjFile.cs
File metadata and controls
1934 lines (1524 loc) · 76 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
/*
* ObjFile.cs / Simple(?) Wavefront .obj loader and renderer
* Class for loading and rendering Wavefront .obj files via OpenTK
* Written in 2011 by xdaniel
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.IO;
using System.Globalization;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Drawing;
using System.Reflection;
using System.Threading;
using System.Xml;
using System.Xml.Serialization;
using OpenTK;
using OpenTK.Graphics;
using OpenTK.Graphics.OpenGL;
using OpenTK.Platform;
using TexLib;
using static SharpOcarina.ZScene;
namespace SharpOcarina
{
public class ObjFile
{
#region Constructors
public ObjFile() { }
public ObjFile(string Filename)
: this(Filename, false) { }
public ObjFile(string Filename, bool IgnoreMats)
{
_IgnoreMaterials = IgnoreMats;
TexUtil.InitTexturing();
if (Filename != string.Empty)
{
if (Filename.Contains(".dae"))
ParseDae(Filename);
else if (Filename.Contains(".zmap"))
{}
else
ParseObj(Filename);
}
}
#endregion
#region Element Classes
public class Triangle
{
public string MaterialName;
public int[] VertIndex;
public int[] VertColor;
public int[] TexCoordIndex;
public int[] NormalIndex;
public Triangle()
{
VertIndex = new int[3];
VertColor = new int[] { 1, 1, 1 };
TexCoordIndex = new int[3];
NormalIndex = new int[3];
}
public Triangle(int[] _VertIndex, int[] _TexCoordIndex, int[] _NormalIndex)
{
MaterialName = string.Empty;
VertIndex = _VertIndex; TexCoordIndex = _TexCoordIndex; NormalIndex = _NormalIndex;
VertColor = new int[] { 1, 1, 1};
}
public Triangle(int[] _VertIndex, int[] _TexCoordIndex, int[] _NormalIndex, int[] _ColorIndex)
{
MaterialName = string.Empty;
VertIndex = _VertIndex; TexCoordIndex = _TexCoordIndex; NormalIndex = _NormalIndex; VertColor = _ColorIndex;
}
public Triangle(string _MaterialName, int[] _VertIndex, int[] _TexCoordIndex, int[] _NormalIndex)
{
MaterialName = _MaterialName;
VertIndex = _VertIndex;
TexCoordIndex = _TexCoordIndex;
if (TexCoordIndex[0] == -1) TexCoordIndex[0]++;
if (TexCoordIndex[1] == -1) TexCoordIndex[1]++;
if (TexCoordIndex[2] == -1) TexCoordIndex[2]++;
NormalIndex = _NormalIndex;
VertColor = new int[] { 1, 1, 1 };
}
}
public class Vertex
{
public double X = 0.0f, Y = 0.0f, Z = 0.0f, W = 0.0f;
public Vector3d VN = new Vector3d();
public Vertex() { }
public Vertex(double _X, double _Y, double _Z)
{
X = _X; Y = _Y; Z = _Z; W = 0.0f;
}
public Vertex(double _X, double _Y, double _Z, double _W)
{
X = _X; Y = _Y; Z = _Z; W = _W;
}
public Vector3d ToVector3d()
{
return new Vector3d(X,Y,Z);
}
public Vector3d ToVector3dRounded()
{
return new Vector3d(Math.Round(X,3), Math.Round(Y,3), Math.Round(Z,3));
}
public Vertex Clone()
{
Vertex clone = (Vertex)this.MemberwiseClone();
return clone;
}
}
public class VertexColor
{
public double R = 1.0f, G = 1.0f, B = 1.0f, A = 1.0f;
public VertexColor() { }
public VertexColor(double _R, double _G, double _B, double _A)
{
R = _R; G = _G; B = _B; A = _A;
}
public VertexColor Clone()
{
VertexColor clone = (VertexColor)this.MemberwiseClone();
return clone;
}
public string ToString()
{
return $"{R},{G},{B},{A}";
}
}
public class TextureCoord
{
public double U = 0.0f, V = 0.0f, W = 0.0f;
public TextureCoord() { }
public TextureCoord(double _U, double _V)
{
U = _U; V = _V; W = 0.0f;
}
public TextureCoord(double _U, double _V, double _W)
{
U = _U; V = _V; W = _W;
}
public TextureCoord Clone()
{
TextureCoord clone = (TextureCoord)this.MemberwiseClone();
return clone;
}
public Vector2d ToVector2dRounded()
{
return new Vector2d(Math.Round(U, 3), Math.Round(V, 3));
}
}
public class Normal
{
public double X = 0.0f, Y = 0.0f, Z = 0.0f;
public Normal() { }
public Normal(double _X, double _Y, double _Z)
{
X = _X; Y = _Y; Z = _Z;
}
public Normal Clone()
{
Normal clone = (Normal)this.MemberwiseClone();
return clone;
}
}
public class Material
{
public string Name;
public float[] Ka, Kd, Ks;
public float Tr;
public int illum;
public string map_Ka, map_Kd, map_Ks, map_d, map_bump, tags, tags_1;
[XmlIgnore]
public Bitmap TexImage;
[XmlIgnore]
public int Width, Height;
[XmlIgnore]
public int GLID;
[XmlIgnore]
public bool ForceRGBA;
[XmlIgnore]
public string ForcedFormat = "";
public Material()
{
Ka = new float[] { 0.2f, 0.2f, 0.2f };
Kd = new float[] { 0.8f, 0.8f, 0.8f };
Ks = new float[] { 1.0f, 1.0f, 1.0f };
Tr = 1.0f;
illum = 0;
tags = "";
tags_1 = "";
ForceRGBA = false;
}
public string DisplayName
{
get { return (map_Kd == null ? "None" : map_Kd.Contains(Path.DirectorySeparatorChar) ? map_Kd.Substring(map_Kd.LastIndexOf(Path.DirectorySeparatorChar) +1) : map_Kd); }
}
public Material Clone()
{
Material clone = (Material)this.MemberwiseClone();
return clone;
}
// public bool ShouldSerializeTexImage()
}
public class Group
{
public string Name;
[XmlIgnore]
public int GLID;
[XmlIgnore]
public uint TintAlpha = 0xFFFFFFFF;
[XmlIgnore]
public int TileS = 0, TileT = 0, PolyType = 0;
[XmlIgnore]
public bool BackfaceCulling = true;
[XmlIgnore]
public bool Animated = false;
[XmlIgnore]
public bool Metallic = false;
[XmlIgnore]
public bool EnvColor = false;
[XmlIgnore]
public bool Decal = false;
[XmlIgnore]
public bool IgnoreFog = false;
[XmlIgnore]
public bool SmoothRGBAEdges = false;
[XmlIgnore]
public bool Pixelated = false;
[XmlIgnore]
public bool Billboard = false;
[XmlIgnore]
public bool TwoAxisBillboard = false;
[XmlIgnore]
public bool ReverseLight = false;
[XmlIgnore]
public int MultiTexMaterial = -1, ShiftS = 0, ShiftT = 0;
[XmlIgnore]
public string MultiTexMaterialName = "";
[XmlIgnore]
public int BaseShiftS = 0, BaseShiftT = 0, AnimationBank = 8;
[XmlIgnore]
public int LodGroup = 0, LodDistance = 0;
[XmlIgnore]
public uint MultiTexAlpha = 0xFFFFFFFF;
[XmlIgnore]
public bool LOD = false;
[XmlIgnore]
public bool AlphaMask = false;
[XmlIgnore]
public bool RenderLast = false;
[XmlIgnore]
public bool VertexNormals = false;
[XmlIgnore]
public bool Custom = false;
[XmlIgnore]
public ulong[] CustomDL = new ulong[4];
[XmlIgnore]
public bool ScaledNormals = false;
[XmlIgnore]
public bool TexPointerPlus1 = false;
[XmlIgnore]
public int Type2Group = -1;
public Vector3s PivotPoint = new Vector3s(32767, 32767, 32767);
private List<Triangle> _Tris = new List<Triangle>();
public List<Triangle> Triangles
{
get { return _Tris; }
set { _Tris = value; }
}
public string DisplayName
{
get { return Name; }
}
public Group Clone()
{
return (Group)this.MemberwiseClone();
}
}
#endregion
#region Element Lists
private List<Group> _Groups = new List<Group>();
private List<Vertex> _Verts = new List<Vertex>();
private List<VertexColor> _VertColors = new List<VertexColor>();
private List<TextureCoord> _TexCoords = new List<TextureCoord>();
private List<Normal> _Norms = new List<Normal>();
private List<Material> _Mats = new List<Material>();
private List<Material> _AdditionalTextures = new List<Material>();
private List<List<int>> _Islands = new List<List<int>>();
public List<Group> Groups
{
get { return _Groups; }
set { _Groups = value; }
}
public List<Vertex> Vertices
{
get { return _Verts; }
}
public List<TextureCoord> TextureCoordinates
{
get { return _TexCoords; }
}
public List<Normal> Normals
{
get { return _Norms; }
}
public List<Material> Materials
{
get { return _Mats; }
}
public List<VertexColor> VertexColors
{
get { return _VertColors; }
}
public List<Material> AdditionalTextures
{
get { return _AdditionalTextures; }
}
#endregion
#region Other Variables
private string _BasePath = string.Empty;
[XmlIgnore]
public string BasePath
{
get { return _BasePath; }
set { _BasePath = value; }
}
private string Line = string.Empty;
private char[] TokenSeperator = { ' ', '\t' };
private char[] TokenValSeperator = { '/' };
public static List<string> ValidImageTypes = new List<string>(new string[] { ".bmp", ".gif", ".jpg", ".jpeg", ".png", ".tiff", ".tif",".tga"});
private string MtlFilename = string.Empty;
private string CurrentMtlName = string.Empty;
private double X, Y, Z, U, V, W, R, G, B, A;
private bool GroupIsOpen;
private bool MaterialIsOpen;
private bool _MaterialLighting = false;
[XmlIgnore]
public bool MaterialLighting
{
get { return _MaterialLighting; }
set { _MaterialLighting = value; }
}
private bool _IgnoreMaterials = false;
[XmlIgnore]
public bool IgnoreMaterials
{
get { return _IgnoreMaterials; }
set { _IgnoreMaterials = value; }
}
#endregion
#region Loading & Setup Functions
public void Load(string Filename)
{
if (Filename.Contains(".dae"))
ParseDae(Filename);
else
ParseObj(Filename);
}
#endregion
#region Model Parser
private void ParseObj(string Filename)
{
_VertColors.Add(new VertexColor(1, 1, 1, 1));
StreamReader SR = File.OpenText(Filename);
Group NewGroup = new Group();
GroupIsOpen = false;
List<int> nocollisionvertexfix = new List<int>();
List<int> nocollisionnormalfix = new List<int>();
while ((Line = SR.ReadLine()) != null)
{
Line = Line.TrimStart(TokenSeperator);
if (Line == string.Empty) continue;
string[] Tokenized = Line.Split(TokenSeperator, StringSplitOptions.RemoveEmptyEntries);
switch (Tokenized[0])
{
case "#":
/* Comment */
break;
case "g":
/* Group */
if (GroupIsOpen == true && NewGroup.Triangles.Count > 0)
AddGroup(NewGroup);
GroupIsOpen = true;
NewGroup = FindGroup(Line.Substring(Line.IndexOf(' ') + 1));
if (NewGroup == null) NewGroup = new Group();
NewGroup.Name = Line.Substring(Line.IndexOf(' ') + 1);
break;
case "mtllib":
//if (IgnoreMaterials) continue;
/* Material lib reference */
MtlFilename = Line.Substring(Line.IndexOf(' ') + 1);
//ParseMtl(Filename.Substring(0, Filename.LastIndexOf('\\')) + "\\" + MtlFilename);
ParseMtl(Path.IsPathRooted(MtlFilename) == true ? Path.GetFileName(MtlFilename) : Path.GetDirectoryName(Path.GetFullPath(Filename)) + Path.DirectorySeparatorChar + Path.GetFileName(MtlFilename));
break;
case "v":
/* Vertex */
if (IgnoreMaterials && NewGroup.Name != null && NewGroup.Name.ToLower().Contains("#nocollision"))
{
nocollisionvertexfix.Add(_Verts.Count);
continue;
}
X = Y = Z = W = 0;
double.TryParse(Tokenized[1], NumberStyles.Float, CultureInfo.InvariantCulture, out X);
double.TryParse(Tokenized[2], NumberStyles.Float, CultureInfo.InvariantCulture, out Y);
double.TryParse(Tokenized[3], NumberStyles.Float, CultureInfo.InvariantCulture, out Z);
if (Tokenized.Length == 5)
double.TryParse(Tokenized[4], NumberStyles.Float, CultureInfo.InvariantCulture, out W);
_Verts.Add(new Vertex(X, Y, Z, W));
if (Math.Abs(X) > 32767 || Math.Abs(Y) > 32767 || Math.Abs(Z) > 32767)
{
MessageBox.Show("Vertex can't be further than 32767 units on both sides, try making a smaller map! cancelling import",
"Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
break;
case "vc":
/* Vertex Color */
if (IgnoreMaterials) continue;
/*
if (IgnoreMaterials && NewGroup.Name != null && NewGroup.Name.ToLower().Contains("#nocollision"))
continue;*/
R = G = B = A = 0;
double.TryParse(Tokenized[1], NumberStyles.Float, CultureInfo.InvariantCulture, out R);
double.TryParse(Tokenized[2], NumberStyles.Float, CultureInfo.InvariantCulture, out G);
double.TryParse(Tokenized[3], NumberStyles.Float, CultureInfo.InvariantCulture, out B);
double.TryParse(Tokenized[4], NumberStyles.Float, CultureInfo.InvariantCulture, out A);
_VertColors.Add(new VertexColor(R, G, B, A));
break;
case "vt":
/* Texture coordinates */
if (IgnoreMaterials) continue;
/*
if (IgnoreMaterials && NewGroup.Name != null && NewGroup.Name.ToLower().Contains("#nocollision"))
continue;*/
U = V = W = 0;
double.TryParse(Tokenized[1], NumberStyles.Float, CultureInfo.InvariantCulture, out U);
double.TryParse(Tokenized[2], NumberStyles.Float, CultureInfo.InvariantCulture, out V);
if (Tokenized.Length == 4)
double.TryParse(Tokenized[3], NumberStyles.Float, CultureInfo.InvariantCulture, out W);
V -= 1; // clamp fix
// if (_Islands.Count == 0) _Islands.Add(new List<int>());
_TexCoords.Add(new TextureCoord(U, -V, W));
// _Islands[_Islands.Count-1].Add(_TexCoords.Count-1);
break;
case "vn":
/* Normals */
if (IgnoreMaterials && NewGroup.Name != null && NewGroup.Name.ToLower().Contains("#nocollision"))
{
nocollisionnormalfix.Add(_Norms.Count);
continue;
}
X = Y = Z = 0;
double.TryParse(Tokenized[1], NumberStyles.Float, CultureInfo.InvariantCulture, out X);
double.TryParse(Tokenized[2], NumberStyles.Float, CultureInfo.InvariantCulture, out Y);
double.TryParse(Tokenized[3], NumberStyles.Float, CultureInfo.InvariantCulture, out Z);
_Norms.Add(new Normal(X, Y, Z));
break;
case "usemtl":
/* Material to use */
// _Islands.Add(new List<int>());
CurrentMtlName = Tokenized[1].Replace("DISPLAY","");
break;
case "fc":
// link colors to triangles
if (IgnoreMaterials) continue;
/*
if (IgnoreMaterials && NewGroup.Name != null && NewGroup.Name.ToLower().Contains("#nocollision"))
continue;*/
X = Y = Z = 0;
double.TryParse(Tokenized[1], NumberStyles.Float, CultureInfo.InvariantCulture, out X);
double.TryParse(Tokenized[2], NumberStyles.Float, CultureInfo.InvariantCulture, out Y);
double.TryParse(Tokenized[3], NumberStyles.Float, CultureInfo.InvariantCulture, out Z);
X += 1;
Y += 1;
Z += 1;
NewGroup.Triangles[NewGroup.Triangles.Count - 1].VertColor = new int[] { (int)X, (int)Y, (int)Z, 0};
break;
case "f":
/* Face/triangle */
if (IgnoreMaterials && NewGroup.Name != null && NewGroup.Name.ToLower().Contains("#nocollision"))
continue;
int[] VIndex = new int[16];
int[] TIndex = new int[16];
int[] NIndex = new int[16];
// Triangulate face
for (int i = 0; i < Tokenized.Length-1; i++)
{
string[] TokenizedVals = Tokenized[i + 1].Split(TokenValSeperator);
int[] VLocal = new int[3];
int[] TLocal = new int[3];
int[] NLocal = new int[3];
int.TryParse(TokenizedVals[0], out VIndex[i]);
int.TryParse(TokenizedVals[1], out TIndex[i]);
if (TokenizedVals.Length == 3)
int.TryParse(TokenizedVals[2], out NIndex[i]);
VIndex[i] -= 1;
TIndex[i] -= 1;
NIndex[i] -= 1;
// Last vertex of triangle, or index to next point in the face (e.g. quad)
if(i >= 2){
if (VIndex[0 + (i - 2)] != -1 && VIndex[1 + (i - 2)] != -1 && VIndex[2 + (i - 2)] != -1)
{
VLocal[0] = VIndex[0]; TLocal[0] = TIndex[0]; NLocal[0] = NIndex[0];
VLocal[1] = VIndex[i - 1]; TLocal[1] = TIndex[i - 1]; NLocal[1] = NIndex[i - 1];
VLocal[2] = VIndex[i]; TLocal[2] = TIndex[i]; NLocal[2] = NIndex[i];
if (IgnoreMaterials)
{
foreach(int val in nocollisionvertexfix)
{
for(int y = 0; y < 3; y++)
{
if (VLocal[y] >= val) VLocal[y]--;
}
}
foreach (int val in nocollisionnormalfix)
{
for (int y = 0; y < 3; y++)
{
if (NLocal[y] >= val) NLocal[y]--;
}
}
}
NewGroup.Triangles.Add(new Triangle(CurrentMtlName, VLocal, TLocal, NLocal));
}
}
}
break; }
}
if (GroupIsOpen == true)
AddGroup(NewGroup);
SR.Close();
if(_VertColors.Count == 0)
{
_VertColors.Add(new VertexColor());
}
//FixUv();
if (IgnoreMaterials)
{
AddDoorMeshes();
}
//cleanup
Dictionary<Vector3d, int> usedvertex = new Dictionary<Vector3d, int>();
Dictionary<Vector2d, int> usedtexcoord = new Dictionary<Vector2d, int>();
int cnt = 0;
int cnt2 = 0;
List<ObjFile.Vertex> newvertex = new List<ObjFile.Vertex>();
List<ObjFile.Normal> newnormal = new List<ObjFile.Normal>();
List<ObjFile.TextureCoord> nextexcoord = new List<ObjFile.TextureCoord>();
List<ObjFile.VertexColor> newvertexcol = new List<ObjFile.VertexColor>();
newvertexcol.Add(new VertexColor(1, 1, 1, 1));
List<int> skip2nd = new List<int>();
if ((IgnoreMaterials && MainForm.settings.FixedCollisionWrite) || (!IgnoreMaterials && MainForm.settings.FixedMeshWrite))
{
foreach (ObjFile.Group group in _Groups)
{
bool isMetallic = group.Name.ToLower().Contains("#metallic") && !IgnoreMaterials;
if (isMetallic)
{
int a = 0;
}
foreach (ObjFile.Triangle tri in group.Triangles)
{
for (int i = 0; i <= 2; i++)
{
if (isMetallic || !usedvertex.ContainsKey(_Verts[tri.VertIndex[i]].ToVector3dRounded()))
{
if (!isMetallic) usedvertex.Add(_Verts[tri.VertIndex[i]].ToVector3dRounded(), cnt);
newvertex.Add(_Verts[tri.VertIndex[i]].Clone());
tri.VertIndex[i] = cnt;
cnt++;
}
else
{
tri.VertIndex[i] = usedvertex[_Verts[tri.VertIndex[i]].ToVector3dRounded()];
}
}
}
}
cnt = 0;
if (_TexCoords.Count > 0)
{
foreach (ObjFile.Group group in _Groups)
{
bool isMetallic = group.Name.ToLower().Contains("#Metallic") && !IgnoreMaterials;
foreach (ObjFile.Triangle tri in group.Triangles)
{
for (int i = 0; i <= 2; i++)
{
if (isMetallic || !usedtexcoord.ContainsKey(_TexCoords[tri.TexCoordIndex[i]].ToVector2dRounded()))
{
if (!isMetallic) usedtexcoord.Add(_TexCoords[tri.TexCoordIndex[i]].ToVector2dRounded(), cnt);
nextexcoord.Add(_TexCoords[tri.TexCoordIndex[i]].Clone());
tri.TexCoordIndex[i] = cnt;
cnt++;
}
else
{
tri.TexCoordIndex[i] = usedtexcoord[_TexCoords[tri.TexCoordIndex[i]].ToVector2dRounded()];
}
}
}
}
}
_Verts = newvertex;
_Norms.Clear(); //they're already recalculated elsewhere
_TexCoords = nextexcoord;
}
if (_TexCoords.Count == 0)
{
_TexCoords.Add(new TextureCoord());
}
Prepare(_Groups);
}
private void ParseDae(string filename)
{
_VertColors.Add(new VertexColor(1, 1, 1, 1));
_VertColors.Add(new VertexColor(1, 1, 1, 1));
XmlDocument doc = new XmlDocument();
// FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
using (XmlTextReader tr = new XmlTextReader(filename))
{
tr.Namespaces = false;
doc.Load(tr);
}
XmlNodeList nodes = doc.SelectNodes("COLLADA/library_images/image");
if (nodes != null)
foreach (XmlNode node in nodes)
{
XmlAttributeCollection nodeAtt = node.Attributes;
string id = nodeAtt["id"].Value;
foreach (XmlNode node2 in node)
{
if (node2.Name == "init_from")
{
Material mat = new Material();
string path = node2.InnerText;
path = path.Replace("%20", " ");
if (!File.Exists(path))
{
path = Path.GetDirectoryName(filename) + Path.DirectorySeparatorChar + path;
if (!File.Exists(path) && !MainForm.settings.DisableTextureWarnings)
{
MessageBox.Show("Texture " + node2.InnerText + " not found",
"Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
mat.map_Kd = path;
mat.map_Ka = path;
mat.Name = id;
Materials.Add(mat);
}
}
}
int vertexstack = 0;
int normalstack = 0;
int texcoordstack = 0;
int colorstack = 2;
nodes = doc.SelectNodes("COLLADA/library_geometries/geometry");
if (nodes != null)
foreach (XmlNode node in nodes)
{
string vertexarray = "", normalarray = "", texcoordarray = "", colorarray = "";
List<string> triangleids = new List<string>();
List<string> materialids = new List<string>();
if (node.Name == "geometry")
{
Group NewGroup = new Group();
XmlAttributeCollection nodeAtt = node.Attributes;
NewGroup.Name = nodeAtt["name"].Value;
foreach (XmlNode node2 in node.ChildNodes)
{
if (node2.Name == "mesh")
{
foreach (XmlNode node3 in node2.ChildNodes)
{
if (node3.Name == "vertices")
{
foreach (XmlNode node4 in node3.ChildNodes)
{
if (node4.Name == "input")
{
nodeAtt = node4.Attributes;
if (nodeAtt["semantic"].Value == "POSITION")
{
vertexarray = nodeAtt["source"].Value.Replace("#", "");
}
}
}
}
else if (node3.Name == "triangles")
{
nodeAtt = node3.Attributes;
if (nodeAtt["material"] != null)
{
bool found = false;
foreach (Material mat in Materials)
{
if (mat.Name == nodeAtt["material"].Value.Replace("-material", ""))
{
materialids.Add(mat.Name);
found = true;
break;
}
}
if (!found)
{
DebugConsole.WriteLine("mat " + nodeAtt["material"].Value.Replace("-material", "") + " NOT FOUND");
materialids.Add("");
}
}
else
{
materialids.Add("");
}
foreach (XmlNode node4 in node3.ChildNodes)
{
if (node4.Name == "input")
{
nodeAtt = node4.Attributes;
if (nodeAtt["semantic"].Value == "NORMAL")
{
normalarray = nodeAtt["source"].Value.Replace("#", "");
}
else if (nodeAtt["semantic"].Value == "TEXCOORD")
{
texcoordarray = nodeAtt["source"].Value.Replace("#", "");
}
else if (nodeAtt["semantic"].Value == "COLOR")
{
colorarray = nodeAtt["source"].Value.Replace("#", "");
}
}
else if (node4.Name == "p")
{
triangleids.Add(node4.InnerText);
}
}
}
}
foreach (XmlNode node3 in node2.ChildNodes)
{
if (node3.Name == "source")
{
nodeAtt = node3.Attributes;
string arraytype = nodeAtt["id"].Value;
foreach (XmlNode node4 in node3.ChildNodes)
{
if (node4.Name == "float_array")
{
if (arraytype == vertexarray)
{
string[] values = node4.InnerText.Split(' ');
if (node4.InnerText == "") continue;
for(int i = 0; i < values.Length; i+=3)
{
_Verts.Add(new Vertex(Convert.ToDouble(values[i], CultureInfo.InvariantCulture), Convert.ToDouble(values[i+2], CultureInfo.InvariantCulture), -Convert.ToDouble(values[i+1], CultureInfo.InvariantCulture)));
if (Math.Abs(_Verts[_Verts.Count-1].X) > 32767 || Math.Abs(_Verts[_Verts.Count - 1].Y) > 32767 || Math.Abs(_Verts[_Verts.Count - 1].Z) > 32767)
{
MessageBox.Show("Vertex can't be further than 32767 units on both sides, try making a smaller map! cancelling import",
"Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
}
else if (arraytype == normalarray)
{
string[] values = node4.InnerText.Split(' ');
if (node4.InnerText == "") continue;
for (int i = 0; i < values.Length; i += 3)
{
_Norms.Add(new Normal(Convert.ToDouble(values[i], CultureInfo.InvariantCulture), Convert.ToDouble(values[i + 1], CultureInfo.InvariantCulture), Convert.ToDouble(values[i + 2], CultureInfo.InvariantCulture)));
}
}
else if (arraytype == texcoordarray)
{
string[] values = node4.InnerText.Split(' ');
if (node4.InnerText == "") continue;
for (int i = 0; i < values.Length; i += 2)
{
_TexCoords.Add(new TextureCoord(Convert.ToDouble(values[i], CultureInfo.InvariantCulture), -Convert.ToDouble(values[i + 1], CultureInfo.InvariantCulture)));
}
}
else if (arraytype == colorarray)
{
string[] values = node4.InnerText.Split(' ');
if (node4.InnerText == "") continue;
for (int i = 0; i < values.Length; i += 4)
{
_VertColors.Add(new VertexColor(Convert.ToDouble(values[i], CultureInfo.InvariantCulture), Convert.ToDouble(values[i + 1], CultureInfo.InvariantCulture), Convert.ToDouble(values[i + 2], CultureInfo.InvariantCulture), Convert.ToDouble(values[i + 3], CultureInfo.InvariantCulture)));
}
}
}
}
}
}
for (int y = 0; y < triangleids.Count; y++)
{
string[] index = triangleids[y].Split(' ');
int incr = (colorarray == "") ? 3 : 4;
// int count = (colorarray == "") ? index.Length / 3 : index.Length / 4;
Triangle tri = new Triangle();
tri.MaterialName = materialids[y];
int t = 0;
for (int i = 0; i < index.Length; i += incr)
{
if (t == 3 && i != 0)
{
// if (incr == 3) tri.VertColor = new int[] { 1, 1, 1 };
NewGroup.Triangles.Add(tri);