-
Notifications
You must be signed in to change notification settings - Fork 53
/
COLLADA.cs
1469 lines (1295 loc) · 67.6 KB
/
COLLADA.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
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 CgfConverter.CryEngineCore;
using CgfConverter.Materials;
using grendgine_collada;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Numerics;
using System.Reflection;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using static Extensions.FileHandlingExtensions;
using static CgfConverter.Utils;
namespace CgfConverter;
public class Collada : BaseRenderer
{
public Grendgine_Collada DaeObject { get; private set; } = new();
private readonly CultureInfo culture = CultureInfo.CreateSpecificCulture("en-US");
private const string colladaVersion = "1.4.1";
readonly XmlSerializer serializer = new(typeof(Grendgine_Collada));
/// <summary>Dictionary of all material libraries in the model, with the key being the library from mtlname chunk.</summary>
private readonly Dictionary<string, Material> createdMaterialLibraries = new();
public Collada(ArgsHandler argsHandler, CryEngine cryEngine) : base(argsHandler, cryEngine) { }
public override void Render(string outputDir = null, bool preservePath = true)
{
GenerateDaeObject();
// At this point, we should have a cryData.Asset object, fully populated.
Utils.Log(LogLevelEnum.Debug);
Utils.Log(LogLevelEnum.Debug, "*** Starting WriteCOLLADA() ***");
Utils.Log(LogLevelEnum.Debug);
// File name will be "<object name>.dae"
var daeOutputFile = new FileInfo(GetOutputFile("dae", outputDir, preservePath));
if (!daeOutputFile.Directory.Exists)
daeOutputFile.Directory.Create();
TextWriter writer = new StreamWriter(daeOutputFile.FullName);
serializer.Serialize(writer, DaeObject);
writer.Close();
Utils.Log(LogLevelEnum.Debug, "End of Write Collada. Export complete.");
}
public void GenerateDaeObject()
{
Utils.Log(LogLevelEnum.Debug, "Number of models: {0}", CryData.Models.Count);
for (int i = 0; i < CryData.Models.Count; i++)
{
Utils.Log(LogLevelEnum.Debug, "\tNumber of nodes in model: {0}", CryData.Models[i].NodeMap.Count);
}
WriteColladaRoot(colladaVersion);
WriteAsset();
WriteScene();
// Create Material, Effects and Textures libraries
Grendgine_Collada_Library_Materials libraryMaterials = new();
DaeObject.Library_Materials = libraryMaterials;
Grendgine_Collada_Library_Images libraryImages = new();
DaeObject.Library_Images = libraryImages;
Grendgine_Collada_Library_Effects libraryEffects = new();
DaeObject.Library_Effects = libraryEffects;
//WriteLibrary_Geometries();
WriteLibrary_Geometries();
// If there is Skinning info, create the controller library and set up visual scene to refer to it. Otherwise just write the Visual Scene
if (CryData.SkinningInfo.HasSkinningInfo)
{
WriteLibrary_Controllers();
WriteLibrary_VisualScenesWithSkeleton();
}
else
WriteLibrary_VisualScenes();
}
protected void WriteColladaRoot(string version)
{
// Blender doesn't like 1.5. :(
if (version == "1.4.1")
DaeObject.Collada_Version = "1.4.1";
else if (version == "1.5.0")
DaeObject.Collada_Version = "1.5.0";
}
protected void WriteAsset()
{
var fileCreated = DateTime.Now;
var fileModified = DateTime.Now;
Grendgine_Collada_Asset asset = new()
{
Revision = Assembly.GetExecutingAssembly().GetName().Version.ToString()
};
Grendgine_Collada_Asset_Contributor[] contributors = new Grendgine_Collada_Asset_Contributor[2];
contributors[0] = new Grendgine_Collada_Asset_Contributor
{
Author = "Heffay",
Author_Website = "https://github.com/Markemp/Cryengine-Converter",
Author_Email = "markemp@gmail.com",
Source_Data = CryData.RootNode.Name // The cgf/cga/skin/whatever file we read
};
// Get the actual file creators from the Source Chunk
contributors[1] = new Grendgine_Collada_Asset_Contributor();
foreach (ChunkSourceInfo sourceInfo in CryData.Chunks.Where(a => a.ChunkType == ChunkType.SourceInfo))
{
contributors[1].Author = sourceInfo.Author;
contributors[1].Source_Data = sourceInfo.SourceFile;
}
asset.Created = fileCreated;
asset.Modified = fileModified;
asset.Up_Axis = "Z_UP";
asset.Unit = new Grendgine_Collada_Asset_Unit()
{
Meter = 1.0,
Name = "meter"
};
asset.Title = CryData.RootNode.Name;
DaeObject.Asset = asset;
DaeObject.Asset.Contributor = contributors;
}
public Grendgine_Collada_Effect CreateColladaEffect(Material material)
{
Grendgine_Collada_Effect colladaEffect = new()
{
ID = material.Name + "-effect",
Name = material.Name
};
// create the profile_common for the effect
List<Grendgine_Collada_Profile_COMMON> profiles = new();
Grendgine_Collada_Profile_COMMON profile = new();
profile.Technique = new() { sID = material.Name + "-technique" };
profiles.Add(profile);
// Create a list for the new_params
List<Grendgine_Collada_New_Param> newparams = new();
for (int j = 0; j < material.Textures.Length; j++)
{
// Add the Surface node
Grendgine_Collada_New_Param texSurface = new()
{
sID = material.Name + "_" + material.Textures[j].Map + "-surface" // CleanTextureFileName(material.Textures[j].File) + "-surface"
};
Grendgine_Collada_Surface surface = new();
texSurface.Surface = surface;
surface.Init_From = new Grendgine_Collada_Init_From();
texSurface.Surface.Type = "2D";
texSurface.Surface.Init_From = new Grendgine_Collada_Init_From
{
Uri = material.Name + "_" + material.Textures[j].Map
};
// Add the Sampler node
Grendgine_Collada_New_Param texSampler = new()
{
sID = material.Name + "_" + material.Textures[j].Map + "-sampler" // CleanTextureFileName(material.Textures[j].File) + "-sampler"
};
Grendgine_Collada_Sampler2D sampler2D = new();
texSampler.Sampler2D = sampler2D;
texSampler.Sampler2D.Source = texSurface.sID;
newparams.Add(texSurface);
newparams.Add(texSampler);
}
#region Create the Technique
// Make the techniques for the profile
Grendgine_Collada_Effect_Technique_COMMON technique = new();
Grendgine_Collada_Phong phong = new();
technique.Phong = phong;
technique.sID = material.Name + "-technique";
profile.Technique = technique;
phong.Diffuse = new Grendgine_Collada_FX_Common_Color_Or_Texture_Type();
phong.Specular = new Grendgine_Collada_FX_Common_Color_Or_Texture_Type();
// Add all the emissive, etc features to the phong
// Need to check if a texture exists. If so, refer to the sampler. Should be a <Texture Map="Diffuse" line if there is a map.
bool diffuseFound = false;
bool specularFound = false;
foreach (var texture in material.Textures)
{
if (texture.Map == Texture.MapTypeEnum.Diffuse)
{
diffuseFound = true;
phong.Diffuse.Texture = new Grendgine_Collada_Texture
{
// Texcoord is the ID of the UV source in geometries. Not needed.
Texture = material.Name + "_" + texture.Map + "-sampler",
TexCoord = ""
};
}
if (texture.Map == Texture.MapTypeEnum.Specular)
{
specularFound = true;
phong.Specular.Texture = new Grendgine_Collada_Texture
{
Texture = material.Name + "_" + texture.Map + "-sampler",
TexCoord = ""
};
}
if (texture.Map == Texture.MapTypeEnum.Bumpmap)
{
// Bump maps go in an extra node.
// bump maps are added to an extra node.
Grendgine_Collada_Extra[] extras = new Grendgine_Collada_Extra[1];
Grendgine_Collada_Extra extra = new();
extras[0] = extra;
technique.Extra = extras;
// Create the technique for the extra
Grendgine_Collada_Technique[] extraTechniques = new Grendgine_Collada_Technique[1];
Grendgine_Collada_Technique extraTechnique = new();
extra.Technique = extraTechniques;
//extraTechnique.Data[0] = new XmlElement();
extraTechniques[0] = extraTechnique;
extraTechnique.profile = "FCOLLADA";
Grendgine_Collada_BumpMap bumpMap = new()
{
Textures = new Grendgine_Collada_Texture[1]
};
bumpMap.Textures[0] = new Grendgine_Collada_Texture
{
Texture = material.Name + "_" + texture.Map + "-sampler"
};
extraTechnique.Data = new XmlElement[1];
extraTechnique.Data[0] = bumpMap;
}
}
if (diffuseFound == false)
{
phong.Diffuse.Color = new Grendgine_Collada_Color
{
Value_As_String = material.Diffuse ?? string.Empty,
sID = "diffuse"
};
}
if (specularFound == false)
{
phong.Specular.Color = new Grendgine_Collada_Color { sID = "specular" };
if (material.Specular != null)
phong.Specular.Color.Value_As_String = material.Specular ?? string.Empty;
else
phong.Specular.Color.Value_As_String = "1 1 1";
}
phong.Emission = new Grendgine_Collada_FX_Common_Color_Or_Texture_Type
{
Color = new Grendgine_Collada_Color
{
sID = "emission",
Value_As_String = material.Emissive ?? string.Empty
}
};
phong.Shininess = new Grendgine_Collada_FX_Common_Float_Or_Param_Type { Float = new Grendgine_Collada_SID_Float() };
phong.Shininess.Float.sID = "shininess";
phong.Shininess.Float.Value = (float)material.Shininess;
phong.Index_Of_Refraction = new Grendgine_Collada_FX_Common_Float_Or_Param_Type { Float = new Grendgine_Collada_SID_Float() };
phong.Transparent = new Grendgine_Collada_FX_Common_Color_Or_Texture_Type
{
Color = new Grendgine_Collada_Color(),
Opaque = new Grendgine_Collada_FX_Opaque_Channel()
};
phong.Transparent.Color.Value_As_String = (1 - double.Parse((material.Opacity == string.Empty ? "1" : material.Opacity) ?? "1")).ToString(); // Subtract from 1 for proper value.
#endregion
colladaEffect.Profile_COMMON = profiles.ToArray();
profile.New_Param = new Grendgine_Collada_New_Param[newparams.Count];
profile.New_Param = newparams.ToArray();
return colladaEffect;
}
public void WriteLibrary_Geometries()
{
if (CryData.Models.Count == 1) // Single file model
WriteGeometries(CryData.Models[0]);
else
WriteGeometries(CryData.Models[1]);
}
public void WriteGeometries(Model model)
{
Grendgine_Collada_Library_Geometries libraryGeometries = new();
// Make a list for all the geometries objects we will need. Will convert to array at end. Define the array here as well
// We have to define a Geometry for EACH meshsubset in the meshsubsets, since the mesh can contain multiple materials
List<Grendgine_Collada_Geometry> geometryList = new();
// For each of the nodes, we need to write the geometry.
foreach (ChunkNode nodeChunk in model.ChunkMap.Values.Where(a => a.ChunkType == ChunkType.Node))
{
// Create a geometry object. Use the chunk ID for the geometry ID
// Create all the materials used by this chunk.
// Will have to be careful with this, since with .cga/.cgam pairs will need to match by Name.
// Make the mesh object. This will have 3 or 4 sources, 1 vertices, and 1 or more Triangles (with material ID)
// If the Object ID of Node chunk points to a Helper or a Controller though, place an empty.
ChunkDataStream? normals = null;
ChunkDataStream? uvs = null;
ChunkDataStream? tmpVertices = null;
ChunkDataStream? vertsUvs = null;
ChunkDataStream? indices = null;
ChunkDataStream? colors = null;
ChunkDataStream? tangents = null;
if (IsNodeNameExcluded(nodeChunk.Name))
{
Utils.Log(LogLevelEnum.Debug, $"Excluding node {nodeChunk.Name}");
continue;
}
if (nodeChunk.ObjectChunk is null)
{
Utils.Log(LogLevelEnum.Warning, "Skipped node with missing Object {0}", nodeChunk.Name);
continue;
}
if (nodeChunk._model.ChunkMap[nodeChunk.ObjectNodeID].ChunkType == ChunkType.Mesh)
{
// Create materials collection for this node. Index of collection in meshSubSets determines which mat to use.
CreateMaterialsFromNodeChunk(nodeChunk);
// Get the mesh chunk and submesh chunk for this node.
var meshChunk = (ChunkMesh)nodeChunk._model.ChunkMap[nodeChunk.ObjectNodeID];
// Check to see if the Mesh points to a PhysicsData mesh. Don't want to write these.
//if (meshChunk.MeshPhysicsData != 0)
// TODO: Implement this chunk
if (meshChunk.MeshSubsetsData != 0) // For the SC files, you can have Mesh chunks with no Mesh Subset. Need to skip these. They are in the .cga file and contain no geometry.
{
var meshSubsets = (ChunkMeshSubsets)nodeChunk._model.ChunkMap[meshChunk.MeshSubsetsData]; // Listed as Object ID for the Node
if (meshChunk.VerticesData != 0)
tmpVertices = (ChunkDataStream)nodeChunk._model.ChunkMap[meshChunk.VerticesData];
if (meshChunk.VertsUVsData != 0)
vertsUvs = (ChunkDataStream)nodeChunk._model.ChunkMap[meshChunk.VertsUVsData];
if (tmpVertices is null && vertsUvs is null) // There is no vertex data for this node. Skip.
continue;
if (meshChunk.NormalsData != 0)
normals = (ChunkDataStream)nodeChunk._model.ChunkMap[meshChunk.NormalsData];
if (meshChunk.UVsData != 0)
uvs = (ChunkDataStream)nodeChunk._model.ChunkMap[meshChunk.UVsData];
if (meshChunk.IndicesData != 0)
indices = (ChunkDataStream)nodeChunk._model.ChunkMap[meshChunk.IndicesData];
if (meshChunk.ColorsData != 0)
colors = (ChunkDataStream)nodeChunk._model.ChunkMap[meshChunk.ColorsData];
if (meshChunk.TangentsData != 0)
tangents = (ChunkDataStream)nodeChunk._model.ChunkMap[meshChunk.TangentsData];
// geometry is a Geometry object for each meshsubset. Name will be "Nodechunk name_matID".
Grendgine_Collada_Geometry geometry = new()
{
Name = nodeChunk.Name,
ID = nodeChunk.Name + "-mesh"
};
Grendgine_Collada_Mesh colladaMesh = new();
geometry.Mesh = colladaMesh;
// TODO: Move the source creation to a separate function. Too much retyping.
Grendgine_Collada_Source[] source = new Grendgine_Collada_Source[4]; // 4 possible source types.
Grendgine_Collada_Source posSource = new();
Grendgine_Collada_Source normSource = new();
Grendgine_Collada_Source uvSource = new();
Grendgine_Collada_Source colorSource = new();
source[0] = posSource;
source[1] = normSource;
source[2] = uvSource;
source[3] = colorSource;
posSource.ID = nodeChunk.Name + "-mesh-pos";
posSource.Name = nodeChunk.Name + "-pos";
normSource.ID = nodeChunk.Name + "-mesh-norm";
normSource.Name = nodeChunk.Name + "-norm";
uvSource.ID = nodeChunk.Name + "-mesh-UV";
uvSource.Name = nodeChunk.Name + "-UV";
colorSource.ID = nodeChunk.Name + "-mesh-color";
colorSource.Name = nodeChunk.Name + "-color";
Grendgine_Collada_Vertices vertices = new() { ID = nodeChunk.Name + "-vertices" };
geometry.Mesh.Vertices = vertices;
Grendgine_Collada_Input_Unshared[] inputshared = new Grendgine_Collada_Input_Unshared[4];
Grendgine_Collada_Input_Unshared posInput = new() { Semantic = Grendgine_Collada_Input_Semantic.POSITION };
vertices.Input = inputshared;
Grendgine_Collada_Input_Unshared normInput = new() { Semantic = Grendgine_Collada_Input_Semantic.NORMAL };
Grendgine_Collada_Input_Unshared uvInput = new() { Semantic = Grendgine_Collada_Input_Semantic.TEXCOORD };
Grendgine_Collada_Input_Unshared colorInput = new() { Semantic = Grendgine_Collada_Input_Semantic.COLOR };
posInput.source = "#" + posSource.ID;
normInput.source = "#" + normSource.ID;
uvInput.source = "#" + uvSource.ID;
colorInput.source = "#" + colorSource.ID;
inputshared[0] = posInput;
Grendgine_Collada_Float_Array floatArrayVerts = new();
Grendgine_Collada_Float_Array floatArrayNormals = new();
Grendgine_Collada_Float_Array floatArrayUVs = new();
Grendgine_Collada_Float_Array floatArrayColors = new();
Grendgine_Collada_Float_Array floatArrayTangents = new();
StringBuilder vertString = new();
StringBuilder normString = new();
StringBuilder uvString = new();
StringBuilder colorString = new();
if (tmpVertices is not null) // Will be null if it's using VertsUVs.
{
floatArrayVerts.ID = posSource.ID + "-array";
floatArrayVerts.Digits = 6;
floatArrayVerts.Magnitude = 38;
floatArrayVerts.Count = (int)tmpVertices.NumElements * 3;
floatArrayUVs.ID = uvSource.ID + "-array";
floatArrayUVs.Digits = 6;
floatArrayUVs.Magnitude = 38;
floatArrayUVs.Count = (int)uvs.NumElements * 2;
floatArrayNormals.ID = normSource.ID + "-array";
floatArrayNormals.Digits = 6;
floatArrayNormals.Magnitude = 38;
if (normals is not null)
floatArrayNormals.Count = (int)normals.NumElements * 3;
floatArrayColors.ID = colorSource.ID + "-array";
floatArrayColors.Digits = 6;
floatArrayColors.Magnitude = 38;
if (colors is not null)
{
floatArrayColors.Count = (int)colors.NumElements * 4;
for (uint j = 0; j < colors.NumElements; j++) // Create Colors string
{
colorString.AppendFormat(culture, "{0:F6} {1:F6} {2:F6} {3:F6} ",
colors.Colors[j].r / 255.0,
colors.Colors[j].g / 255.0,
colors.Colors[j].b / 255.0,
colors.Colors[j].a / 255.0);
}
}
// Create Vertices and normals string
for (uint j = 0; j < meshChunk.NumVertices; j++)
{
Vector3 vertex = tmpVertices.Vertices[j];
vertString.AppendFormat(culture, "{0:F6} {1:F6} {2:F6} ", vertex.X, vertex.Y, vertex.Z);
Vector3 normal = normals?.Normals[j] ?? tangents?.Normals[j] ?? new Vector3(0.0f, 0.0f, 0.0f);
normString.AppendFormat(culture, "{0:F6} {1:F6} {2:F6} ", Safe(normal.X), Safe(normal.Y), Safe(normal.Z));
}
for (uint j = 0; j < uvs.NumElements; j++) // Create UV string
{
uvString.AppendFormat(culture, "{0:F6} {1:F6} ", Safe(uvs.UVs[j].U), 1 - Safe(uvs.UVs[j].V));
}
}
else // VertsUV structure. Pull out verts and UVs from tmpVertsUVs.
{
floatArrayVerts.ID = posSource.ID + "-array";
floatArrayVerts.Digits = 6;
floatArrayVerts.Magnitude = 38;
floatArrayVerts.Count = (int)vertsUvs.NumElements * 3;
floatArrayUVs.ID = uvSource.ID + "-array";
floatArrayUVs.Digits = 6;
floatArrayUVs.Magnitude = 38;
floatArrayUVs.Count = (int)vertsUvs.NumElements * 2;
floatArrayNormals.ID = normSource.ID + "-array";
floatArrayNormals.Digits = 6;
floatArrayNormals.Magnitude = 38;
floatArrayNormals.Count = (int)vertsUvs.NumElements * 3;
floatArrayColors.ID = colorSource.ID + "-array";
floatArrayColors.Digits = 6;
floatArrayColors.Magnitude = 38;
if (vertsUvs.Colors != null)
{
floatArrayColors.Count = vertsUvs.Colors.Length * 4;
for (uint j = 0; j < vertsUvs.Colors.Length; j++) // Create Colors string
{
colorString.AppendFormat(culture, "{0:F6} {1:F6} {2:F6} {3:F6} ",
vertsUvs.Colors[j].r / 255.0,
vertsUvs.Colors[j].g / 255.0,
vertsUvs.Colors[j].b / 255.0,
vertsUvs.Colors[j].a / 255.0);
}
}
// Dymek's code to rescale by bounding box. Only apply to geometry (cga or cgf), and not skin or chr objects.
var multiplerVector = Vector3.Abs((meshChunk.MinBound - meshChunk.MaxBound) / 2f);
if (multiplerVector.X < 1) { multiplerVector.X = 1; }
if (multiplerVector.Y < 1) { multiplerVector.Y = 1; }
if (multiplerVector.Z < 1) { multiplerVector.Z = 1; }
var boundaryBoxCenter = (meshChunk.MinBound + meshChunk.MaxBound) / 2f;
// Create Vertices, normals and colors string
for (uint j = 0; j < meshChunk.NumVertices; j++)
{
Vector3 vertex = vertsUvs.Vertices[j];
// Rotate/translate the vertex
if (!CryData.InputFile.EndsWith("skin") && !CryData.InputFile.EndsWith("chr"))
vertex = (vertex * multiplerVector) + boundaryBoxCenter;
vertString.AppendFormat("{0:F6} {1:F6} {2:F6} ", Safe(vertex.X), Safe(vertex.Y), Safe(vertex.Z));
// TODO: This isn't right? VertsUvs may always have color as the 3rd element.
// Normals depend on the data size. 16 byte structures have the normals in the Tangents. 20 byte structures are in the VertsUV.
Vector3 normal = new();
if (vertsUvs.Normals != null)
normal = vertsUvs.Normals[j];
else if (tangents != null && tangents.Normals != null)
normal = tangents.Normals[j];
normString.AppendFormat("{0:F6} {1:F6} {2:F6} ", Safe(normal.X), Safe(normal.Y), Safe(normal.Z));
}
// Create UV string
for (uint j = 0; j < vertsUvs.NumElements; j++)
{
uvString.AppendFormat("{0:F6} {1:F6} ", Safe(vertsUvs.UVs[j].U), Safe(1 - vertsUvs.UVs[j].V));
}
}
CleanNumbers(vertString);
CleanNumbers(normString);
CleanNumbers(uvString);
CleanNumbers(colorString);
#region Create the triangles node.
var triangles = new Grendgine_Collada_Triangles[meshSubsets.NumMeshSubset];
geometry.Mesh.Triangles = triangles;
for (uint j = 0; j < meshSubsets.NumMeshSubset; j++) // Need to make a new Triangles entry for each submesh.
{
triangles[j] = new Grendgine_Collada_Triangles
{
Count = meshSubsets.MeshSubsets[j].NumIndices / 3,
Material = GetMaterialName(nodeChunk, meshSubsets, (int)j)
};
// Create the inputs. vertex, normal, texcoord, color
int inputCount = 3;
if (colors != null || vertsUvs?.Colors != null)
inputCount++;
triangles[j].Input = new Grendgine_Collada_Input_Shared[inputCount];
triangles[j].Input[0] = new Grendgine_Collada_Input_Shared
{
Semantic = new Grendgine_Collada_Input_Semantic()
};
triangles[j].Input[0].Semantic = Grendgine_Collada_Input_Semantic.VERTEX;
triangles[j].Input[0].Offset = 0;
triangles[j].Input[0].source = "#" + vertices.ID;
triangles[j].Input[1] = new Grendgine_Collada_Input_Shared
{
Semantic = Grendgine_Collada_Input_Semantic.NORMAL,
Offset = 1,
source = "#" + normSource.ID
};
triangles[j].Input[2] = new Grendgine_Collada_Input_Shared
{
Semantic = Grendgine_Collada_Input_Semantic.TEXCOORD,
Offset = 2,
source = "#" + uvSource.ID
};
int nextInputID = 3;
if (colors != null || vertsUvs?.Colors != null)
{
triangles[j].Input[nextInputID] = new Grendgine_Collada_Input_Shared
{
Semantic = Grendgine_Collada_Input_Semantic.COLOR,
Offset = nextInputID,
source = "#" + colorSource.ID
};
nextInputID++;
}
// Create the vcount list. All triangles, so the subset number of indices.
StringBuilder vc = new();
for (var k = meshSubsets.MeshSubsets[j].FirstIndex; k < (meshSubsets.MeshSubsets[j].FirstIndex + meshSubsets.MeshSubsets[j].NumIndices); k++)
{
int ccount = 3;
if (colors != null || vertsUvs?.Colors != null)
ccount++;
vc.AppendFormat(culture, String.Format("{0} ", ccount));
k += 2;
}
// Create the P node for the Triangles.
StringBuilder p = new();
for (var k = meshSubsets.MeshSubsets[j].FirstIndex; k < (meshSubsets.MeshSubsets[j].FirstIndex + meshSubsets.MeshSubsets[j].NumIndices); k++)
{
int values = 0;
if (colors != null || vertsUvs?.Colors != null)
{
values++;
}
List<string> formatlist = new();
formatlist.Add("{0} {0} {0} ");
formatlist.Add("{1} {1} {1} ");
formatlist.Add("{2} {2} {2} ");
for (var valuecount = 0; valuecount < values; valuecount++)
{
formatlist[0] += "{0} ";
formatlist[1] += "{1} ";
formatlist[2] += "{2} ";
}
string finalformat = String.Join("", formatlist);
p.AppendFormat(finalformat, indices.Indices[k], indices.Indices[k + 1], indices.Indices[k + 2]);
k += 2;
}
triangles[j].P = new Grendgine_Collada_Int_Array_String
{
Value_As_String = p.ToString().TrimEnd()
};
}
#endregion
#region Create the source float_array nodes. Vertex, normal, UV. May need color as well.
floatArrayVerts.Value_As_String = vertString.ToString().TrimEnd();
floatArrayNormals.Value_As_String = normString.ToString().TrimEnd();
floatArrayUVs.Value_As_String = uvString.ToString().TrimEnd();
floatArrayColors.Value_As_String = colorString.ToString();
source[0].Float_Array = floatArrayVerts;
source[1].Float_Array = floatArrayNormals;
source[2].Float_Array = floatArrayUVs;
source[3].Float_Array = floatArrayColors;
geometry.Mesh.Source = source;
// create the technique_common for each of these
posSource.Technique_Common = new Grendgine_Collada_Technique_Common_Source
{
Accessor = new Grendgine_Collada_Accessor()
};
posSource.Technique_Common.Accessor.Source = "#" + floatArrayVerts.ID;
posSource.Technique_Common.Accessor.Stride = 3;
posSource.Technique_Common.Accessor.Count = (uint)meshChunk.NumVertices;
Grendgine_Collada_Param[] paramPos = new Grendgine_Collada_Param[3];
paramPos[0] = new Grendgine_Collada_Param();
paramPos[1] = new Grendgine_Collada_Param();
paramPos[2] = new Grendgine_Collada_Param();
paramPos[0].Name = "X";
paramPos[0].Type = "float";
paramPos[1].Name = "Y";
paramPos[1].Type = "float";
paramPos[2].Name = "Z";
paramPos[2].Type = "float";
posSource.Technique_Common.Accessor.Param = paramPos;
normSource.Technique_Common = new Grendgine_Collada_Technique_Common_Source
{
Accessor = new Grendgine_Collada_Accessor
{
Source = "#" + floatArrayNormals.ID,
Stride = 3,
Count = (uint)meshChunk.NumVertices
}
};
Grendgine_Collada_Param[] paramNorm = new Grendgine_Collada_Param[3];
paramNorm[0] = new Grendgine_Collada_Param();
paramNorm[1] = new Grendgine_Collada_Param();
paramNorm[2] = new Grendgine_Collada_Param();
paramNorm[0].Name = "X";
paramNorm[0].Type = "float";
paramNorm[1].Name = "Y";
paramNorm[1].Type = "float";
paramNorm[2].Name = "Z";
paramNorm[2].Type = "float";
normSource.Technique_Common.Accessor.Param = paramNorm;
uvSource.Technique_Common = new Grendgine_Collada_Technique_Common_Source
{
Accessor = new Grendgine_Collada_Accessor
{
Source = "#" + floatArrayUVs.ID,
Stride = 2
}
};
if (tmpVertices != null)
uvSource.Technique_Common.Accessor.Count = uvs.NumElements;
else
uvSource.Technique_Common.Accessor.Count = vertsUvs.NumElements;
Grendgine_Collada_Param[] paramUV = new Grendgine_Collada_Param[2];
paramUV[0] = new Grendgine_Collada_Param();
paramUV[1] = new Grendgine_Collada_Param();
paramUV[0].Name = "S";
paramUV[0].Type = "float";
paramUV[1].Name = "T";
paramUV[1].Type = "float";
uvSource.Technique_Common.Accessor.Param = paramUV;
if (colors != null || vertsUvs?.Colors != null)
{
uint numberOfElements;
if (colors != null)
numberOfElements = colors.NumElements;
else
numberOfElements = (uint)vertsUvs.Colors.Length;
colorSource.Technique_Common = new Grendgine_Collada_Technique_Common_Source
{
Accessor = new Grendgine_Collada_Accessor()
};
colorSource.Technique_Common.Accessor.Source = "#" + floatArrayColors.ID;
colorSource.Technique_Common.Accessor.Stride = 4;
colorSource.Technique_Common.Accessor.Count = numberOfElements;
Grendgine_Collada_Param[] paramColor = new Grendgine_Collada_Param[4];
paramColor[0] = new Grendgine_Collada_Param();
paramColor[1] = new Grendgine_Collada_Param();
paramColor[2] = new Grendgine_Collada_Param();
paramColor[3] = new Grendgine_Collada_Param();
paramColor[0].Name = "R";
paramColor[0].Type = "float";
paramColor[1].Name = "G";
paramColor[1].Type = "float";
paramColor[2].Name = "B";
paramColor[2].Type = "float";
paramColor[3].Name = "A";
paramColor[3].Type = "float";
colorSource.Technique_Common.Accessor.Param = paramColor;
}
geometryList.Add(geometry);
#endregion
}
}
// There is no geometry for a helper or controller node. Can skip the rest.
}
libraryGeometries.Geometry = geometryList.ToArray();
DaeObject.Library_Geometries = libraryGeometries;
}
private void CreateMaterialsFromNodeChunk(ChunkNode nodeChunk)
{
List<Grendgine_Collada_Material> colladaMaterials = new();
List<Grendgine_Collada_Effect> colladaEffects = new();
if (DaeObject.Library_Materials.Material is null)
DaeObject.Library_Materials.Material = Array.Empty<Grendgine_Collada_Material>();
foreach (var mat in nodeChunk.Materials.SubMaterials)
{
// Check to see if the collada object already has a material with this name. If not, add.
var matNames = DaeObject.Library_Materials.Material.Select(c => c.Name);
if (!matNames.Contains(mat.Name))
{
colladaMaterials.Add(AddMaterialToMaterialLibrary(mat));
colladaEffects.Add(CreateColladaEffect(mat));
}
}
int arraySize = DaeObject.Library_Materials.Material.Length;
Array.Resize(ref DaeObject.Library_Materials.Material, DaeObject.Library_Materials.Material.Length + colladaMaterials.Count);
colladaMaterials.CopyTo(DaeObject.Library_Materials.Material, arraySize);
if (DaeObject.Library_Effects.Effect is null)
DaeObject.Library_Effects.Effect = colladaEffects.ToArray();
else
{
int effectsArraySize = DaeObject.Library_Effects.Effect.Length;
Array.Resize(ref DaeObject.Library_Effects.Effect, DaeObject.Library_Effects.Effect.Length + colladaEffects.Count);
colladaEffects.CopyTo(DaeObject.Library_Effects.Effect, effectsArraySize);
}
}
private Grendgine_Collada_Material AddMaterialToMaterialLibrary(Material mat)
{
Grendgine_Collada_Material material = new()
{
Instance_Effect = new Grendgine_Collada_Instance_Effect(),
Name = mat.Name,
ID = mat.Name + "-material"
};
material.Instance_Effect.URL = "#" + mat.Name + "-effect";
AddImagesToImagesLibrary(mat);
return material;
}
private void AddImagesToImagesLibrary(Material mat)
{
List<Grendgine_Collada_Image> imageList = new();
int numberOfTextures = mat.Textures.Length;
for (int i = 0; i < numberOfTextures; i++)
{
// For each texture in the material, we make a new <image> object and add it to the list.
Grendgine_Collada_Image image = new()
{
ID = mat.Name + "_" + mat.Textures[i].Map,
Name = mat.Name + "_" + mat.Textures[i].Map,
Init_From = new Grendgine_Collada_Init_From()
};
// Try to resolve the texture file to a file on disk. Texture are always based on DataDir.
StringBuilder builder = new(ResolveTextureFile(mat.Textures[i].File, Args.DataDir));
if (Args.PngTextures && File.Exists(builder.ToString().Replace(".dds", ".png")))
builder.Replace(".dds", ".png");
else if (Args.TgaTextures && File.Exists(builder.ToString().Replace(".dds", ".tga")))
builder.Replace(".dds", ".tga");
else if (Args.TiffTextures && File.Exists(builder.ToString().Replace(".dds", ".tif")))
builder.Replace(".dds", ".tif");
if (Args.DataDir.ToString() != ".")
builder.Insert(0, "/"); // Path is absolute, preface with a "/"
builder.Replace(" ", @"%20");
// if 1.4.1, use URI. If 1.5.0, use Ref.
_ = DaeObject.Collada_Version == "1.4.1" ? image.Init_From.Uri = builder.ToString() : image.Init_From.Ref = builder.ToString();
imageList.Add(image);
}
Grendgine_Collada_Image[] images = imageList.ToArray();
if (DaeObject.Library_Images.Image is null)
DaeObject.Library_Images.Image = images;
else
{
int arraySize = DaeObject.Library_Images.Image.Length;
Array.Resize(ref DaeObject.Library_Images.Image, DaeObject.Library_Images.Image.Length + images.Length);
images.CopyTo(DaeObject.Library_Images.Image, arraySize);
}
}
private void WriteLibrary_Controllers()
{
if (DaeObject.Library_Geometries.Geometry.Length != 0)
{
Grendgine_Collada_Library_Controllers libraryController = new();
// There can be multiple controllers in the controller library. But for Cryengine files, there is only one rig.
// So if a rig exists, make that the controller. This applies mostly to .chr files, which will have a rig and may have geometry.
Grendgine_Collada_Controller controller = new() { ID = "Controller" };
// Create the skin object and assign to the controller
Grendgine_Collada_Skin skin = new()
{
source = "#" + DaeObject.Library_Geometries.Geometry[0].ID,
Bind_Shape_Matrix = new Grendgine_Collada_Float_Array_String()
};
skin.Bind_Shape_Matrix.Value_As_String = CreateStringFromMatrix4x4(Matrix4x4.Identity); // We will assume the BSM is the identity matrix for now
// Create the 3 sources for this controller: joints, bind poses, and weights
skin.Source = new Grendgine_Collada_Source[3];
// Populate the data.
// Need to map the exterior vertices (geometry) to the int vertices. Or use the Bone Map datastream if it exists (check HasBoneMapDatastream).
#region Joints Source
Grendgine_Collada_Source jointsSource = new()
{
ID = "Controller-joints"
};
jointsSource.Name_Array = new Grendgine_Collada_Name_Array()
{
ID = "Controller-joints-array",
Count = CryData.SkinningInfo.CompiledBones.Count,
};
StringBuilder boneNames = new();
for (int i = 0; i < CryData.SkinningInfo.CompiledBones.Count; i++)
{
boneNames.Append(CryData.SkinningInfo.CompiledBones[i].boneName.Replace(' ', '_') + " ");
}
jointsSource.Name_Array.Value_Pre_Parse = boneNames.ToString().TrimEnd();
jointsSource.Technique_Common = new Grendgine_Collada_Technique_Common_Source
{
Accessor = new Grendgine_Collada_Accessor
{
Source = "#Controller-joints-array",
Count = (uint)CryData.SkinningInfo.CompiledBones.Count,
Stride = 1
}
};
skin.Source[0] = jointsSource;
#endregion
#region Bind Pose Array Source
Grendgine_Collada_Source bindPoseArraySource = new()
{
ID = "Controller-bind_poses",
Float_Array = new()
{
ID = "Controller-bind_poses-array",
Count = CryData.SkinningInfo.CompiledBones.Count * 16,
Value_As_String = GetBindPoseArray(CryData.SkinningInfo.CompiledBones)
},
Technique_Common = new Grendgine_Collada_Technique_Common_Source
{
Accessor = new Grendgine_Collada_Accessor
{
Source = "#Controller-bind_poses-array",
Count = (uint)CryData.SkinningInfo.CompiledBones.Count,
Stride = 16,
}
}
};
bindPoseArraySource.Technique_Common.Accessor.Param = new Grendgine_Collada_Param[1];
bindPoseArraySource.Technique_Common.Accessor.Param[0] = new Grendgine_Collada_Param
{
Name = "TRANSFORM",
Type = "float4x4"
};
skin.Source[1] = bindPoseArraySource;
#endregion
#region Weights Source
Grendgine_Collada_Source weightArraySource = new()
{
ID = "Controller-weights",
Technique_Common = new Grendgine_Collada_Technique_Common_Source()
};
Grendgine_Collada_Accessor accessor = weightArraySource.Technique_Common.Accessor = new Grendgine_Collada_Accessor();
weightArraySource.Float_Array = new Grendgine_Collada_Float_Array()
{
ID = "Controller-weights-array",
};
StringBuilder weights = new();
if (CryData.SkinningInfo.IntVertices == null) // This is a case where there are bones, and only Bone Mapping data from a datastream chunk. Skin files.
{
weightArraySource.Float_Array.Count = CryData.SkinningInfo.BoneMapping.Count;
for (int i = 0; i < CryData.SkinningInfo.BoneMapping.Count; i++)
{
for (int j = 0; j < 4; j++)
{
weights.Append(((float)CryData.SkinningInfo.BoneMapping[i].Weight[j] / 255).ToString() + " ");
}
};
accessor.Count = (uint)CryData.SkinningInfo.BoneMapping.Count * 4;
}
else // Bones and int verts. Will use int verts for weights, but this doesn't seem perfect either.
{
weightArraySource.Float_Array.Count = CryData.SkinningInfo.Ext2IntMap.Count;
for (int i = 0; i < CryData.SkinningInfo.Ext2IntMap.Count; i++)
{
for (int j = 0; j < 4; j++)
{
weights.Append(CryData.SkinningInfo.IntVertices[CryData.SkinningInfo.Ext2IntMap[i]].Weights[j] + " ");
}
accessor.Count = (uint)CryData.SkinningInfo.Ext2IntMap.Count * 4;
};
}
CleanNumbers(weights);
weightArraySource.Float_Array.Value_As_String = weights.ToString().TrimEnd();
// Add technique_common part.
accessor.Source = "#Controller-weights-array";
accessor.Stride = 1;
accessor.Param = new Grendgine_Collada_Param[1];
accessor.Param[0] = new Grendgine_Collada_Param
{
Name = "WEIGHT",
Type = "float"
};
skin.Source[2] = weightArraySource;
#endregion
#region Joints
skin.Joints = new Grendgine_Collada_Joints
{
Input = new Grendgine_Collada_Input_Unshared[2]
};
skin.Joints.Input[0] = new Grendgine_Collada_Input_Unshared
{
Semantic = new Grendgine_Collada_Input_Semantic()
};
skin.Joints.Input[0].Semantic = Grendgine_Collada_Input_Semantic.JOINT;
skin.Joints.Input[0].source = "#Controller-joints";
skin.Joints.Input[1] = new Grendgine_Collada_Input_Unshared
{
Semantic = new Grendgine_Collada_Input_Semantic()
};
skin.Joints.Input[1].Semantic = Grendgine_Collada_Input_Semantic.INV_BIND_MATRIX;
skin.Joints.Input[1].source = "#Controller-bind_poses";