meshoptimizer.h 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090
  1. /**
  2. * meshoptimizer - version 0.21
  3. *
  4. * Copyright (C) 2016-2024, by Arseny Kapoulkine ([email protected])
  5. * Report bugs and download new versions at https://github.com/zeux/meshoptimizer
  6. *
  7. * This library is distributed under the MIT License. See notice at the end of this file.
  8. */
  9. #pragma once
  10. #include <assert.h>
  11. #include <stddef.h>
  12. /* Version macro; major * 1000 + minor * 10 + patch */
  13. #define MESHOPTIMIZER_VERSION 210 /* 0.21 */
  14. /* If no API is defined, assume default */
  15. #ifndef MESHOPTIMIZER_API
  16. #define MESHOPTIMIZER_API
  17. #endif
  18. /* Set the calling-convention for alloc/dealloc function pointers */
  19. #ifndef MESHOPTIMIZER_ALLOC_CALLCONV
  20. #ifdef _MSC_VER
  21. #define MESHOPTIMIZER_ALLOC_CALLCONV __cdecl
  22. #else
  23. #define MESHOPTIMIZER_ALLOC_CALLCONV
  24. #endif
  25. #endif
  26. /* Experimental APIs have unstable interface and might have implementation that's not fully tested or optimized */
  27. #define MESHOPTIMIZER_EXPERIMENTAL MESHOPTIMIZER_API
  28. /* C interface */
  29. #ifdef __cplusplus
  30. extern "C" {
  31. #endif
  32. /**
  33. * Vertex attribute stream
  34. * Each element takes size bytes, beginning at data, with stride controlling the spacing between successive elements (stride >= size).
  35. */
  36. struct meshopt_Stream
  37. {
  38. const void* data;
  39. size_t size;
  40. size_t stride;
  41. };
  42. /**
  43. * Generates a vertex remap table from the vertex buffer and an optional index buffer and returns number of unique vertices
  44. * As a result, all vertices that are binary equivalent map to the same (new) location, with no gaps in the resulting sequence.
  45. * Resulting remap table maps old vertices to new vertices and can be used in meshopt_remapVertexBuffer/meshopt_remapIndexBuffer.
  46. * Note that binary equivalence considers all vertex_size bytes, including padding which should be zero-initialized.
  47. *
  48. * destination must contain enough space for the resulting remap table (vertex_count elements)
  49. * indices can be NULL if the input is unindexed
  50. */
  51. MESHOPTIMIZER_API size_t meshopt_generateVertexRemap(unsigned int* destination, const unsigned int* indices, size_t index_count, const void* vertices, size_t vertex_count, size_t vertex_size);
  52. /**
  53. * Generates a vertex remap table from multiple vertex streams and an optional index buffer and returns number of unique vertices
  54. * As a result, all vertices that are binary equivalent map to the same (new) location, with no gaps in the resulting sequence.
  55. * Resulting remap table maps old vertices to new vertices and can be used in meshopt_remapVertexBuffer/meshopt_remapIndexBuffer.
  56. * To remap vertex buffers, you will need to call meshopt_remapVertexBuffer for each vertex stream.
  57. * Note that binary equivalence considers all size bytes in each stream, including padding which should be zero-initialized.
  58. *
  59. * destination must contain enough space for the resulting remap table (vertex_count elements)
  60. * indices can be NULL if the input is unindexed
  61. * stream_count must be <= 16
  62. */
  63. MESHOPTIMIZER_API size_t meshopt_generateVertexRemapMulti(unsigned int* destination, const unsigned int* indices, size_t index_count, size_t vertex_count, const struct meshopt_Stream* streams, size_t stream_count);
  64. /**
  65. * Generates vertex buffer from the source vertex buffer and remap table generated by meshopt_generateVertexRemap
  66. *
  67. * destination must contain enough space for the resulting vertex buffer (unique_vertex_count elements, returned by meshopt_generateVertexRemap)
  68. * vertex_count should be the initial vertex count and not the value returned by meshopt_generateVertexRemap
  69. */
  70. MESHOPTIMIZER_API void meshopt_remapVertexBuffer(void* destination, const void* vertices, size_t vertex_count, size_t vertex_size, const unsigned int* remap);
  71. /**
  72. * Generate index buffer from the source index buffer and remap table generated by meshopt_generateVertexRemap
  73. *
  74. * destination must contain enough space for the resulting index buffer (index_count elements)
  75. * indices can be NULL if the input is unindexed
  76. */
  77. MESHOPTIMIZER_API void meshopt_remapIndexBuffer(unsigned int* destination, const unsigned int* indices, size_t index_count, const unsigned int* remap);
  78. /**
  79. * Generate index buffer that can be used for more efficient rendering when only a subset of the vertex attributes is necessary
  80. * All vertices that are binary equivalent (wrt first vertex_size bytes) map to the first vertex in the original vertex buffer.
  81. * This makes it possible to use the index buffer for Z pre-pass or shadowmap rendering, while using the original index buffer for regular rendering.
  82. * Note that binary equivalence considers all vertex_size bytes, including padding which should be zero-initialized.
  83. *
  84. * destination must contain enough space for the resulting index buffer (index_count elements)
  85. */
  86. MESHOPTIMIZER_API void meshopt_generateShadowIndexBuffer(unsigned int* destination, const unsigned int* indices, size_t index_count, const void* vertices, size_t vertex_count, size_t vertex_size, size_t vertex_stride);
  87. /**
  88. * Generate index buffer that can be used for more efficient rendering when only a subset of the vertex attributes is necessary
  89. * All vertices that are binary equivalent (wrt specified streams) map to the first vertex in the original vertex buffer.
  90. * This makes it possible to use the index buffer for Z pre-pass or shadowmap rendering, while using the original index buffer for regular rendering.
  91. * Note that binary equivalence considers all size bytes in each stream, including padding which should be zero-initialized.
  92. *
  93. * destination must contain enough space for the resulting index buffer (index_count elements)
  94. * stream_count must be <= 16
  95. */
  96. MESHOPTIMIZER_API void meshopt_generateShadowIndexBufferMulti(unsigned int* destination, const unsigned int* indices, size_t index_count, size_t vertex_count, const struct meshopt_Stream* streams, size_t stream_count);
  97. /**
  98. * Generate index buffer that can be used as a geometry shader input with triangle adjacency topology
  99. * Each triangle is converted into a 6-vertex patch with the following layout:
  100. * - 0, 2, 4: original triangle vertices
  101. * - 1, 3, 5: vertices adjacent to edges 02, 24 and 40
  102. * The resulting patch can be rendered with geometry shaders using e.g. VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST_WITH_ADJACENCY.
  103. * This can be used to implement algorithms like silhouette detection/expansion and other forms of GS-driven rendering.
  104. *
  105. * destination must contain enough space for the resulting index buffer (index_count*2 elements)
  106. * vertex_positions should have float3 position in the first 12 bytes of each vertex
  107. */
  108. MESHOPTIMIZER_API void meshopt_generateAdjacencyIndexBuffer(unsigned int* destination, const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride);
  109. /**
  110. * Generate index buffer that can be used for PN-AEN tessellation with crack-free displacement
  111. * Each triangle is converted into a 12-vertex patch with the following layout:
  112. * - 0, 1, 2: original triangle vertices
  113. * - 3, 4: opposing edge for edge 0, 1
  114. * - 5, 6: opposing edge for edge 1, 2
  115. * - 7, 8: opposing edge for edge 2, 0
  116. * - 9, 10, 11: dominant vertices for corners 0, 1, 2
  117. * The resulting patch can be rendered with hardware tessellation using PN-AEN and displacement mapping.
  118. * See "Tessellation on Any Budget" (John McDonald, GDC 2011) for implementation details.
  119. *
  120. * destination must contain enough space for the resulting index buffer (index_count*4 elements)
  121. * vertex_positions should have float3 position in the first 12 bytes of each vertex
  122. */
  123. MESHOPTIMIZER_API void meshopt_generateTessellationIndexBuffer(unsigned int* destination, const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride);
  124. /**
  125. * Vertex transform cache optimizer
  126. * Reorders indices to reduce the number of GPU vertex shader invocations
  127. * If index buffer contains multiple ranges for multiple draw calls, this functions needs to be called on each range individually.
  128. *
  129. * destination must contain enough space for the resulting index buffer (index_count elements)
  130. */
  131. MESHOPTIMIZER_API void meshopt_optimizeVertexCache(unsigned int* destination, const unsigned int* indices, size_t index_count, size_t vertex_count);
  132. /**
  133. * Vertex transform cache optimizer for strip-like caches
  134. * Produces inferior results to meshopt_optimizeVertexCache from the GPU vertex cache perspective
  135. * However, the resulting index order is more optimal if the goal is to reduce the triangle strip length or improve compression efficiency
  136. *
  137. * destination must contain enough space for the resulting index buffer (index_count elements)
  138. */
  139. MESHOPTIMIZER_API void meshopt_optimizeVertexCacheStrip(unsigned int* destination, const unsigned int* indices, size_t index_count, size_t vertex_count);
  140. /**
  141. * Vertex transform cache optimizer for FIFO caches
  142. * Reorders indices to reduce the number of GPU vertex shader invocations
  143. * Generally takes ~3x less time to optimize meshes but produces inferior results compared to meshopt_optimizeVertexCache
  144. * If index buffer contains multiple ranges for multiple draw calls, this functions needs to be called on each range individually.
  145. *
  146. * destination must contain enough space for the resulting index buffer (index_count elements)
  147. * cache_size should be less than the actual GPU cache size to avoid cache thrashing
  148. */
  149. MESHOPTIMIZER_API void meshopt_optimizeVertexCacheFifo(unsigned int* destination, const unsigned int* indices, size_t index_count, size_t vertex_count, unsigned int cache_size);
  150. /**
  151. * Overdraw optimizer
  152. * Reorders indices to reduce the number of GPU vertex shader invocations and the pixel overdraw
  153. * If index buffer contains multiple ranges for multiple draw calls, this functions needs to be called on each range individually.
  154. *
  155. * destination must contain enough space for the resulting index buffer (index_count elements)
  156. * indices must contain index data that is the result of meshopt_optimizeVertexCache (*not* the original mesh indices!)
  157. * vertex_positions should have float3 position in the first 12 bytes of each vertex
  158. * threshold indicates how much the overdraw optimizer can degrade vertex cache efficiency (1.05 = up to 5%) to reduce overdraw more efficiently
  159. */
  160. MESHOPTIMIZER_API void meshopt_optimizeOverdraw(unsigned int* destination, const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, float threshold);
  161. /**
  162. * Vertex fetch cache optimizer
  163. * Reorders vertices and changes indices to reduce the amount of GPU memory fetches during vertex processing
  164. * Returns the number of unique vertices, which is the same as input vertex count unless some vertices are unused
  165. * This functions works for a single vertex stream; for multiple vertex streams, use meshopt_optimizeVertexFetchRemap + meshopt_remapVertexBuffer for each stream.
  166. *
  167. * destination must contain enough space for the resulting vertex buffer (vertex_count elements)
  168. * indices is used both as an input and as an output index buffer
  169. */
  170. MESHOPTIMIZER_API size_t meshopt_optimizeVertexFetch(void* destination, unsigned int* indices, size_t index_count, const void* vertices, size_t vertex_count, size_t vertex_size);
  171. /**
  172. * Vertex fetch cache optimizer
  173. * Generates vertex remap to reduce the amount of GPU memory fetches during vertex processing
  174. * Returns the number of unique vertices, which is the same as input vertex count unless some vertices are unused
  175. * The resulting remap table should be used to reorder vertex/index buffers using meshopt_remapVertexBuffer/meshopt_remapIndexBuffer
  176. *
  177. * destination must contain enough space for the resulting remap table (vertex_count elements)
  178. */
  179. MESHOPTIMIZER_API size_t meshopt_optimizeVertexFetchRemap(unsigned int* destination, const unsigned int* indices, size_t index_count, size_t vertex_count);
  180. /**
  181. * Index buffer encoder
  182. * Encodes index data into an array of bytes that is generally much smaller (<1.5 bytes/triangle) and compresses better (<1 bytes/triangle) compared to original.
  183. * Input index buffer must represent a triangle list.
  184. * Returns encoded data size on success, 0 on error; the only error condition is if buffer doesn't have enough space
  185. * For maximum efficiency the index buffer being encoded has to be optimized for vertex cache and vertex fetch first.
  186. *
  187. * buffer must contain enough space for the encoded index buffer (use meshopt_encodeIndexBufferBound to compute worst case size)
  188. */
  189. MESHOPTIMIZER_API size_t meshopt_encodeIndexBuffer(unsigned char* buffer, size_t buffer_size, const unsigned int* indices, size_t index_count);
  190. MESHOPTIMIZER_API size_t meshopt_encodeIndexBufferBound(size_t index_count, size_t vertex_count);
  191. /**
  192. * Set index encoder format version
  193. * version must specify the data format version to encode; valid values are 0 (decodable by all library versions) and 1 (decodable by 0.14+)
  194. */
  195. MESHOPTIMIZER_API void meshopt_encodeIndexVersion(int version);
  196. /**
  197. * Index buffer decoder
  198. * Decodes index data from an array of bytes generated by meshopt_encodeIndexBuffer
  199. * Returns 0 if decoding was successful, and an error code otherwise
  200. * The decoder is safe to use for untrusted input, but it may produce garbage data (e.g. out of range indices).
  201. *
  202. * destination must contain enough space for the resulting index buffer (index_count elements)
  203. */
  204. MESHOPTIMIZER_API int meshopt_decodeIndexBuffer(void* destination, size_t index_count, size_t index_size, const unsigned char* buffer, size_t buffer_size);
  205. /**
  206. * Index sequence encoder
  207. * Encodes index sequence into an array of bytes that is generally smaller and compresses better compared to original.
  208. * Input index sequence can represent arbitrary topology; for triangle lists meshopt_encodeIndexBuffer is likely to be better.
  209. * Returns encoded data size on success, 0 on error; the only error condition is if buffer doesn't have enough space
  210. *
  211. * buffer must contain enough space for the encoded index sequence (use meshopt_encodeIndexSequenceBound to compute worst case size)
  212. */
  213. MESHOPTIMIZER_API size_t meshopt_encodeIndexSequence(unsigned char* buffer, size_t buffer_size, const unsigned int* indices, size_t index_count);
  214. MESHOPTIMIZER_API size_t meshopt_encodeIndexSequenceBound(size_t index_count, size_t vertex_count);
  215. /**
  216. * Index sequence decoder
  217. * Decodes index data from an array of bytes generated by meshopt_encodeIndexSequence
  218. * Returns 0 if decoding was successful, and an error code otherwise
  219. * The decoder is safe to use for untrusted input, but it may produce garbage data (e.g. out of range indices).
  220. *
  221. * destination must contain enough space for the resulting index sequence (index_count elements)
  222. */
  223. MESHOPTIMIZER_API int meshopt_decodeIndexSequence(void* destination, size_t index_count, size_t index_size, const unsigned char* buffer, size_t buffer_size);
  224. /**
  225. * Vertex buffer encoder
  226. * Encodes vertex data into an array of bytes that is generally smaller and compresses better compared to original.
  227. * Returns encoded data size on success, 0 on error; the only error condition is if buffer doesn't have enough space
  228. * This function works for a single vertex stream; for multiple vertex streams, call meshopt_encodeVertexBuffer for each stream.
  229. * Note that all vertex_size bytes of each vertex are encoded verbatim, including padding which should be zero-initialized.
  230. *
  231. * buffer must contain enough space for the encoded vertex buffer (use meshopt_encodeVertexBufferBound to compute worst case size)
  232. */
  233. MESHOPTIMIZER_API size_t meshopt_encodeVertexBuffer(unsigned char* buffer, size_t buffer_size, const void* vertices, size_t vertex_count, size_t vertex_size);
  234. MESHOPTIMIZER_API size_t meshopt_encodeVertexBufferBound(size_t vertex_count, size_t vertex_size);
  235. /**
  236. * Set vertex encoder format version
  237. * version must specify the data format version to encode; valid values are 0 (decodable by all library versions)
  238. */
  239. MESHOPTIMIZER_API void meshopt_encodeVertexVersion(int version);
  240. /**
  241. * Vertex buffer decoder
  242. * Decodes vertex data from an array of bytes generated by meshopt_encodeVertexBuffer
  243. * Returns 0 if decoding was successful, and an error code otherwise
  244. * The decoder is safe to use for untrusted input, but it may produce garbage data.
  245. *
  246. * destination must contain enough space for the resulting vertex buffer (vertex_count * vertex_size bytes)
  247. */
  248. MESHOPTIMIZER_API int meshopt_decodeVertexBuffer(void* destination, size_t vertex_count, size_t vertex_size, const unsigned char* buffer, size_t buffer_size);
  249. /**
  250. * Vertex buffer filters
  251. * These functions can be used to filter output of meshopt_decodeVertexBuffer in-place.
  252. *
  253. * meshopt_decodeFilterOct decodes octahedral encoding of a unit vector with K-bit (K <= 16) signed X/Y as an input; Z must store 1.0f.
  254. * Each component is stored as an 8-bit or 16-bit normalized integer; stride must be equal to 4 or 8. W is preserved as is.
  255. *
  256. * meshopt_decodeFilterQuat decodes 3-component quaternion encoding with K-bit (4 <= K <= 16) component encoding and a 2-bit component index indicating which component to reconstruct.
  257. * Each component is stored as an 16-bit integer; stride must be equal to 8.
  258. *
  259. * meshopt_decodeFilterExp decodes exponential encoding of floating-point data with 8-bit exponent and 24-bit integer mantissa as 2^E*M.
  260. * Each 32-bit component is decoded in isolation; stride must be divisible by 4.
  261. */
  262. MESHOPTIMIZER_EXPERIMENTAL void meshopt_decodeFilterOct(void* buffer, size_t count, size_t stride);
  263. MESHOPTIMIZER_EXPERIMENTAL void meshopt_decodeFilterQuat(void* buffer, size_t count, size_t stride);
  264. MESHOPTIMIZER_EXPERIMENTAL void meshopt_decodeFilterExp(void* buffer, size_t count, size_t stride);
  265. /**
  266. * Vertex buffer filter encoders
  267. * These functions can be used to encode data in a format that meshopt_decodeFilter can decode
  268. *
  269. * meshopt_encodeFilterOct encodes unit vectors with K-bit (K <= 16) signed X/Y as an output.
  270. * Each component is stored as an 8-bit or 16-bit normalized integer; stride must be equal to 4 or 8. W is preserved as is.
  271. * Input data must contain 4 floats for every vector (count*4 total).
  272. *
  273. * meshopt_encodeFilterQuat encodes unit quaternions with K-bit (4 <= K <= 16) component encoding.
  274. * Each component is stored as an 16-bit integer; stride must be equal to 8.
  275. * Input data must contain 4 floats for every quaternion (count*4 total).
  276. *
  277. * meshopt_encodeFilterExp encodes arbitrary (finite) floating-point data with 8-bit exponent and K-bit integer mantissa (1 <= K <= 24).
  278. * Exponent can be shared between all components of a given vector as defined by stride or all values of a given component; stride must be divisible by 4.
  279. * Input data must contain stride/4 floats for every vector (count*stride/4 total).
  280. */
  281. enum meshopt_EncodeExpMode
  282. {
  283. /* When encoding exponents, use separate values for each component (maximum quality) */
  284. meshopt_EncodeExpSeparate,
  285. /* When encoding exponents, use shared value for all components of each vector (better compression) */
  286. meshopt_EncodeExpSharedVector,
  287. /* When encoding exponents, use shared value for each component of all vectors (best compression) */
  288. meshopt_EncodeExpSharedComponent,
  289. };
  290. MESHOPTIMIZER_EXPERIMENTAL void meshopt_encodeFilterOct(void* destination, size_t count, size_t stride, int bits, const float* data);
  291. MESHOPTIMIZER_EXPERIMENTAL void meshopt_encodeFilterQuat(void* destination, size_t count, size_t stride, int bits, const float* data);
  292. MESHOPTIMIZER_EXPERIMENTAL void meshopt_encodeFilterExp(void* destination, size_t count, size_t stride, int bits, const float* data, enum meshopt_EncodeExpMode mode);
  293. /**
  294. * Simplification options
  295. */
  296. enum
  297. {
  298. /* Do not move vertices that are located on the topological border (vertices on triangle edges that don't have a paired triangle). Useful for simplifying portions of the larger mesh. */
  299. meshopt_SimplifyLockBorder = 1 << 0,
  300. /* Improve simplification performance assuming input indices are a sparse subset of the mesh. Note that error becomes relative to subset extents. */
  301. meshopt_SimplifySparse = 1 << 1,
  302. /* Treat error limit and resulting error as absolute instead of relative to mesh extents. */
  303. meshopt_SimplifyErrorAbsolute = 1 << 2,
  304. };
  305. /**
  306. * Mesh simplifier
  307. * Reduces the number of triangles in the mesh, attempting to preserve mesh appearance as much as possible
  308. * The algorithm tries to preserve mesh topology and can stop short of the target goal based on topology constraints or target error.
  309. * If not all attributes from the input mesh are required, it's recommended to reindex the mesh using meshopt_generateShadowIndexBuffer prior to simplification.
  310. * Returns the number of indices after simplification, with destination containing new index data
  311. * The resulting index buffer references vertices from the original vertex buffer.
  312. * If the original vertex data isn't required, creating a compact vertex buffer using meshopt_optimizeVertexFetch is recommended.
  313. *
  314. * destination must contain enough space for the target index buffer, worst case is index_count elements (*not* target_index_count)!
  315. * vertex_positions should have float3 position in the first 12 bytes of each vertex
  316. * target_error represents the error relative to mesh extents that can be tolerated, e.g. 0.01 = 1% deformation; value range [0..1]
  317. * options must be a bitmask composed of meshopt_SimplifyX options; 0 is a safe default
  318. * result_error can be NULL; when it's not NULL, it will contain the resulting (relative) error after simplification
  319. */
  320. MESHOPTIMIZER_API size_t meshopt_simplify(unsigned int* destination, const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, size_t target_index_count, float target_error, unsigned int options, float* result_error);
  321. /**
  322. * Experimental: Mesh simplifier with attribute metric
  323. * The algorithm ehnahces meshopt_simplify by incorporating attribute values into the error metric used to prioritize simplification order; see meshopt_simplify documentation for details.
  324. * Note that the number of attributes affects memory requirements and running time; this algorithm requires ~1.5x more memory and time compared to meshopt_simplify when using 4 scalar attributes.
  325. *
  326. * vertex_attributes should have attribute_count floats for each vertex
  327. * attribute_weights should have attribute_count floats in total; the weights determine relative priority of attributes between each other and wrt position. The recommended weight range is [1e-3..1e-1], assuming attribute data is in [0..1] range.
  328. * attribute_count must be <= 16
  329. * vertex_lock can be NULL; when it's not NULL, it should have a value for each vertex; 1 denotes vertices that can't be moved
  330. * TODO target_error/result_error currently use combined distance+attribute error; this may change in the future
  331. */
  332. MESHOPTIMIZER_EXPERIMENTAL size_t meshopt_simplifyWithAttributes(unsigned int* destination, const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, const float* vertex_attributes, size_t vertex_attributes_stride, const float* attribute_weights, size_t attribute_count, const unsigned char* vertex_lock, size_t target_index_count, float target_error, unsigned int options, float* result_error);
  333. /**
  334. * Experimental: Mesh simplifier (sloppy)
  335. * Reduces the number of triangles in the mesh, sacrificing mesh appearance for simplification performance
  336. * The algorithm doesn't preserve mesh topology but can stop short of the target goal based on target error.
  337. * Returns the number of indices after simplification, with destination containing new index data
  338. * The resulting index buffer references vertices from the original vertex buffer.
  339. * If the original vertex data isn't required, creating a compact vertex buffer using meshopt_optimizeVertexFetch is recommended.
  340. *
  341. * destination must contain enough space for the target index buffer, worst case is index_count elements (*not* target_index_count)!
  342. * vertex_positions should have float3 position in the first 12 bytes of each vertex
  343. * target_error represents the error relative to mesh extents that can be tolerated, e.g. 0.01 = 1% deformation; value range [0..1]
  344. * result_error can be NULL; when it's not NULL, it will contain the resulting (relative) error after simplification
  345. */
  346. MESHOPTIMIZER_EXPERIMENTAL size_t meshopt_simplifySloppy(unsigned int* destination, const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, size_t target_index_count, float target_error, float* result_error);
  347. /**
  348. * Experimental: Point cloud simplifier
  349. * Reduces the number of points in the cloud to reach the given target
  350. * Returns the number of points after simplification, with destination containing new index data
  351. * The resulting index buffer references vertices from the original vertex buffer.
  352. * If the original vertex data isn't required, creating a compact vertex buffer using meshopt_optimizeVertexFetch is recommended.
  353. *
  354. * destination must contain enough space for the target index buffer (target_vertex_count elements)
  355. * vertex_positions should have float3 position in the first 12 bytes of each vertex
  356. * vertex_colors should can be NULL; when it's not NULL, it should have float3 color in the first 12 bytes of each vertex
  357. */
  358. MESHOPTIMIZER_EXPERIMENTAL size_t meshopt_simplifyPoints(unsigned int* destination, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, const float* vertex_colors, size_t vertex_colors_stride, float color_weight, size_t target_vertex_count);
  359. /**
  360. * Returns the error scaling factor used by the simplifier to convert between absolute and relative extents
  361. *
  362. * Absolute error must be *divided* by the scaling factor before passing it to meshopt_simplify as target_error
  363. * Relative error returned by meshopt_simplify via result_error must be *multiplied* by the scaling factor to get absolute error.
  364. */
  365. MESHOPTIMIZER_API float meshopt_simplifyScale(const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride);
  366. /**
  367. * Mesh stripifier
  368. * Converts a previously vertex cache optimized triangle list to triangle strip, stitching strips using restart index or degenerate triangles
  369. * Returns the number of indices in the resulting strip, with destination containing new index data
  370. * For maximum efficiency the index buffer being converted has to be optimized for vertex cache first.
  371. * Using restart indices can result in ~10% smaller index buffers, but on some GPUs restart indices may result in decreased performance.
  372. *
  373. * destination must contain enough space for the target index buffer, worst case can be computed with meshopt_stripifyBound
  374. * restart_index should be 0xffff or 0xffffffff depending on index size, or 0 to use degenerate triangles
  375. */
  376. MESHOPTIMIZER_API size_t meshopt_stripify(unsigned int* destination, const unsigned int* indices, size_t index_count, size_t vertex_count, unsigned int restart_index);
  377. MESHOPTIMIZER_API size_t meshopt_stripifyBound(size_t index_count);
  378. /**
  379. * Mesh unstripifier
  380. * Converts a triangle strip to a triangle list
  381. * Returns the number of indices in the resulting list, with destination containing new index data
  382. *
  383. * destination must contain enough space for the target index buffer, worst case can be computed with meshopt_unstripifyBound
  384. */
  385. MESHOPTIMIZER_API size_t meshopt_unstripify(unsigned int* destination, const unsigned int* indices, size_t index_count, unsigned int restart_index);
  386. MESHOPTIMIZER_API size_t meshopt_unstripifyBound(size_t index_count);
  387. struct meshopt_VertexCacheStatistics
  388. {
  389. unsigned int vertices_transformed;
  390. unsigned int warps_executed;
  391. float acmr; /* transformed vertices / triangle count; best case 0.5, worst case 3.0, optimum depends on topology */
  392. float atvr; /* transformed vertices / vertex count; best case 1.0, worst case 6.0, optimum is 1.0 (each vertex is transformed once) */
  393. };
  394. /**
  395. * Vertex transform cache analyzer
  396. * Returns cache hit statistics using a simplified FIFO model
  397. * Results may not match actual GPU performance
  398. */
  399. MESHOPTIMIZER_API struct meshopt_VertexCacheStatistics meshopt_analyzeVertexCache(const unsigned int* indices, size_t index_count, size_t vertex_count, unsigned int cache_size, unsigned int warp_size, unsigned int primgroup_size);
  400. struct meshopt_OverdrawStatistics
  401. {
  402. unsigned int pixels_covered;
  403. unsigned int pixels_shaded;
  404. float overdraw; /* shaded pixels / covered pixels; best case 1.0 */
  405. };
  406. /**
  407. * Overdraw analyzer
  408. * Returns overdraw statistics using a software rasterizer
  409. * Results may not match actual GPU performance
  410. *
  411. * vertex_positions should have float3 position in the first 12 bytes of each vertex
  412. */
  413. MESHOPTIMIZER_API struct meshopt_OverdrawStatistics meshopt_analyzeOverdraw(const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride);
  414. struct meshopt_VertexFetchStatistics
  415. {
  416. unsigned int bytes_fetched;
  417. float overfetch; /* fetched bytes / vertex buffer size; best case 1.0 (each byte is fetched once) */
  418. };
  419. /**
  420. * Vertex fetch cache analyzer
  421. * Returns cache hit statistics using a simplified direct mapped model
  422. * Results may not match actual GPU performance
  423. */
  424. MESHOPTIMIZER_API struct meshopt_VertexFetchStatistics meshopt_analyzeVertexFetch(const unsigned int* indices, size_t index_count, size_t vertex_count, size_t vertex_size);
  425. struct meshopt_Meshlet
  426. {
  427. /* offsets within meshlet_vertices and meshlet_triangles arrays with meshlet data */
  428. unsigned int vertex_offset;
  429. unsigned int triangle_offset;
  430. /* number of vertices and triangles used in the meshlet; data is stored in consecutive range defined by offset and count */
  431. unsigned int vertex_count;
  432. unsigned int triangle_count;
  433. };
  434. /**
  435. * Meshlet builder
  436. * Splits the mesh into a set of meshlets where each meshlet has a micro index buffer indexing into meshlet vertices that refer to the original vertex buffer
  437. * The resulting data can be used to render meshes using NVidia programmable mesh shading pipeline, or in other cluster-based renderers.
  438. * When using buildMeshlets, vertex positions need to be provided to minimize the size of the resulting clusters.
  439. * When using buildMeshletsScan, for maximum efficiency the index buffer being converted has to be optimized for vertex cache first.
  440. *
  441. * meshlets must contain enough space for all meshlets, worst case size can be computed with meshopt_buildMeshletsBound
  442. * meshlet_vertices must contain enough space for all meshlets, worst case size is equal to max_meshlets * max_vertices
  443. * meshlet_triangles must contain enough space for all meshlets, worst case size is equal to max_meshlets * max_triangles * 3
  444. * vertex_positions should have float3 position in the first 12 bytes of each vertex
  445. * max_vertices and max_triangles must not exceed implementation limits (max_vertices <= 255 - not 256!, max_triangles <= 512; max_triangles must be divisible by 4)
  446. * cone_weight should be set to 0 when cone culling is not used, and a value between 0 and 1 otherwise to balance between cluster size and cone culling efficiency
  447. */
  448. MESHOPTIMIZER_API size_t meshopt_buildMeshlets(struct meshopt_Meshlet* meshlets, unsigned int* meshlet_vertices, unsigned char* meshlet_triangles, const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, size_t max_vertices, size_t max_triangles, float cone_weight);
  449. MESHOPTIMIZER_API size_t meshopt_buildMeshletsScan(struct meshopt_Meshlet* meshlets, unsigned int* meshlet_vertices, unsigned char* meshlet_triangles, const unsigned int* indices, size_t index_count, size_t vertex_count, size_t max_vertices, size_t max_triangles);
  450. MESHOPTIMIZER_API size_t meshopt_buildMeshletsBound(size_t index_count, size_t max_vertices, size_t max_triangles);
  451. /**
  452. * Experimental: Meshlet optimizer
  453. * Reorders meshlet vertices and triangles to maximize locality to improve rasterizer throughput
  454. *
  455. * meshlet_triangles and meshlet_vertices must refer to meshlet triangle and vertex index data; when buildMeshlets* is used, these
  456. * need to be computed from meshlet's vertex_offset and triangle_offset
  457. * triangle_count and vertex_count must not exceed implementation limits (vertex_count <= 255 - not 256!, triangle_count <= 512)
  458. */
  459. MESHOPTIMIZER_EXPERIMENTAL void meshopt_optimizeMeshlet(unsigned int* meshlet_vertices, unsigned char* meshlet_triangles, size_t triangle_count, size_t vertex_count);
  460. struct meshopt_Bounds
  461. {
  462. /* bounding sphere, useful for frustum and occlusion culling */
  463. float center[3];
  464. float radius;
  465. /* normal cone, useful for backface culling */
  466. float cone_apex[3];
  467. float cone_axis[3];
  468. float cone_cutoff; /* = cos(angle/2) */
  469. /* normal cone axis and cutoff, stored in 8-bit SNORM format; decode using x/127.0 */
  470. signed char cone_axis_s8[3];
  471. signed char cone_cutoff_s8;
  472. };
  473. /**
  474. * Cluster bounds generator
  475. * Creates bounding volumes that can be used for frustum, backface and occlusion culling.
  476. *
  477. * For backface culling with orthographic projection, use the following formula to reject backfacing clusters:
  478. * dot(view, cone_axis) >= cone_cutoff
  479. *
  480. * For perspective projection, you can use the formula that needs cone apex in addition to axis & cutoff:
  481. * dot(normalize(cone_apex - camera_position), cone_axis) >= cone_cutoff
  482. *
  483. * Alternatively, you can use the formula that doesn't need cone apex and uses bounding sphere instead:
  484. * dot(normalize(center - camera_position), cone_axis) >= cone_cutoff + radius / length(center - camera_position)
  485. * or an equivalent formula that doesn't have a singularity at center = camera_position:
  486. * dot(center - camera_position, cone_axis) >= cone_cutoff * length(center - camera_position) + radius
  487. *
  488. * The formula that uses the apex is slightly more accurate but needs the apex; if you are already using bounding sphere
  489. * to do frustum/occlusion culling, the formula that doesn't use the apex may be preferable (for derivation see
  490. * Real-Time Rendering 4th Edition, section 19.3).
  491. *
  492. * vertex_positions should have float3 position in the first 12 bytes of each vertex
  493. * index_count/3 should be less than or equal to 512 (the function assumes clusters of limited size)
  494. */
  495. MESHOPTIMIZER_API struct meshopt_Bounds meshopt_computeClusterBounds(const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride);
  496. MESHOPTIMIZER_API struct meshopt_Bounds meshopt_computeMeshletBounds(const unsigned int* meshlet_vertices, const unsigned char* meshlet_triangles, size_t triangle_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride);
  497. /**
  498. * Spatial sorter
  499. * Generates a remap table that can be used to reorder points for spatial locality.
  500. * Resulting remap table maps old vertices to new vertices and can be used in meshopt_remapVertexBuffer.
  501. *
  502. * destination must contain enough space for the resulting remap table (vertex_count elements)
  503. * vertex_positions should have float3 position in the first 12 bytes of each vertex
  504. */
  505. MESHOPTIMIZER_API void meshopt_spatialSortRemap(unsigned int* destination, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride);
  506. /**
  507. * Experimental: Spatial sorter
  508. * Reorders triangles for spatial locality, and generates a new index buffer. The resulting index buffer can be used with other functions like optimizeVertexCache.
  509. *
  510. * destination must contain enough space for the resulting index buffer (index_count elements)
  511. * vertex_positions should have float3 position in the first 12 bytes of each vertex
  512. */
  513. MESHOPTIMIZER_EXPERIMENTAL void meshopt_spatialSortTriangles(unsigned int* destination, const unsigned int* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride);
  514. /**
  515. * Set allocation callbacks
  516. * These callbacks will be used instead of the default operator new/operator delete for all temporary allocations in the library.
  517. * Note that all algorithms only allocate memory for temporary use.
  518. * allocate/deallocate are always called in a stack-like order - last pointer to be allocated is deallocated first.
  519. */
  520. MESHOPTIMIZER_API void meshopt_setAllocator(void* (MESHOPTIMIZER_ALLOC_CALLCONV *allocate)(size_t), void (MESHOPTIMIZER_ALLOC_CALLCONV *deallocate)(void*));
  521. #ifdef __cplusplus
  522. } /* extern "C" */
  523. #endif
  524. /* Quantization into commonly supported data formats */
  525. #ifdef __cplusplus
  526. /**
  527. * Quantize a float in [0..1] range into an N-bit fixed point unorm value
  528. * Assumes reconstruction function (q / (2^N-1)), which is the case for fixed-function normalized fixed point conversion
  529. * Maximum reconstruction error: 1/2^(N+1)
  530. */
  531. inline int meshopt_quantizeUnorm(float v, int N);
  532. /**
  533. * Quantize a float in [-1..1] range into an N-bit fixed point snorm value
  534. * Assumes reconstruction function (q / (2^(N-1)-1)), which is the case for fixed-function normalized fixed point conversion (except early OpenGL versions)
  535. * Maximum reconstruction error: 1/2^N
  536. */
  537. inline int meshopt_quantizeSnorm(float v, int N);
  538. /**
  539. * Quantize a float into half-precision (as defined by IEEE-754 fp16) floating point value
  540. * Generates +-inf for overflow, preserves NaN, flushes denormals to zero, rounds to nearest
  541. * Representable magnitude range: [6e-5; 65504]
  542. * Maximum relative reconstruction error: 5e-4
  543. */
  544. MESHOPTIMIZER_API unsigned short meshopt_quantizeHalf(float v);
  545. /**
  546. * Quantize a float into a floating point value with a limited number of significant mantissa bits, preserving the IEEE-754 fp32 binary representation
  547. * Generates +-inf for overflow, preserves NaN, flushes denormals to zero, rounds to nearest
  548. * Assumes N is in a valid mantissa precision range, which is 1..23
  549. */
  550. MESHOPTIMIZER_API float meshopt_quantizeFloat(float v, int N);
  551. /**
  552. * Reverse quantization of a half-precision (as defined by IEEE-754 fp16) floating point value
  553. * Preserves Inf/NaN, flushes denormals to zero
  554. */
  555. MESHOPTIMIZER_API float meshopt_dequantizeHalf(unsigned short h);
  556. #endif
  557. /**
  558. * C++ template interface
  559. *
  560. * These functions mirror the C interface the library provides, providing template-based overloads so that
  561. * the caller can use an arbitrary type for the index data, both for input and output.
  562. * When the supplied type is the same size as that of unsigned int, the wrappers are zero-cost; when it's not,
  563. * the wrappers end up allocating memory and copying index data to convert from one type to another.
  564. */
  565. #if defined(__cplusplus) && !defined(MESHOPTIMIZER_NO_WRAPPERS)
  566. template <typename T>
  567. inline size_t meshopt_generateVertexRemap(unsigned int* destination, const T* indices, size_t index_count, const void* vertices, size_t vertex_count, size_t vertex_size);
  568. template <typename T>
  569. inline size_t meshopt_generateVertexRemapMulti(unsigned int* destination, const T* indices, size_t index_count, size_t vertex_count, const meshopt_Stream* streams, size_t stream_count);
  570. template <typename T>
  571. inline void meshopt_remapIndexBuffer(T* destination, const T* indices, size_t index_count, const unsigned int* remap);
  572. template <typename T>
  573. inline void meshopt_generateShadowIndexBuffer(T* destination, const T* indices, size_t index_count, const void* vertices, size_t vertex_count, size_t vertex_size, size_t vertex_stride);
  574. template <typename T>
  575. inline void meshopt_generateShadowIndexBufferMulti(T* destination, const T* indices, size_t index_count, size_t vertex_count, const meshopt_Stream* streams, size_t stream_count);
  576. template <typename T>
  577. inline void meshopt_generateAdjacencyIndexBuffer(T* destination, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride);
  578. template <typename T>
  579. inline void meshopt_generateTessellationIndexBuffer(T* destination, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride);
  580. template <typename T>
  581. inline void meshopt_optimizeVertexCache(T* destination, const T* indices, size_t index_count, size_t vertex_count);
  582. template <typename T>
  583. inline void meshopt_optimizeVertexCacheStrip(T* destination, const T* indices, size_t index_count, size_t vertex_count);
  584. template <typename T>
  585. inline void meshopt_optimizeVertexCacheFifo(T* destination, const T* indices, size_t index_count, size_t vertex_count, unsigned int cache_size);
  586. template <typename T>
  587. inline void meshopt_optimizeOverdraw(T* destination, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, float threshold);
  588. template <typename T>
  589. inline size_t meshopt_optimizeVertexFetchRemap(unsigned int* destination, const T* indices, size_t index_count, size_t vertex_count);
  590. template <typename T>
  591. inline size_t meshopt_optimizeVertexFetch(void* destination, T* indices, size_t index_count, const void* vertices, size_t vertex_count, size_t vertex_size);
  592. template <typename T>
  593. inline size_t meshopt_encodeIndexBuffer(unsigned char* buffer, size_t buffer_size, const T* indices, size_t index_count);
  594. template <typename T>
  595. inline int meshopt_decodeIndexBuffer(T* destination, size_t index_count, const unsigned char* buffer, size_t buffer_size);
  596. template <typename T>
  597. inline size_t meshopt_encodeIndexSequence(unsigned char* buffer, size_t buffer_size, const T* indices, size_t index_count);
  598. template <typename T>
  599. inline int meshopt_decodeIndexSequence(T* destination, size_t index_count, const unsigned char* buffer, size_t buffer_size);
  600. template <typename T>
  601. inline size_t meshopt_simplify(T* destination, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, size_t target_index_count, float target_error, unsigned int options = 0, float* result_error = NULL);
  602. template <typename T>
  603. inline size_t meshopt_simplifyWithAttributes(T* destination, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, const float* vertex_attributes, size_t vertex_attributes_stride, const float* attribute_weights, size_t attribute_count, const unsigned char* vertex_lock, size_t target_index_count, float target_error, unsigned int options = 0, float* result_error = NULL);
  604. template <typename T>
  605. inline size_t meshopt_simplifySloppy(T* destination, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, size_t target_index_count, float target_error, float* result_error = NULL);
  606. template <typename T>
  607. inline size_t meshopt_stripify(T* destination, const T* indices, size_t index_count, size_t vertex_count, T restart_index);
  608. template <typename T>
  609. inline size_t meshopt_unstripify(T* destination, const T* indices, size_t index_count, T restart_index);
  610. template <typename T>
  611. inline meshopt_VertexCacheStatistics meshopt_analyzeVertexCache(const T* indices, size_t index_count, size_t vertex_count, unsigned int cache_size, unsigned int warp_size, unsigned int buffer_size);
  612. template <typename T>
  613. inline meshopt_OverdrawStatistics meshopt_analyzeOverdraw(const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride);
  614. template <typename T>
  615. inline meshopt_VertexFetchStatistics meshopt_analyzeVertexFetch(const T* indices, size_t index_count, size_t vertex_count, size_t vertex_size);
  616. template <typename T>
  617. inline size_t meshopt_buildMeshlets(meshopt_Meshlet* meshlets, unsigned int* meshlet_vertices, unsigned char* meshlet_triangles, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, size_t max_vertices, size_t max_triangles, float cone_weight);
  618. template <typename T>
  619. inline size_t meshopt_buildMeshletsScan(meshopt_Meshlet* meshlets, unsigned int* meshlet_vertices, unsigned char* meshlet_triangles, const T* indices, size_t index_count, size_t vertex_count, size_t max_vertices, size_t max_triangles);
  620. template <typename T>
  621. inline meshopt_Bounds meshopt_computeClusterBounds(const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride);
  622. template <typename T>
  623. inline void meshopt_spatialSortTriangles(T* destination, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride);
  624. #endif
  625. /* Inline implementation */
  626. #ifdef __cplusplus
  627. inline int meshopt_quantizeUnorm(float v, int N)
  628. {
  629. const float scale = float((1 << N) - 1);
  630. v = (v >= 0) ? v : 0;
  631. v = (v <= 1) ? v : 1;
  632. return int(v * scale + 0.5f);
  633. }
  634. inline int meshopt_quantizeSnorm(float v, int N)
  635. {
  636. const float scale = float((1 << (N - 1)) - 1);
  637. float round = (v >= 0 ? 0.5f : -0.5f);
  638. v = (v >= -1) ? v : -1;
  639. v = (v <= +1) ? v : +1;
  640. return int(v * scale + round);
  641. }
  642. #endif
  643. /* Internal implementation helpers */
  644. #ifdef __cplusplus
  645. class meshopt_Allocator
  646. {
  647. public:
  648. template <typename T>
  649. struct StorageT
  650. {
  651. static void* (MESHOPTIMIZER_ALLOC_CALLCONV *allocate)(size_t);
  652. static void (MESHOPTIMIZER_ALLOC_CALLCONV *deallocate)(void*);
  653. };
  654. typedef StorageT<void> Storage;
  655. meshopt_Allocator()
  656. : blocks()
  657. , count(0)
  658. {
  659. }
  660. ~meshopt_Allocator()
  661. {
  662. for (size_t i = count; i > 0; --i)
  663. Storage::deallocate(blocks[i - 1]);
  664. }
  665. template <typename T> T* allocate(size_t size)
  666. {
  667. assert(count < sizeof(blocks) / sizeof(blocks[0]));
  668. T* result = static_cast<T*>(Storage::allocate(size > size_t(-1) / sizeof(T) ? size_t(-1) : size * sizeof(T)));
  669. blocks[count++] = result;
  670. return result;
  671. }
  672. void deallocate(void* ptr)
  673. {
  674. assert(count > 0 && blocks[count - 1] == ptr);
  675. Storage::deallocate(ptr);
  676. count--;
  677. }
  678. private:
  679. void* blocks[24];
  680. size_t count;
  681. };
  682. // This makes sure that allocate/deallocate are lazily generated in translation units that need them and are deduplicated by the linker
  683. template <typename T> void* (MESHOPTIMIZER_ALLOC_CALLCONV *meshopt_Allocator::StorageT<T>::allocate)(size_t) = operator new;
  684. template <typename T> void (MESHOPTIMIZER_ALLOC_CALLCONV *meshopt_Allocator::StorageT<T>::deallocate)(void*) = operator delete;
  685. #endif
  686. /* Inline implementation for C++ templated wrappers */
  687. #if defined(__cplusplus) && !defined(MESHOPTIMIZER_NO_WRAPPERS)
  688. template <typename T, bool ZeroCopy = sizeof(T) == sizeof(unsigned int)>
  689. struct meshopt_IndexAdapter;
  690. template <typename T>
  691. struct meshopt_IndexAdapter<T, false>
  692. {
  693. T* result;
  694. unsigned int* data;
  695. size_t count;
  696. meshopt_IndexAdapter(T* result_, const T* input, size_t count_)
  697. : result(result_)
  698. , data(NULL)
  699. , count(count_)
  700. {
  701. size_t size = count > size_t(-1) / sizeof(unsigned int) ? size_t(-1) : count * sizeof(unsigned int);
  702. data = static_cast<unsigned int*>(meshopt_Allocator::Storage::allocate(size));
  703. if (input)
  704. {
  705. for (size_t i = 0; i < count; ++i)
  706. data[i] = input[i];
  707. }
  708. }
  709. ~meshopt_IndexAdapter()
  710. {
  711. if (result)
  712. {
  713. for (size_t i = 0; i < count; ++i)
  714. result[i] = T(data[i]);
  715. }
  716. meshopt_Allocator::Storage::deallocate(data);
  717. }
  718. };
  719. template <typename T>
  720. struct meshopt_IndexAdapter<T, true>
  721. {
  722. unsigned int* data;
  723. meshopt_IndexAdapter(T* result, const T* input, size_t)
  724. : data(reinterpret_cast<unsigned int*>(result ? result : const_cast<T*>(input)))
  725. {
  726. }
  727. };
  728. template <typename T>
  729. inline size_t meshopt_generateVertexRemap(unsigned int* destination, const T* indices, size_t index_count, const void* vertices, size_t vertex_count, size_t vertex_size)
  730. {
  731. meshopt_IndexAdapter<T> in(NULL, indices, indices ? index_count : 0);
  732. return meshopt_generateVertexRemap(destination, indices ? in.data : NULL, index_count, vertices, vertex_count, vertex_size);
  733. }
  734. template <typename T>
  735. inline size_t meshopt_generateVertexRemapMulti(unsigned int* destination, const T* indices, size_t index_count, size_t vertex_count, const meshopt_Stream* streams, size_t stream_count)
  736. {
  737. meshopt_IndexAdapter<T> in(NULL, indices, indices ? index_count : 0);
  738. return meshopt_generateVertexRemapMulti(destination, indices ? in.data : NULL, index_count, vertex_count, streams, stream_count);
  739. }
  740. template <typename T>
  741. inline void meshopt_remapIndexBuffer(T* destination, const T* indices, size_t index_count, const unsigned int* remap)
  742. {
  743. meshopt_IndexAdapter<T> in(NULL, indices, indices ? index_count : 0);
  744. meshopt_IndexAdapter<T> out(destination, 0, index_count);
  745. meshopt_remapIndexBuffer(out.data, indices ? in.data : NULL, index_count, remap);
  746. }
  747. template <typename T>
  748. inline void meshopt_generateShadowIndexBuffer(T* destination, const T* indices, size_t index_count, const void* vertices, size_t vertex_count, size_t vertex_size, size_t vertex_stride)
  749. {
  750. meshopt_IndexAdapter<T> in(NULL, indices, index_count);
  751. meshopt_IndexAdapter<T> out(destination, NULL, index_count);
  752. meshopt_generateShadowIndexBuffer(out.data, in.data, index_count, vertices, vertex_count, vertex_size, vertex_stride);
  753. }
  754. template <typename T>
  755. inline void meshopt_generateShadowIndexBufferMulti(T* destination, const T* indices, size_t index_count, size_t vertex_count, const meshopt_Stream* streams, size_t stream_count)
  756. {
  757. meshopt_IndexAdapter<T> in(NULL, indices, index_count);
  758. meshopt_IndexAdapter<T> out(destination, NULL, index_count);
  759. meshopt_generateShadowIndexBufferMulti(out.data, in.data, index_count, vertex_count, streams, stream_count);
  760. }
  761. template <typename T>
  762. inline void meshopt_generateAdjacencyIndexBuffer(T* destination, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride)
  763. {
  764. meshopt_IndexAdapter<T> in(NULL, indices, index_count);
  765. meshopt_IndexAdapter<T> out(destination, NULL, index_count * 2);
  766. meshopt_generateAdjacencyIndexBuffer(out.data, in.data, index_count, vertex_positions, vertex_count, vertex_positions_stride);
  767. }
  768. template <typename T>
  769. inline void meshopt_generateTessellationIndexBuffer(T* destination, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride)
  770. {
  771. meshopt_IndexAdapter<T> in(NULL, indices, index_count);
  772. meshopt_IndexAdapter<T> out(destination, NULL, index_count * 4);
  773. meshopt_generateTessellationIndexBuffer(out.data, in.data, index_count, vertex_positions, vertex_count, vertex_positions_stride);
  774. }
  775. template <typename T>
  776. inline void meshopt_optimizeVertexCache(T* destination, const T* indices, size_t index_count, size_t vertex_count)
  777. {
  778. meshopt_IndexAdapter<T> in(NULL, indices, index_count);
  779. meshopt_IndexAdapter<T> out(destination, NULL, index_count);
  780. meshopt_optimizeVertexCache(out.data, in.data, index_count, vertex_count);
  781. }
  782. template <typename T>
  783. inline void meshopt_optimizeVertexCacheStrip(T* destination, const T* indices, size_t index_count, size_t vertex_count)
  784. {
  785. meshopt_IndexAdapter<T> in(NULL, indices, index_count);
  786. meshopt_IndexAdapter<T> out(destination, NULL, index_count);
  787. meshopt_optimizeVertexCacheStrip(out.data, in.data, index_count, vertex_count);
  788. }
  789. template <typename T>
  790. inline void meshopt_optimizeVertexCacheFifo(T* destination, const T* indices, size_t index_count, size_t vertex_count, unsigned int cache_size)
  791. {
  792. meshopt_IndexAdapter<T> in(NULL, indices, index_count);
  793. meshopt_IndexAdapter<T> out(destination, NULL, index_count);
  794. meshopt_optimizeVertexCacheFifo(out.data, in.data, index_count, vertex_count, cache_size);
  795. }
  796. template <typename T>
  797. inline void meshopt_optimizeOverdraw(T* destination, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, float threshold)
  798. {
  799. meshopt_IndexAdapter<T> in(NULL, indices, index_count);
  800. meshopt_IndexAdapter<T> out(destination, NULL, index_count);
  801. meshopt_optimizeOverdraw(out.data, in.data, index_count, vertex_positions, vertex_count, vertex_positions_stride, threshold);
  802. }
  803. template <typename T>
  804. inline size_t meshopt_optimizeVertexFetchRemap(unsigned int* destination, const T* indices, size_t index_count, size_t vertex_count)
  805. {
  806. meshopt_IndexAdapter<T> in(NULL, indices, index_count);
  807. return meshopt_optimizeVertexFetchRemap(destination, in.data, index_count, vertex_count);
  808. }
  809. template <typename T>
  810. inline size_t meshopt_optimizeVertexFetch(void* destination, T* indices, size_t index_count, const void* vertices, size_t vertex_count, size_t vertex_size)
  811. {
  812. meshopt_IndexAdapter<T> inout(indices, indices, index_count);
  813. return meshopt_optimizeVertexFetch(destination, inout.data, index_count, vertices, vertex_count, vertex_size);
  814. }
  815. template <typename T>
  816. inline size_t meshopt_encodeIndexBuffer(unsigned char* buffer, size_t buffer_size, const T* indices, size_t index_count)
  817. {
  818. meshopt_IndexAdapter<T> in(NULL, indices, index_count);
  819. return meshopt_encodeIndexBuffer(buffer, buffer_size, in.data, index_count);
  820. }
  821. template <typename T>
  822. inline int meshopt_decodeIndexBuffer(T* destination, size_t index_count, const unsigned char* buffer, size_t buffer_size)
  823. {
  824. char index_size_valid[sizeof(T) == 2 || sizeof(T) == 4 ? 1 : -1];
  825. (void)index_size_valid;
  826. return meshopt_decodeIndexBuffer(destination, index_count, sizeof(T), buffer, buffer_size);
  827. }
  828. template <typename T>
  829. inline size_t meshopt_encodeIndexSequence(unsigned char* buffer, size_t buffer_size, const T* indices, size_t index_count)
  830. {
  831. meshopt_IndexAdapter<T> in(NULL, indices, index_count);
  832. return meshopt_encodeIndexSequence(buffer, buffer_size, in.data, index_count);
  833. }
  834. template <typename T>
  835. inline int meshopt_decodeIndexSequence(T* destination, size_t index_count, const unsigned char* buffer, size_t buffer_size)
  836. {
  837. char index_size_valid[sizeof(T) == 2 || sizeof(T) == 4 ? 1 : -1];
  838. (void)index_size_valid;
  839. return meshopt_decodeIndexSequence(destination, index_count, sizeof(T), buffer, buffer_size);
  840. }
  841. template <typename T>
  842. inline size_t meshopt_simplify(T* destination, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, size_t target_index_count, float target_error, unsigned int options, float* result_error)
  843. {
  844. meshopt_IndexAdapter<T> in(NULL, indices, index_count);
  845. meshopt_IndexAdapter<T> out(destination, NULL, index_count);
  846. return meshopt_simplify(out.data, in.data, index_count, vertex_positions, vertex_count, vertex_positions_stride, target_index_count, target_error, options, result_error);
  847. }
  848. template <typename T>
  849. inline size_t meshopt_simplifyWithAttributes(T* destination, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, const float* vertex_attributes, size_t vertex_attributes_stride, const float* attribute_weights, size_t attribute_count, const unsigned char* vertex_lock, size_t target_index_count, float target_error, unsigned int options, float* result_error)
  850. {
  851. meshopt_IndexAdapter<T> in(NULL, indices, index_count);
  852. meshopt_IndexAdapter<T> out(destination, NULL, index_count);
  853. return meshopt_simplifyWithAttributes(out.data, in.data, index_count, vertex_positions, vertex_count, vertex_positions_stride, vertex_attributes, vertex_attributes_stride, attribute_weights, attribute_count, vertex_lock, target_index_count, target_error, options, result_error);
  854. }
  855. template <typename T>
  856. inline size_t meshopt_simplifySloppy(T* destination, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, size_t target_index_count, float target_error, float* result_error)
  857. {
  858. meshopt_IndexAdapter<T> in(NULL, indices, index_count);
  859. meshopt_IndexAdapter<T> out(destination, NULL, index_count);
  860. return meshopt_simplifySloppy(out.data, in.data, index_count, vertex_positions, vertex_count, vertex_positions_stride, target_index_count, target_error, result_error);
  861. }
  862. template <typename T>
  863. inline size_t meshopt_stripify(T* destination, const T* indices, size_t index_count, size_t vertex_count, T restart_index)
  864. {
  865. meshopt_IndexAdapter<T> in(NULL, indices, index_count);
  866. meshopt_IndexAdapter<T> out(destination, NULL, (index_count / 3) * 5);
  867. return meshopt_stripify(out.data, in.data, index_count, vertex_count, unsigned(restart_index));
  868. }
  869. template <typename T>
  870. inline size_t meshopt_unstripify(T* destination, const T* indices, size_t index_count, T restart_index)
  871. {
  872. meshopt_IndexAdapter<T> in(NULL, indices, index_count);
  873. meshopt_IndexAdapter<T> out(destination, NULL, (index_count - 2) * 3);
  874. return meshopt_unstripify(out.data, in.data, index_count, unsigned(restart_index));
  875. }
  876. template <typename T>
  877. inline meshopt_VertexCacheStatistics meshopt_analyzeVertexCache(const T* indices, size_t index_count, size_t vertex_count, unsigned int cache_size, unsigned int warp_size, unsigned int buffer_size)
  878. {
  879. meshopt_IndexAdapter<T> in(NULL, indices, index_count);
  880. return meshopt_analyzeVertexCache(in.data, index_count, vertex_count, cache_size, warp_size, buffer_size);
  881. }
  882. template <typename T>
  883. inline meshopt_OverdrawStatistics meshopt_analyzeOverdraw(const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride)
  884. {
  885. meshopt_IndexAdapter<T> in(NULL, indices, index_count);
  886. return meshopt_analyzeOverdraw(in.data, index_count, vertex_positions, vertex_count, vertex_positions_stride);
  887. }
  888. template <typename T>
  889. inline meshopt_VertexFetchStatistics meshopt_analyzeVertexFetch(const T* indices, size_t index_count, size_t vertex_count, size_t vertex_size)
  890. {
  891. meshopt_IndexAdapter<T> in(NULL, indices, index_count);
  892. return meshopt_analyzeVertexFetch(in.data, index_count, vertex_count, vertex_size);
  893. }
  894. template <typename T>
  895. inline size_t meshopt_buildMeshlets(meshopt_Meshlet* meshlets, unsigned int* meshlet_vertices, unsigned char* meshlet_triangles, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride, size_t max_vertices, size_t max_triangles, float cone_weight)
  896. {
  897. meshopt_IndexAdapter<T> in(NULL, indices, index_count);
  898. return meshopt_buildMeshlets(meshlets, meshlet_vertices, meshlet_triangles, in.data, index_count, vertex_positions, vertex_count, vertex_positions_stride, max_vertices, max_triangles, cone_weight);
  899. }
  900. template <typename T>
  901. inline size_t meshopt_buildMeshletsScan(meshopt_Meshlet* meshlets, unsigned int* meshlet_vertices, unsigned char* meshlet_triangles, const T* indices, size_t index_count, size_t vertex_count, size_t max_vertices, size_t max_triangles)
  902. {
  903. meshopt_IndexAdapter<T> in(NULL, indices, index_count);
  904. return meshopt_buildMeshletsScan(meshlets, meshlet_vertices, meshlet_triangles, in.data, index_count, vertex_count, max_vertices, max_triangles);
  905. }
  906. template <typename T>
  907. inline meshopt_Bounds meshopt_computeClusterBounds(const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride)
  908. {
  909. meshopt_IndexAdapter<T> in(NULL, indices, index_count);
  910. return meshopt_computeClusterBounds(in.data, index_count, vertex_positions, vertex_count, vertex_positions_stride);
  911. }
  912. template <typename T>
  913. inline void meshopt_spatialSortTriangles(T* destination, const T* indices, size_t index_count, const float* vertex_positions, size_t vertex_count, size_t vertex_positions_stride)
  914. {
  915. meshopt_IndexAdapter<T> in(NULL, indices, index_count);
  916. meshopt_IndexAdapter<T> out(destination, NULL, index_count);
  917. meshopt_spatialSortTriangles(out.data, in.data, index_count, vertex_positions, vertex_count, vertex_positions_stride);
  918. }
  919. #endif
  920. /**
  921. * Copyright (c) 2016-2024 Arseny Kapoulkine
  922. *
  923. * Permission is hereby granted, free of charge, to any person
  924. * obtaining a copy of this software and associated documentation
  925. * files (the "Software"), to deal in the Software without
  926. * restriction, including without limitation the rights to use,
  927. * copy, modify, merge, publish, distribute, sublicense, and/or sell
  928. * copies of the Software, and to permit persons to whom the
  929. * Software is furnished to do so, subject to the following
  930. * conditions:
  931. *
  932. * The above copyright notice and this permission notice shall be
  933. * included in all copies or substantial portions of the Software.
  934. *
  935. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  936. * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
  937. * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  938. * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  939. * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  940. * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  941. * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  942. * OTHER DEALINGS IN THE SOFTWARE.
  943. */