Program.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  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. using JSONSCHEMA = NJsonSchema.JsonSchema;
  9. namespace SharpGLTF
  10. {
  11. using CodeGen;
  12. using SchemaReflection;
  13. class Program
  14. {
  15. #region MAIN
  16. static void Main(string[] args)
  17. {
  18. SchemaDownload.Syncronize(Constants.RemoteSchemaRepo, Constants.LocalRepoDirectory);
  19. _ProcessMainSchema();
  20. _ProcessKhronosSpecularGlossinessExtension();
  21. _ProcessKhronosUnlitExtension();
  22. _ProcessKhronosClearCoatExtension();
  23. _ProcessKhronosModelLightsPunctualExtension();
  24. _ProcessKhronosNodeLightsPunctualExtension();
  25. _ProcessKhronosTextureTransformExtension();
  26. _ProcessMicrosoftTextureDDSExtension();
  27. _ProcessTextureWebpExtension();
  28. // these extansions are not fully supported and temporarily removed:
  29. // _ProcessDracoExtension();
  30. // _ProcessMicrosoftLODExtension();
  31. }
  32. #endregion
  33. #region Main Schema code generation
  34. private static void _ProcessMainSchema()
  35. {
  36. // load and process schema
  37. var ctx1 = LoadSchemaContext(Constants.MainSchemaFile);
  38. // Ignore "glTF Property" because it is completely hand coded.
  39. ctx1.IgnoredByCodeEmitter("glTF Property");
  40. // We will mimeType "anyof" as a plain string.
  41. ctx1.Remove("image/jpeg-image/png");
  42. // replace Image.mimeType type from an Enum to String, so we can serialize it with more formats if required
  43. ctx1.FindClass("Image")
  44. .GetField("mimeType")
  45. .FieldType = ctx1.UseString();
  46. // replace Node.Matrix, Node.Rotation, Node.Scale and Node.Translation with System.Numerics.Vectors types
  47. var node = ctx1.FindClass("Node");
  48. node.GetField("matrix").SetDataType(typeof(System.Numerics.Matrix4x4), true).RemoveDefaultValue().SetItemsRange(0);
  49. node.GetField("rotation").SetDataType(typeof(System.Numerics.Quaternion), true).RemoveDefaultValue().SetItemsRange(0);
  50. node.GetField("scale").SetDataType(typeof(System.Numerics.Vector3), true).RemoveDefaultValue().SetItemsRange(0);
  51. node.GetField("translation").SetDataType(typeof(System.Numerics.Vector3), true).RemoveDefaultValue().SetItemsRange(0);
  52. // replace Material.emissiveFactor with System.Numerics.Vectors types
  53. ctx1.FindClass("Material")
  54. .GetField("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.FindClass("Material PBR Metallic Roughness")
  60. .GetField("baseColorFactor")
  61. .SetDataType(typeof(System.Numerics.Vector4), true)
  62. .SetDefaultValue("Vector4.One")
  63. .SetItemsRange(0);
  64. var tex1 = ctx1.FindEnum("LINEAR-NEAREST");
  65. tex1.SetValue("DEFAULT",0);
  66. var tex2 = ctx1.FindEnum("LINEAR-LINEAR_MIPMAP_LINEAR-LINEAR_MIPMAP_NEAREST-NEAREST-NEAREST_MIPMAP_LINEAR-NEAREST_MIPMAP_NEAREST");
  67. tex2.SetValue("DEFAULT", 0);
  68. ProcessSchema("gltf.g", ctx1);
  69. }
  70. #endregion
  71. #region Extensions code generation
  72. private static void _ProcessKhronosSpecularGlossinessExtension()
  73. {
  74. var ctx = LoadSchemaContext(Constants.KhronosPbrSpecGlossSchemaFile);
  75. ctx.IgnoredByCodeEmitter("glTF Property");
  76. ctx.IgnoredByCodeEmitter("glTF Child of Root Property");
  77. ctx.IgnoredByCodeEmitter("Texture Info");
  78. ctx.FindClass("KHR_materials_pbrSpecularGlossiness glTF extension")
  79. .GetField("diffuseFactor")
  80. .SetDataType(typeof(System.Numerics.Vector4), true)
  81. .SetDefaultValue("Vector4.One")
  82. .SetItemsRange(0);
  83. ctx.FindClass("KHR_materials_pbrSpecularGlossiness glTF extension")
  84. .GetField("specularFactor")
  85. .SetDataType(typeof(System.Numerics.Vector3), true)
  86. .SetDefaultValue("Vector3.One")
  87. .SetItemsRange(0);
  88. ProcessSchema("ext.pbrSpecularGlossiness.g", ctx);
  89. }
  90. private static void _ProcessKhronosUnlitExtension()
  91. {
  92. var ctx = LoadSchemaContext(Constants.KhronosUnlitSchemaFile);
  93. ctx.IgnoredByCodeEmitter("glTF Property");
  94. ctx.IgnoredByCodeEmitter("glTF Child of Root Property");
  95. ProcessSchema("ext.Unlit.g", ctx);
  96. }
  97. private static void _ProcessKhronosClearCoatExtension()
  98. {
  99. var ctx = LoadSchemaContext(Constants.KhronosPbrClearCoatSchemaFile);
  100. ctx.IgnoredByCodeEmitter("glTF Property");
  101. ctx.IgnoredByCodeEmitter("glTF Child of Root Property");
  102. ctx.IgnoredByCodeEmitter("Texture Info");
  103. ctx.IgnoredByCodeEmitter("Material Normal Texture Info");
  104. /*
  105. ctx.FindClass("KHR_materials_pbrSpecularGlossiness glTF extension")
  106. .GetField("diffuseFactor")
  107. .SetDataType(typeof(System.Numerics.Vector4), true)
  108. .SetDefaultValue("Vector4.One")
  109. .SetItemsRange(0);
  110. ctx.FindClass("KHR_materials_pbrSpecularGlossiness glTF extension")
  111. .GetField("specularFactor")
  112. .SetDataType(typeof(System.Numerics.Vector3), true)
  113. .SetDefaultValue("Vector3.One")
  114. .SetItemsRange(0);*/
  115. ProcessSchema("ext.ClearCoat.g", ctx);
  116. }
  117. private static void _ProcessKhronosModelLightsPunctualExtension()
  118. {
  119. var ctx = LoadSchemaContext(Constants.KhronosModelLightsPunctualSchemaFile);
  120. ctx.IgnoredByCodeEmitter("glTF Property");
  121. ctx.IgnoredByCodeEmitter("glTF Child of Root Property");
  122. ctx.FindClass("light")
  123. .GetField("color")
  124. .SetDataType(typeof(System.Numerics.Vector3), true)
  125. .SetDefaultValue("Vector3.One")
  126. .SetItemsRange(0);
  127. ProcessSchema("ext.ModelLightsPunctual.g", ctx);
  128. }
  129. private static void _ProcessKhronosNodeLightsPunctualExtension()
  130. {
  131. var ctx = LoadSchemaContext(Constants.KhronosNodeLightsPunctualSchemaFile);
  132. ctx.IgnoredByCodeEmitter("glTF Property");
  133. ctx.IgnoredByCodeEmitter("glTF Child of Root Property");
  134. ProcessSchema("ext.NodeLightsPunctual.g", ctx);
  135. }
  136. private static void _ProcessKhronosTextureTransformExtension()
  137. {
  138. var ctx = LoadSchemaContext(Constants.KhronosTextureTransformSchemaFile);
  139. ctx.IgnoredByCodeEmitter("glTF Property");
  140. ctx.IgnoredByCodeEmitter("glTF Child of Root Property");
  141. var tex = ctx.FindClass("KHR_texture_transform textureInfo extension");
  142. tex.GetField("offset")
  143. .SetDataType(typeof(System.Numerics.Vector2), true)
  144. .SetDefaultValue("Vector2.Zero")
  145. .SetItemsRange(0);
  146. tex.GetField("scale")
  147. .SetDataType(typeof(System.Numerics.Vector2), true)
  148. .SetDefaultValue("Vector2.One")
  149. .SetItemsRange(0);
  150. ProcessSchema("ext.TextureTransform.g", ctx);
  151. }
  152. private static void _ProcessMicrosoftTextureDDSExtension()
  153. {
  154. var ctx = LoadSchemaContext(Constants.MicrosoftTextureDDSSchemaFile);
  155. ctx.IgnoredByCodeEmitter("glTF Property");
  156. ProcessSchema("ext.MSFT.textureDDS.g", ctx);
  157. }
  158. private static void _ProcessTextureWebpExtension()
  159. {
  160. var ctx = LoadSchemaContext(Constants.TextureWebpSchemaFile);
  161. ctx.IgnoredByCodeEmitter("glTF Property");
  162. ProcessSchema("ext.textureWEBP.g", ctx);
  163. }
  164. #endregion
  165. #region code generation
  166. private static string _FindTargetDirectory(string dstDir)
  167. {
  168. var dir = Constants.LocalRepoDirectory;
  169. while(dir.Length > 3)
  170. {
  171. var xdir = System.IO.Path.Combine(dir, dstDir);
  172. if (System.IO.Directory.Exists(xdir)) return xdir;
  173. dir = System.IO.Path.GetDirectoryName(dir); // move up
  174. }
  175. return null;
  176. }
  177. private static void ProcessSchema(string dstFile, SchemaType.Context ctx)
  178. {
  179. var newEmitter = new CSharpEmitter();
  180. newEmitter.DeclareContext(ctx);
  181. newEmitter.SetCollectionContainer("List<TItem>");
  182. const string rootName = "ModelRoot";
  183. newEmitter.SetRuntimeName("glTF", rootName);
  184. newEmitter.SetRuntimeName("glTF Property", "ExtraProperties");
  185. newEmitter.SetRuntimeName("glTF Child of Root Property", "LogicalChildOfRoot");
  186. newEmitter.SetRuntimeName("Sampler", "TextureSampler");
  187. newEmitter.SetRuntimeName("UNSIGNED_BYTE-UNSIGNED_INT-UNSIGNED_SHORT", "IndexEncodingType");
  188. newEmitter.SetRuntimeName("BYTE-FLOAT-SHORT-UNSIGNED_BYTE-UNSIGNED_INT-UNSIGNED_SHORT", "EncodingType");
  189. newEmitter.SetRuntimeName("MAT2-MAT3-MAT4-SCALAR-VEC2-VEC3-VEC4", "DimensionType");
  190. newEmitter.SetRuntimeName("rotation-scale-translation-weights", "PropertyPath");
  191. newEmitter.SetRuntimeName("ARRAY_BUFFER-ELEMENT_ARRAY_BUFFER", "BufferMode");
  192. newEmitter.SetRuntimeName("orthographic-perspective", "CameraType");
  193. newEmitter.SetRuntimeName("BLEND-MASK-OPAQUE", "AlphaMode");
  194. newEmitter.SetRuntimeName("LINE_LOOP-LINE_STRIP-LINES-POINTS-TRIANGLE_FAN-TRIANGLE_STRIP-TRIANGLES", "PrimitiveType");
  195. newEmitter.SetRuntimeName("CUBICSPLINE-LINEAR-STEP", "AnimationInterpolationMode");
  196. newEmitter.SetRuntimeName("LINEAR-NEAREST", "TextureInterpolationFilter");
  197. newEmitter.SetRuntimeName("CLAMP_TO_EDGE-MIRRORED_REPEAT-REPEAT", "TextureWrapMode");
  198. newEmitter.SetRuntimeName("LINEAR-LINEAR_MIPMAP_LINEAR-LINEAR_MIPMAP_NEAREST-NEAREST-NEAREST_MIPMAP_LINEAR-NEAREST_MIPMAP_NEAREST", "TextureMipMapFilter");
  199. newEmitter.SetRuntimeName("KHR_materials_pbrSpecularGlossiness glTF extension", "MaterialPBRSpecularGlossiness");
  200. newEmitter.SetRuntimeName("KHR_materials_unlit glTF extension", "MaterialUnlit");
  201. newEmitter.SetRuntimeName("KHR_materials_clearcoat glTF extension", "MaterialClearCoat");
  202. newEmitter.SetRuntimeName("light", "PunctualLight");
  203. newEmitter.SetRuntimeName("light/spot", "PunctualLightSpot");
  204. newEmitter.SetRuntimeName("KHR_texture_transform textureInfo extension", "TextureTransform");
  205. newEmitter.SetRuntimeName("MSFT_texture_dds extension", "TextureDDS");
  206. newEmitter.SetRuntimeName("EXT_texture_webp glTF extension", "TextureWEBP");
  207. var classes = ctx.Classes.ToArray();
  208. var fields = classes.SelectMany(item => item.Fields).ToArray();
  209. var meshClass = ctx.FindClass("Mesh");
  210. if (meshClass != null)
  211. {
  212. newEmitter.SetCollectionContainer(meshClass.UseField("primitives"), "ChildrenCollection<TItem,Mesh>");
  213. }
  214. var animationClass = ctx.FindClass("Animation");
  215. if (animationClass != null)
  216. {
  217. newEmitter.SetCollectionContainer(animationClass.UseField("channels"), "ChildrenCollection<TItem,Animation>");
  218. newEmitter.SetCollectionContainer(animationClass.UseField("samplers"), "ChildrenCollection<TItem,Animation>");
  219. }
  220. foreach (var f in fields)
  221. {
  222. if (f.FieldType is ArrayType atype)
  223. {
  224. if (atype.ItemType is ClassType ctype)
  225. {
  226. if (ctype.BaseClass != null && ctype.BaseClass.PersistentName == "glTF Child of Root Property")
  227. {
  228. newEmitter.SetCollectionContainer(f, $"ChildrenCollection<TItem,{rootName}>");
  229. }
  230. }
  231. }
  232. }
  233. var textOut = newEmitter.EmitContext(ctx);
  234. var dstDir = _FindTargetDirectory(Constants.TargetProjectDirectory);
  235. var dstPath = System.IO.Path.Combine(dstDir, $"{dstFile}.cs");
  236. System.IO.File.WriteAllText(dstPath, textOut);
  237. }
  238. #endregion
  239. #region schema loader
  240. private static SchemaType.Context LoadSchemaContext(string srcSchema)
  241. {
  242. var schema = LoadSchema(srcSchema);
  243. var settings = new NJsonSchema.CodeGeneration.CSharp.CSharpGeneratorSettings
  244. {
  245. Namespace = "glTf.POCO",
  246. ClassStyle = NJsonSchema.CodeGeneration.CSharp.CSharpClassStyle.Poco
  247. };
  248. var ctypes = new NJsonSchema.CodeGeneration.CSharp.CSharpTypeResolver(settings);
  249. ctypes.Resolve(schema, false, null);
  250. return SchemaTypesReader.Generate(ctypes);
  251. }
  252. static JSONSCHEMA LoadSchema(string filePath)
  253. {
  254. // https://blogs.msdn.microsoft.com/benjaminperkins/2017/03/08/how-to-call-an-async-method-from-a-console-app-main-method/
  255. if (!System.IO.File.Exists(filePath)) throw new System.IO.FileNotFoundException(nameof(filePath), filePath);
  256. return JSONSCHEMA
  257. .FromFileAsync(filePath, s => _Resolver(s,filePath) )
  258. .ConfigureAwait(false)
  259. .GetAwaiter()
  260. .GetResult();
  261. }
  262. static NJsonSchema.JsonReferenceResolver _Resolver(JSONSCHEMA schema, string basePath)
  263. {
  264. var generator = new NJsonSchema.Generation.JsonSchemaGeneratorSettings();
  265. var solver = new NJsonSchema.JsonSchemaAppender(schema, generator.TypeNameGenerator);
  266. return new MyReferenceResolver(solver);
  267. }
  268. class MyReferenceResolver : NJsonSchema.JsonReferenceResolver
  269. {
  270. public MyReferenceResolver(NJsonSchema.JsonSchemaAppender resolver) : base(resolver) { }
  271. public override Task<IJsonReference> ResolveFileReferenceAsync(string filePath)
  272. {
  273. if (System.IO.File.Exists(filePath)) return base.ResolveFileReferenceAsync(filePath);
  274. filePath = System.IO.Path.GetFileName(filePath);
  275. filePath = System.IO.Path.Combine(Constants.MainSchemaDir, filePath);
  276. if (System.IO.File.Exists(filePath)) return base.ResolveFileReferenceAsync(filePath);
  277. throw new System.IO.FileNotFoundException(filePath);
  278. }
  279. }
  280. #endregion
  281. }
  282. }