_Extensions.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Numerics;
  5. using System.Linq;
  6. using SharpGLTF.Schema2;
  7. namespace SharpGLTF
  8. {
  9. /// <summary>
  10. /// Extensions used internally.
  11. /// </summary>
  12. static class _Extensions
  13. {
  14. #region constants
  15. // constants from: https://github.com/KhronosGroup/glTF-Validator/blob/master/lib/src/errors.dart
  16. private const float _UnitLengthThresholdVec3 = 0.00674f;
  17. private const float _UnitLengthThresholdVec4 = 0.00769f;
  18. // This value is slightly greater
  19. // than the maximum error from unsigned 8-bit quantization
  20. // 1..2 elements - 0 * step
  21. // 3..4 elements - 1 * step
  22. // 5..6 elements - 2 * step
  23. // ...
  24. private const float _UnitSumThresholdStep = 0.0039216f;
  25. #endregion
  26. #region private numerics extensions
  27. internal static bool IsMultipleOf(this int value, int mult)
  28. {
  29. return (value % mult) == 0;
  30. }
  31. internal static int WordPadded(this int length)
  32. {
  33. var padding = length & 3;
  34. return length + (padding == 0 ? 0 : 4 - padding);
  35. }
  36. internal static bool _IsFinite(this float value)
  37. {
  38. return !(float.IsNaN(value) || float.IsInfinity(value));
  39. }
  40. internal static bool _IsFinite(this Vector2 v)
  41. {
  42. return v.X._IsFinite() && v.Y._IsFinite();
  43. }
  44. internal static bool _IsFinite(this Vector3 v)
  45. {
  46. return v.X._IsFinite() && v.Y._IsFinite() && v.Z._IsFinite();
  47. }
  48. internal static bool _IsFinite(this Vector4 v)
  49. {
  50. return v.X._IsFinite() && v.Y._IsFinite() && v.Z._IsFinite() && v.W._IsFinite();
  51. }
  52. internal static bool _IsFinite(this Matrix4x4 v)
  53. {
  54. if (!(v.M11._IsFinite() && v.M12._IsFinite() && v.M13._IsFinite() && v.M14._IsFinite())) return false;
  55. if (!(v.M21._IsFinite() && v.M22._IsFinite() && v.M23._IsFinite() && v.M24._IsFinite())) return false;
  56. if (!(v.M31._IsFinite() && v.M32._IsFinite() && v.M33._IsFinite() && v.M34._IsFinite())) return false;
  57. if (!(v.M41._IsFinite() && v.M42._IsFinite() && v.M43._IsFinite() && v.M44._IsFinite())) return false;
  58. return true;
  59. }
  60. internal static bool _IsFinite(this Quaternion v)
  61. {
  62. return v.X._IsFinite() && v.Y._IsFinite() && v.Z._IsFinite() && v.W._IsFinite();
  63. }
  64. internal static Vector3 WithLength(this Vector3 v, float len)
  65. {
  66. return Vector3.Normalize(v) * len;
  67. }
  68. internal static Boolean IsNormalized(this Vector3 normal)
  69. {
  70. if (!normal._IsFinite()) return false;
  71. return Math.Abs(normal.Length() - 1) <= _UnitLengthThresholdVec3;
  72. }
  73. internal static Boolean IsNormalized(this Quaternion rotation)
  74. {
  75. if (!rotation._IsFinite()) return false;
  76. return Math.Abs(rotation.Length() - 1) <= _UnitLengthThresholdVec4;
  77. }
  78. internal static Quaternion AsQuaternion(this Vector4 v)
  79. {
  80. return new Quaternion(v.X, v.Y, v.Z, v.W);
  81. }
  82. internal static Quaternion Sanitized(this Quaternion q)
  83. {
  84. return q.IsNormalized() ? q : Quaternion.Normalize(q);
  85. }
  86. internal static bool IsInRange(this Vector3 value, Vector3 min, Vector3 max)
  87. {
  88. if (value.X < min.X || value.X > max.X) return false;
  89. if (value.Y < min.Y || value.Y > max.Y) return false;
  90. if (value.Z < min.Z || value.Z > max.Z) return false;
  91. return true;
  92. }
  93. internal static bool IsInRange(this Vector4 value, Vector4 min, Vector4 max)
  94. {
  95. if (value.X < min.X || value.X > max.X) return false;
  96. if (value.Y < min.Y || value.Y > max.Y) return false;
  97. if (value.Z < min.Z || value.Z > max.Z) return false;
  98. if (value.W < min.W || value.W > max.W) return false;
  99. return true;
  100. }
  101. internal static bool IsRound(this Vector4 value)
  102. {
  103. var r = new Vector4((int)value.X, (int)value.Y, (int)value.Z, (int)value.W);
  104. return (value - r) == Vector4.Zero;
  105. }
  106. /*
  107. internal static void Validate(this Vector3 vector, string msg)
  108. {
  109. if (!vector._IsFinite()) throw new NotFiniteNumberException($"{msg} is invalid.");
  110. }*/
  111. internal static void ValidateNormal(this Vector3 normal, string msg)
  112. {
  113. if (!normal._IsFinite()) throw new NotFiniteNumberException($"{msg} is invalid.");
  114. if (!normal.IsNormalized()) throw new ArithmeticException($"{msg} is not unit length.");
  115. }
  116. internal static void ValidateTangent(this Vector4 tangent, string msg)
  117. {
  118. if (tangent.W != 1 && tangent.W != -1) throw new ArithmeticException(msg);
  119. new Vector3(tangent.X, tangent.Y, tangent.Z).ValidateNormal(msg);
  120. }
  121. internal static Vector3 SanitizeNormal(this Vector3 normal)
  122. {
  123. return normal.IsNormalized() ? normal : Vector3.Normalize(normal);
  124. }
  125. internal static bool IsValidTangent(this Vector4 tangent)
  126. {
  127. if (tangent.W != 1 && tangent.W != -1) return false;
  128. return new Vector3(tangent.X, tangent.Y, tangent.Z).IsNormalized();
  129. }
  130. internal static Vector4 SanitizeTangent(this Vector4 tangent)
  131. {
  132. var n = new Vector3(tangent.X, tangent.Y, tangent.Z).SanitizeNormal();
  133. var s = float.IsNaN(tangent.W) ? 1 : tangent.W;
  134. return new Vector4(n, s > 0 ? 1 : -1);
  135. }
  136. internal static Matrix4x4 Inverse(this Matrix4x4 src)
  137. {
  138. if (!Matrix4x4.Invert(src, out Matrix4x4 dst)) Guard.IsTrue(false, nameof(src), "Matrix cannot be inverted.");
  139. return dst;
  140. }
  141. internal static bool IsValid(this in Matrix4x4 matrix)
  142. {
  143. if (!matrix._IsFinite()) return false;
  144. if (!Matrix4x4.Decompose(matrix, out Vector3 s, out Quaternion r, out Vector3 t)) return false;
  145. if (!Matrix4x4.Invert(matrix, out Matrix4x4 inverse)) return false;
  146. return true;
  147. }
  148. #endregion
  149. #region linq
  150. internal static int GetContentHashCode<T>(this IEnumerable<T> collection, int count = int.MaxValue)
  151. {
  152. if (collection == null) return 0;
  153. int h = 0;
  154. // this will handle default(ArraySegment<T>)
  155. if (collection is IReadOnlyList<T> list)
  156. {
  157. count = Math.Min(count, list.Count);
  158. for (int i = 0; i < count; ++i)
  159. {
  160. var element = list[i];
  161. h ^= element == null ? 0 : element.GetHashCode();
  162. h *= 17;
  163. }
  164. return h;
  165. }
  166. foreach (var element in collection.Take(count))
  167. {
  168. h ^= element == null ? 0 : element.GetHashCode();
  169. h *= 17;
  170. }
  171. return h;
  172. }
  173. internal static ArraySegment<T> Slice<T>(this T[] array, int offset)
  174. {
  175. return new ArraySegment<T>(array, offset, array.Length - offset);
  176. }
  177. internal static ArraySegment<T> Slice<T>(this ArraySegment<T> array, int offset)
  178. {
  179. return new ArraySegment<T>(array.Array, array.Offset + offset, array.Count - offset);
  180. }
  181. internal static ArraySegment<T> Slice<T>(this ArraySegment<T> array, int offset, int count)
  182. {
  183. return new ArraySegment<T>(array.Array, array.Offset + offset, count);
  184. }
  185. internal static T[] CloneArray<T>(this T[] srcArray)
  186. {
  187. if (srcArray == null) return null;
  188. var dstArray = new T[srcArray.Length];
  189. srcArray.CopyTo(dstArray, 0);
  190. return dstArray;
  191. }
  192. internal static void Fill<T>(this IList<T> collection, T value)
  193. {
  194. for (int i = 0; i < collection.Count; ++i)
  195. {
  196. collection[i] = value;
  197. }
  198. }
  199. internal static void Fill<T>(this T[] array, T value)
  200. {
  201. for (int i = 0; i < array.Length; ++i)
  202. {
  203. array[i] = value;
  204. }
  205. }
  206. internal static int IndexOf<T>(this IReadOnlyList<T> collection, T value)
  207. {
  208. var l = collection.Count;
  209. for (int i = 0; i < l; ++i)
  210. {
  211. if (Object.Equals(collection[i], value)) return i;
  212. }
  213. return -1;
  214. }
  215. internal static int IndexOf<T>(this IReadOnlyList<T> collection, Predicate<T> predicate)
  216. {
  217. var l = collection.Count;
  218. for (int i = 0; i < l; ++i)
  219. {
  220. if (predicate(collection[i])) return i;
  221. }
  222. return -1;
  223. }
  224. internal static int IndexOfReference<T>(this IReadOnlyList<T> collection, T value)
  225. where T : class
  226. {
  227. var l = collection.Count;
  228. for (int i = 0; i < l; ++i)
  229. {
  230. if (Object.ReferenceEquals(collection[i], value)) return i;
  231. }
  232. return -1;
  233. }
  234. internal static int IndexOf<T>(this IReadOnlyList<T> collection, T[] subset)
  235. where T : IEquatable<T>
  236. {
  237. var l = collection.Count - subset.Length;
  238. for (int i = 0; i < l; ++i)
  239. {
  240. bool r = false;
  241. for (int j = 0; j < subset.Length; ++j)
  242. {
  243. if (!collection[i + j].Equals(subset[j])) break;
  244. r = true;
  245. }
  246. if (r) return i;
  247. }
  248. return -1;
  249. }
  250. internal static void CopyTo<T>(this T[] src, int srcOffset, IList<T> dst, int dstOffset, int count)
  251. {
  252. var srcArray = new ArraySegment<T>(src);
  253. srcArray.CopyTo(srcOffset, dst, dstOffset, count);
  254. }
  255. internal static void CopyTo<T>(this ArraySegment<T> src, int srcOffset, IList<T> dst, int dstOffset, int count)
  256. {
  257. if (dst is T[] dstArray)
  258. {
  259. Array.Copy(src.Array, src.Offset + srcOffset, dstArray, dstOffset, count);
  260. return;
  261. }
  262. for (int i = 0; i < count; ++i)
  263. {
  264. dst[dstOffset + i] = src.Array[src.Offset + srcOffset + i];
  265. }
  266. }
  267. internal static void AddRange<Tin, Tout>(this IList<Tout> dst, IEnumerable<Tin> src, Converter<Tin, Tout> cvt)
  268. {
  269. foreach (var item in src)
  270. {
  271. dst.Add(cvt(item));
  272. }
  273. }
  274. internal static IEnumerable<T> ConcatItems<T>(this IEnumerable<T> collection, params T[] instances)
  275. {
  276. return collection.Concat(instances.Where(item => item != null));
  277. }
  278. public static void SanitizeNormals(this IList<Vector3> normals)
  279. {
  280. for (int i = 0; i < normals.Count; ++i)
  281. {
  282. if (!normals[i].IsNormalized()) normals[i] = normals[i].SanitizeNormal();
  283. }
  284. }
  285. public static void SanitizeTangents(this IList<Vector4> tangents)
  286. {
  287. for (int i = 0; i < tangents.Count; ++i)
  288. {
  289. if (!tangents[i].IsValidTangent()) tangents[i] = tangents[i].SanitizeTangent();
  290. }
  291. }
  292. #endregion
  293. #region vertex & index accessors
  294. public static String ToDebugString(this EncodingType encoding, DimensionType dimensions, bool normalized)
  295. {
  296. var txt = string.Empty;
  297. switch (encoding)
  298. {
  299. case EncodingType.BYTE: txt += "SByte"; break;
  300. case EncodingType.FLOAT: txt += "Float"; break;
  301. case EncodingType.SHORT: txt += "SShort"; break;
  302. case EncodingType.UNSIGNED_BYTE: txt += "UByte"; break;
  303. case EncodingType.UNSIGNED_INT: txt += "UInt"; break;
  304. case EncodingType.UNSIGNED_SHORT: txt += "UShort"; break;
  305. }
  306. switch (dimensions)
  307. {
  308. case DimensionType.SCALAR: break;
  309. case DimensionType.VEC2: txt += "2"; break;
  310. case DimensionType.VEC3: txt += "3"; break;
  311. case DimensionType.VEC4: txt += "4"; break;
  312. case DimensionType.MAT2: txt += "2x2"; break;
  313. case DimensionType.MAT3: txt += "3x3"; break;
  314. case DimensionType.MAT4: txt += "4x4"; break;
  315. }
  316. if (normalized) txt = "Norm" + txt;
  317. return txt;
  318. }
  319. public static int ByteLength(this IndexEncodingType encoding)
  320. {
  321. switch (encoding)
  322. {
  323. case IndexEncodingType.UNSIGNED_BYTE: return 1;
  324. case IndexEncodingType.UNSIGNED_SHORT: return 2;
  325. case IndexEncodingType.UNSIGNED_INT: return 4;
  326. default: throw new NotImplementedException();
  327. }
  328. }
  329. public static int ByteLength(this EncodingType encoding)
  330. {
  331. switch (encoding)
  332. {
  333. case EncodingType.BYTE: return 1;
  334. case EncodingType.SHORT: return 2;
  335. case EncodingType.FLOAT: return 4;
  336. case EncodingType.UNSIGNED_BYTE: return 1;
  337. case EncodingType.UNSIGNED_SHORT: return 2;
  338. case EncodingType.UNSIGNED_INT: return 4;
  339. default: throw new NotImplementedException();
  340. }
  341. }
  342. public static EncodingType ToComponent(this IndexEncodingType t)
  343. {
  344. switch (t)
  345. {
  346. case IndexEncodingType.UNSIGNED_BYTE: return EncodingType.UNSIGNED_BYTE;
  347. case IndexEncodingType.UNSIGNED_SHORT: return EncodingType.UNSIGNED_SHORT;
  348. case IndexEncodingType.UNSIGNED_INT: return EncodingType.UNSIGNED_INT;
  349. default: throw new NotImplementedException();
  350. }
  351. }
  352. public static IndexEncodingType ToIndex(this EncodingType t)
  353. {
  354. switch (t)
  355. {
  356. case EncodingType.UNSIGNED_BYTE: return IndexEncodingType.UNSIGNED_BYTE;
  357. case EncodingType.UNSIGNED_SHORT: return IndexEncodingType.UNSIGNED_SHORT;
  358. case EncodingType.UNSIGNED_INT: return IndexEncodingType.UNSIGNED_INT;
  359. default: throw new NotImplementedException();
  360. }
  361. }
  362. public static int DimCount(this DimensionType dimension)
  363. {
  364. switch (dimension)
  365. {
  366. case DimensionType.SCALAR: return 1;
  367. case DimensionType.VEC2: return 2;
  368. case DimensionType.VEC3: return 3;
  369. case DimensionType.VEC4: return 4;
  370. case DimensionType.MAT2: return 4;
  371. case DimensionType.MAT3: return 9;
  372. case DimensionType.MAT4: return 16;
  373. default: throw new NotImplementedException();
  374. }
  375. }
  376. internal static DimensionType ToDimension(this int l)
  377. {
  378. switch (l)
  379. {
  380. case 1: return DimensionType.SCALAR;
  381. case 2: return DimensionType.VEC2;
  382. case 3: return DimensionType.VEC3;
  383. case 4: return DimensionType.VEC4;
  384. // case 4: return ElementType.MAT2;
  385. case 9: return DimensionType.MAT3;
  386. case 16: return DimensionType.MAT4;
  387. default: throw new NotImplementedException();
  388. }
  389. }
  390. public static int GetPrimitiveVertexSize(this PrimitiveType ptype)
  391. {
  392. switch (ptype)
  393. {
  394. case PrimitiveType.POINTS: return 1;
  395. case PrimitiveType.LINES: return 2;
  396. case PrimitiveType.LINE_LOOP: return 2;
  397. case PrimitiveType.LINE_STRIP: return 2;
  398. case PrimitiveType.TRIANGLES: return 3;
  399. case PrimitiveType.TRIANGLE_FAN: return 3;
  400. case PrimitiveType.TRIANGLE_STRIP: return 3;
  401. default: throw new NotImplementedException();
  402. }
  403. }
  404. public static IEnumerable<(int A, int B)> GetLinesIndices(this PrimitiveType ptype, int vertexCount)
  405. {
  406. return ptype.GetLinesIndices(Enumerable.Range(0, vertexCount).Select(item => (UInt32)item));
  407. }
  408. public static IEnumerable<(int A, int B, int C)> GetTrianglesIndices(this PrimitiveType ptype, int vertexCount)
  409. {
  410. return ptype.GetTrianglesIndices(Enumerable.Range(0, vertexCount).Select(item => (UInt32)item));
  411. }
  412. public static IEnumerable<(int A, int B)> GetLinesIndices(this PrimitiveType ptype, IEnumerable<UInt32> sourceIndices)
  413. {
  414. switch (ptype)
  415. {
  416. case PrimitiveType.LINES:
  417. {
  418. using (var ptr = sourceIndices.GetEnumerator())
  419. {
  420. while (true)
  421. {
  422. if (!ptr.MoveNext()) break;
  423. var a = ptr.Current;
  424. if (!ptr.MoveNext()) break;
  425. var b = ptr.Current;
  426. if (!_IsDegenerated(a, b)) yield return ((int)a, (int)b);
  427. }
  428. }
  429. break;
  430. }
  431. default: throw new NotImplementedException();
  432. }
  433. }
  434. public static IEnumerable<(int A, int B, int C)> GetTrianglesIndices(this PrimitiveType ptype, IEnumerable<UInt32> sourceIndices)
  435. {
  436. switch (ptype)
  437. {
  438. case PrimitiveType.TRIANGLES:
  439. {
  440. using (var ptr = sourceIndices.GetEnumerator())
  441. {
  442. while (true)
  443. {
  444. if (!ptr.MoveNext()) break;
  445. var a = ptr.Current;
  446. if (!ptr.MoveNext()) break;
  447. var b = ptr.Current;
  448. if (!ptr.MoveNext()) break;
  449. var c = ptr.Current;
  450. if (!_IsDegenerated(a, b, c)) yield return ((int)a, (int)b, (int)c);
  451. }
  452. }
  453. break;
  454. }
  455. case PrimitiveType.TRIANGLE_FAN:
  456. {
  457. using (var ptr = sourceIndices.GetEnumerator())
  458. {
  459. if (!ptr.MoveNext()) break;
  460. var a = ptr.Current;
  461. if (!ptr.MoveNext()) break;
  462. var b = ptr.Current;
  463. while (true)
  464. {
  465. if (!ptr.MoveNext()) break;
  466. var c = ptr.Current;
  467. if (!_IsDegenerated(a, b, c)) yield return ((int)a, (int)b, (int)c);
  468. b = c;
  469. }
  470. }
  471. break;
  472. }
  473. case PrimitiveType.TRIANGLE_STRIP:
  474. {
  475. using (var ptr = sourceIndices.GetEnumerator())
  476. {
  477. if (!ptr.MoveNext()) break;
  478. var a = ptr.Current;
  479. if (!ptr.MoveNext()) break;
  480. var b = ptr.Current;
  481. bool reversed = false;
  482. while (true)
  483. {
  484. if (!ptr.MoveNext()) break;
  485. var c = ptr.Current;
  486. if (!_IsDegenerated(a, b, c))
  487. {
  488. if (reversed) yield return ((int)b, (int)a, (int)c);
  489. else yield return ((int)a, (int)b, (int)c);
  490. }
  491. a = b;
  492. b = c;
  493. reversed = !reversed;
  494. }
  495. }
  496. break;
  497. }
  498. default: throw new NotImplementedException();
  499. }
  500. }
  501. private static bool _IsDegenerated(uint a, uint b)
  502. {
  503. return a == b;
  504. }
  505. private static bool _IsDegenerated(uint a, uint b, uint c)
  506. {
  507. if (a == b) return true;
  508. if (a == c) return true;
  509. if (b == c) return true;
  510. return false;
  511. }
  512. #endregion
  513. #region serialization
  514. public static Byte[] ToUnderlayingArray(this ArraySegment<Byte> segment)
  515. {
  516. if (segment.Offset == 0 && segment.Count == segment.Array.Length) return segment.Array;
  517. return segment.ToArray();
  518. }
  519. public static ArraySegment<Byte> ToArraySegment(this System.IO.MemoryStream m)
  520. {
  521. if (m.TryGetBuffer(out ArraySegment<Byte> data)) return data;
  522. return new ArraySegment<byte>(m.ToArray());
  523. }
  524. public static Byte[] GetPaddedContent(this Byte[] content)
  525. {
  526. if (content == null) return null;
  527. if (content.Length.IsMultipleOf(4)) return content;
  528. var rest = content.Length % 4;
  529. rest = rest == 0 ? 0 : 4 - rest;
  530. var paddedContent = new Byte[content.Length + rest];
  531. content.CopyTo(paddedContent, 0);
  532. return paddedContent;
  533. }
  534. public static Byte[] TryParseBase64Unchecked(this string uri, params string[] prefixes)
  535. {
  536. if (uri == null) return null;
  537. if (!uri.StartsWith("data:", StringComparison.OrdinalIgnoreCase)) return null;
  538. foreach (var prefix in prefixes)
  539. {
  540. var data = _TryParseBase64Unchecked(uri, prefix);
  541. if (data != null) return data;
  542. }
  543. return null;
  544. }
  545. private static Byte[] _TryParseBase64Unchecked(string uri, string prefix)
  546. {
  547. if (!uri.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) return null;
  548. var content = uri.Substring(prefix.Length);
  549. if (content.StartsWith(";base64,", StringComparison.OrdinalIgnoreCase))
  550. {
  551. content = content.Substring(";base64,".Length);
  552. return Convert.FromBase64String(content);
  553. }
  554. if (content.StartsWith(",", StringComparison.OrdinalIgnoreCase))
  555. {
  556. content = content.Substring(",".Length);
  557. if (content.Length == 1) return new Byte[] { Byte.Parse(content, System.Globalization.NumberStyles.HexNumber, System.Globalization.CultureInfo.InvariantCulture) };
  558. throw new NotImplementedException();
  559. }
  560. throw new NotImplementedException();
  561. }
  562. #endregion
  563. }
  564. }