Program.cs 17 KB

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