Program.cs 20 KB

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