Program.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Reflection;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. using NJsonSchema.References;
  8. namespace SharpGLTF
  9. {
  10. using CodeGen;
  11. using SchemaReflection;
  12. class Program
  13. {
  14. #region MAIN
  15. static void Main(string[] args)
  16. {
  17. SchemaDownload.Syncronize(Constants.RemoteSchemaRepo, Constants.LocalRepoDirectory);
  18. _ProcessMainSchema();
  19. _ProcessKhronosPBRExtension();
  20. _ProcessKhronosUnlitExtension();
  21. _ProcessKhronosLightsPunctualExtension();
  22. // these extansions are not fully supported and temporarily removed:
  23. // _ProcessDracoExtension();
  24. // _ProcessMicrosoftLODExtension();
  25. }
  26. #endregion
  27. #region Main Schema code generation
  28. private static void _ProcessMainSchema()
  29. {
  30. // load and process schema
  31. var ctx1 = LoadSchemaContext(Constants.MainSchemaFile);
  32. // we remove "glTF Property" because it is hand coded.
  33. ctx1.Remove(ctx1.Classes.FirstOrDefault(item => item.PersistentName == "glTF Property"));
  34. // mimeType "anyof" is basically the string to use.
  35. ctx1.Remove(ctx1.Enumerations.FirstOrDefault(item => item.PersistentName == "image/jpeg-image/png"));
  36. // replace Image.mimeType type from an Enum to String, so we can serialize it with more formats if required
  37. ctx1.Classes
  38. .ToArray()
  39. .FirstOrDefault(item => item.PersistentName == "Image")
  40. .UseField("mimeType")
  41. .FieldType = ctx1.UseString();
  42. // replace Node.Matrix, Node.Rotation, Node.Scale and Node.Translation with System.Numerics.Vectors types
  43. var node = ctx1.Classes
  44. .ToArray()
  45. .FirstOrDefault(item => item.PersistentName == "Node");
  46. node.UseField("matrix").SetDataType(typeof(System.Numerics.Matrix4x4), true).RemoveDefaultValue().SetItemsRange(0);
  47. node.UseField("rotation").SetDataType(typeof(System.Numerics.Quaternion), true).RemoveDefaultValue().SetItemsRange(0);
  48. node.UseField("scale").SetDataType(typeof(System.Numerics.Vector3), true).RemoveDefaultValue().SetItemsRange(0);
  49. node.UseField("translation").SetDataType(typeof(System.Numerics.Vector3), true).RemoveDefaultValue().SetItemsRange(0);
  50. // replace Material.emissiveFactor with System.Numerics.Vectors types
  51. ctx1.Classes
  52. .ToArray()
  53. .FirstOrDefault(item => item.PersistentName == "Material")
  54. .UseField("emissiveFactor")
  55. .SetDataType(typeof(System.Numerics.Vector3), true)
  56. .SetDefaultValue("Vector3.Zero")
  57. .SetItemsRange(0);
  58. // replace Material.baseColorFactor with System.Numerics.Vectors types
  59. ctx1.Classes
  60. .ToArray()
  61. .FirstOrDefault(item => item.PersistentName == "Material PBR Metallic Roughness")
  62. .UseField("baseColorFactor")
  63. .SetDataType(typeof(System.Numerics.Vector4), true)
  64. .SetDefaultValue("Vector4.One")
  65. .SetItemsRange(0);
  66. ProcessSchema("gltf.g", ctx1);
  67. }
  68. #endregion
  69. #region Extensions code generation
  70. private static void _ProcessDracoExtension()
  71. {
  72. var ctx2 = LoadSchemaContext(Constants.KhronosDracoSchemaFile);
  73. ProcessSchema("ext.draco.g",ctx2);
  74. }
  75. private static void _ProcessKhronosPBRExtension()
  76. {
  77. var ctx = LoadSchemaContext(Constants.KhronosPbrSpecGlossSchemaFile);
  78. // remove already defined classes
  79. ctx.Remove("glTF Property");
  80. ctx.Remove("Texture Info");
  81. ctx.Classes
  82. .ToArray()
  83. .FirstOrDefault(item => item.PersistentName == "KHR_materials_pbrSpecularGlossiness glTF extension")
  84. .UseField("diffuseFactor")
  85. .SetDataType(typeof(System.Numerics.Vector4), true)
  86. .SetDefaultValue("Vector4.One")
  87. .SetItemsRange(0);
  88. ctx.Classes
  89. .ToArray()
  90. .FirstOrDefault(item => item.PersistentName == "KHR_materials_pbrSpecularGlossiness glTF extension")
  91. .UseField("specularFactor")
  92. .SetDataType(typeof(System.Numerics.Vector3), true)
  93. .SetDefaultValue("Vector3.One")
  94. .SetItemsRange(0);
  95. ProcessSchema("ext.pbrSpecularGlossiness.g", ctx);
  96. }
  97. private static void _ProcessKhronosUnlitExtension()
  98. {
  99. var ctx = LoadSchemaContext(Constants.KhronosUnlitSchemaFile);
  100. ctx.Remove("glTF Property");
  101. ProcessSchema("ext.Unlit.g", ctx);
  102. }
  103. private static void _ProcessKhronosLightsPunctualExtension()
  104. {
  105. var ctx = LoadSchemaContext(Constants.KhronosLightsPunctualSchemaFile);
  106. ctx.Remove("glTF Property");
  107. ctx.Classes.FirstOrDefault(item => item.PersistentName == "glTF Child of Root Property").IgnoredByEmitter = true;
  108. var light = ctx.Classes
  109. .ToArray()
  110. .FirstOrDefault(item => item.PersistentName == "light");
  111. light.UseField("color")
  112. .SetDataType(typeof(System.Numerics.Vector3), true)
  113. .SetDefaultValue("Vector3.One")
  114. .SetItemsRange(0);
  115. ProcessSchema("ext.LightsPunctual.g", ctx);
  116. }
  117. /*
  118. private static void _ProcessMicrosoftLODExtension()
  119. {
  120. var ctx3 = LoadSchemaContext("glTF\\extensions\\2.0\\Vendor\\MSFT_lod\\schema\\glTF.MSFT_lod.schema.json");
  121. ctx3.Remove("glTF Property");
  122. ProcessSchema("ext.msft_lod.g", ctx3);
  123. }*/
  124. #endregion
  125. #region code generation
  126. private static string _FindTargetDirectory(string dstDir)
  127. {
  128. var dir = Constants.LocalRepoDirectory;
  129. while(dir.Length > 3)
  130. {
  131. var xdir = System.IO.Path.Combine(dir, dstDir);
  132. if (System.IO.Directory.Exists(xdir)) return xdir;
  133. dir = System.IO.Path.GetDirectoryName(dir); // move up
  134. }
  135. return null;
  136. }
  137. private static void ProcessSchema(string dstFile, SchemaType.Context ctx)
  138. {
  139. var newEmitter = new CSharpEmitter();
  140. newEmitter.DeclareContext(ctx);
  141. newEmitter.SetCollectionContainer("List<TItem>");
  142. const string rootName = "ModelRoot";
  143. newEmitter.SetRuntimeName("glTF", rootName);
  144. newEmitter.SetRuntimeName("glTF Property", "ExtensionsProperty");
  145. newEmitter.SetRuntimeName("glTF Child of Root Property", "LogicalChildOfRoot");
  146. // newEmitter.SetRuntimeName("Sampler", "TextureSampler");
  147. newEmitter.SetRuntimeName("UNSIGNED_BYTE-UNSIGNED_INT-UNSIGNED_SHORT", "IndexType");
  148. newEmitter.SetRuntimeName("BYTE-FLOAT-SHORT-UNSIGNED_BYTE-UNSIGNED_INT-UNSIGNED_SHORT", "ComponentType");
  149. newEmitter.SetRuntimeName("MAT2-MAT3-MAT4-SCALAR-VEC2-VEC3-VEC4", "ElementType");
  150. newEmitter.SetRuntimeName("rotation-scale-translation-weights", "PathType");
  151. newEmitter.SetRuntimeName("ARRAY_BUFFER-ELEMENT_ARRAY_BUFFER", "BufferMode");
  152. newEmitter.SetRuntimeName("orthographic-perspective", "CameraType");
  153. newEmitter.SetRuntimeName("BLEND-MASK-OPAQUE", "AlphaMode");
  154. newEmitter.SetRuntimeName("LINE_LOOP-LINE_STRIP-LINES-POINTS-TRIANGLE_FAN-TRIANGLE_STRIP-TRIANGLES", "PrimitiveType");
  155. newEmitter.SetRuntimeName("CUBICSPLINE-LINEAR-STEP", "AnimationInterpolationMode");
  156. newEmitter.SetRuntimeName("LINEAR-NEAREST", "TextureInterpolationMode");
  157. newEmitter.SetRuntimeName("CLAMP_TO_EDGE-MIRRORED_REPEAT-REPEAT", "TextureWrapMode");
  158. newEmitter.SetRuntimeName("LINEAR-LINEAR_MIPMAP_LINEAR-LINEAR_MIPMAP_NEAREST-NEAREST-NEAREST_MIPMAP_LINEAR-NEAREST_MIPMAP_NEAREST", "TextureMipMapMode");
  159. newEmitter.SetRuntimeName("KHR_materials_pbrSpecularGlossiness glTF extension", "MaterialPBRSpecularGlossiness_KHR");
  160. newEmitter.SetRuntimeName("KHR_materials_unlit glTF extension", "MaterialUnlit_KHR");
  161. newEmitter.SetRuntimeName("light", "Light_KHR");
  162. newEmitter.SetRuntimeName("light/spot", "LightSpot_KHR");
  163. var classes = ctx.Classes.ToArray();
  164. var fields = classes.SelectMany(item => item.Fields).ToArray();
  165. var meshClass = classes.FirstOrDefault(c => c.PersistentName == "Mesh");
  166. if (meshClass != null)
  167. {
  168. newEmitter.SetCollectionContainer(meshClass.UseField("primitives"), "ChildrenCollection<TItem,Mesh>");
  169. }
  170. var animationClass = classes.FirstOrDefault(c => c.PersistentName == "Animation");
  171. if (animationClass != null)
  172. {
  173. newEmitter.SetCollectionContainer(animationClass.UseField("channels"), "ChildrenCollection<TItem,Animation>");
  174. newEmitter.SetCollectionContainer(animationClass.UseField("samplers"), "ChildrenCollection<TItem,Animation>");
  175. }
  176. foreach (var f in fields)
  177. {
  178. if (f.FieldType is ArrayType atype)
  179. {
  180. if (atype.ItemType is ClassType ctype)
  181. {
  182. if (ctype.BaseClass != null && ctype.BaseClass.PersistentName == "glTF Child of Root Property")
  183. {
  184. newEmitter.SetCollectionContainer(f, $"ChildrenCollection<TItem,{rootName}>");
  185. }
  186. }
  187. }
  188. }
  189. var textOut = newEmitter.EmitContext(ctx);
  190. var dstDir = _FindTargetDirectory(Constants.TargetProjectDirectory);
  191. var dstPath = System.IO.Path.Combine(dstDir, $"{dstFile}.cs");
  192. System.IO.File.WriteAllText(dstPath, textOut);
  193. }
  194. #endregion
  195. #region schema loader
  196. private static SchemaType.Context LoadSchemaContext(string srcSchema)
  197. {
  198. var schema = LoadSchema(srcSchema);
  199. var settings = new NJsonSchema.CodeGeneration.CSharp.CSharpGeneratorSettings
  200. {
  201. Namespace = "glTf.POCO",
  202. ClassStyle = NJsonSchema.CodeGeneration.CSharp.CSharpClassStyle.Poco
  203. };
  204. var ctypes = new NJsonSchema.CodeGeneration.CSharp.CSharpTypeResolver(settings);
  205. ctypes.Resolve(schema, false, null);
  206. return SchemaTypesReader.Generate(ctypes);
  207. }
  208. static NJsonSchema.JsonSchema4 LoadSchema(string filePath)
  209. {
  210. // https://blogs.msdn.microsoft.com/benjaminperkins/2017/03/08/how-to-call-an-async-method-from-a-console-app-main-method/
  211. if (!System.IO.File.Exists(filePath)) throw new System.IO.FileNotFoundException(nameof(filePath), filePath);
  212. return NJsonSchema.JsonSchema4
  213. .FromFileAsync(filePath, s => _Resolver(s,filePath) )
  214. .ConfigureAwait(false)
  215. .GetAwaiter()
  216. .GetResult();
  217. }
  218. static NJsonSchema.JsonReferenceResolver _Resolver(NJsonSchema.JsonSchema4 schema, string basePath)
  219. {
  220. var solver = new NJsonSchema.JsonSchemaResolver(schema, new NJsonSchema.Generation.JsonSchemaGeneratorSettings());
  221. return new MyReferenceResolver(solver);
  222. }
  223. class MyReferenceResolver : NJsonSchema.JsonReferenceResolver
  224. {
  225. public MyReferenceResolver(NJsonSchema.JsonSchemaResolver resolver) : base(resolver) { }
  226. public override Task<IJsonReference> ResolveFileReferenceAsync(string filePath)
  227. {
  228. if (System.IO.File.Exists(filePath)) return base.ResolveFileReferenceAsync(filePath);
  229. filePath = System.IO.Path.GetFileName(filePath);
  230. filePath = System.IO.Path.Combine(Constants.MainSchemaDir, filePath);
  231. if (System.IO.File.Exists(filePath)) return base.ResolveFileReferenceAsync(filePath);
  232. throw new System.IO.FileNotFoundException(filePath);
  233. }
  234. }
  235. #endregion
  236. }
  237. }