Program.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  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. // XMP
  21. _ProcessKhronosXMPExtension();
  22. // material extensions
  23. _ProcessKhronosUnlitExtension();
  24. _ProcessKhronosSheenExtension();
  25. _ProcessKhronosClearCoatExtension();
  26. _ProcessKhronosTransmissionExtension();
  27. _ProcessKhronosSpecularGlossinessExtension();
  28. // lights
  29. _ProcessKhronosLightsPunctualExtension();
  30. // gpu mesh instancing
  31. _ProcessMeshGpuInstancingExtension();
  32. // textures
  33. _ProcessKhronosTextureTransformExtension();
  34. _ProcessMicrosoftTextureDDSExtension();
  35. _ProcessTextureWebpExtension();
  36. _ProcessTextureKtx2Extension();
  37. // these extansions are not fully supported and temporarily removed:
  38. // _ProcessDracoExtension();
  39. // _ProcessMicrosoftLODExtension();
  40. }
  41. #endregion
  42. #region Main Schema code generation
  43. private static void _ProcessMainSchema()
  44. {
  45. // load and process schema
  46. var ctx1 = LoadSchemaContext(Constants.MainSchemaFile);
  47. // Ignore "glTF Property" because it is completely hand coded.
  48. ctx1.IgnoredByCodeEmitter("glTF Property");
  49. // We will mimeType "anyof" as a plain string.
  50. ctx1.Remove("image/jpeg-image/png");
  51. // replace Image.mimeType type from an Enum to String, so we can serialize it with more formats if required
  52. ctx1.FindClass("Image")
  53. .GetField("mimeType")
  54. .FieldType = ctx1.UseString();
  55. // replace Node.Matrix, Node.Rotation, Node.Scale and Node.Translation with System.Numerics.Vectors types
  56. var node = ctx1.FindClass("Node");
  57. node.GetField("matrix").SetDataType(typeof(System.Numerics.Matrix4x4), true).RemoveDefaultValue().SetItemsRange(0);
  58. node.GetField("rotation").SetDataType(typeof(System.Numerics.Quaternion), true).RemoveDefaultValue().SetItemsRange(0);
  59. node.GetField("scale").SetDataType(typeof(System.Numerics.Vector3), true).RemoveDefaultValue().SetItemsRange(0);
  60. node.GetField("translation").SetDataType(typeof(System.Numerics.Vector3), true).RemoveDefaultValue().SetItemsRange(0);
  61. // replace Material.emissiveFactor with System.Numerics.Vectors types
  62. ctx1.FindClass("Material")
  63. .GetField("emissiveFactor")
  64. .SetDataType(typeof(System.Numerics.Vector3), true)
  65. .SetDefaultValue("Vector3.Zero")
  66. .SetItemsRange(0);
  67. // replace Material.baseColorFactor with System.Numerics.Vectors types
  68. ctx1.FindClass("Material PBR Metallic Roughness")
  69. .GetField("baseColorFactor")
  70. .SetDataType(typeof(System.Numerics.Vector4), true)
  71. .SetDefaultValue("Vector4.One")
  72. .SetItemsRange(0);
  73. var tex1 = ctx1.FindEnum("LINEAR-NEAREST");
  74. tex1.SetValue("DEFAULT",0);
  75. var tex2 = ctx1.FindEnum("LINEAR-LINEAR_MIPMAP_LINEAR-LINEAR_MIPMAP_NEAREST-NEAREST-NEAREST_MIPMAP_LINEAR-NEAREST_MIPMAP_NEAREST");
  76. tex2.SetValue("DEFAULT", 0);
  77. ProcessSchema("gltf.g", ctx1);
  78. }
  79. #endregion
  80. #region Extensions code generation
  81. private static void _ProcessKhronosXMPExtension()
  82. {
  83. // Model extension
  84. var ctx = LoadSchemaContext(Constants.KhronosExtensions.XMP_Model);
  85. ctx.IgnoredByCodeEmitter("glTF Property");
  86. ctx.IgnoredByCodeEmitter("glTF Child of Root Property");
  87. /*
  88. var jdict = ctx.UseClass("JsonDictionary");
  89. var jlist = ctx.UseClass("JsonList");
  90. ctx.FindClass("KHR_xmp glTF extension")
  91. .GetField("@context")
  92. .SetDataType(jdict);
  93. ctx.FindClass("KHR_xmp glTF extension")
  94. .GetField("packets")
  95. .SetDataType(jlist);*/
  96. /*
  97. ctx.FindClass("KHR_xmp glTF extension")
  98. .GetField("@context")
  99. .SetDataType(typeof(Dictionary<string,Object>), true);
  100. */
  101. ProcessSchema("ext.XMP.Model.g", ctx);
  102. // Node extension
  103. ctx = LoadSchemaContext(Constants.KhronosExtensions.XMP_Node);
  104. ctx.IgnoredByCodeEmitter("glTF Property");
  105. ctx.IgnoredByCodeEmitter("glTF Child of Root Property");
  106. ProcessSchema("ext.XMP.Node.g", ctx);
  107. }
  108. private static void _ProcessKhronosSpecularGlossinessExtension()
  109. {
  110. var ctx = LoadSchemaContext(Constants.KhronosExtensions.PbrSpecularGlossiness);
  111. ctx.IgnoredByCodeEmitter("glTF Property");
  112. ctx.IgnoredByCodeEmitter("glTF Child of Root Property");
  113. ctx.IgnoredByCodeEmitter("Texture Info");
  114. ctx.FindClass("KHR_materials_pbrSpecularGlossiness glTF extension")
  115. .GetField("diffuseFactor")
  116. .SetDataType(typeof(System.Numerics.Vector4), true)
  117. .SetDefaultValue("Vector4.One")
  118. .SetItemsRange(0);
  119. ctx.FindClass("KHR_materials_pbrSpecularGlossiness glTF extension")
  120. .GetField("specularFactor")
  121. .SetDataType(typeof(System.Numerics.Vector3), true)
  122. .SetDefaultValue("Vector3.One")
  123. .SetItemsRange(0);
  124. ProcessSchema("ext.pbrSpecularGlossiness.g", ctx);
  125. }
  126. private static void _ProcessKhronosUnlitExtension()
  127. {
  128. var ctx = LoadSchemaContext(Constants.KhronosExtensions.Unlit);
  129. ctx.IgnoredByCodeEmitter("glTF Property");
  130. ctx.IgnoredByCodeEmitter("glTF Child of Root Property");
  131. ProcessSchema("ext.Unlit.g", ctx);
  132. }
  133. private static void _ProcessKhronosClearCoatExtension()
  134. {
  135. var ctx = LoadSchemaContext(Constants.KhronosExtensions.PbrClearCoat);
  136. ctx.IgnoredByCodeEmitter("glTF Property");
  137. ctx.IgnoredByCodeEmitter("glTF Child of Root Property");
  138. ctx.IgnoredByCodeEmitter("Texture Info");
  139. ctx.IgnoredByCodeEmitter("Material Normal Texture Info");
  140. ProcessSchema("ext.ClearCoat.g", ctx);
  141. }
  142. private static void _ProcessKhronosTransmissionExtension()
  143. {
  144. var ctx = LoadSchemaContext(Constants.KhronosExtensions.PbrTransmission);
  145. ctx.IgnoredByCodeEmitter("glTF Property");
  146. ctx.IgnoredByCodeEmitter("glTF Child of Root Property");
  147. ctx.IgnoredByCodeEmitter("Texture Info");
  148. ctx.IgnoredByCodeEmitter("Material Normal Texture Info");
  149. ProcessSchema("ext.Transmission.g", ctx);
  150. }
  151. private static void _ProcessKhronosSheenExtension()
  152. {
  153. var ctx = LoadSchemaContext(Constants.KhronosExtensions.PbrSheen);
  154. ctx.IgnoredByCodeEmitter("glTF Property");
  155. ctx.IgnoredByCodeEmitter("glTF Child of Root Property");
  156. ctx.IgnoredByCodeEmitter("Texture Info");
  157. ctx.IgnoredByCodeEmitter("Material Normal Texture Info");
  158. ctx.FindClass("KHR_materials_sheen glTF extension")
  159. .GetField("sheenColorFactor")
  160. .SetDataType(typeof(System.Numerics.Vector3), true)
  161. .SetDefaultValue("Vector3.Zero")
  162. .SetItemsRange(0);
  163. ctx.FindClass("KHR_materials_sheen glTF extension")
  164. .GetField("sheenRoughnessFactor")
  165. .SetDataType(typeof(float), true)
  166. .SetItemsRange(0);
  167. ProcessSchema("ext.Sheen.g", ctx);
  168. }
  169. private static void _ProcessKhronosLightsPunctualExtension()
  170. {
  171. // Model
  172. var ctx = LoadSchemaContext(Constants.KhronosExtensions.LightsPunctual_Model);
  173. ctx.IgnoredByCodeEmitter("glTF Property");
  174. ctx.IgnoredByCodeEmitter("glTF Child of Root Property");
  175. ctx.FindClass("light")
  176. .GetField("color")
  177. .SetDataType(typeof(System.Numerics.Vector3), true)
  178. .SetDefaultValue("Vector3.One")
  179. .SetItemsRange(0);
  180. ProcessSchema("ext.ModelLightsPunctual.g", ctx);
  181. // Node
  182. ctx = LoadSchemaContext(Constants.KhronosExtensions.LightsPunctual_Node);
  183. ctx.IgnoredByCodeEmitter("glTF Property");
  184. ctx.IgnoredByCodeEmitter("glTF Child of Root Property");
  185. ProcessSchema("ext.NodeLightsPunctual.g", ctx);
  186. }
  187. private static void _ProcessKhronosTextureTransformExtension()
  188. {
  189. var ctx = LoadSchemaContext(Constants.KhronosExtensions.TextureTransform);
  190. ctx.IgnoredByCodeEmitter("glTF Property");
  191. ctx.IgnoredByCodeEmitter("glTF Child of Root Property");
  192. var tex = ctx.FindClass("KHR_texture_transform textureInfo extension");
  193. tex.GetField("offset")
  194. .SetDataType(typeof(System.Numerics.Vector2), true)
  195. .SetDefaultValue("Vector2.Zero")
  196. .SetItemsRange(0);
  197. tex.GetField("scale")
  198. .SetDataType(typeof(System.Numerics.Vector2), true)
  199. .SetDefaultValue("Vector2.One")
  200. .SetItemsRange(0);
  201. ProcessSchema("ext.TextureTransform.g", ctx);
  202. }
  203. private static void _ProcessMicrosoftTextureDDSExtension()
  204. {
  205. var ctx = LoadSchemaContext(Constants.VendorExtensions.TextureDDS);
  206. ctx.IgnoredByCodeEmitter("glTF Property");
  207. ProcessSchema("ext.MSFT.TextureDDS.g", ctx);
  208. }
  209. private static void _ProcessTextureWebpExtension()
  210. {
  211. var ctx = LoadSchemaContext(Constants.VendorExtensions.TextureWebp);
  212. ctx.IgnoredByCodeEmitter("glTF Property");
  213. ProcessSchema("ext.TextureWEBP.g", ctx);
  214. }
  215. private static void _ProcessTextureKtx2Extension()
  216. {
  217. var ctx = LoadSchemaContext(Constants.KhronosExtensions.Ktx2);
  218. ctx.IgnoredByCodeEmitter("glTF Property");
  219. ProcessSchema("ext.TextureKTX2.g", ctx);
  220. }
  221. private static void _ProcessMeshGpuInstancingExtension()
  222. {
  223. var ctx = LoadSchemaContext(Constants.VendorExtensions.MeshGpuInstancing);
  224. ctx.IgnoredByCodeEmitter("glTF Property");
  225. ctx.IgnoredByCodeEmitter("glTF Child of Root Property");
  226. ProcessSchema("ext.MeshGpuInstancing.g", ctx);
  227. }
  228. #endregion
  229. #region code generation
  230. private static string _FindTargetDirectory(string dstDir)
  231. {
  232. var dir = Constants.LocalRepoDirectory;
  233. while(dir.Length > 3)
  234. {
  235. var xdir = System.IO.Path.Combine(dir, dstDir);
  236. if (System.IO.Directory.Exists(xdir)) return xdir;
  237. dir = System.IO.Path.GetDirectoryName(dir); // move up
  238. }
  239. return null;
  240. }
  241. private static void ProcessSchema(string dstFile, SchemaType.Context ctx)
  242. {
  243. var newEmitter = new CSharpEmitter();
  244. newEmitter.DeclareContext(ctx);
  245. newEmitter.SetCollectionContainer("List<TItem>");
  246. const string rootName = "ModelRoot";
  247. newEmitter.SetRuntimeName("glTF", rootName);
  248. newEmitter.SetRuntimeName("glTF Property", "ExtraProperties");
  249. newEmitter.SetRuntimeName("glTF Child of Root Property", "LogicalChildOfRoot");
  250. newEmitter.SetRuntimeName("Sampler", "TextureSampler");
  251. newEmitter.SetRuntimeName("UNSIGNED_BYTE-UNSIGNED_INT-UNSIGNED_SHORT", "IndexEncodingType");
  252. newEmitter.SetRuntimeName("BYTE-FLOAT-SHORT-UNSIGNED_BYTE-UNSIGNED_INT-UNSIGNED_SHORT", "EncodingType");
  253. newEmitter.SetRuntimeName("MAT2-MAT3-MAT4-SCALAR-VEC2-VEC3-VEC4", "DimensionType");
  254. newEmitter.SetRuntimeName("rotation-scale-translation-weights", "PropertyPath");
  255. newEmitter.SetRuntimeName("ARRAY_BUFFER-ELEMENT_ARRAY_BUFFER", "BufferMode");
  256. newEmitter.SetRuntimeName("orthographic-perspective", "CameraType");
  257. newEmitter.SetRuntimeName("BLEND-MASK-OPAQUE", "AlphaMode");
  258. newEmitter.SetRuntimeName("LINE_LOOP-LINE_STRIP-LINES-POINTS-TRIANGLE_FAN-TRIANGLE_STRIP-TRIANGLES", "PrimitiveType");
  259. newEmitter.SetRuntimeName("CUBICSPLINE-LINEAR-STEP", "AnimationInterpolationMode");
  260. newEmitter.SetRuntimeName("LINEAR-NEAREST", "TextureInterpolationFilter");
  261. newEmitter.SetRuntimeName("CLAMP_TO_EDGE-MIRRORED_REPEAT-REPEAT", "TextureWrapMode");
  262. newEmitter.SetRuntimeName("LINEAR-LINEAR_MIPMAP_LINEAR-LINEAR_MIPMAP_NEAREST-NEAREST-NEAREST_MIPMAP_LINEAR-NEAREST_MIPMAP_NEAREST", "TextureMipMapFilter");
  263. newEmitter.SetRuntimeName("KHR_materials_pbrSpecularGlossiness glTF extension", "MaterialPBRSpecularGlossiness");
  264. newEmitter.SetRuntimeName("KHR_materials_unlit glTF extension", "MaterialUnlit");
  265. newEmitter.SetRuntimeName("KHR_materials_clearcoat glTF extension", "MaterialClearCoat");
  266. newEmitter.SetRuntimeName("KHR_materials_transmission glTF extension", "MaterialTransmission");
  267. newEmitter.SetRuntimeName("KHR_materials_sheen glTF extension", "MaterialSheen");
  268. newEmitter.SetRuntimeName("KHR_xmp glTF extension", "XMPPacketsCollection");
  269. newEmitter.SetRuntimeName("KHR_xmp node extension", "XMPPacketReference");
  270. newEmitter.SetRuntimeName("light", "PunctualLight");
  271. newEmitter.SetRuntimeName("light/spot", "PunctualLightSpot");
  272. newEmitter.SetRuntimeName("KHR_lights_punctual glTF extension", "_ModelPunctualLights");
  273. newEmitter.SetRuntimeName("KHR_lights_punctual node extension", "_NodePunctualLight");
  274. newEmitter.SetRuntimeName("KHR_texture_transform textureInfo extension", "TextureTransform");
  275. newEmitter.SetRuntimeName("MSFT_texture_dds extension", "TextureDDS");
  276. newEmitter.SetRuntimeName("EXT_texture_webp glTF extension", "TextureWEBP");
  277. newEmitter.SetRuntimeName("KHR_texture_basisu glTF extension", "TextureKTX2");
  278. newEmitter.SetRuntimeName("EXT_mesh_gpu_instancing glTF extension", "MeshGpuInstancing");
  279. var classes = ctx.Classes.ToArray();
  280. var fields = classes.SelectMany(item => item.Fields).ToArray();
  281. var meshClass = ctx.FindClass("Mesh");
  282. if (meshClass != null)
  283. {
  284. newEmitter.SetCollectionContainer(meshClass.UseField("primitives"), "ChildrenCollection<TItem,Mesh>");
  285. }
  286. var animationClass = ctx.FindClass("Animation");
  287. if (animationClass != null)
  288. {
  289. newEmitter.SetCollectionContainer(animationClass.UseField("channels"), "ChildrenCollection<TItem,Animation>");
  290. newEmitter.SetCollectionContainer(animationClass.UseField("samplers"), "ChildrenCollection<TItem,Animation>");
  291. }
  292. foreach (var f in fields)
  293. {
  294. if (f.FieldType is ArrayType atype)
  295. {
  296. if (atype.ItemType is ClassType ctype)
  297. {
  298. if (ctype.BaseClass != null && ctype.BaseClass.PersistentName == "glTF Child of Root Property")
  299. {
  300. newEmitter.SetCollectionContainer(f, $"ChildrenCollection<TItem,{rootName}>");
  301. }
  302. }
  303. }
  304. }
  305. var textOut = newEmitter.EmitContext(ctx);
  306. var dstDir = _FindTargetDirectory(Constants.TargetProjectDirectory);
  307. var dstPath = System.IO.Path.Combine(dstDir, $"{dstFile}.cs");
  308. System.IO.File.WriteAllText(dstPath, textOut);
  309. }
  310. #endregion
  311. #region schema loader
  312. private static SchemaType.Context LoadSchemaContext(string srcSchema)
  313. {
  314. var schema = LoadSchema(srcSchema);
  315. var settings = new NJsonSchema.CodeGeneration.CSharp.CSharpGeneratorSettings
  316. {
  317. Namespace = "glTf.POCO",
  318. ClassStyle = NJsonSchema.CodeGeneration.CSharp.CSharpClassStyle.Poco
  319. };
  320. var ctypes = new NJsonSchema.CodeGeneration.CSharp.CSharpTypeResolver(settings);
  321. ctypes.Resolve(schema, false, null);
  322. return SchemaTypesReader.Generate(ctypes);
  323. }
  324. static JSONSCHEMA LoadSchema(string filePath)
  325. {
  326. // https://blogs.msdn.microsoft.com/benjaminperkins/2017/03/08/how-to-call-an-async-method-from-a-console-app-main-method/
  327. if (!System.IO.File.Exists(filePath)) throw new System.IO.FileNotFoundException(nameof(filePath), filePath);
  328. return JSONSCHEMA
  329. .FromFileAsync(filePath, s => _Resolver(s,filePath) )
  330. .ConfigureAwait(false)
  331. .GetAwaiter()
  332. .GetResult();
  333. }
  334. static NJsonSchema.JsonReferenceResolver _Resolver(JSONSCHEMA schema, string basePath)
  335. {
  336. var generator = new NJsonSchema.Generation.JsonSchemaGeneratorSettings();
  337. var solver = new NJsonSchema.JsonSchemaAppender(schema, generator.TypeNameGenerator);
  338. return new MyReferenceResolver(solver);
  339. }
  340. class MyReferenceResolver : NJsonSchema.JsonReferenceResolver
  341. {
  342. public MyReferenceResolver(NJsonSchema.JsonSchemaAppender resolver) : base(resolver) { }
  343. public override Task<IJsonReference> ResolveFileReferenceAsync(string filePath, System.Threading.CancellationToken cancellationToken)
  344. {
  345. if (System.IO.File.Exists(filePath)) return base.ResolveFileReferenceAsync(filePath);
  346. filePath = System.IO.Path.GetFileName(filePath);
  347. filePath = System.IO.Path.Combine(Constants.MainSchemaDir, filePath);
  348. if (System.IO.File.Exists(filePath)) return base.ResolveFileReferenceAsync(filePath);
  349. throw new System.IO.FileNotFoundException(filePath);
  350. }
  351. }
  352. #endregion
  353. }
  354. }