Debian Codegraph @

thirdparty/ufbx/ufbx.c

raw symbols SCIP
1 #ifndef UFBX_UFBX_C_INCLUDED
2 #define UFBX_UFBX_C_INCLUDED
3
4 #if defined(UFBX_HEADER_PATH)
5 #include UFBX_HEADER_PATH
6 #else
7 #include "ufbx.h"
8 #endif
9
10 // -- User configuration
11
12 // User configuration:
13 // UFBX_REGRESSION Enable regression mode for development
14 // UFBX_UBSAN Explicitly enable undefined behavior sanitizer workarounds
15 // UFBX_NO_UNALIGNED_LOADS Do not use unaligned loads even when they are supported
16 // UFBX_USE_UNALIGNED_LOADS Forcibly use unaligned loads on unknown platforms
17 // UFBX_USE_SSE Explicitly enable SSE2 support (for x86)
18 // UFBX_HAS_FTELLO Allow ufbx to use `ftello()` to measure file size
19 // UFBX_WASM_32BIT Optimize WASM for 32-bit architectures
20 // UFBX_TRACE Log calls of `ufbxi_check()` for tracing execution
21 // UFBX_LITTLE_ENDIAN=0/1 Explicitly define little/big endian architecture
22 // UFBX_PATH_SEPARATOR='' Specify default platform path separator
23 // UFBX_NO_SSE Do not try to include SSE
24
25 // Dependencies:
26 // UFBX_NO_MALLOC Disable default malloc/realloc/free
27 // UFBX_NO_STDIO Disable stdio FILE API
28 // UFBX_EXTERNAL_MALLOC Link to external ufbx_malloc() interface
29 // UFBX_EXTERNAL_STDIO Link to external ufbx_stdio_() interface
30 // UFBX_EXTERNAL_MATH Link to external <math.h> interface
31 // UFBX_EXTERNAL_STRING Link to external <string.h> interface
32
33 // Freestanding:
34 // UFBX_MATH_PREFIX='ufbx_' Prefix for external <math.h> functions used
35 // UFBX_STRING_PREFIX='ufbx_' Prefix for external <string.h> functions used
36 // UFBX_NO_LIBC Do not include libc (implies UFBX_EXTERNAL_MATH/STRING/MALLOC/STDIO by default)
37 // UFBX_NO_LIBC_TYPES Do not include any libc headers, you must define all types in <stdint.h/stddef.h/etc>
38
39 // Mostly internal for debugging:
40 // UFBX_STATIC_ANALYSIS Enable static analysis augmentation
41 // UFBX_DEBUG_BINARY_SEARCH Force using binary search for debugging
42 // UFBX_EXTENSIVE_THREADING Use threads for small inputs
43 // UFBX_POINTER_SIZE Allow specifying sizeof(void*) as a preprocessor constant
44 // UFBX_MAXIMUM_ALIGNMENT Maximum alignment used for allocation
45
46 #if defined(UFBX_CONFIG_SOURCE)
47 #include UFBX_CONFIG_SOURCE
48 #endif
49
50 // -- Configuration
51
52 #define UFBXI_MAX_NON_ARRAY_VALUES 8
53 #define UFBXI_MAX_NODE_DEPTH 32
54 #define UFBXI_MAX_XML_DEPTH 32
55 #define UFBXI_MAX_SKIP_SIZE 0x40000000
56 #define UFBXI_MAP_MAX_SCAN 32
57 #define UFBXI_KD_FAST_DEPTH 6
58 #define UFBXI_HUGE_MAX_SCAN 16
59 #define UFBXI_MIN_FILE_FORMAT_LOOKAHEAD 32
60 #define UFBXI_FACE_GROUP_HASH_BITS 8
61 #define UFBXI_MIN_THREADED_DEFLATE_BYTES 256
62 #define UFBXI_MIN_THREADED_ASCII_VALUES 64
63 #define UFBXI_GEOMETRY_CACHE_BUFFER_SIZE 512
64
65 #ifndef UFBXI_MAX_NURBS_ORDER
66 #define UFBXI_MAX_NURBS_ORDER 128
67 #endif
68
69 // By default enough to have squares be non-denormal
70 #ifndef UFBX_EPSILON
71 #define UFBX_EPSILON (sizeof(ufbx_real) == sizeof(float) ? \
72 (ufbx_real)1.0842021795674597e-19f : (ufbx_real)1.4916681462400413e-154)
73 #endif
74
75 // -- Feature exclusion
76
77 #if !defined(UFBX_MINIMAL)
78 #if !defined(UFBX_NO_SUBDIVISION)
79 #define UFBXI_FEATURE_SUBDIVISION 1
80 #endif
81 #if !defined(UFBX_NO_TESSELLATION)
82 #define UFBXI_FEATURE_TESSELLATION 1
83 #endif
84 #if !defined(UFBX_NO_GEOMETRY_CACHE)
85 #define UFBXI_FEATURE_GEOMETRY_CACHE 1
86 #endif
87 #if !defined(UFBX_NO_SCENE_EVALUATION)
88 #define UFBXI_FEATURE_SCENE_EVALUATION 1
89 #endif
90 #if !defined(UFBX_NO_SKINNING_EVALUATION)
91 #define UFBXI_FEATURE_SKINNING_EVALUATION 1
92 #endif
93 #if !defined(UFBX_NO_ANIMATION_BAKING)
94 #define UFBXI_FEATURE_ANIMATION_BAKING 1
95 #endif
96 #if !defined(UFBX_NO_TRIANGULATION)
97 #define UFBXI_FEATURE_TRIANGULATION 1
98 #endif
99 #if !defined(UFBX_NO_INDEX_GENERATION)
100 #define UFBXI_FEATURE_INDEX_GENERATION 1
101 #endif
102 #if !defined(UFBX_NO_FORMAT_OBJ)
103 #define UFBXI_FEATURE_FORMAT_OBJ 1
104 #endif
105 #endif
106
107 #if defined(UFBX_DEV)
108 #if !defined(UFBX_NO_ERROR_STACK)
109 #define UFBXI_FEATURE_ERROR_STACK 1
110 #endif
111 #endif
112
113 #if !defined(UFBXI_FEATURE_SUBDIVISION) && defined(UFBX_ENABLE_SUBDIVISION)
114 #define UFBXI_FEATURE_SUBDIVISION 1
115 #endif
116 #if !defined(UFBXI_FEATURE_TESSELLATION) && defined(UFBX_ENABLE_TESSELLATION)
117 #define UFBXI_FEATURE_TESSELLATION 1
118 #endif
119 #if !defined(UFBXI_FEATURE_GEOMETRY_CACHE) && defined(UFBX_ENABLE_GEOMETRY_CACHE)
120 #define UFBXI_FEATURE_GEOMETRY_CACHE 1
121 #endif
122 #if !defined(UFBXI_FEATURE_SCENE_EVALUATION) && defined(UFBX_ENABLE_SCENE_EVALUATION)
123 #define UFBXI_FEATURE_SCENE_EVALUATION 1
124 #endif
125 #if !defined(UFBXI_FEATURE_SKINNING_EVALUATION) && defined(UFBX_ENABLE_SKINNING_EVALUATION)
126 #define UFBXI_FEATURE_SKINNING_EVALUATION 1
127 #endif
128 #if !defined(UFBXI_FEATURE_ANIMATION_BAKING) && defined(UFBX_ENABLE_ANIMATION_BAKING)
129 #define UFBXI_FEATURE_ANIMATION_BAKING 1
130 #endif
131 #if !defined(UFBXI_FEATURE_TRIANGULATION) && defined(UFBX_ENABLE_TRIANGULATION)
132 #define UFBXI_FEATURE_TRIANGULATION 1
133 #endif
134 #if !defined(UFBXI_FEATURE_INDEX_GENERATION) && defined(UFBX_ENABLE_INDEX_GENERATION)
135 #define UFBXI_FEATURE_INDEX_GENERATION 1
136 #endif
137 #if !defined(UFBXI_FEATURE_FORMAT_OBJ) && defined(UFBX_ENABLE_FORMAT_OBJ)
138 #define UFBXI_FEATURE_FORMAT_OBJ 1
139 #endif
140 #if !defined(UFBXI_FEATURE_ERROR_STACK) && defined(UFBX_ENABLE_ERROR_STACK)
141 #define UFBXI_FEATURE_ERROR_STACK 1
142 #endif
143
144 #if !defined(UFBXI_FEATURE_SUBDIVISION)
145 #define UFBXI_FEATURE_SUBDIVISION 0
146 #endif
147 #if !defined(UFBXI_FEATURE_TESSELLATION)
148 #define UFBXI_FEATURE_TESSELLATION 0
149 #endif
150 #if !defined(UFBXI_FEATURE_GEOMETRY_CACHE)
151 #define UFBXI_FEATURE_GEOMETRY_CACHE 0
152 #endif
153 #if !defined(UFBXI_FEATURE_SCENE_EVALUATION)
154 #define UFBXI_FEATURE_SCENE_EVALUATION 0
155 #endif
156 #if !defined(UFBXI_FEATURE_SKINNING_EVALUATION)
157 #define UFBXI_FEATURE_SKINNING_EVALUATION 0
158 #endif
159 #if !defined(UFBXI_FEATURE_ANIMATION_BAKING)
160 #define UFBXI_FEATURE_ANIMATION_BAKING 0
161 #endif
162 #if !defined(UFBXI_FEATURE_TRIANGULATION)
163 #define UFBXI_FEATURE_TRIANGULATION 0
164 #endif
165 #if !defined(UFBXI_FEATURE_INDEX_GENERATION)
166 #define UFBXI_FEATURE_INDEX_GENERATION 0
167 #endif
168 #if !defined(UFBXI_FEATURE_FORMAT_OBJ)
169 #define UFBXI_FEATURE_FORMAT_OBJ 0
170 #endif
171 #if !defined(UFBXI_FEATURE_ERROR_STACK)
172 #define UFBXI_FEATURE_ERROR_STACK 0
173 #endif
174
175 // Derived features
176
177 #if UFBXI_FEATURE_GEOMETRY_CACHE
178 #define UFBXI_FEATURE_XML 1
179 #else
180 #define UFBXI_FEATURE_XML 0
181 #endif
182
183 #if UFBXI_FEATURE_TRIANGULATION
184 #define UFBXI_FEATURE_KD 1
185 #else
186 #define UFBXI_FEATURE_KD 0
187 #endif
188
189 #if !UFBXI_FEATURE_SUBDIVISION || !UFBXI_FEATURE_TESSELLATION || !UFBXI_FEATURE_GEOMETRY_CACHE || !UFBXI_FEATURE_SCENE_EVALUATION || !UFBXI_FEATURE_SKINNING_EVALUATION || !UFBXI_FEATURE_ANIMATION_BAKING || !UFBXI_FEATURE_TRIANGULATION || !UFBXI_FEATURE_INDEX_GENERATION || !UFBXI_FEATURE_XML || !UFBXI_FEATURE_KD || !UFBXI_FEATURE_FORMAT_OBJ
190 #define UFBXI_PARTIAL_FEATURES 1
191 #endif
192
193 // -- Headers
194
195 // Legacy mapping
196 #if !defined(UFBX_EXTERNAL_MATH) && defined(UFBX_NO_MATH_H)
197 #define UFBX_EXTERNAL_MATH
198 #endif
199
200 #if !defined(UFBX_NO_LIBC_TYPES)
201 #include <stdarg.h>
202 #endif
203
204 #if !defined(UFBX_NO_LIBC)
205 #if !defined(UFBX_NO_FLOAT_H)
206 #include <float.h>
207 #endif
208 #if !defined(UFBX_EXTERNAL_MATH)
209 #include <math.h>
210 #endif
211 #if !defined(UFBX_EXTERNAL_STRING)
212 #include <string.h>
213 #endif
214 #if !defined(UFBX_NO_STDIO) && !defined(UFBX_EXTERNAL_STDIO)
215 #include <stdio.h>
216 #endif
217 #if !defined(UFBX_NO_MALLOC) && !defined(UFBX_EXTERNAL_MALLOC)
218 #include <stdlib.h>
219 #endif
220 #else
221 #if !defined(UFBX_EXTERNAL_MATH) && !defined(UFBX_NO_EXTERNAL_MATH)
222 #define UFBX_EXTERNAL_MATH
223 #endif
224 #if !defined(UFBX_EXTERNAL_STRING) && !defined(UFBX_NO_EXTERNAL_STRING)
225 #define UFBX_EXTERNAL_STRING
226 #endif
227 #if !defined(UFBX_EXTERNAL_MALLOC) && !defined(UFBX_NO_EXTERNAL_MALLOC) && !defined(UFBX_NO_MALLOC)
228 #define UFBX_EXTERNAL_MALLOC
229 #endif
230 #if !defined(UFBX_EXTERNAL_STDIO) && !defined(UFBX_NO_EXTERNAL_STDIO) && !defined(UFBX_NO_STDIO)
231 #define UFBX_EXTERNAL_STDIO
232 #endif
233 #endif
234
235 #if defined(UFBX_EXTERNAL_STRING) && !defined(UFBX_STRING_PREFIX)
236 #define UFBX_STRING_PREFIX ufbx_
237 #endif
238
239 #if !defined(UFBX_EXTERNAL_MATH)
240 #if !defined(UFBX_MATH_PREFIX)
241 #define UFBX_MATH_PREFIX
242 #endif
243 #endif
244
245 #define ufbxi_pre_cat2(a, b) a##b
246 #define ufbxi_pre_cat(a, b) ufbxi_pre_cat2(a, b)
247
248 // -- External functions
249
250 #ifndef ufbx_extern_abi
251 #if defined(UFBX_STATIC)
252 #define ufbx_extern_abi static
253 #else
254 #define ufbx_extern_abi
255 #endif
256 #endif
257
258 #if defined(UFBX_MATH_PREFIX)
259 #define ufbxi_math_fn(name) ufbxi_pre_cat(UFBX_MATH_PREFIX, name)
260 #define ufbx_sqrt ufbxi_math_fn(sqrt)
261 #define ufbx_fabs ufbxi_math_fn(fabs)
262 #define ufbx_pow ufbxi_math_fn(pow)
263 #define ufbx_sin ufbxi_math_fn(sin)
264 #define ufbx_cos ufbxi_math_fn(cos)
265 #define ufbx_tan ufbxi_math_fn(tan)
266 #define ufbx_asin ufbxi_math_fn(asin)
267 #define ufbx_acos ufbxi_math_fn(acos)
268 #define ufbx_atan ufbxi_math_fn(atan)
269 #define ufbx_atan2 ufbxi_math_fn(atan2)
270 #define ufbx_copysign ufbxi_math_fn(copysign)
271 #define ufbx_fmin ufbxi_math_fn(fmin)
272 #define ufbx_fmax ufbxi_math_fn(fmax)
273 #define ufbx_nextafter ufbxi_math_fn(nextafter)
274 #define ufbx_rint ufbxi_math_fn(rint)
275 #define ufbx_floor ufbxi_math_fn(floor)
276 #define ufbx_ceil ufbxi_math_fn(ceil)
277 #define ufbx_isnan ufbxi_math_fn(isnan)
278 #endif
279
280 #if !defined(UFBX_NO_EXTERNAL_DEFINES)
281
282 #if defined(__cplusplus)
283 extern "C" {
284 #endif
285
286 #if defined(UFBX_EXTERNAL_MATH)
287 ufbx_extern_abi double ufbx_sqrt(double x);
288 ufbx_extern_abi double ufbx_sin(double x);
289 ufbx_extern_abi double ufbx_cos(double x);
290 ufbx_extern_abi double ufbx_tan(double x);
291 ufbx_extern_abi double ufbx_asin(double x);
292 ufbx_extern_abi double ufbx_acos(double x);
293 ufbx_extern_abi double ufbx_atan(double x);
294 ufbx_extern_abi double ufbx_atan2(double y, double x);
295 ufbx_extern_abi double ufbx_pow(double x, double y);
296 ufbx_extern_abi double ufbx_fmin(double a, double b);
297 ufbx_extern_abi double ufbx_fmax(double a, double b);
298 ufbx_extern_abi double ufbx_fabs(double x);
299 ufbx_extern_abi double ufbx_copysign(double x, double y);
300 ufbx_extern_abi double ufbx_nextafter(double x, double y);
301 ufbx_extern_abi double ufbx_rint(double x);
302 ufbx_extern_abi double ufbx_floor(double x);
303 ufbx_extern_abi double ufbx_ceil(double x);
304 ufbx_extern_abi int ufbx_isnan(double x);
305 #endif
306
307 #if defined(UFBX_EXTERNAL_STRING)
308 ufbx_extern_abi size_t ufbx_strlen(const char *str);
309 ufbx_extern_abi void *ufbx_memcpy(void *dst, const void *src, size_t count);
310 ufbx_extern_abi void *ufbx_memmove(void *dst, const void *src, size_t count);
311 ufbx_extern_abi void *ufbx_memset(void *dst, int ch, size_t count);
312 ufbx_extern_abi const void *ufbx_memchr(const void *ptr, int value, size_t count);
313 ufbx_extern_abi int ufbx_memcmp(const void *a, const void *b, size_t count);
314 ufbx_extern_abi int ufbx_strcmp(const char *a, const char *b);
315 ufbx_extern_abi int ufbx_strncmp(const char *a, const char *b, size_t count);
316 #endif
317
318 #if defined(UFBX_EXTERNAL_MALLOC)
319 ufbx_extern_abi void *ufbx_malloc(size_t size);
320 ufbx_extern_abi void *ufbx_realloc(void *ptr, size_t old_size, size_t new_size);
321 ufbx_extern_abi void ufbx_free(void *ptr, size_t old_size);
322 #endif
323
324 #if defined(UFBX_EXTERNAL_STDIO)
325 ufbx_extern_abi void *ufbx_stdio_open(const char *path, size_t path_len);
326 ufbx_extern_abi size_t ufbx_stdio_read(void *file, void *data, size_t size);
327 ufbx_extern_abi bool ufbx_stdio_skip(void *file, size_t size);
328 ufbx_extern_abi uint64_t ufbx_stdio_size(void *file);
329 ufbx_extern_abi void ufbx_stdio_close(void *file);
330 #endif
331
332 #if defined(__cplusplus)
333 }
334 #endif
335
336 #endif
337
338 #if !defined(UFBX_INFINITY)
339 #if defined(INFINITY)
340 #define UFBX_INFINITY INFINITY
341 #else
342 #define UFBX_INFINITY (1e+300 * 1e+300)
343 #endif
344 #endif
345 #if !defined(UFBX_NAN)
346 #if defined(NAN)
347 #define UFBX_NAN NAN
348 #else
349 #define UFBX_NAN (UFBX_INFINITY * 0.0f)
350 #endif
351 #endif
352 #if !defined(UFBX_FLT_EPSILON)
353 #if defined(FLT_EPSILON)
354 #define UFBX_FLT_EPSILON FLT_EPSILON
355 #else
356 #define UFBX_FLT_EPSILON 1.192092896e-07f
357 #endif
358 #endif
359 #if !defined(UFBX_FLT_EVAL_METHOD)
360 #if defined(FLT_EVAL_METHOD)
361 #define UFBX_FLT_EVAL_METHOD FLT_EVAL_METHOD
362 #elif defined(__FLT_EVAL_METHOD__)
363 #define UFBX_FLT_EVAL_METHOD __FLT_EVAL_METHOD__
364 #elif defined(_MSC_VER) && (defined(_M_X64) || defined(_M_ARM64))
365 #define UFBX_FLT_EVAL_METHOD 0
366 #else
367 #define UFBX_FLT_EVAL_METHOD -1
368 #endif
369 #endif
370
371 #if defined(ufbx_malloc) || defined(ufbx_realloc) || defined(ufbx_free)
372 // User provided allocators
373 #if !defined(ufbx_malloc) || !defined(ufbx_realloc) || !defined(ufbx_free)
374 #error Inconsistent custom global allocator
375 #endif
376 #elif defined(UFBX_NO_MALLOC)
377 #define ufbx_malloc(size) ((void)(size), (void)NULL)
378 #define ufbx_realloc(ptr, old_size, new_size) ((void)(ptr), (void)(old_size), (void)(new_size), (void)NULL)
379 #define ufbx_free(ptr, old_size) ((void)(ptr), (void)(old_size))
380 #elif defined(UFBX_EXTERNAL_MALLOC)
381 // Nop
382 #else
383 #define ufbx_malloc(size) malloc((size))
384 #define ufbx_realloc(ptr, old_size, new_size) realloc((ptr), (new_size))
385 #define ufbx_free(ptr, old_size) free((ptr))
386 #endif
387
388 #if !defined(ufbx_panic_handler)
389 static void ufbxi_panic_handler(const char *message)
390 {
391 (void)message;
392 #if !defined(UFBX_NO_STDIO) && !defined(UFBX_EXTERNAL_STDIO)
393 fprintf(stderr, "ufbx panic: %s\n", message);
394 #endif
395 ufbx_assert(false && "ufbx panic: See stderr for more information");
396 }
397 #define ufbx_panic_handler ufbxi_panic_handler
398 #endif
399
400 // -- Platform
401
402 #if defined(_MSC_VER)
403 #define UFBXI_MSC_VER _MSC_VER
404 #else
405 #define UFBXI_MSC_VER 0
406 #endif
407
408 #if defined(__GNUC__)
409 #define UFBXI_GNUC __GNUC__
410 #define UFBXI_GNUC_VERSION ufbx_pack_version(__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__)
411 #else
412 #define UFBXI_GNUC 0
413 #define UFBXI_GNUC_VERSION 0
414 #endif
415
416 #if !defined(UFBX_STANDARD_C) && defined(_MSC_VER)
417 #define ufbxi_noinline __declspec(noinline)
418 #define ufbxi_forceinline __forceinline
419 #define ufbxi_restrict __restrict
420 #if defined(_Check_return_)
421 #define ufbxi_nodiscard _Check_return_
422 #else
423 #define ufbxi_nodiscard
424 #endif
425 #define ufbxi_unused
426 #define ufbxi_unlikely(cond) (cond)
427 #elif !defined(UFBX_STANDARD_C) && (defined(__GNUC__) || defined(__clang__))
428 #define ufbxi_noinline __attribute__((noinline))
429 #define ufbxi_forceinline inline __attribute__((always_inline))
430 #define ufbxi_restrict __restrict
431 #define ufbxi_nodiscard __attribute__((warn_unused_result))
432 #define ufbxi_unused __attribute__((unused))
433 #define ufbxi_unlikely(cond) __builtin_expect((cond), 0)
434 #else
435 #define ufbxi_noinline
436 #define ufbxi_forceinline
437 #define ufbxi_nodiscard
438 #define ufbxi_restrict
439 #define ufbxi_unused
440 #define ufbxi_unlikely(cond) (cond)
441 #endif
442
443 #if !defined(UFBX_STANDARD_C) && defined(__clang__)
444 #define ufbxi_nounroll _Pragma("clang loop unroll(disable)") _Pragma("clang loop vectorize(disable)")
445 #elif !defined(UFBX_STANDARD_C) && UFBXI_GNUC >= 8
446 #define ufbxi_nounroll _Pragma("GCC unroll 0")
447 #elif !defined(UFBX_STANDARD_C) && defined(_MSC_VER)
448 #define ufbxi_nounroll __pragma(loop(no_vector))
449 #else
450 #define ufbxi_nounroll
451 #endif
452
453 #if defined(__GNUC__) && !defined(__clang__)
454 #define ufbxi_ignore(cond) (void)!(cond)
455 #else
456 #define ufbxi_ignore(cond) (void)(cond)
457 #endif
458
459 #if defined(_MSC_VER)
460 #pragma warning(push)
461 #pragma warning(disable: 4061) // enumerator 'ENUM' in switch of enum 'enum' is not explicitly handled by a case label
462 #pragma warning(disable: 4200) // nonstandard extension used: zero-sized array in struct/union
463 #pragma warning(disable: 4201) // nonstandard extension used: nameless struct/union
464 #pragma warning(disable: 4210) // nonstandard extension used: function given file scope
465 #pragma warning(disable: 4127) // conditional expression is constant
466 #pragma warning(disable: 4706) // assignment within conditional expression
467 #pragma warning(disable: 4789) // buffer 'type_and_name' of size 8 bytes will be overrun; 16 bytes will be written starting at offset 0
468 #pragma warning(disable: 4820) // type': 'N' bytes padding added after data member 'member'
469 #if defined(UFBX_STANDARD_C)
470 #pragma warning(disable: 4996) // 'fopen': This function or variable may be unsafe. Consider using fopen_s instead.
471 #endif
472 #if defined(UFBXI_PARTIAL_FEATURES)
473 #pragma warning(disable: 4100) // 'name': unreferenced formal parameter
474 #pragma warning(disable: 4505) // 'func': unreferenced function with internal linkage has been removed
475 #endif
476 #endif
477
478 #if defined(__clang__)
479 #pragma clang diagnostic push
480 #pragma clang diagnostic ignored "-Wmissing-field-initializers"
481 #pragma clang diagnostic ignored "-Wmissing-braces"
482 #pragma clang diagnostic ignored "-Wdouble-promotion"
483 #pragma clang diagnostic ignored "-Wpedantic"
484 #pragma clang diagnostic ignored "-Wcast-qual"
485 #pragma clang diagnostic ignored "-Wcast-align"
486 #pragma clang diagnostic ignored "-Wcovered-switch-default"
487 #pragma clang diagnostic ignored "-Wpadded"
488 #pragma clang diagnostic ignored "-Wswitch-enum"
489 #pragma clang diagnostic ignored "-Wfloat-equal"
490 #pragma clang diagnostic ignored "-Wformat-nonliteral"
491 #if __has_warning("-Watomic-implicit-seq-cst")
492 #pragma clang diagnostic ignored "-Watomic-implicit-seq-cst"
493 #endif
494 #if defined(UFBX_STANDARD_C)
495 #pragma clang diagnostic ignored "-Wunused-function"
496 #endif
497 #if defined(UFBXI_PARTIAL_FEATURES)
498 #pragma clang diagnostic ignored "-Wunused-function"
499 #pragma clang diagnostic ignored "-Wunused-parameter"
500 #endif
501 #if defined(__cplusplus)
502 #pragma clang diagnostic ignored "-Wold-style-cast"
503 #pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant"
504 #else
505 #pragma clang diagnostic ignored "-Wdeclaration-after-statement"
506 #pragma clang diagnostic ignored "-Wbad-function-cast"
507 #endif
508 #endif
509
510 #if defined(__GNUC__)
511 #pragma GCC diagnostic push
512 #pragma GCC diagnostic ignored "-Wmissing-field-initializers"
513 #pragma GCC diagnostic ignored "-Wmissing-braces"
514 #pragma GCC diagnostic ignored "-Wdouble-promotion"
515 #pragma GCC diagnostic ignored "-Wpedantic"
516 #pragma GCC diagnostic ignored "-Wcast-qual"
517 #pragma GCC diagnostic ignored "-Wcast-align"
518 #pragma GCC diagnostic ignored "-Wpadded"
519 #pragma GCC diagnostic ignored "-Wswitch-enum"
520 #pragma GCC diagnostic ignored "-Wfloat-equal"
521 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
522 #pragma GCC diagnostic ignored "-Wlong-long"
523 #if defined(UFBX_STANDARD_C)
524 #pragma GCC diagnostic ignored "-Wunused-function"
525 #endif
526 #if defined(UFBXI_PARTIAL_FEATURES)
527 #pragma GCC diagnostic ignored "-Wunused-function"
528 #pragma GCC diagnostic ignored "-Wunused-parameter"
529 #endif
530 #if defined(__cplusplus)
531 #pragma GCC diagnostic ignored "-Wold-style-cast"
532 #pragma GCC diagnostic ignored "-Wzero-as-null-pointer-constant"
533 #else
534 #pragma GCC diagnostic ignored "-Wdeclaration-after-statement"
535 #pragma GCC diagnostic ignored "-Wbad-function-cast"
536 #if __GNUC__ >= 5
537 #pragma GCC diagnostic ignored "-Wc90-c99-compat"
538 #pragma GCC diagnostic ignored "-Wc99-c11-compat"
539 #endif
540 #endif
541 // MSC isnan() definition triggers this error on MinGW GCC
542 #if defined(__MINGW32__)
543 #pragma GCC diagnostic ignored "-Wfloat-conversion"
544 #endif
545 // `-Warray-bounds` results in warnings if UBsan is enabled and pre-GCC-14 has no way of detecting it..
546 #if UFBXI_GNUC_VERSION >= ufbx_pack_version(4, 3, 0) && UFBXI_GNUC_VERSION < ufbx_pack_version(14, 0, 0)
547 #pragma GCC diagnostic ignored "-Warray-bounds"
548 #endif
549 #endif
550
551 #if !defined(ufbx_static_assert)
552 #if defined(__cplusplus) && __cplusplus >= 201103
553 #define ufbx_static_assert(desc, cond) static_assert(cond, #desc ": " #cond)
554 #else
555 #define ufbx_static_assert(desc, cond) typedef char ufbxi_static_assert_##desc[(cond)?1:-1]
556 #endif
557 #endif
558
559 #if defined(__has_feature)
560 #if __has_feature(undefined_behavior_sanitizer) && !defined(UFBX_UBSAN)
561 #define UFBX_UBSAN 1
562 #endif
563 #endif
564
565 #if defined(__SANITIZE_UNDEFINED__) && !defined(UFBX_UBSAN)
566 #define UFBX_UBSAN 1
567 #endif
568
569 // Don't use unaligned loads with UB-sanitizer
570 #if defined(UFBX_UBSAN) && !defined(UFBX_NO_UNALIGNED_LOADS)
571 #define UFBX_NO_UNALIGNED_LOADS
572 #endif
573
574 #if defined(__clang_analyzer__) && !defined(UFBX_STATIC_ANALYSIS)
575 #define UFBX_STATIC_ANALYSIS 1
576 #endif
577
578 #if defined(UFBX_STATIC_ANALYSIS)
579 bool ufbxi_analysis_opaque;
580 #define ufbxi_maybe_null(ptr) (ufbxi_analysis_opaque ? (ptr) : NULL)
581 #define ufbxi_analysis_assert(cond) ufbx_assert(cond)
582 #else
583 #define ufbxi_maybe_null(ptr) (ptr)
584 #define ufbxi_analysis_assert(cond) (void)0
585 #endif
586
587 #if defined(UFBX_STATIC_ANALYSIS) || defined(UFBX_UBSAN)
588 #define ufbxi_maybe_uninit(cond, value, def) ((cond) ? (value) : (def))
589 #else
590 #define ufbxi_maybe_uninit(cond, value, def) (value)
591 #endif
592
593 #if !defined(ufbxi_trace)
594 #if defined(UFBX_TRACE)
595 #define ufbxi_trace(desc) (fprintf(stderr, "ufbx trace: %s:%d: %s\n", __FILE__, __LINE__, #desc), fflush(stderr), desc)
596 #else
597 #define ufbxi_trace(desc) (desc)
598 #endif
599 #endif
600
601 #ifndef UFBX_PATH_SEPARATOR
602 #if defined(_WIN32)
603 #define UFBX_PATH_SEPARATOR '\\'
604 #else
605 #define UFBX_PATH_SEPARATOR '/'
606 #endif
607 #endif
608
609 #if !defined(UFBX_STANDARD_C) && defined(_POSIX_C_SOURCE)
610 #if _POSIX_C_SOURCE >= 200112l
611 #ifndef UFBX_HAS_FTELLO
612 #define UFBX_HAS_FTELLO
613 #endif
614 #endif
615 #endif
616
617 #if !defined(UFBX_STANDARD_C) && ((defined(_MSC_VER) && defined(_M_X64) && !defined(_M_ARM64EC)) || ((defined(__GNUC__) || defined(__clang__)) && defined(__x86_64__)))
618 #define UFBXI_ARCH_X64 1
619 #else
620 #define UFBXI_ARCH_X64 0
621 #endif
622
623 #if defined(UFBX_USE_SSE) || (!defined(UFBX_STANDARD_C) && !defined(UFBX_NO_SSE) && UFBXI_ARCH_X64)
624 #define UFBXI_HAS_SSE 1
625 #include <xmmintrin.h>
626 #include <emmintrin.h>
627 #else
628 #define UFBXI_HAS_SSE 0
629 #endif
630
631 // -- Atomic counter
632
633 #define UFBXI_THREAD_SAFE 1
634
635 #if defined(__cplusplus)
636 #define ufbxi_extern_c extern "C"
637 #else
638 #define ufbxi_extern_c
639 #endif
640
641 #if !defined(UFBX_STANDARD_C) && (defined(__GNUC__) || defined(__clang__) || defined(__INTEL_COMPILER))
642 typedef size_t ufbxi_atomic_counter;
643 #define ufbxi_atomic_counter_init(ptr) (*(ptr) = 0)
644 #define ufbxi_atomic_counter_free(ptr) (*(ptr) = 0)
645 #define ufbxi_atomic_counter_inc(ptr) __sync_fetch_and_add((ptr), 1)
646 #define ufbxi_atomic_counter_dec(ptr) __sync_fetch_and_sub((ptr), 1)
647 #define ufbxi_atomic_counter_load(ptr) __sync_fetch_and_add((ptr), 0) // TODO: Proper atomic load
648 #elif !defined(UFBX_STANDARD_C) && defined(_MSC_VER)
649 #if defined(_M_X64) || defined(_M_ARM64)
650 ufbxi_extern_c __int64 _InterlockedIncrement64(__int64 volatile * lpAddend);
651 ufbxi_extern_c __int64 _InterlockedDecrement64(__int64 volatile * lpAddend);
652 ufbxi_extern_c __int64 _InterlockedExchangeAdd64(__int64 volatile * lpAddend, __int64 Value);
653 typedef volatile __int64 ufbxi_atomic_counter;
654 #define ufbxi_atomic_counter_init(ptr) (*(ptr) = 0)
655 #define ufbxi_atomic_counter_free(ptr) (*(ptr) = 0)
656 #define ufbxi_atomic_counter_inc(ptr) ((size_t)_InterlockedIncrement64(ptr) - 1)
657 #define ufbxi_atomic_counter_dec(ptr) ((size_t)_InterlockedDecrement64(ptr) + 1)
658 #define ufbxi_atomic_counter_load(ptr) ((size_t)_InterlockedExchangeAdd64((ptr), 0))
659 #else
660 ufbxi_extern_c long __cdecl _InterlockedIncrement(long volatile * lpAddend);
661 ufbxi_extern_c long __cdecl _InterlockedDecrement(long volatile * lpAddend);
662 ufbxi_extern_c long __cdecl _InterlockedExchangeAdd(long volatile * lpAddend, long Value);
663 typedef volatile long ufbxi_atomic_counter;
664 #define ufbxi_atomic_counter_init(ptr) (*(ptr) = 0)
665 #define ufbxi_atomic_counter_free(ptr) (*(ptr) = 0)
666 #define ufbxi_atomic_counter_inc(ptr) ((size_t)_InterlockedIncrement(ptr) - 1)
667 #define ufbxi_atomic_counter_dec(ptr) ((size_t)_InterlockedDecrement(ptr) + 1)
668 #define ufbxi_atomic_counter_load(ptr) ((size_t)_InterlockedExchangeAdd((ptr), 0))
669 #endif
670 #elif !defined(UFBX_STANDARD_C) && defined(__TINYC__)
671 #if defined(__x86_64__) || defined(_AMD64_)
672 static size_t ufbxi_tcc_atomic_add(volatile size_t *dst, size_t value) {
673 __asm__ __volatile__("lock; xaddq %0, %1;" : "+r" (value), "=m" (*dst) : "m" (dst));
674 return value;
675 }
676 #elif defined(__i386__) || defined(_X86_)
677 static size_t ufbxi_tcc_atomic_add(volatile size_t *dst, size_t value) {
678 __asm__ __volatile__("lock; xaddl %0, %1;" : "+r" (value), "=m" (*dst) : "m" (dst));
679 return value;
680 }
681 #else
682 #error Unexpected TCC architecture
683 #endif
684 typedef volatile size_t ufbxi_atomic_counter;
685 #define ufbxi_atomic_counter_init(ptr) (*(ptr) = 0)
686 #define ufbxi_atomic_counter_free(ptr) (*(ptr) = 0)
687 #define ufbxi_atomic_counter_inc(ptr) ufbxi_tcc_atomic_add((ptr), 1)
688 #define ufbxi_atomic_counter_dec(ptr) ufbxi_tcc_atomic_add((ptr), SIZE_MAX)
689 #define ufbxi_atomic_counter_load(ptr) ufbxi_tcc_atomic_add((ptr), 0)
690 #elif defined(__cplusplus) && (__cplusplus >= 201103L)
691 #include <new>
692 #include <atomic>
693 typedef struct { alignas(std::atomic_size_t) char data[sizeof(std::atomic_size_t)]; } ufbxi_atomic_counter;
694 #define ufbxi_atomic_counter_init(ptr) (new (&(ptr)->data) std::atomic_size_t(0))
695 #define ufbxi_atomic_counter_free(ptr) (((std::atomic_size_t*)(ptr)->data)->~atomic())
696 #define ufbxi_atomic_counter_inc(ptr) ((std::atomic_size_t*)(ptr)->data)->fetch_add(1)
697 #define ufbxi_atomic_counter_dec(ptr) ((std::atomic_size_t*)(ptr)->data)->fetch_sub(1)
698 #define ufbxi_atomic_counter_load(ptr) ((std::atomic_size_t*)(ptr)->data)->load(std::memory_order_acquire)
699 #elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L) && !defined(__STDC_NO_ATOMICS__)
700 #include <stdatomic.h>
701 typedef volatile atomic_size_t ufbxi_atomic_counter;
702 #define ufbxi_atomic_counter_init(ptr) atomic_init(ptr, 0)
703 #define ufbxi_atomic_counter_free(ptr) (void)(ptr)
704 #define ufbxi_atomic_counter_inc(ptr) atomic_fetch_add((ptr), 1)
705 #define ufbxi_atomic_counter_dec(ptr) atomic_fetch_sub((ptr), 1)
706 #define ufbxi_atomic_counter_load(ptr) atomic_load_explicit((ptr), memory_order_acquire)
707 #else
708 typedef volatile size_t ufbxi_atomic_counter;
709 #define ufbxi_atomic_counter_init(ptr) (*(ptr) = 0)
710 #define ufbxi_atomic_counter_free(ptr) (*(ptr) = 0)
711 #define ufbxi_atomic_counter_inc(ptr) ((*(ptr))++)
712 #define ufbxi_atomic_counter_dec(ptr) ((*(ptr))--)
713 #define ufbxi_atomic_counter_load(ptr) (*(ptr))
714 #undef UFBXI_THREAD_SAFE
715 #define UFBXI_THREAD_SAFE 0
716 #endif
717
718 // ^^ No references to <string.h> before this point ^^
719 // vv No more includes past this point vv
720
721 #if defined(UFBX_STRING_PREFIX)
722 #define ufbxi_string_fn(name) ufbxi_pre_cat(UFBX_STRING_PREFIX, name)
723 #define strlen ufbxi_string_fn(strlen)
724 #define memcpy ufbxi_string_fn(memcpy)
725 #define memmove ufbxi_string_fn(memmove)
726 #define memset ufbxi_string_fn(memset)
727 #define memchr ufbxi_string_fn(memchr)
728 #define memcmp ufbxi_string_fn(memcmp)
729 #define strcmp ufbxi_string_fn(strcmp)
730 #define strncmp ufbxi_string_fn(strncmp)
731 #endif
732
733 #if !defined(UFBX_LITTLE_ENDIAN)
734 #if !defined(UFBX_STANDARD_C) && (defined(_M_IX86) || defined(__i386__) || defined(_M_X64) || defined(__x86_64__) || defined(_M_ARM64) || defined(__aarch64__) || defined(__wasm__) || defined(__EMSCRIPTEN__))
735 #define UFBX_LITTLE_ENDIAN 1
736 #else
737 #define UFBX_LITTLE_ENDIAN 0
738 #endif
739 #endif
740
741 // Unaligned little-endian load functions
742 // On platforms that support unaligned access natively (x86, x64, ARM64) just use normal loads,
743 // with unaligned attributes, otherwise do manual byte-wise load.
744
745 #define ufbxi_read_u8(ptr) (*(const uint8_t*)(ptr))
746
747 // Detect support for `__attribute__((aligned(1)))`
748 #if !defined(UFBX_STANDARD_C) && (defined(__clang__) && defined(__APPLE__))
749 // Apple overrides Clang versioning, 5.0 here maps to 3.3
750 #if __clang_major__ >= 5
751 #define UFBXI_HAS_ATTRIBUTE_ALIGNED 1
752 #endif
753 #elif !defined(UFBX_STANDARD_C) && defined(__clang__)
754 #if (__clang_major__ >= 4) || (__clang_major__ == 3 && __clang_minor__ >= 3)
755 #define UFBXI_HAS_ATTRIBUTE_ALIGNED 1
756 #endif
757 #elif !defined(UFBX_STANDARD_C) && defined(__GNUC__)
758 #if __GNUC__ >= 5
759 #define UFBXI_HAS_ATTRIBUTE_ALIGNED 1
760 #endif
761 #endif
762
763 #if defined(UFBXI_HAS_ATTRIBUTE_ALIGNED)
764 #define UFBXI_HAS_UNALIGNED 1
765 #define UFBXI_HAS_ALIASING 1
766 #define ufbxi_unaligned
767 typedef uint16_t __attribute__((aligned(1))) ufbxi_unaligned_u16;
768 typedef uint32_t __attribute__((aligned(1))) ufbxi_unaligned_u32;
769 typedef uint64_t __attribute__((aligned(1))) ufbxi_unaligned_u64;
770 typedef float __attribute__((aligned(1))) ufbxi_unaligned_f32;
771 typedef double __attribute__((aligned(1))) ufbxi_unaligned_f64;
772 typedef uint32_t __attribute__((may_alias)) ufbxi_aliasing_u32;
773 #elif !defined(UFBX_STANDARD_C) && defined(_MSC_VER)
774 #define UFBXI_HAS_UNALIGNED 1
775 #if defined(_M_IX86)
776 // MSVC seems to assume all pointers are unaligned for x86
777 #define ufbxi_unaligned
778 #else
779 #define ufbxi_unaligned __unaligned
780 #endif
781 typedef uint16_t ufbxi_unaligned_u16;
782 typedef uint32_t ufbxi_unaligned_u32;
783 typedef uint64_t ufbxi_unaligned_u64;
784 typedef float ufbxi_unaligned_f32;
785 typedef double ufbxi_unaligned_f64;
786 // MSVC doesn't have aliasing types in theory, but it works in practice..
787 #define UFBXI_HAS_ALIASING 1
788 typedef uint32_t ufbxi_aliasing_u32;
789 #endif
790
791 #if (defined(UFBXI_HAS_UNALIGNED) && UFBX_LITTLE_ENDIAN && !defined(UFBX_NO_UNALIGNED_LOADS)) || defined(UFBX_USE_UNALIGNED_LOADS)
792 #define ufbxi_read_u16(ptr) (*(const ufbxi_unaligned ufbxi_unaligned_u16*)(ptr))
793 #define ufbxi_read_u32(ptr) (*(const ufbxi_unaligned ufbxi_unaligned_u32*)(ptr))
794 #define ufbxi_read_u64(ptr) (*(const ufbxi_unaligned ufbxi_unaligned_u64*)(ptr))
795 #define ufbxi_read_f32(ptr) (*(const ufbxi_unaligned ufbxi_unaligned_f32*)(ptr))
796 #define ufbxi_read_f64(ptr) (*(const ufbxi_unaligned ufbxi_unaligned_f64*)(ptr))
797 #else
798 static ufbxi_forceinline uint16_t ufbxi_read_u16(const void *ptr) {
799 const char *p = (const char*)ptr;
800 return (uint16_t)(
801 (unsigned)(uint8_t)p[0] << 0u |
802 (unsigned)(uint8_t)p[1] << 8u );
803 }
804 static ufbxi_forceinline uint32_t ufbxi_read_u32(const void *ptr) {
805 const char *p = (const char*)ptr;
806 return (uint32_t)(
807 (unsigned)(uint8_t)p[0] << 0u |
808 (unsigned)(uint8_t)p[1] << 8u |
809 (unsigned)(uint8_t)p[2] << 16u |
810 (unsigned)(uint8_t)p[3] << 24u );
811 }
812 static ufbxi_forceinline uint64_t ufbxi_read_u64(const void *ptr) {
813 const char *p = (const char*)ptr;
814 return (uint64_t)(
815 (uint64_t)(uint8_t)p[0] << 0u |
816 (uint64_t)(uint8_t)p[1] << 8u |
817 (uint64_t)(uint8_t)p[2] << 16u |
818 (uint64_t)(uint8_t)p[3] << 24u |
819 (uint64_t)(uint8_t)p[4] << 32u |
820 (uint64_t)(uint8_t)p[5] << 40u |
821 (uint64_t)(uint8_t)p[6] << 48u |
822 (uint64_t)(uint8_t)p[7] << 56u );
823 }
824 static ufbxi_forceinline float ufbxi_read_f32(const void *ptr) {
825 uint32_t u = ufbxi_read_u32(ptr);
826 float f;
827 memcpy(&f, &u, 4);
828 return f;
829 }
830 static ufbxi_forceinline double ufbxi_read_f64(const void *ptr) {
831 uint64_t u = ufbxi_read_u64(ptr);
832 double f;
833 memcpy(&f, &u, 8);
834 return f;
835 }
836 #endif
837
838 #define ufbxi_read_i8(ptr) (int8_t)(ufbxi_read_u8(ptr))
839 #define ufbxi_read_i16(ptr) (int16_t)(ufbxi_read_u16(ptr))
840 #define ufbxi_read_i32(ptr) (int32_t)(ufbxi_read_u32(ptr))
841 #define ufbxi_read_i64(ptr) (int64_t)(ufbxi_read_u64(ptr))
842
843 ufbx_static_assert(sizeof_bool, sizeof(bool) == 1);
844 ufbx_static_assert(sizeof_char, sizeof(char) == 1);
845 ufbx_static_assert(sizeof_i8, sizeof(int8_t) == 1);
846 ufbx_static_assert(sizeof_i16, sizeof(int16_t) == 2);
847 ufbx_static_assert(sizeof_i32, sizeof(int32_t) == 4);
848 ufbx_static_assert(sizeof_i64, sizeof(int64_t) == 8);
849 ufbx_static_assert(sizeof_u8, sizeof(uint8_t) == 1);
850 ufbx_static_assert(sizeof_u16, sizeof(uint16_t) == 2);
851 ufbx_static_assert(sizeof_u32, sizeof(uint32_t) == 4);
852 ufbx_static_assert(sizeof_u64, sizeof(uint64_t) == 8);
853 ufbx_static_assert(sizeof_f32, sizeof(float) == 4);
854 ufbx_static_assert(sizeof_f64, sizeof(double) == 8);
855
856 // -- Alignment
857
858 #ifndef UFBX_MAXIMUM_ALIGNMENT
859 enum { UFBX_MAXIMUM_ALIGNMENT = sizeof(void*) > 8 ? sizeof(void*) : 8 };
860 #endif
861
862 #if !defined(UFBX_POINTER_SIZE) && !defined(UFBX_STANDARD_C)
863 #if (defined(_M_X64) || defined(__x86_64__) || defined(_M_ARM64) || defined(__aarch64__)) && !defined(__CHERI__)
864 #define UFBX_POINTER_SIZE 8
865 #elif defined(__wasm__) || defined(__EMSCRIPTEN__)
866 #define UFBX_POINTER_SIZE 4
867 #endif
868 #endif
869 #if defined(UFBX_POINTER_SIZE)
870 ufbx_static_assert(pointer_size, UFBX_POINTER_SIZE == sizeof(void*));
871 #else
872 #define UFBX_POINTER_SIZE 0
873 #endif
874
875 // -- Version
876
877 #define UFBX_SOURCE_VERSION ufbx_pack_version(0, 20, 0)
878 ufbx_abi_data_def const uint32_t ufbx_source_version = UFBX_SOURCE_VERSION;
879
880 ufbx_static_assert(source_header_version, UFBX_SOURCE_VERSION/1000u == UFBX_HEADER_VERSION/1000u);
881
882 // -- Fast copy
883
884 #if UFBXI_HAS_SSE
885 #define ufbxi_copy_16_bytes(dst, src) _mm_storeu_si128((__m128i*)(dst), _mm_loadu_si128((const __m128i*)(src)))
886 #elif defined(UFBXI_HAS_UNALIGNED)
887 #define ufbxi_copy_16_bytes(dst, src) do { \
888 ufbxi_unaligned ufbxi_unaligned_u64 *mi_dst = (ufbxi_unaligned ufbxi_unaligned_u64 *)(dst); \
889 const ufbxi_unaligned ufbxi_unaligned_u64 *mi_src = (const ufbxi_unaligned ufbxi_unaligned_u64 *)src; \
890 mi_dst[0] = mi_src[0]; \
891 mi_dst[1] = mi_src[1]; \
892 } while (0)
893 #else
894 #define ufbxi_copy_16_bytes(dst, src) memcpy((dst), (src), 16)
895 #endif
896
897
898 // -- Large fast integer
899
900 #if !defined(UFBX_STANDARD_C) && (defined(__wasm__) || defined(__EMSCRIPTEN__)) && !defined(UFBX_WASM_32BIT)
901 typedef uint64_t ufbxi_fast_uint;
902 #else
903 typedef size_t ufbxi_fast_uint;
904 #endif
905
906 // -- Wrapping right shift
907
908 #if !defined(UFBX_UBSAN) && UFBXI_ARCH_X64
909 #define ufbxi_wrap_shr64(a, b) ((a) >> (b))
910 #else
911 #define ufbxi_wrap_shr64(a, b) ((a) >> ((b) & 63))
912 #endif
913
914 // -- Bit manipulation
915
916 #if !defined(UFBX_STANDARD_C) && defined(_MSC_VER) && (defined(_M_X64) || defined(_M_IX86))
917 ufbxi_extern_c unsigned char _BitScanReverse(unsigned long * _Index, unsigned long _Mask);
918 ufbxi_extern_c unsigned char _BitScanReverse64(unsigned long * _Index, unsigned __int64 _Mask);
919 static ufbxi_forceinline ufbxi_unused uint32_t ufbxi_lzcnt32(uint32_t v) {
920 unsigned long index;
921 _BitScanReverse(&index, (unsigned long)v);
922 return 31 - (uint32_t)index;
923 }
924 static ufbxi_forceinline ufbxi_unused uint32_t ufbxi_lzcnt64(uint64_t v) {
925 unsigned long index;
926 #if defined(_M_X64)
927 _BitScanReverse64(&index, (unsigned __int64)v);
928 #else
929 uint32_t hi = (uint32_t)(v >> 32u);
930 uint32_t hi_nonzero = hi != 0 ? 1 : 0;
931 uint32_t part = hi_nonzero ? hi : (uint32_t)v;
932 _BitScanReverse(&index, (unsigned long)part);
933 index += hi_nonzero * 32u;
934 #endif
935 return 63 - (uint32_t)index;
936 }
937 #elif !defined(UFBX_STANDARD_C) && (defined(__GNUC__) || defined(__clang__))
938 #define ufbxi_lzcnt32(v) ((uint32_t)__builtin_clz((unsigned)(v)))
939 #define ufbxi_lzcnt64(v) ((uint32_t)__builtin_clzll((unsigned long long)(v)))
940 #else
941 // DeBrujin table lookup
942 static const uint8_t ufbxi_lzcnt32_table[] = {
943 31, 22, 30, 21, 18, 10, 29, 2, 20, 17, 15, 13, 9, 6, 28, 1, 23, 19, 11, 3, 16, 14, 7, 24, 12, 4, 8, 25, 5, 26, 27, 0,
944 };
945 static const uint8_t ufbxi_lzcnt64_table[] = {
946 63, 16, 62, 7, 15, 36, 61, 3, 6, 14, 22, 26, 35, 47, 60, 2, 9, 5, 28, 11, 13, 21, 42,
947 19, 25, 31, 34, 40, 46, 52, 59, 1, 17, 8, 37, 4, 23, 27, 48, 10, 29, 12, 43, 20, 32, 41,
948 53, 18, 38, 24, 49, 30, 44, 33, 54, 39, 50, 45, 55, 51, 56, 57, 58, 0,
949 };
950 static ufbxi_noinline ufbxi_unused uint32_t ufbxi_lzcnt32(uint32_t v) {
951 v |= v >> 1;
952 v |= v >> 2;
953 v |= v >> 4;
954 v |= v >> 8;
955 v |= v >> 16;
956 return ufbxi_lzcnt32_table[(v * 0x07c4acddu) >> 27];
957 }
958 static ufbxi_noinline ufbxi_unused uint32_t ufbxi_lzcnt64(uint64_t v) {
959 v |= v >> 1;
960 v |= v >> 2;
961 v |= v >> 4;
962 v |= v >> 8;
963 v |= v >> 16;
964 v |= v >> 32;
965 return ufbxi_lzcnt64_table[(v * UINT64_C(0x03f79d71b4cb0a89)) >> 58];
966 }
967 #endif
968
969 // -- Bit conversion
970
971 #if defined(__cplusplus)
972 #define ufbxi_bit_cast(m_dst_type, m_dst, m_src_type, m_src) memcpy(&(m_dst), &(m_src), sizeof(m_dst_type))
973 #else
974 #define ufbxi_bit_cast(m_dst_type, m_dst, m_src_type, m_src) do { \
975 union { m_dst_type mi_dst; m_src_type mi_src; } mi_union; \
976 mi_union.mi_src = (m_src); (m_dst) = mi_union.mi_dst; } while (0)
977 #endif
978
979 // -- Pointer alignment
980
981 #if !defined(UFBX_STANDARD_C) && defined(__GNUC__) && defined(__has_builtin)
982 #if __has_builtin(__builtin_is_aligned)
983 #define ufbxi_is_aligned(m_ptr, m_align) __builtin_is_aligned((m_ptr), (m_align))
984 #define ufbxi_is_aligned_mask(m_ptr, m_align) __builtin_is_aligned((m_ptr), (m_align) + 1)
985 #endif
986 #endif
987 #ifndef ufbxi_is_aligned
988 #define ufbxi_is_aligned(m_ptr, m_align) (((uintptr_t)(m_ptr) & ((m_align) - 1)) == 0)
989 #define ufbxi_is_aligned_mask(m_ptr, m_align) (((uintptr_t)(m_ptr) & (m_align)) == 0)
990 #endif
991
992 // -- Debug
993
994 #if defined(UFBX_DEBUG_BINARY_SEARCH) || defined(UFBX_REGRESSION)
995 #define ufbxi_clamp_linear_threshold(v) (2)
996 #else
997 #define ufbxi_clamp_linear_threshold(v) (v)
998 #endif
999
1000 #if defined(UFBX_REGRESSION)
1001 #undef UFBXI_MAX_SKIP_SIZE
1002 #define UFBXI_MAX_SKIP_SIZE 128
1003
1004 #undef UFBXI_MAP_MAX_SCAN
1005 #define UFBXI_MAP_MAX_SCAN 2
1006
1007 #undef UFBXI_KD_FAST_DEPTH
1008 #define UFBXI_KD_FAST_DEPTH 2
1009
1010 #undef UFBXI_FACE_GROUP_HASH_BITS
1011 #define UFBXI_FACE_GROUP_HASH_BITS 2
1012 #endif
1013
1014 #if defined(UFBX_REGRESSION) || defined(UFBX_EXTENSIVE_THREADING)
1015 #undef UFBXI_MIN_THREADED_DEFLATE_BYTES
1016 #define UFBXI_MIN_THREADED_DEFLATE_BYTES 2
1017
1018 #undef UFBXI_MIN_THREADED_ASCII_VALUES
1019 #define UFBXI_MIN_THREADED_ASCII_VALUES 2
1020 #endif
1021
1022 #if defined(UFBX_REGRESSION)
1023 #define ufbxi_regression_assert(cond) ufbx_assert(cond)
1024 #else
1025 #define ufbxi_regression_assert(cond) (void)0
1026 #endif
1027
1028 #if defined(UFBX_REGRESSION) || defined(UFBX_DEV) || defined(UFBX_UBSAN)
1029 #define ufbxi_dev_assert(cond) ufbx_assert(cond)
1030 #else
1031 #define ufbxi_dev_assert(cond) (void)0
1032 #endif
1033
1034 #define ufbxi_unreachable(reason) do { ufbx_assert(0 && reason); } while (0)
1035
1036 #if defined(UFBX_REGRESSION)
1037 #define UFBXI_IS_REGRESSION 1
1038 #else
1039 #define UFBXI_IS_REGRESSION 0
1040 #endif
1041
1042 #if defined(_MSC_VER)
1043 #define ufbxi_thread_local __declspec(thread)
1044 #elif defined(__GNUC__) || defined(__clang__)
1045 #define ufbxi_thread_local __thread
1046 #elif UFBXI_HAS_CPP11
1047 #define ufbxi_thread_local thread_local
1048 #elif UFBX_STDC >= 201112L
1049 #define ufbxi_thread_local _Thread_local
1050 #endif
1051
1052 #if defined(UFBXI_ANALYSIS_RECURSIVE)
1053 #define ufbxi_recursive_function(m_ret, m_name, m_args, m_max_depth, m_params) UFBXI_RECURSIVE_FUNCTION(m_name, m_max_depth);
1054 #define ufbxi_recursive_function_void(m_name, m_args, m_max_depth, m_params) UFBXI_RECURSIVE_FUNCTION(m_name, m_max_depth);
1055 #elif UFBXI_IS_REGRESSION && defined(ufbxi_thread_local)
1056 #define ufbxi_recursive_function(m_ret, m_name, m_args, m_max_depth, m_params) \
1057 { \
1058 m_ret m_name##_rec m_params; \
1059 static ufbxi_thread_local unsigned ufbxi_recursion_depth; \
1060 ufbx_assert(ufbxi_recursion_depth < m_max_depth); \
1061 ++ufbxi_recursion_depth; \
1062 m_ret ret = m_name##_rec m_args; \
1063 --ufbxi_recursion_depth; \
1064 return ret; \
1065 } \
1066 m_ret m_name##_rec m_params
1067 #define ufbxi_recursive_function_void(m_name, m_args, m_max_depth, m_params) \
1068 { \
1069 void m_name##_rec m_params; \
1070 static ufbxi_thread_local unsigned ufbxi_recursion_depth; \
1071 ufbx_assert(ufbxi_recursion_depth < m_max_depth); \
1072 ++ufbxi_recursion_depth; \
1073 m_name##_rec m_args; \
1074 --ufbxi_recursion_depth; \
1075 } \
1076 void m_name##_rec m_params
1077 #else
1078 #define ufbxi_recursive_function(m_ret, m_name, m_args, m_max_depth, m_params)
1079 #define ufbxi_recursive_function_void(m_name, m_args, m_max_depth, m_params)
1080 #endif
1081
1082 // -- Utility
1083
1084 #if defined(UFBX_UBSAN)
1085 static void ufbxi_assert_zero(size_t offset) { ufbx_assert(offset == 0); }
1086 #define ufbxi_add_ptr(ptr, offset) ((ptr) ? (ptr) + (offset) : (ufbxi_assert_zero((size_t)(offset)), (ptr)))
1087 #define ufbxi_sub_ptr(ptr, offset) ((ptr) ? (ptr) - (offset) : (ufbxi_assert_zero((size_t)(offset)), (ptr)))
1088 #else
1089 #define ufbxi_add_ptr(ptr, offset) ((ptr) + (offset))
1090 #define ufbxi_sub_ptr(ptr, offset) ((ptr) - (offset))
1091 #endif
1092
1093 #define ufbxi_arraycount(arr) (sizeof(arr) / sizeof(*(arr)))
1094 #define ufbxi_for(m_type, m_name, m_begin, m_num) for (m_type *m_name = m_begin, *m_name##_end = ufbxi_add_ptr(m_name, m_num); m_name != m_name##_end; m_name++)
1095 #define ufbxi_for_ptr(m_type, m_name, m_begin, m_num) for (m_type **m_name = m_begin, **m_name##_end = ufbxi_add_ptr(m_name, m_num); m_name != m_name##_end; m_name++)
1096
1097 // WARNING: Evaluates `m_list` twice!
1098 #define ufbxi_for_list(m_type, m_name, m_list) for (m_type *m_name = (m_list).data, *m_name##_end = ufbxi_add_ptr(m_name, (m_list).count); m_name != m_name##_end; m_name++)
1099 #define ufbxi_for_ptr_list(m_type, m_name, m_list) for (m_type **m_name = (m_list).data, **m_name##_end = ufbxi_add_ptr(m_name, (m_list).count); m_name != m_name##_end; m_name++)
1100
1101 #define ufbxi_string_literal(str) { str, sizeof(str) - 1 }
1102
1103 static ufbxi_forceinline uint32_t ufbxi_min32(uint32_t a, uint32_t b) { return a < b ? a : b; }
1104 static ufbxi_forceinline uint32_t ufbxi_max32(uint32_t a, uint32_t b) { return a < b ? b : a; }
1105 static ufbxi_forceinline uint64_t ufbxi_min64(uint64_t a, uint64_t b) { return a < b ? a : b; }
1106 static ufbxi_forceinline uint64_t ufbxi_max64(uint64_t a, uint64_t b) { return a < b ? b : a; }
1107 static ufbxi_forceinline size_t ufbxi_min_sz(size_t a, size_t b) { return a < b ? a : b; }
1108 static ufbxi_forceinline size_t ufbxi_max_sz(size_t a, size_t b) { return a < b ? b : a; }
1109 static ufbxi_forceinline ufbx_real ufbxi_min_real(ufbx_real a, ufbx_real b) { return a < b ? a : b; }
1110 static ufbxi_forceinline ufbx_real ufbxi_max_real(ufbx_real a, ufbx_real b) { return a < b ? b : a; }
1111
1112 static ufbxi_forceinline int32_t ufbxi_f64_to_i32(double value)
1113 {
1114 if (ufbx_fabs(value) <= (double)INT32_MAX) {
1115 return (int32_t)value;
1116 } else {
1117 return value >= 0.0 ? INT32_MAX : INT32_MIN;
1118 }
1119 }
1120
1121 static ufbxi_forceinline int64_t ufbxi_f64_to_i64(double value)
1122 {
1123 if (ufbx_fabs(value) <= (double)INT64_MAX) {
1124 return (int64_t)value;
1125 } else {
1126 return value >= 0.0 ? INT64_MAX : INT64_MIN;
1127 }
1128 }
1129
1130 #if defined(UFBX_REGRESSION)
1131 static size_t ufbxi_to_size(ptrdiff_t delta) {
1132 ufbx_assert(delta >= 0);
1133 return (size_t)delta;
1134 }
1135 #else
1136 #define ufbxi_to_size(delta) ((size_t)(delta))
1137 #endif
1138
1139 // Stable sort array `m_type m_data[m_size]` using the predicate `m_cmp_lambda(a, b)`
1140 // `m_linear_size` is a hint for how large blocks handle initially do with insertion sort
1141 // `m_tmp` must be a memory buffer with at least the same size and alignment as `m_data`
1142 #define ufbxi_macro_stable_sort(m_type, m_linear_size, m_data, m_tmp, m_size, m_cmp_lambda) do { \
1143 typedef m_type mi_type; \
1144 mi_type *mi_src = (mi_type*)(m_tmp); \
1145 mi_type *mi_data = m_data, *mi_dst = mi_data; \
1146 size_t mi_block_size = ufbxi_clamp_linear_threshold(m_linear_size), mi_size = m_size; \
1147 /* Insertion sort in `m_linear_size` blocks */ \
1148 for (size_t mi_base = 0; mi_base < mi_size; mi_base += mi_block_size) { \
1149 size_t mi_i_end = mi_base + mi_block_size; \
1150 if (mi_i_end > mi_size) mi_i_end = mi_size; \
1151 for (size_t mi_i = mi_base + 1; mi_i < mi_i_end; mi_i++) { \
1152 size_t mi_j = mi_i; \
1153 mi_src[0] = mi_dst[mi_i]; \
1154 for (; mi_j != mi_base; --mi_j) { \
1155 mi_type *a = &mi_src[0], *b = &mi_dst[mi_j - 1]; \
1156 if (!( m_cmp_lambda )) break; \
1157 mi_dst[mi_j] = mi_dst[mi_j - 1]; \
1158 } \
1159 mi_dst[mi_j] = mi_src[0]; \
1160 } \
1161 } \
1162 /* Merge sort ping-ponging between `m_data` and `m_tmp` */ \
1163 for (; mi_block_size < mi_size; mi_block_size *= 2) { \
1164 mi_type *mi_swap = mi_dst; mi_dst = mi_src; mi_src = mi_swap; \
1165 for (size_t mi_base = 0; mi_base < mi_size; mi_base += mi_block_size * 2) { \
1166 size_t mi_i = mi_base, mi_i_end = mi_base + mi_block_size; \
1167 size_t mi_j = mi_i_end, mi_j_end = mi_j + mi_block_size; \
1168 size_t mi_k = mi_base; \
1169 if (mi_i_end > mi_size) mi_i_end = mi_size; \
1170 if (mi_j_end > mi_size) mi_j_end = mi_size; \
1171 while ((mi_i < mi_i_end) & (mi_j < mi_j_end)) { \
1172 mi_type *a = &mi_src[mi_j], *b = &mi_src[mi_i]; \
1173 if ( m_cmp_lambda ) { \
1174 mi_dst[mi_k] = *a; mi_j++; \
1175 } else { \
1176 mi_dst[mi_k] = *b; mi_i++; \
1177 } \
1178 mi_k++; \
1179 } \
1180 while (mi_i < mi_i_end) mi_dst[mi_k++] = mi_src[mi_i++]; \
1181 while (mi_j < mi_j_end) mi_dst[mi_k++] = mi_src[mi_j++]; \
1182 } \
1183 } \
1184 /* Copy the result to `m_data` if we ended up in `m_tmp` */ \
1185 if (mi_dst != mi_data) memcpy((void*)mi_data, mi_dst, sizeof(mi_type) * mi_size); \
1186 } while (0)
1187
1188 #define ufbxi_macro_lower_bound_eq(m_type, m_linear_size, m_result_ptr, m_data, m_begin, m_size, m_cmp_lambda, m_eq_lambda) do { \
1189 typedef m_type mi_type; \
1190 const mi_type *mi_data = (m_data); \
1191 size_t mi_lo = m_begin, mi_hi = m_size, mi_linear_size = ufbxi_clamp_linear_threshold(m_linear_size); \
1192 ufbx_assert(mi_linear_size > 1); \
1193 /* Binary search until we get down to `m_linear_size` elements */ \
1194 while (mi_hi - mi_lo > mi_linear_size) { \
1195 size_t mi_mid = mi_lo + (mi_hi - mi_lo) / 2; \
1196 const mi_type *a = &mi_data[mi_mid]; \
1197 if ( m_cmp_lambda ) { mi_lo = mi_mid + 1; } else { mi_hi = mi_mid + 1; } \
1198 } \
1199 /* Linearly scan until we find the edge */ \
1200 for (; mi_lo < mi_hi; mi_lo++) { \
1201 const mi_type *a = &mi_data[mi_lo]; \
1202 if ( m_eq_lambda ) { *(m_result_ptr) = mi_lo; break; } \
1203 } \
1204 } while (0)
1205
1206 #define ufbxi_macro_upper_bound_eq(m_type, m_linear_size, m_result_ptr, m_data, m_begin, m_size, m_eq_lambda) do { \
1207 typedef m_type mi_type; \
1208 const mi_type *mi_data = (m_data); \
1209 size_t mi_lo = m_begin, mi_hi = m_size, mi_linear_size = ufbxi_clamp_linear_threshold(m_linear_size); \
1210 ufbx_assert(mi_linear_size > 1); \
1211 /* Linearly scan with galloping */ \
1212 for (size_t mi_step = 1; mi_step < 100 && mi_hi - mi_lo > mi_step; mi_step *= 2) { \
1213 const mi_type *a = &mi_data[mi_lo + mi_step]; \
1214 if (!( m_eq_lambda )) { mi_hi = mi_lo + mi_step; break; } \
1215 mi_lo += mi_step; \
1216 } \
1217 /* Binary search until we get down to `m_linear_size` elements */ \
1218 while (mi_hi - mi_lo > mi_linear_size) { \
1219 size_t mi_mid = mi_lo + (mi_hi - mi_lo) / 2; \
1220 const mi_type *a = &mi_data[mi_mid]; \
1221 if ( m_eq_lambda ) { mi_lo = mi_mid + 1; } else { mi_hi = mi_mid + 1; } \
1222 } \
1223 /* Linearly scan until we find the edge */ \
1224 for (; mi_lo < mi_hi; mi_lo++) { \
1225 const mi_type *a = &mi_data[mi_lo]; \
1226 if (!( m_eq_lambda )) break; \
1227 } \
1228 *(m_result_ptr) = mi_lo; \
1229 } while (0)
1230
1231 typedef bool ufbxi_less_fn(void *user, const void *a, const void *b);
1232
1233 static ufbxi_noinline void ufbxi_stable_sort(size_t stride, size_t linear_size, void *in_data, void *in_tmp, size_t size, ufbxi_less_fn *less_fn, void *less_user)
1234 {
1235 (void)linear_size;
1236
1237 char *src = (char*)in_tmp;
1238 char *data = (char*)in_data, *dst = (char*)data;
1239 size_t block_size = ufbxi_clamp_linear_threshold(linear_size);
1240 /* Insertion sort in `linear_size` blocks */
1241 for (size_t base = 0; base < size; base += block_size) {
1242 size_t i_end = base + block_size;
1243 if (i_end > size) i_end = size;
1244 for (size_t i = base + 1; i < i_end; i++) {
1245
1246 {
1247 char *a = dst + i * stride, *b = dst + (i - 1) * stride;
1248 if (!less_fn(less_user, a, b)) continue;
1249 }
1250
1251 size_t j = i - 1;
1252 memcpy(src, dst + i * stride, stride);
1253 memcpy(dst + i * stride, dst + j * stride, stride);
1254 for (; j != base; --j) {
1255 char *a = src, *b = dst + (j - 1) * stride;
1256 if (!less_fn(less_user, a, b)) break;
1257 memcpy(dst + j * stride, dst + (j - 1) * stride, stride);
1258 }
1259 memcpy(dst + j * stride, src, stride);
1260 }
1261 }
1262 /* Merge sort ping-ponging between `data` and `tmp` */
1263 for (; block_size < size; block_size *= 2) {
1264 char *swap = dst; dst = src; src = swap;
1265 for (size_t base = 0; base < size; base += block_size * 2) {
1266 size_t i = base, i_end = base + block_size;
1267 size_t j = i_end, j_end = j + block_size;
1268 size_t k = base;
1269 if (i_end > size) i_end = size;
1270 if (j_end > size) j_end = size;
1271 while ((i < i_end) & (j < j_end)) {
1272 char *a = src + j * stride, *b = src + i * stride;
1273 if (less_fn(less_user, a, b)) {
1274 memcpy(dst + k * stride, a, stride);
1275 j++;
1276 } else {
1277 memcpy(dst + k * stride, b, stride);
1278 i++;
1279 }
1280 k++;
1281 }
1282
1283 memcpy(dst + k * stride, src + i * stride, (i_end - i) * stride);
1284 if (j < j_end) {
1285 memcpy(dst + (k + (i_end - i)) * stride, src + j * stride, (j_end - j) * stride);
1286 }
1287 }
1288 }
1289 /* Copy the result to `data` if we ended up in `tmp` */
1290 if (dst != data) memcpy((void*)data, dst, size * stride);
1291 }
1292
1293 static ufbxi_forceinline void ufbxi_swap(void *a, void *b, size_t size)
1294 {
1295 #if UFBXI_HAS_ALIASING && !defined(__CHERI__) // CHERI needs to copy pointer metadata tag bits..
1296 ufbxi_dev_assert(size % 4 == 0 && (uintptr_t)a % 4 == 0 && (uintptr_t)b % 4 == 0);
1297 char *ca = (char*)a, *cb = (char*)b;
1298 for (size_t i = 0; i < size; i += 4, ca += 4, cb += 4) {
1299 ufbxi_aliasing_u32 *ua = (ufbxi_aliasing_u32*)ca, *ub = (ufbxi_aliasing_u32*)cb;
1300 uint32_t va = *ua, vb = *ub;
1301 *ua = vb;
1302 *ub = va;
1303 }
1304 #else
1305 union {
1306 void *align_ptr;
1307 uintptr_t align_uptr;
1308 uint64_t align_u64;
1309 char data[256];
1310 } tmp;
1311 ufbxi_dev_assert(size <= sizeof(tmp));
1312 memcpy(tmp.data, a, size);
1313 memcpy(a, b, size);
1314 memcpy(b, tmp.data, size);
1315 #endif
1316 }
1317
1318 static ufbxi_noinline void ufbxi_unstable_sort(void *in_data, size_t size, size_t stride, ufbxi_less_fn *less_fn, void *less_user)
1319 {
1320 if (size <= 1) return;
1321
1322 char *data = (char*)in_data;
1323 size_t start = (size - 1) >> 1;
1324 size_t end = size - 1;
1325 for (;;) {
1326 size_t root = start;
1327 size_t child;
1328 while ((child = root*2 + 1) <= end) {
1329 size_t next = less_fn(less_user, data + child * stride, data + root * stride) ? root : child;
1330 if (child + 1 <= end && less_fn(less_user, data + next * stride, data + (child + 1) * stride)) {
1331 next = child + 1;
1332 }
1333 if (next == root) break;
1334 ufbxi_swap(data + root * stride, data + next * stride, stride);
1335 root = next;
1336 }
1337
1338 if (start > 0) {
1339 start--;
1340 } else if (end > 0) {
1341 ufbxi_swap(data + end * stride, data, stride);
1342 end--;
1343 } else {
1344 break;
1345 }
1346 }
1347 }
1348
1349 // -- Float parsing
1350
1351 #define UFBXI_BIGINT_LIMB_BITS 32
1352 #define UFBXI_BIGINT_ACCUM_BITS (UFBXI_BIGINT_LIMB_BITS * 2)
1353 #define UFBXI_BIGINT_LIMB_MAX (ufbxi_bigint_limb)(((ufbxi_bigint_accum)1 << UFBXI_BIGINT_LIMB_BITS) - 1)
1354 typedef uint32_t ufbxi_bigint_limb;
1355 typedef uint64_t ufbxi_bigint_accum;
1356
1357 typedef struct {
1358 ufbxi_bigint_limb *limbs;
1359 uint32_t capacity;
1360 uint32_t length;
1361 } ufbxi_bigint;
1362
1363 static ufbxi_bigint ufbxi_bigint_make(ufbxi_bigint_limb *limbs, size_t capacity)
1364 {
1365 ufbxi_bigint bi = { limbs, (uint32_t)capacity };
1366 return bi;
1367 }
1368
1369 #define ufbxi_bigint_array(arr) ufbxi_bigint_make((arr), sizeof(arr) / sizeof(*(arr)))
1370
1371 static const uint64_t ufbxi_pow5_tab[] = {
1372 UINT64_C(0x1), UINT64_C(0x5), UINT64_C(0x19), UINT64_C(0x7d), UINT64_C(0x271), UINT64_C(0xc35), UINT64_C(0x3d09), UINT64_C(0x1312d), UINT64_C(0x5f5e1),
1373 UINT64_C(0x1dcd65), UINT64_C(0x9502f9), UINT64_C(0x2e90edd), UINT64_C(0xe8d4a51), UINT64_C(0x48c27395), UINT64_C(0x16bcc41e9), UINT64_C(0x71afd498d),
1374 UINT64_C(0x2386f26fc1), UINT64_C(0xb1a2bc2ec5), UINT64_C(0x3782dace9d9), UINT64_C(0x1158e460913d), UINT64_C(0x56bc75e2d631), UINT64_C(0x1b1ae4d6e2ef5),
1375 UINT64_C(0x878678326eac9), UINT64_C(0x2a5a058fc295ed), UINT64_C(0xd3c21bcecceda1), UINT64_C(0x422ca8b0a00a425), UINT64_C(0x14adf4b7320334b9), UINT64_C(0x6765c793fa10079d),
1376 };
1377
1378 static const double ufbxi_pow10_tab_f64[] = {
1379 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19, 1e20, 1e21, 1e22,
1380 };
1381
1382 static ufbxi_noinline void ufbxi_bigint_mad(ufbxi_bigint *bigint, ufbxi_bigint_accum multiplicand, ufbxi_bigint_accum addend)
1383 {
1384 ufbxi_dev_assert((multiplicand | addend) >> (UFBXI_BIGINT_ACCUM_BITS - 1) == 0);
1385 ufbxi_bigint b = *bigint;
1386 ufbxi_bigint_limb m_lo = (ufbxi_bigint_limb)multiplicand;
1387 ufbxi_bigint_limb m_hi = (ufbxi_bigint_limb)(multiplicand >> UFBXI_BIGINT_LIMB_BITS);
1388 ufbxi_bigint_accum carry = addend;
1389 for (uint32_t i = 0; i < b.length; i++) {
1390 ufbxi_bigint_accum limb = (ufbxi_bigint_accum)b.limbs[i];
1391 ufbxi_bigint_accum lo = limb * m_lo + (carry & UFBXI_BIGINT_LIMB_MAX);
1392 ufbxi_bigint_accum hi = limb * m_hi;
1393 b.limbs[i] = (ufbxi_bigint_limb)lo;
1394 carry = (carry >> 32u) + (lo >> 32u) + hi;
1395 }
1396 while (carry) {
1397 b.limbs[b.length++] = (ufbxi_bigint_limb)carry;
1398 ufbxi_dev_assert(b.length < b.capacity);
1399 carry >>= 32u;
1400 }
1401 bigint->length = b.length;
1402 }
1403
1404 static ufbxi_noinline bool ufbxi_bigint_div(ufbxi_bigint *q, ufbxi_bigint *u, ufbxi_bigint *v)
1405 {
1406 int32_t n = (int32_t)v->length;
1407 int32_t m = (int32_t)u->length - n;
1408 ufbxi_bigint_limb v_hi = v->limbs[v->length - 1];
1409 ufbxi_bigint_limb *un = u->limbs, *vn = v->limbs;
1410 ufbxi_dev_assert(n >= 2 && m >= 1 && v_hi >> (UFBXI_BIGINT_LIMB_BITS - 1) != 0 && un[n+m - 1] >> (UFBXI_BIGINT_LIMB_BITS - 1) == 0);
1411 un[n + m] = 0;
1412 q->length = 0;
1413 for (int32_t j = m - 1; j >= 0; j--) {
1414 ufbxi_bigint_accum u_hi = ((ufbxi_bigint_accum)un[n+j] << UFBXI_BIGINT_LIMB_BITS) | un[n+j-1];
1415 ufbxi_bigint_accum t, qhat = u_hi / v_hi, rhat = u_hi % v_hi;
1416 while (qhat >> UFBXI_BIGINT_LIMB_BITS != 0 || qhat*vn[n-2] > ((rhat<<UFBXI_BIGINT_LIMB_BITS)|un[j+n-2])) {
1417 qhat -= 1;
1418 rhat += v_hi;
1419 if (rhat >> UFBXI_BIGINT_LIMB_BITS != 0) break;
1420 }
1421 ufbxi_bigint_limb carry = 0;
1422 for (int32_t i = 0; i < n; i++) {
1423 ufbxi_bigint_accum p = qhat * vn[i];
1424 t = (ufbxi_bigint_accum)un[i+j] - carry - (ufbxi_bigint_limb)p;
1425 un[i+j] = (ufbxi_bigint_limb)t;
1426 carry = (ufbxi_bigint_limb)((p >> UFBXI_BIGINT_LIMB_BITS) - (t >> UFBXI_BIGINT_LIMB_BITS));
1427 }
1428 t = (ufbxi_bigint_accum)un[j+n] - carry;
1429 un[j+n] = (ufbxi_bigint_limb)t;
1430 if (t >> UFBXI_BIGINT_LIMB_BITS != 0) {
1431 qhat -= 1;
1432 carry = 0;
1433 for (int32_t i = 0; i < n; i++) {
1434 t = (ufbxi_bigint_accum)un[i+j] + vn[i] + carry;
1435 un[i+j] = (ufbxi_bigint_limb)t;
1436 carry = (ufbxi_bigint_limb)(t >> UFBXI_BIGINT_LIMB_BITS);
1437 }
1438 un[j+n] += carry;
1439 }
1440 q->limbs[j] = (ufbxi_bigint_limb)qhat;
1441 if (qhat && !q->length) {
1442 ufbxi_dev_assert(j + 1 < (int32_t)q->capacity);
1443 q->length = (uint32_t)(j + 1);
1444 }
1445 }
1446 for (int32_t i = 0; i < n; i++) {
1447 if (un[i]) return true;
1448 }
1449 return false;
1450 }
1451
1452 static void ufbxi_bigint_mul_pow5(ufbxi_bigint *b, uint32_t power)
1453 {
1454 for (; power > 27; power -= 27) {
1455 ufbxi_bigint_mad(b, ufbxi_pow5_tab[27], 0);
1456 }
1457 ufbxi_bigint_mad(b, ufbxi_pow5_tab[power], 0);
1458 }
1459
1460 static ufbxi_noinline void ufbxi_bigint_shift_left(ufbxi_bigint *bigint, uint32_t amount)
1461 {
1462 uint32_t words = amount / UFBXI_BIGINT_LIMB_BITS, bits = amount % UFBXI_BIGINT_LIMB_BITS;
1463 ufbxi_bigint b = *bigint;
1464 ufbxi_dev_assert(b.length + words + 1 < b.capacity && b.capacity >= 4);
1465 uint32_t bits_down = UFBXI_BIGINT_LIMB_BITS - bits - 1;
1466 bigint->length += words + (b.limbs[b.length - 1] >> 1 >> bits_down != 0 ? 1 : 0);
1467 b.limbs[b.length] = 0;
1468 if (b.length <= 3 && words <= 3) {
1469 ufbxi_bigint_limb l0 = b.limbs[0];
1470 ufbxi_bigint_limb l1 = ufbxi_maybe_uninit(b.length >= 1, b.limbs[1], ~0u);
1471 ufbxi_bigint_limb l2 = ufbxi_maybe_uninit(b.length >= 2, b.limbs[2], ~0u);
1472 b.limbs[0] = 0;
1473 b.limbs[1] = 0;
1474 b.limbs[2] = 0;
1475 b.limbs[words + 0] = l0 << bits;
1476 b.limbs[words + 1] = (l1 << bits) | (l0 >> 1 >> bits_down);
1477 b.limbs[words + 2] = (l2 << bits) | (l1 >> 1 >> bits_down);
1478 b.limbs[words + 3] = (l2 >> 1 >> bits_down);
1479 } else {
1480 for (uint32_t i = b.length + 1; i-- > 1; ) {
1481 b.limbs[i + words] = (b.limbs[i] << bits) | (b.limbs[i - 1] >> 1 >> bits_down);
1482 }
1483 b.limbs[words] = b.limbs[0] << bits;
1484 for (uint32_t i = 0; i < words; i++) {
1485 b.limbs[i] = 0;
1486 }
1487 }
1488 }
1489
1490 static ufbxi_bigint_limb ufbxi_bigint_top_limb(const ufbxi_bigint b, uint32_t index) {
1491 return index < b.length ? b.limbs[b.length - 1 - index] : 0;
1492 }
1493
1494 static ufbxi_noinline uint64_t ufbxi_bigint_extract_high(const ufbxi_bigint b, int32_t *p_exponent, bool *p_tail)
1495 {
1496 ufbxi_dev_assert(b.length != 0);
1497 uint64_t result = 0;
1498 const uint32_t limb_count = 64 / UFBXI_BIGINT_LIMB_BITS;
1499 for (uint32_t i = 0; i < limb_count; i++) {
1500 result = (result << UFBXI_BIGINT_LIMB_BITS) | ufbxi_bigint_top_limb(b, i);
1501 }
1502 uint32_t shift = ufbxi_lzcnt64(result);
1503 result <<= shift;
1504 ufbxi_bigint_limb lo = ufbxi_bigint_top_limb(b, limb_count);
1505 if (shift > 0) {
1506 result |= lo >> (UFBXI_BIGINT_LIMB_BITS - shift);
1507 }
1508 *p_tail |= (ufbxi_bigint_limb)(lo << shift) != 0;
1509 for (uint32_t i = limb_count + 1; i < b.length; i++) {
1510 *p_tail |= ufbxi_bigint_top_limb(b, i) != 0;
1511 }
1512 *p_exponent += (int32_t)(b.length * UFBXI_BIGINT_LIMB_BITS - shift - 1);
1513 return result;
1514 }
1515
1516 static uint64_t ufbxi_shift_right_round(uint64_t value, uint32_t shift, bool tail)
1517 {
1518 if (shift == 0) return value;
1519 if (shift > 64) return 0;
1520 uint64_t result = value >> (shift - 1);
1521 uint64_t tail_mask = (UINT64_C(1) << (shift - 1)) - 1;
1522
1523 bool r_odd = (result & 0x2) != 0;
1524 bool r_round = (result & 0x1) != 0;
1525 bool r_tail = tail || (value & tail_mask) != 0;
1526 uint64_t round_bit = (r_round && (r_odd || r_tail)) ? 1u : 0u;
1527
1528 return (result >> 1u) + round_bit;
1529 }
1530
1531 typedef enum {
1532 UFBXI_PARSE_DOUBLE_ALLOW_FAST_PATH = 0x1,
1533 UFBXI_PARSE_DOUBLE_AS_BINARY32 = 0x2,
1534 } ufbxi_parse_double_flag;
1535
1536 static bool ufbxi_scan_ignorecase(const char *p, const char *end, const char *fmt)
1537 {
1538 for (const char *f = fmt; *f; f++, p++) {
1539 if (p >= end) return false;
1540 if ((*p | 0x20) != *f) return false;
1541 }
1542 return true;
1543 }
1544
1545 static ufbxi_noinline bool ufbxi_parse_inf_nan(double *p_result, const char *str, size_t max_length, char **p_end)
1546 {
1547 bool negative = false;
1548 const char *p = str, *end = p + max_length;
1549 if (p != end && (*p == '+' || *p == '-')) {
1550 negative = *p++ == '-';
1551 }
1552
1553 uint32_t top_bits = 0;
1554 if (end - p >= 3 && (p[0] >= '0' && p[0] <= '9') && p[1] == '.' && p[2] == '#') {
1555 // Legacy MSVC 1.#NAN
1556 p += 3;
1557 if (ufbxi_scan_ignorecase(p, end, "inf")) {
1558 p += 3;
1559 top_bits = 0x7ff0;
1560 } else if (ufbxi_scan_ignorecase(p, end, "nan") || ufbxi_scan_ignorecase(p, end, "ind")) {
1561 p += 3;
1562 top_bits = 0x7ff8;
1563 } else {
1564 return false;
1565 }
1566 while (p != end && *p >= '0' && *p <= '9') {
1567 p++;
1568 }
1569 } else {
1570 // Standard
1571 if (ufbxi_scan_ignorecase(p, end, "nan")) {
1572 p += 3;
1573 top_bits = 0x7ff8;
1574 if (p != end && *p == '(') {
1575 p++;
1576 while (p != end && *p != ')') {
1577 char c = *p;
1578 if (!((c>='0'&&c<='9') || (c>='a'&&c<='z') || (c>='A'&&c<='Z'))) {
1579 return false;
1580 }
1581 p++;
1582 }
1583 if (p == end) return false;
1584 p++;
1585 }
1586 } else if (ufbxi_scan_ignorecase(p, end, "inf")) {
1587 p += ufbxi_scan_ignorecase(p + 3, end, "inity") ? 8 : 3;
1588 top_bits = 0x7ff0;
1589 }
1590 }
1591
1592 *p_end = (char*)p;
1593 top_bits |= negative ? 0x8000 : 0;
1594 uint64_t bits = (uint64_t)top_bits << 48;
1595 double result;
1596 ufbxi_bit_cast(double, result, uint64_t, bits);
1597 *p_result = result;
1598 return true;
1599 }
1600
1601 static ufbxi_noinline double ufbxi_parse_double(const char *str, size_t max_length, char **p_end, uint32_t flags)
1602 {
1603 const uint32_t max_limbs = 14;
1604
1605 ufbxi_bigint_limb mantissa_limbs[42], divisor_limbs[42], quotient_limbs[42];
1606 ufbxi_bigint big_mantissa = ufbxi_bigint_array(mantissa_limbs);
1607 ufbxi_bigint big_quotient = ufbxi_bigint_array(quotient_limbs);
1608 int32_t dec_exponent = 0, has_dot = 0;
1609 bool negative = false, tail = false, digits_valid = true;
1610 uint64_t digits = 0;
1611 uint32_t num_digits = 0;
1612
1613 const char *p = str, *end = p + max_length;
1614 if (p != end && (*p == '+' || *p == '-')) {
1615 negative = *p++ == '-';
1616 }
1617 while (p != end) {
1618 char c = *p;
1619 if (c >= '0' && c <= '9') {
1620 if (big_mantissa.length < max_limbs) {
1621 digits = digits * 10 + (uint64_t)(c - '0');
1622 num_digits++;
1623 if (num_digits >= 18) {
1624 ufbxi_dev_assert(num_digits < ufbxi_arraycount(ufbxi_pow5_tab));
1625 ufbxi_bigint_mad(&big_mantissa, ufbxi_pow5_tab[num_digits] << num_digits, digits);
1626 digits = 0;
1627 num_digits = 0;
1628 digits_valid = false;
1629 }
1630 dec_exponent -= has_dot;
1631 } else {
1632 dec_exponent += 1 - has_dot;
1633 }
1634 p++;
1635 } else if (c == '.' && !has_dot) {
1636 has_dot = true;
1637 p++;
1638 } else {
1639 break;
1640 }
1641 }
1642 if (p != end && (*p == 'e' || *p == 'E')) {
1643 p++;
1644 bool exp_negative = false;
1645 if (p != end && (*p == '+' || *p == '-')) {
1646 exp_negative = *p == '-';
1647 p++;
1648 }
1649 int32_t exp = 0;
1650 while (p != end) {
1651 char c = *p;
1652 if (c >= '0' && c <= '9') {
1653 p++;
1654 exp = exp * 10 + (c - '0');
1655 if (exp >= 10000) break;
1656 } else {
1657 break;
1658 }
1659 }
1660 dec_exponent += exp_negative ? -exp : exp;
1661 }
1662
1663 if (p != end) {
1664 char c = *p;
1665 if (c == '#' || c == 'i' || c == 'I' || c == 'n' || c == 'N') {
1666 double result;
1667 if (ufbxi_parse_inf_nan(&result, str, max_length, p_end)) {
1668 return result;
1669 }
1670 }
1671 }
1672
1673 *p_end = (char*)p;
1674
1675 // Both power of 10 and integer are exactly representable as doubles
1676 // Powers of 10 are factored as 2*5, and 2^N can be always exactly represented.
1677 if ((flags & UFBXI_PARSE_DOUBLE_ALLOW_FAST_PATH) != 0 && big_mantissa.length == 0 && dec_exponent >= -22 && dec_exponent <= 22 && (digits >> 53) == 0) {
1678 double value;
1679 if (dec_exponent < 0) {
1680 value = (double)digits / ufbxi_pow10_tab_f64[-dec_exponent];
1681 } else {
1682 value = (double)digits * ufbxi_pow10_tab_f64[dec_exponent];
1683 }
1684 return negative ? -value : value;
1685 }
1686
1687 if (big_mantissa.length == 0) {
1688 big_mantissa.limbs[0] = (ufbxi_bigint_limb)digits;
1689 big_mantissa.limbs[1] = (ufbxi_bigint_limb)(digits >> 32u);
1690 big_mantissa.length = (digits >> 32u) ? 2 : digits ? 1 : 0;
1691 if (big_mantissa.length == 0) return negative ? -0.0 : 0.0;
1692 } else {
1693 ufbxi_dev_assert(num_digits < ufbxi_arraycount(ufbxi_pow5_tab));
1694 ufbxi_bigint_mad(&big_mantissa, ufbxi_pow5_tab[num_digits] << num_digits, digits);
1695 }
1696
1697 uint32_t enc_sign_shift = 63;
1698 uint32_t enc_mantissa_bits = 53;
1699 int32_t enc_max_exponent = 1023;
1700 if (flags & UFBXI_PARSE_DOUBLE_AS_BINARY32) {
1701 enc_sign_shift = 31;
1702 enc_mantissa_bits = 24;
1703 enc_max_exponent = 127;
1704 }
1705
1706 int32_t exponent = 0;
1707 if (dec_exponent < 0) {
1708 if (dec_exponent + (int32_t)big_mantissa.length * 10 <= -325) return negative ? -0.0 : 0.0;
1709
1710 ufbxi_bigint big_divisor = ufbxi_bigint_array(divisor_limbs);
1711 uint32_t pow5 = (uint32_t)-dec_exponent;
1712 uint32_t initial_pow5 = pow5 <= 27 ? pow5 : 27;
1713 uint64_t pow5_value = ufbxi_pow5_tab[initial_pow5];
1714 pow5 -= initial_pow5;
1715 exponent += dec_exponent;
1716
1717 if (pow5 == 0 && digits_valid && digits >> 63 == 0) {
1718 uint32_t divisor_zeros = ufbxi_lzcnt64(pow5_value);
1719 uint64_t mantissa_zeros = ufbxi_lzcnt64(digits) - 1;
1720 uint64_t divisor_bits = pow5_value << divisor_zeros;
1721 uint64_t mantissa_bits = digits << mantissa_zeros;
1722 big_divisor.limbs[0] = (ufbxi_bigint_limb)divisor_bits;
1723 big_divisor.limbs[1] = (ufbxi_bigint_limb)(divisor_bits >> 32u);
1724 big_divisor.length = 2;
1725 big_mantissa.limbs[0] = 0;
1726 big_mantissa.limbs[1] = 0;
1727 big_mantissa.limbs[2] = (ufbxi_bigint_limb)mantissa_bits;
1728 big_mantissa.limbs[3] = (ufbxi_bigint_limb)(mantissa_bits >> 32u);
1729 big_mantissa.length = 4;
1730 exponent += (int32_t)divisor_zeros - (int32_t)mantissa_zeros - 64;
1731 } else {
1732 big_divisor.limbs[0] = (ufbxi_bigint_limb)pow5_value;
1733 big_divisor.limbs[1] = (ufbxi_bigint_limb)(pow5_value >> 32u);
1734 big_divisor.length = (pow5_value >> 32u) != 0 ? 2 : 1;
1735 if (pow5 > 0) {
1736 ufbxi_bigint_mul_pow5(&big_divisor, pow5);
1737 }
1738
1739 uint32_t divisor_zeros = ufbxi_lzcnt32(big_divisor.limbs[big_divisor.length - 1]);
1740 if (big_divisor.length == 1) divisor_zeros += UFBXI_BIGINT_LIMB_BITS;
1741 ufbxi_bigint_shift_left(&big_divisor, divisor_zeros);
1742 uint32_t divisor_bits = big_divisor.length * UFBXI_BIGINT_LIMB_BITS;
1743
1744 uint32_t mantissa_zeros = ufbxi_lzcnt32(big_mantissa.limbs[big_mantissa.length - 1]);
1745 uint32_t mantissa_bits = big_mantissa.length * UFBXI_BIGINT_LIMB_BITS - mantissa_zeros;
1746 uint32_t mantissa_min_bits = divisor_bits + enc_mantissa_bits + 2;
1747 uint32_t mantissa_shift = mantissa_bits < mantissa_min_bits ? mantissa_min_bits - mantissa_bits : 0;
1748 // Align mantissa to never have a high bit, this means we can skip the first digit during division.
1749 mantissa_shift += ((mantissa_shift - mantissa_zeros) & (UFBXI_BIGINT_LIMB_BITS - 1)) == 0 ? 1 : 0;
1750 if (mantissa_shift > 0) {
1751 ufbxi_bigint_shift_left(&big_mantissa, mantissa_shift);
1752 }
1753 exponent += (int32_t)divisor_zeros - (int32_t)mantissa_shift;
1754 }
1755
1756 tail = ufbxi_bigint_div(&big_quotient, &big_mantissa, &big_divisor);
1757 big_mantissa = big_quotient;
1758 } else if (dec_exponent > 0) {
1759 if (dec_exponent + (int32_t)(big_mantissa.length - 1) * 9 >= 310) return negative ? -UFBX_INFINITY : UFBX_INFINITY;
1760
1761 exponent += dec_exponent;
1762 ufbxi_bigint_mul_pow5(&big_mantissa, (uint32_t)dec_exponent);
1763 }
1764
1765 uint64_t mantissa = ufbxi_bigint_extract_high(big_mantissa, &exponent, &tail);
1766 uint64_t sign_bit = (uint64_t)(negative ? 1u : 0u) << enc_sign_shift;
1767
1768 uint32_t mantissa_shift = 64 - enc_mantissa_bits;
1769 if (exponent > enc_max_exponent) {
1770 return negative ? -UFBX_INFINITY : UFBX_INFINITY;
1771 } else if (exponent <= -enc_max_exponent) {
1772 mantissa_shift += (uint32_t)(-enc_max_exponent + 1 - exponent);
1773 exponent = -enc_max_exponent + 1;
1774 }
1775
1776 mantissa = ufbxi_shift_right_round(mantissa, mantissa_shift, tail);
1777 if (mantissa == 0) return negative ? -0.0 : 0.0;
1778
1779 uint64_t bits = mantissa;
1780 bits += (uint64_t)(exponent + enc_max_exponent - 1) << (enc_mantissa_bits - 1);
1781 bits |= sign_bit;
1782
1783 if (flags & UFBXI_PARSE_DOUBLE_AS_BINARY32) {
1784 uint32_t bits_lo = (uint32_t)bits;
1785 float result;
1786 ufbxi_bit_cast(float, result, uint32_t, bits_lo);
1787 return result;
1788 } else {
1789 double result;
1790 ufbxi_bit_cast(double, result, uint64_t, bits);
1791 return result;
1792 }
1793 }
1794
1795 static ufbxi_noinline uint32_t ufbxi_parse_double_init_flags(void)
1796 {
1797 // We require evaluation in double precision, either for doubles (0) or always (1)
1798 // and rounding to nearest, which we can check for with `1 + eps == 1 - eps`.
1799 #if UFBX_FLT_EVAL_METHOD == 0 || UFBX_FLT_EVAL_METHOD == 1
1800 static volatile double ufbxi_volatile_eps = 2.2250738585072014e-308;
1801 if (1.0 + ufbxi_volatile_eps == 1.0 - ufbxi_volatile_eps) return UFBXI_PARSE_DOUBLE_ALLOW_FAST_PATH;
1802 #endif
1803
1804 return 0;
1805 }
1806
1807 static ufbxi_forceinline int64_t ufbxi_parse_int64(const char *str, char **end)
1808 {
1809 uint64_t abs_val = 0;
1810 bool negative = *str == '-';
1811 bool positive = *str == '+';
1812
1813 size_t init_len = (negative | positive) ? 1 : 0;
1814 size_t len = init_len;
1815 for (; len < 30; len++) {
1816 char c = str[len];
1817 if (!(c >= '0' && c <= '9')) break;
1818 abs_val = 10 * abs_val + (uint64_t)(c - '0');
1819 }
1820 if (len == 30 || len == init_len) {
1821 *end = NULL;
1822 return 0;
1823 }
1824
1825 // TODO: Wrap/clamp?
1826 *end = (char*)str + len;
1827 return negative ? (int64_t)(0 - abs_val) : (int64_t)abs_val;
1828 }
1829
1830 static ufbxi_noinline uint32_t ufbxi_parse_uint32_radix(const char *str, uint32_t radix)
1831 {
1832 uint32_t value = 0;
1833 for (const char *p = str; ; p++) {
1834 char c = *p;
1835 if (c >= '0' && c <= '9') {
1836 value = value * radix + (uint32_t)(c - '0');
1837 } else if (radix == 16 && (c >= 'a' && c <= 'f')) {
1838 value = value * radix + (uint32_t)(c + (10 - 'a'));
1839 } else if (radix == 16 && (c >= 'A' && c <= 'F')) {
1840 value = value * radix + (uint32_t)(c + (10 - 'A'));
1841 } else {
1842 break;
1843 }
1844 }
1845 return value;
1846 }
1847
1848 // -- DEFLATE implementation
1849
1850 #if !defined(ufbx_inflate)
1851
1852 // Lookup data: [0:5] extra bits [5:8] flags [16:32] base value
1853 // Generated by `misc/deflate_lut.py`
1854 static const uint32_t ufbxi_deflate_length_lut[] = {
1855 0x00000020, 0x00030040, 0x00040040, 0x00050040, 0x00060040, 0x00070040, 0x00080040, 0x00090040,
1856 0x000a0040, 0x000b0041, 0x000d0041, 0x000f0041, 0x00110041, 0x00130042, 0x00170042, 0x001b0042,
1857 0x001f0042, 0x00230043, 0x002b0043, 0x00330043, 0x003b0043, 0x00430044, 0x00530044, 0x00630044,
1858 0x00730044, 0x00830045, 0x00a30045, 0x00c30045, 0x00e30045, 0x01020040, 0x00010020, 0x00010020,
1859 };
1860 static const uint32_t ufbxi_deflate_dist_lut[] = {
1861 0x00010000, 0x00020000, 0x00030000, 0x00040000, 0x00050001, 0x00070001, 0x00090002, 0x000d0002,
1862 0x00110003, 0x00190003, 0x00210004, 0x00310004, 0x00410005, 0x00610005, 0x00810006, 0x00c10006,
1863 0x01010007, 0x01810007, 0x02010008, 0x03010008, 0x04010009, 0x06010009, 0x0801000a, 0x0c01000a,
1864 0x1001000b, 0x1801000b, 0x2001000c, 0x3001000c, 0x4001000d, 0x6001000d, 0x00010020, 0x00010020,
1865 };
1866
1867 static const uint8_t ufbxi_deflate_code_length_permutation[] = {
1868 16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15,
1869 };
1870
1871 #define UFBXI_INFLATE_FAST_MIN_IN 8
1872 #define UFBXI_INFLATE_FAST_MIN_OUT 2
1873
1874 #define UFBXI_HUFF_MAX_BITS 16
1875 #define UFBXI_HUFF_MAX_VALUE 288
1876 #define UFBXI_HUFF_FAST_BITS 10
1877 #define UFBXI_HUFF_FAST_SIZE (1 << UFBXI_HUFF_FAST_BITS)
1878 #define UFBXI_HUFF_FAST_MASK (UFBXI_HUFF_FAST_SIZE - 1)
1879 #define UFBXI_HUFF_MAX_LONG_BITS 5
1880 #define UFBXI_HUFF_MAX_LONG_SYMS 380
1881
1882 #define UFBXI_HUFF_CODELEN_FAST_BITS 8
1883 #define UFBXI_HUFF_CODELEN_FAST_MASK ((1<<UFBXI_HUFF_CODELEN_FAST_BITS)-1)
1884
1885 #define UFBXI_HUFF_MAX_EXTRA_SYMS 32
1886
1887 typedef struct {
1888
1889 // Number of bytes left to read from `read_fn()`
1890 size_t input_left;
1891
1892 // User-supplied read callback
1893 ufbx_read_fn *read_fn;
1894 void *read_user;
1895
1896 // Buffer to read to from `read_fn()`, may point to `local_buffer` if user
1897 // didn't supply a suitable buffer.
1898 char *buffer;
1899 size_t buffer_size;
1900
1901 // Current chunk of data to process, either the initial buffer of input
1902 // or part of `buffer`.
1903 const char *chunk_begin; // < Begin of the buffer
1904 const char *chunk_ptr; // < Next bytes to read to `bits`
1905 const char *chunk_yield; // < End of data before needing to call `ufbxi_bit_yield()`
1906 const char *chunk_end; // < End of data before needing to call `ufbxi_bit_refill()`
1907 const char *chunk_real_end; // < Actual end of the data buffer
1908
1909 // Amount of bytes read before the current chunk
1910 size_t num_read_before_chunk;
1911 uint64_t progress_bias;
1912 uint64_t progress_total;
1913 size_t progress_interval;
1914
1915 uint64_t bits; // < Buffered bits
1916 size_t left; // < Number of valid low bits in `bits`
1917
1918 // Progress tracking, maybe `NULL` it not requested
1919 ufbx_progress_cb progress_cb;
1920
1921 // When `progress_cb.fn()` returns `false` set the `cancelled` flag and
1922 // set the buffered bits to `cancel_bits`.
1923 uint64_t cancel_bits;
1924 bool cancelled;
1925
1926 char local_buffer[256];
1927 } ufbxi_bit_stream;
1928
1929 // Packed symbol information:
1930 //
1931 // [0:5] total_bits // [fast=1] Number of bits in the symbol _including_ extra bits
1932 // [0:5] extra_mask // [fast=0] Mask of extra bits to use
1933 // [5] end // 1 if end/invalid symbol, always 0 if `fast` (*1)
1934 // [6] match // 1 if the symbol is a match length, always 0 in non `lit_length` trees (always 0 if `end`)
1935 // [7] fast // 1 if the symbol can be determined from the table bits and `end=0`
1936 // [8:16] lit_byte // [lit_length] Literal byte
1937 // [8:16] len_index // [lit_length, match=1] Match length index
1938 // [8:16] dist_index // [dist] Match distance index
1939 // [8:16] code_length // [code_length] Dynamic Huffman code length code
1940 // [8:16] long_offset // [fast_sym, fast=0, extra_mask>0] Base offset (halved) to `long_sym[]`
1941 // [8:16] code_prefix // [fast_sym, fast=0, extra_mask=0] First 8-bits of the code (reverse of the lookup)
1942 //
1943 // (*1) Not allowing `end` if `fast` serves a dual purpose: It allows us to omit a check for the end symbol in the
1944 // fast path and allows using the symbol as a 64-bit shift amount (x64/ARM64/WASM have native modulo 64 shifts).
1945 //
1946 // Valid bit patterns, all other patterns are forbidden (`sorted_to_sym[]` contains same patterns as `long_sym[]`):
1947 //
1948 // tree b e m f v
1949 //
1950 // lit_length.fast_sym[] N 0 0 1 L // Short N bit code (no extra allowed) for literal byte L
1951 // lit_length.fast_sym[] N 0 1 1 I // Short N bit code (huff+extra bits) for length index I
1952 // lit_length.fast_sym[] M 0 0 0 X // Long code at `lit_length.long_sym[X*2 + ((bits>>FAST_BITS) & M)]`
1953 // lit_length.fast_sym[] 0 0 0 0 R // Extra long code with prefix R, use `lit_length.sorted_to_sym[]` to resolve (*1)
1954 // lit_length.fast_sym[] N 1 0 0 0 // Short N bit code for end-of-block (256) symbol
1955 // lit_length.fast_sym[] 0 1 0 0 1 // Invalid lit_length code
1956 //
1957 // lit_length.long_sym[] N 0 0 0 L // Long N bit code (no extra allowed) for literal byte L
1958 // lit_length.long_sym[] N 0 1 0 I // Long N bit code (huff+extra bits) for length index I
1959 // lit_length.long_sym[] N 1 0 0 0 // Long N bit code for end-of-block (256) symbol
1960 // lit_length.long_sym[] 0 1 0 0 1 // Invalid lit_length code
1961 //
1962 // dist.fast_sym[] N 0 0 1 L // Short N bit code (huff+extra bits) for distance index I
1963 // dist.fast_sym[] M 0 0 0 X // Long code at `dist.long_sym[X*2 + ((bits>>FAST_BITS) & M)]`
1964 // dist.fast_sym[] 0 0 0 0 R // Extra long code with prefix R, use `dist.sorted_to_sym[]` to resolve (*1)
1965 // dist.fast_sym[] N 1 0 0 1 // Unused symbol 30-31 or invalid distance code
1966 //
1967 // dist.long_sym[] N 0 0 0 I // Long N bit code (huff+extra bits) for distance index I
1968 // dist.long_sym[] N 1 0 0 1 // Unused symbol 30-31 or invalid distance code
1969 //
1970 // code_length.fast_sym[] N 0 0 1 B // Short N bit code (huff only, extra handled explicitly) for symbol bit count B
1971 // code_length.fast_sym[] M 0 0 0 X // Long code at `dist.long_sym[X*2 + ((bits>>FAST_BITS) & M)]`
1972 // code_length.fast_sym[] 0 0 0 0 R // Extra long code with prefix R, use `code_length.sorted_to_sym[]` to resolve (*1)
1973 //
1974 // code_length.long_sym[] N 0 0 0 B // Long N bit code (huff only, extra handled explicitly) for symbol bit count B
1975 //
1976 // (*1) Never necessary if `fast_bits >= 10` due to `long_sym[]` covering all possible codes,
1977 //
1978 typedef uint16_t ufbxi_huff_sym;
1979
1980 #define ufbxi_huff_sym_total_bits(sym) ((uint32_t)(sym) & 0x1f)
1981 #define ufbxi_huff_sym_long_mask(sym) ((uint32_t)(sym) & 0x1f)
1982 #define ufbxi_huff_sym_long_offset(sym) ((uint32_t)(sym) >> 7u)
1983 #define ufbxi_huff_sym_value(sym) ((uint32_t)(sym) >> 8u)
1984
1985 enum {
1986 UFBXI_HUFF_SYM_END = 0x20,
1987 UFBXI_HUFF_SYM_MATCH = 0x40,
1988 UFBXI_HUFF_SYM_FAST = 0x80,
1989 };
1990
1991 #define UFBXI_HUFF_ERROR_SYM ((ufbxi_huff_sym)0x0120) // Error symbol, END (value 1)
1992 #define UFBXI_HUFF_UNINITIALIZED_SYM ((ufbxi_huff_sym)0x0220) // Uninitialized symbol for regression, END (value 2)
1993
1994 typedef struct {
1995 ufbxi_huff_sym fast_sym[UFBXI_HUFF_FAST_SIZE]; // < Lookup from N bytes to symbol information
1996 ufbxi_huff_sym long_sym[UFBXI_HUFF_MAX_LONG_SYMS]; // < Fast long symbol lookup
1997 ufbxi_huff_sym sorted_to_sym[UFBXI_HUFF_MAX_VALUE]; // < Symbol information per sorted index
1998
1999 uint32_t extra_shift_base[UFBXI_HUFF_MAX_EXTRA_SYMS]; // < [0:6] shift [16:32] base value
2000 uint16_t extra_mask[UFBXI_HUFF_MAX_EXTRA_SYMS]; // < Mask for extra bits
2001
2002 uint16_t past_max_code[UFBXI_HUFF_MAX_BITS]; // < One past maximum code value per bit length
2003 int16_t code_to_sorted[UFBXI_HUFF_MAX_BITS]; // < Code to sorted symbol index per bit length
2004 uint32_t num_symbols;
2005
2006 uint32_t end_of_block_bits;
2007 } ufbxi_huff_tree;
2008
2009 typedef struct {
2010 union {
2011 struct {
2012 ufbxi_huff_tree lit_length;
2013 ufbxi_huff_tree dist;
2014 };
2015 ufbxi_huff_tree trees[2];
2016 };
2017 uint32_t fast_bits;
2018 } ufbxi_trees;
2019
2020 typedef struct {
2021 bool initialized;
2022 ufbxi_trees static_trees;
2023 } ufbxi_inflate_retain_imp;
2024
2025 ufbx_static_assert(inflate_retain_size, sizeof(ufbxi_inflate_retain_imp) <= sizeof(ufbx_inflate_retain));
2026
2027 typedef struct {
2028 ufbxi_bit_stream stream;
2029 uint32_t fast_bits;
2030
2031 char *out_begin;
2032 char *out_ptr;
2033 char *out_end;
2034 } ufbxi_deflate_context;
2035
2036 static ufbxi_forceinline uint32_t
2037 ufbxi_bit_reverse(uint32_t mask, uint32_t num_bits)
2038 {
2039 ufbxi_dev_assert(num_bits <= 16);
2040 uint32_t x = mask;
2041 x = (((x & 0xaaaa) >> 1) | ((x & 0x5555) << 1));
2042 x = (((x & 0xcccc) >> 2) | ((x & 0x3333) << 2));
2043 x = (((x & 0xf0f0) >> 4) | ((x & 0x0f0f) << 4));
2044 x = (((x & 0xff00) >> 8) | ((x & 0x00ff) << 8));
2045 return x >> (16 - num_bits);
2046 }
2047
2048 static ufbxi_noinline const char *
2049 ufbxi_bit_chunk_refill(ufbxi_bit_stream *s, const char *ptr)
2050 {
2051 // Copy any left-over data to the beginning of `buffer`
2052 size_t left = ufbxi_to_size(s->chunk_real_end - ptr);
2053 ufbxi_dev_assert(left < 64);
2054 if (left > 0) memmove(s->buffer, ptr, left);
2055
2056 s->num_read_before_chunk += ufbxi_to_size(ptr - s->chunk_begin);
2057
2058 // Read more user data if the user supplied a `read_fn()`, otherwise
2059 // we assume the initial data chunk is the whole input buffer.
2060 if (s->read_fn && !s->cancelled) {
2061 size_t to_read = ufbxi_min_sz(s->input_left, s->buffer_size - left);
2062 if (to_read > 0) {
2063 size_t num_read = s->read_fn(s->read_user, s->buffer + left, to_read);
2064 // TODO: IO error, should unify with (currently broken) cancel logic
2065 if (num_read > to_read) num_read = 0;
2066 ufbxi_dev_assert(s->input_left >= num_read);
2067 s->input_left -= num_read;
2068 left += num_read;
2069 }
2070 }
2071
2072 // Pad the rest with zeros
2073 if (left < 64) {
2074 memset(s->buffer + left, 0, 64 - left);
2075 left = 64;
2076 }
2077
2078 s->chunk_begin = s->buffer;
2079 s->chunk_ptr = s->buffer;
2080 s->chunk_end = s->buffer + left - 8;
2081 s->chunk_real_end = s->buffer + left;
2082 return s->buffer;
2083 }
2084
2085 static ufbxi_noinline void ufbxi_bit_stream_init(ufbxi_bit_stream *s, const ufbx_inflate_input *input)
2086 {
2087 size_t data_size = input->data_size;
2088 if (data_size > input->total_size) {
2089 data_size = input->total_size;
2090 }
2091
2092 s->read_fn = input->read_fn;
2093 s->read_user = input->read_user;
2094 s->progress_cb = input->progress_cb;
2095 s->chunk_begin = (const char*)input->data;
2096 s->chunk_ptr = (const char*)input->data;
2097 s->chunk_end = ufbxi_add_ptr((const char*)input->data, ufbxi_max_sz(8, data_size) - 8);
2098 s->chunk_real_end = ufbxi_add_ptr((const char*)input->data, data_size);
2099 s->input_left = input->total_size - data_size;
2100
2101 // Use the user buffer if it's large enough, otherwise `local_buffer`
2102 if (input->buffer_size > sizeof(s->local_buffer)) {
2103 s->buffer = (char*)input->buffer;
2104 s->buffer_size = input->buffer_size;
2105 } else {
2106 s->buffer = s->local_buffer;
2107 s->buffer_size = sizeof(s->local_buffer);
2108 }
2109 s->num_read_before_chunk = 0;
2110 s->progress_bias = input->progress_size_before;
2111 s->progress_total = input->total_size + input->progress_size_before + input->progress_size_after;
2112 if (!s->progress_cb.fn || input->progress_interval_hint >= SIZE_MAX) {
2113 s->progress_interval = SIZE_MAX;
2114 } else if (input->progress_interval_hint > 0) {
2115 s->progress_interval = (size_t)input->progress_interval_hint;
2116 } else {
2117 s->progress_interval = 0x4000;
2118 }
2119 s->cancelled = false;
2120
2121 // Clear the initial bit buffer
2122 s->bits = 0;
2123 s->left = 0;
2124
2125 // If the initial data buffer is not large enough to be read directly
2126 // from refill the chunk once.
2127 if (data_size < 64) {
2128 ufbxi_bit_chunk_refill(s, s->chunk_begin);
2129 }
2130
2131 if (s->progress_cb.fn && ufbxi_to_size(s->chunk_end - s->chunk_ptr) > s->progress_interval + 8) {
2132 s->chunk_yield = s->chunk_ptr + s->progress_interval;
2133 } else {
2134 s->chunk_yield = s->chunk_end;
2135 }
2136 }
2137
2138 static ufbxi_noinline const char *
2139 ufbxi_bit_yield(ufbxi_bit_stream *s, const char *ptr)
2140 {
2141 if (ptr > s->chunk_end) {
2142 ptr = ufbxi_bit_chunk_refill(s, ptr);
2143 }
2144
2145 if (s->progress_cb.fn) {
2146 size_t num_read = s->num_read_before_chunk + ufbxi_to_size(ptr - s->chunk_begin);
2147
2148 ufbx_progress progress = { s->progress_bias + num_read, s->progress_total };
2149 uint32_t result = (uint32_t)s->progress_cb.fn(s->progress_cb.user, &progress);
2150 ufbx_assert(result == UFBX_PROGRESS_CONTINUE || result == UFBX_PROGRESS_CANCEL);
2151 if (result == UFBX_PROGRESS_CANCEL) {
2152 s->cancelled = true;
2153 ptr = s->local_buffer;
2154 s->buffer = s->local_buffer;
2155 s->buffer_size = sizeof(s->local_buffer);
2156 s->chunk_begin = ptr;
2157 s->chunk_ptr = ptr;
2158 s->chunk_end = ptr + sizeof(s->local_buffer) - 8;
2159 s->chunk_real_end = ptr + sizeof(s->local_buffer);
2160 memset(s->local_buffer, 0, sizeof(s->local_buffer));
2161 }
2162 }
2163
2164 if (s->progress_cb.fn && ufbxi_to_size(s->chunk_end - ptr) > s->progress_interval + 8) {
2165 s->chunk_yield = ptr + s->progress_interval;
2166 } else {
2167 s->chunk_yield = s->chunk_end;
2168 }
2169
2170 return ptr;
2171 }
2172
2173 static ufbxi_forceinline void
2174 ufbxi_bit_refill(uint64_t *p_bits, size_t *p_left, const char **p_data, ufbxi_bit_stream *s)
2175 {
2176 if (*p_data > s->chunk_yield) {
2177 *p_data = ufbxi_bit_yield(s, *p_data);
2178 if (s->cancelled) {
2179 // Force an end-of-block symbol when cancelled so we don't need an
2180 // extra branch in the chunk decoding loop.
2181 *p_bits = s->cancel_bits;
2182 }
2183 }
2184
2185 // See https://fgiesen.wordpress.com/2018/02/20/reading-bits-in-far-too-many-ways-part-2/
2186 // variant 4. This branchless refill guarantees [56,63] bits to be valid in `*p_bits`.
2187 ufbxi_regression_assert(*p_left <= 64); \
2188 *p_bits |= ufbxi_read_u64(*p_data) << *p_left;
2189 *p_data += (63 - *p_left) >> 3;
2190 *p_left |= 56;
2191 }
2192
2193 // See `ufbxi_bit_refill()`
2194 #define ufbxi_macro_bit_refill_fast(m_bits, m_left, m_data, m_refill_bits) do { \
2195 ufbxi_regression_assert(m_left <= 64); \
2196 m_bits |= m_refill_bits << m_left; \
2197 m_data += (63 - m_left) >> 3; \
2198 m_left |= 56; \
2199 } while (0)
2200
2201 static ufbxi_noinline int
2202 ufbxi_bit_copy_bytes(void *dst, ufbxi_bit_stream *s, size_t len)
2203 {
2204 ufbx_assert(s->left % 8 == 0);
2205 char *ptr = (char*)dst;
2206
2207 // Copy the buffered bits first
2208 while (len > 0 && s->left > 0) {
2209 *ptr++ = (char)(uint8_t)s->bits;
2210 len -= 1;
2211 s->bits >>= 8;
2212 s->left -= 8;
2213 }
2214
2215 // We need to clear the top bits as there may be data
2216 // read ahead past `s->left` in some cases
2217 s->bits = 0;
2218
2219 // Copy the current chunk
2220 size_t chunk_left = ufbxi_to_size(s->chunk_real_end - s->chunk_ptr);
2221 if (chunk_left >= len) {
2222 memcpy(ptr, s->chunk_ptr, len);
2223 s->chunk_ptr += len;
2224 return 1;
2225 } else {
2226 memcpy(ptr, s->chunk_ptr, chunk_left);
2227 s->chunk_ptr += chunk_left;
2228 ptr += chunk_left;
2229 len -= chunk_left;
2230 }
2231
2232 // Read extra bytes from user
2233 if (len > s->input_left) return 0;
2234 size_t num_read = 0;
2235 if (s->read_fn) {
2236 num_read = s->read_fn(s->read_user, ptr, len);
2237 s->input_left -= num_read;
2238 }
2239 return num_read == len;
2240 }
2241
2242 // 0: Success
2243 // -1: Overfull
2244 // -2: Underfull
2245 static ufbxi_noinline ptrdiff_t
2246 ufbxi_huff_build_imp(ufbxi_huff_tree *tree, uint8_t *sym_bits, uint32_t sym_count, const uint32_t *sym_extra, uint32_t sym_extra_offset, uint32_t fast_bits, uint32_t *bits_counts)
2247 {
2248 uint32_t fast_mask = (1u << fast_bits) - 1;
2249
2250 ufbx_assert(sym_count <= UFBXI_HUFF_MAX_VALUE);
2251 tree->num_symbols = sym_count;
2252
2253 uint32_t nonzero_sym_count = sym_count - bits_counts[0];
2254
2255 uint32_t total_syms[UFBXI_HUFF_MAX_BITS]; // ufbxi_uninit
2256 uint32_t first_code[UFBXI_HUFF_MAX_BITS]; // ufbxi_uninit
2257
2258 tree->code_to_sorted[0] = INT16_MAX;
2259 tree->past_max_code[0] = 0;
2260 total_syms[0] = 0;
2261
2262 // Clear to uninitialized symbols
2263 #if defined(UFBX_REGRESSION)
2264 {
2265 for (size_t i = 0; i < UFBXI_HUFF_FAST_SIZE; i++) {
2266 tree->fast_sym[i] = UFBXI_HUFF_UNINITIALIZED_SYM;
2267 }
2268 for (size_t i = 0; i < UFBXI_HUFF_MAX_VALUE; i++) {
2269 tree->sorted_to_sym[i] = UFBXI_HUFF_UNINITIALIZED_SYM;
2270 }
2271 for (size_t i = 0; i < UFBXI_HUFF_MAX_LONG_SYMS; i++) {
2272 tree->long_sym[i] = UFBXI_HUFF_UNINITIALIZED_SYM;
2273 }
2274 }
2275 #endif
2276
2277 uint32_t last_valid_prefix = 0;
2278
2279 // Resolve the maximum code per bit length and ensure that the tree is not
2280 // overfull or underfull.
2281 {
2282 int num_codes_left = 1;
2283 uint32_t code = 0;
2284 uint32_t prev_count = 0;
2285 uint32_t long_offset = 0;
2286 for (uint32_t bits = 1; bits < UFBXI_HUFF_MAX_BITS; bits++) {
2287 uint32_t count = bits_counts[bits];
2288 code = (code + prev_count) << 1;
2289 first_code[bits] = code;
2290 tree->past_max_code[bits] = (uint16_t)(code + count);
2291
2292 uint32_t prev_syms = total_syms[bits - 1];
2293 total_syms[bits] = prev_syms + count;
2294
2295 // Each bit level doubles the amount of codes and potentially removes some
2296 num_codes_left = (num_codes_left << 1) - (int32_t)count;
2297 if (num_codes_left < 0) {
2298 return -1;
2299 }
2300
2301 if (count > 0 && bits > fast_bits && bits - fast_bits <= UFBXI_HUFF_MAX_LONG_BITS) {
2302 uint32_t shift = bits - fast_bits;
2303 uint32_t last_inclusive = num_codes_left == 0 ? (1u<<shift) - 1u : 0u;
2304 uint32_t first_prefix = code >> shift;
2305 uint32_t last_prefix = (code + count + last_inclusive) >> shift;
2306 uint32_t mask = (1u << shift) - 1u;
2307 uint32_t half_step = 1u << (shift - 1u);
2308 for (uint32_t prefix = first_prefix; prefix < last_prefix; prefix++) {
2309 uint32_t rev_prefix = ufbxi_bit_reverse(prefix, fast_bits);
2310 tree->fast_sym[rev_prefix] = (ufbxi_huff_sym)(mask | (long_offset << 8));
2311 long_offset += half_step;
2312 }
2313
2314 last_valid_prefix = last_prefix;
2315 }
2316
2317 if (count > 0) {
2318 tree->code_to_sorted[bits] = (int16_t)((int)prev_syms - (int)code);
2319 } else {
2320 tree->code_to_sorted[bits] = INT16_MAX;
2321 }
2322 prev_count = count;
2323 }
2324
2325 // All codes should be used if there's more than one symbol, if there's only one symbol there should be
2326 // only a single 1-bit code.
2327 if (nonzero_sym_count > 1 && num_codes_left != 0) {
2328 return -2;
2329 } else if (nonzero_sym_count == 1 && total_syms[1] != 1) {
2330 return -2;
2331 }
2332
2333 // We should always have enough space for long symbols as we support up to 5 (UFBXI_HUFF_MAX_LONG_BITS)
2334 // bits and the largest tree has 286 symbols. For each bit we may waste at most 2^bits slots (conservative)
2335 // and in the end we may waste 2^5 slots giving us `286+2+4+8+16+32+32 = 380` (UFBXI_HUFF_MAX_LONG_SYMS)
2336 ufbx_assert(long_offset <= UFBXI_HUFF_MAX_LONG_SYMS);
2337 }
2338
2339 tree->end_of_block_bits = 0;
2340 uint32_t num_extra = 0;
2341 tree->extra_shift_base[0] = 0;
2342 tree->extra_mask[0] = 0;
2343
2344 // Fill `fast_sym[]` with error symbols if necessary, we don't need to do this if we have two or more symbols
2345 // as the tree is guaranteed to be full, which means we will populate the whole `fast_sym[]`
2346 if (nonzero_sym_count <= 1) {
2347 for (uint32_t i = 0; i <= fast_mask; i++) {
2348 tree->fast_sym[i] = UFBXI_HUFF_ERROR_SYM;
2349 }
2350 }
2351
2352 // Generate per-length sorted-to-symbol and fast lookup tables
2353 uint32_t bits_index[UFBXI_HUFF_MAX_BITS] = { 0 };
2354 for (uint32_t i = 0; i < sym_count; i++) {
2355 uint32_t bits = sym_bits[i];
2356 if (bits == 0) continue;
2357
2358 uint32_t sym = i << 8 | bits;
2359 if (i >= sym_extra_offset) {
2360 uint32_t extra = sym_extra[i - sym_extra_offset];
2361 sym += extra;
2362
2363 // Store length/distance codes with extra values in a table.
2364 // TODO: This is unnecessary for small values
2365 if ((extra & 0xffff001f) != 0 && (extra & 0x20) == 0) {
2366 uint32_t ix = ++num_extra;
2367 tree->extra_shift_base[ix] = (extra & 0xffff0000) | bits;
2368 tree->extra_mask[ix] = (uint16_t)((1u << (extra & 0x1f)) - 1);
2369 sym = (sym & 0xff) | ix << 8;
2370 }
2371
2372 }
2373
2374 uint32_t index = bits_index[bits]++;
2375 uint32_t sorted = total_syms[bits - 1] + index;
2376 tree->sorted_to_sym[sorted] = (ufbxi_huff_sym)sym;
2377
2378 // Reverse the code and fill all fast lookups with the reversed prefix
2379 uint32_t code = first_code[bits] + index;
2380 uint32_t rev_code = ufbxi_bit_reverse(code, bits);
2381
2382 if (bits <= fast_bits) {
2383 uint32_t fast_sym = sym;
2384 // The `end` and `fast` flags are mutually exclusive
2385 if ((fast_sym & UFBXI_HUFF_SYM_END) == 0) {
2386 fast_sym |= UFBXI_HUFF_SYM_FAST;
2387 }
2388 uint32_t hi_max = 1u << (fast_bits - bits);
2389 for (uint32_t hi = 0; hi < hi_max; hi++) {
2390 ufbxi_regression_assert(nonzero_sym_count <= 1 || tree->fast_sym[rev_code | hi << bits] == UFBXI_HUFF_UNINITIALIZED_SYM);
2391 tree->fast_sym[rev_code | hi << bits] = (ufbxi_huff_sym)fast_sym;
2392 }
2393 } else if (bits <= fast_bits + UFBXI_HUFF_MAX_LONG_BITS && (code >> (bits - fast_bits)) < last_valid_prefix) {
2394 uint32_t fast_sym = tree->fast_sym[rev_code & fast_mask];
2395 ufbxi_regression_assert(fast_sym != UFBXI_HUFF_UNINITIALIZED_SYM);
2396 uint32_t long_bits = 0;
2397
2398 uint32_t long_mask = fast_sym;
2399 while (long_bits < UFBXI_HUFF_MAX_LONG_BITS && (long_mask & 1) != 0) {
2400 long_mask >>= 1;
2401 long_bits += 1;
2402 }
2403 ufbxi_dev_assert(long_bits >= 1);
2404
2405 uint32_t long_base = fast_sym >> 7u; // aka (fast_sym >> 8) * 2
2406 uint32_t lo_bits = bits - fast_bits;
2407 uint32_t hi_max = 1u << (long_bits - lo_bits);
2408 uint32_t rev_suffix = rev_code >> fast_bits;
2409 for (uint32_t hi = 0; hi < hi_max; hi++) {
2410 ufbxi_regression_assert(tree->long_sym[long_base + (rev_suffix | hi << lo_bits)] == UFBXI_HUFF_UNINITIALIZED_SYM);
2411 tree->long_sym[long_base + (rev_suffix | hi << lo_bits)] = (ufbxi_huff_sym)sym;
2412 }
2413 } else {
2414 uint32_t fast_sym = (code >> (bits - fast_bits)) << 8;
2415 ufbxi_regression_assert(
2416 tree->fast_sym[rev_code & fast_mask] == UFBXI_HUFF_UNINITIALIZED_SYM ||
2417 tree->fast_sym[rev_code & fast_mask] == (ufbxi_huff_sym)fast_sym);
2418 tree->fast_sym[rev_code & fast_mask] = (ufbxi_huff_sym)fast_sym;
2419 }
2420
2421 // Make sure the end-of-block symbol goes through the slow path
2422 // Also store the end-of-block code so we can interrupt decoding
2423 if (i == 256) {
2424 tree->end_of_block_bits = rev_code;
2425 }
2426 }
2427
2428 // Make sure all `fast_sym[]` are filled with an initialized value.
2429 #if defined(UFBX_REGRESSION)
2430 {
2431 for (size_t i = 0; i < UFBXI_HUFF_FAST_SIZE; i++) {
2432 if (i <= fast_mask) {
2433 ufbx_assert(tree->fast_sym[i] != UFBXI_HUFF_UNINITIALIZED_SYM);
2434 } else {
2435 ufbx_assert(tree->fast_sym[i] == UFBXI_HUFF_UNINITIALIZED_SYM);
2436 }
2437 }
2438 for (size_t i = 0; i < nonzero_sym_count; i++) {
2439 ufbx_assert(tree->sorted_to_sym[i] != UFBXI_HUFF_UNINITIALIZED_SYM);
2440 }
2441 }
2442 #endif
2443
2444 return 0;
2445 }
2446
2447 // 0: Success
2448 // -1: Overfull
2449 // -2: Underfull
2450 static ufbxi_noinline ptrdiff_t
2451 ufbxi_huff_build(ufbxi_huff_tree *tree, uint8_t *sym_bits, uint32_t sym_count, const uint32_t *sym_extra, uint32_t sym_extra_offset, uint32_t fast_bits)
2452 {
2453 // Count the number of codes per bit length
2454 // `bits_counts[0]` contains the number of non-used symbols
2455 uint32_t bits_counts[UFBXI_HUFF_MAX_BITS]; // ufbxi_uninit
2456 memset(bits_counts, 0, sizeof(bits_counts));
2457 for (uint32_t i = 0; i < sym_count; i++) {
2458 uint32_t bits = sym_bits[i];
2459 ufbx_assert(bits < UFBXI_HUFF_MAX_BITS);
2460 bits_counts[bits]++;
2461 }
2462
2463 return ufbxi_huff_build_imp(tree, sym_bits, sym_count, sym_extra, sym_extra_offset, fast_bits, bits_counts);
2464 }
2465
2466 static ufbxi_forceinline ufbxi_huff_sym
2467 ufbxi_huff_decode_bits(const ufbxi_huff_tree *tree, uint64_t bits, uint32_t fast_bits, uint32_t fast_mask)
2468 {
2469 ufbxi_huff_sym sym = tree->fast_sym[bits & fast_mask];
2470 ufbxi_regression_assert(sym != UFBXI_HUFF_UNINITIALIZED_SYM);
2471
2472 if ((sym & (UFBXI_HUFF_SYM_FAST|UFBXI_HUFF_SYM_END)) != 0) {
2473 return sym;
2474 }
2475
2476 uint32_t tail = (uint32_t)(bits >> fast_bits);
2477 uint32_t long_mask = ufbxi_huff_sym_long_mask(sym);
2478 if (long_mask) {
2479 sym = tree->long_sym[ufbxi_huff_sym_long_offset(sym) + (tail & long_mask)];
2480 ufbxi_regression_assert(sym != UFBXI_HUFF_UNINITIALIZED_SYM);
2481 return sym;
2482 }
2483
2484 ufbxi_dev_assert(fast_bits <= 8);
2485
2486 uint32_t code = ufbxi_huff_sym_value(sym);
2487 uint32_t num_bits = fast_bits;
2488 for (;;) {
2489 code = code << 1 | (tail & 1);
2490 tail >>= 1;
2491 num_bits++;
2492
2493 ufbxi_regression_assert(num_bits < UFBXI_HUFF_MAX_BITS);
2494 if (code < tree->past_max_code[num_bits]) {
2495 sym = tree->sorted_to_sym[(int32_t)code + (int32_t)tree->code_to_sorted[num_bits]];
2496 ufbxi_regression_assert(sym != UFBXI_HUFF_UNINITIALIZED_SYM);
2497 return sym;
2498 }
2499 }
2500 }
2501
2502 static ufbxi_noinline void ufbxi_init_static_huff(ufbxi_trees *trees, const ufbx_inflate_input *input)
2503 {
2504 ptrdiff_t err = 0;
2505
2506 // Override `fast_bits` if necessary, this must always be valid as it's checked in the beginning of `ufbx_inflate()`.
2507 if (input && input->internal_fast_bits != 0) {
2508 trees->fast_bits = (uint32_t)input->internal_fast_bits;
2509 ufbx_assert(!(trees->fast_bits < 1 || trees->fast_bits == 9 || trees->fast_bits > 10));
2510 } else {
2511 trees->fast_bits = UFBXI_HUFF_FAST_BITS;
2512 }
2513
2514 // 0-143: 8 bits, 144-255: 9 bits, 256-279: 7 bits, 280-287: 8 bits
2515 uint8_t lit_length_bits[288]; // ufbxi_uninit
2516 memset(lit_length_bits + 0, 8, 144 - 0);
2517 memset(lit_length_bits + 144, 9, 256 - 144);
2518 memset(lit_length_bits + 256, 7, 280 - 256);
2519 memset(lit_length_bits + 280, 8, 288 - 280);
2520 err |= ufbxi_huff_build(&trees->lit_length, lit_length_bits, sizeof(lit_length_bits), ufbxi_deflate_length_lut, 256, trees->fast_bits);
2521
2522 // "Distance codes 0-31 are represented by (fixed-length) 5-bit codes"
2523 uint8_t dist_bits[32]; // ufbxi_uninit
2524 memset(dist_bits + 0, 5, 32 - 0);
2525 err |= ufbxi_huff_build(&trees->dist, dist_bits, sizeof(dist_bits), ufbxi_deflate_dist_lut, 0, trees->fast_bits);
2526
2527 // Building the static trees cannot fail as we use pre-defined code lengths.
2528 ufbxi_ignore(err);
2529 ufbx_assert(err == 0);
2530 }
2531
2532 // 0: Success
2533 // -1: Huffman Overfull
2534 // -2: Huffman Underfull
2535 // -3: Code 16 repeat overflow
2536 // -4: Code 17 repeat overflow
2537 // -5: Code 18 repeat overflow
2538 // -6: Bad length code
2539 // -7: Cancelled
2540 static ufbxi_noinline ptrdiff_t ufbxi_init_dynamic_huff_tree(ufbxi_deflate_context *dc, const ufbxi_huff_tree *huff_code_length, ufbxi_huff_tree *tree,
2541 uint32_t num_symbols, const uint32_t *sym_extra, uint32_t sym_extra_offset, uint32_t fast_bits)
2542 {
2543 uint8_t code_lengths[UFBXI_HUFF_MAX_VALUE]; // ufbxi_uninit
2544 ufbx_assert(num_symbols <= UFBXI_HUFF_MAX_VALUE);
2545
2546 uint64_t bits = dc->stream.bits;
2547 size_t left = dc->stream.left;
2548 const char *data = dc->stream.chunk_ptr;
2549 uint32_t bits_counts[UFBXI_HUFF_MAX_BITS]; // ufbxi_uninit
2550 memset(bits_counts, 0, sizeof(bits_counts));
2551
2552 uint32_t symbol_index = 0;
2553 uint8_t prev = 0;
2554 while (symbol_index < num_symbols) {
2555 ufbxi_bit_refill(&bits, &left, &data, &dc->stream);
2556 if (dc->stream.cancelled) return -7;
2557
2558 ufbxi_huff_sym sym = ufbxi_huff_decode_bits(huff_code_length, bits, UFBXI_HUFF_CODELEN_FAST_BITS, UFBXI_HUFF_CODELEN_FAST_MASK);
2559 ufbxi_regression_assert(sym != UFBXI_HUFF_UNINITIALIZED_SYM);
2560
2561 uint32_t inst = ufbxi_huff_sym_value(sym);
2562 uint32_t sym_len = ufbxi_huff_sym_total_bits(sym);
2563
2564 bits >>= sym_len;
2565 left -= sym_len;
2566
2567 if (inst <= 15) {
2568 // "0 - 15: Represent code lengths of 0 - 15"
2569 prev = (uint8_t)inst;
2570 code_lengths[symbol_index++] = (uint8_t)inst;
2571 bits_counts[(int32_t)inst]++;
2572 } else if (inst == 16) {
2573 // "16: Copy the previous code length 3 - 6 times. The next 2 bits indicate repeat length."
2574 uint32_t num = 3 + ((uint32_t)bits & 0x3);
2575 bits >>= 2;
2576 left -= 2;
2577 if (symbol_index + num > num_symbols) return -3;
2578 memset(code_lengths + symbol_index, prev, num);
2579 symbol_index += num;
2580 bits_counts[(int32_t)prev] += num;
2581 } else if (inst == 17) {
2582 // "17: Repeat a code length of 0 for 3 - 10 times. (3 bits of length)"
2583 uint32_t num = 3 + ((uint32_t)bits & 0x7);
2584 bits >>= 3;
2585 left -= 3;
2586 if (symbol_index + num > num_symbols) return -4;
2587 memset(code_lengths + symbol_index, 0, num);
2588 symbol_index += num;
2589 prev = 0;
2590 bits_counts[0] += num;
2591 } else if (inst == 18) {
2592 // "18: Repeat a code length of 0 for 11 - 138 times (7 bits of length)"
2593 uint32_t num = 11 + ((uint32_t)bits & 0x7f);
2594 bits >>= 7;
2595 left -= 7;
2596 if (symbol_index + num > num_symbols) return -5;
2597 memset(code_lengths + symbol_index, 0, num);
2598 symbol_index += num;
2599 prev = 0;
2600 bits_counts[0] += num;
2601 } else {
2602 return -6;
2603 }
2604 }
2605
2606 ptrdiff_t err = ufbxi_huff_build_imp(tree, code_lengths, num_symbols, sym_extra, sym_extra_offset, fast_bits, bits_counts);
2607 if (err != 0) return err;
2608
2609 dc->stream.bits = bits;
2610 dc->stream.left = left;
2611 dc->stream.chunk_ptr = data;
2612
2613 return 0;
2614 }
2615
2616 static ufbxi_noinline ptrdiff_t
2617 ufbxi_init_dynamic_huff(ufbxi_deflate_context *dc, ufbxi_trees *trees)
2618 {
2619 uint64_t bits = dc->stream.bits;
2620 size_t left = dc->stream.left;
2621 const char *data = dc->stream.chunk_ptr;
2622 ufbxi_bit_refill(&bits, &left, &data, &dc->stream);
2623 if (dc->stream.cancelled) return -28;
2624
2625 trees->fast_bits = dc->fast_bits;
2626
2627 // The header contains the number of Huffman codes in each of the three trees.
2628 uint32_t num_lit_lengths = 257 + (uint32_t)(bits & 0x1f);
2629 uint32_t num_dists = 1 + (uint32_t)(bits >> 5 & 0x1f);
2630 uint32_t num_code_lengths = 4 + (uint32_t)(bits >> 10 & 0xf);
2631 bits >>= 14;
2632 left -= 14;
2633
2634 // Code lengths for the "code length" Huffman tree are represented literally
2635 // 3 bits in order of: 16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15 up to
2636 // `num_code_lengths`, rest of the code lengths are 0 (unused)
2637 uint8_t code_lengths[19]; // ufbxi_uninit
2638 memset(code_lengths, 0, sizeof(code_lengths));
2639 for (size_t len_i = 0; len_i < num_code_lengths; len_i++) {
2640 if (len_i == 14) {
2641 ufbxi_bit_refill(&bits, &left, &data, &dc->stream);
2642 if (dc->stream.cancelled) return -28;
2643 }
2644 code_lengths[ufbxi_deflate_code_length_permutation[len_i]] = (uint32_t)bits & 0x7;
2645 bits >>= 3;
2646 left -= 3;
2647 }
2648
2649 dc->stream.bits = bits;
2650 dc->stream.left = left;
2651 dc->stream.chunk_ptr = data;
2652
2653 ufbxi_huff_tree huff_code_length; // ufbxi_uninit
2654 ptrdiff_t err; // ufbxi_uninit
2655
2656 // Build the temporary "code length" Huffman tree used to encode the actual
2657 // trees used to compress the data. Use that to build the literal/length and
2658 // distance trees.
2659 err = ufbxi_huff_build(&huff_code_length, code_lengths, ufbxi_arraycount(code_lengths), NULL, INT32_MAX, UFBXI_HUFF_CODELEN_FAST_BITS);
2660 if (err) return -14 + 1 + err;
2661 err = ufbxi_init_dynamic_huff_tree(dc, &huff_code_length, &trees->lit_length, num_lit_lengths, ufbxi_deflate_length_lut, 256, dc->fast_bits);
2662 if (err) return err == -7 ? -28 : -16 + 1 + err;
2663 err = ufbxi_init_dynamic_huff_tree(dc, &huff_code_length, &trees->dist, num_dists, ufbxi_deflate_dist_lut, 0, dc->fast_bits);
2664 if (err) return err == -7 ? -28 : -22 + 1 + err;
2665
2666 return 0;
2667 }
2668
2669 static ufbxi_noinline uint32_t ufbxi_adler32(const void *data, size_t size)
2670 {
2671 ufbxi_fast_uint a = 1, b = 0;
2672 const char *p = (const char*)data;
2673
2674 // Adler-32 consists of two running sums modulo 65521. As an optimization
2675 // we can accumulate N sums before applying the modulo, where N depends on
2676 // the size of the type holding the sum.
2677 const ufbxi_fast_uint num_before_wrap = sizeof(ufbxi_fast_uint) == 8 ? 380368439u : 5552u;
2678
2679 ufbxi_fast_uint size_left = size;
2680 while (size_left > 0) {
2681 ufbxi_fast_uint num = size_left <= num_before_wrap ? size_left : num_before_wrap;
2682 size_left -= num;
2683 const char *end = p + num;
2684
2685 // Align to 16 bytes
2686 while (p != end && !ufbxi_is_aligned(p, 16)) {
2687 a += (ufbxi_fast_uint)(uint8_t)p[0]; b += a;
2688 p++;
2689 }
2690
2691 #if UFBXI_HAS_SSE
2692 static const uint16_t factors[2][8] = {
2693 { 16, 15, 14, 13, 12, 11, 10, 9, },
2694 { 8, 7, 6, 5, 4, 3, 2, 1, },
2695 };
2696
2697 const __m128i zero = _mm_setzero_si128();
2698 const __m128i factor_1 = _mm_set1_epi16(1);
2699 const __m128i factor_16 = _mm_set1_epi16(16);
2700 const __m128i factor_lo = _mm_loadu_si128((const __m128i*)factors[0]);
2701 const __m128i factor_hi = _mm_loadu_si128((const __m128i*)factors[1]);
2702
2703 for (;;) {
2704 size_t chunk_size = ufbxi_min_sz(ufbxi_to_size(end - p), 5803) & ~(size_t)0xff;
2705 if (chunk_size == 0) break;
2706 const char *chunk_end = p + chunk_size;
2707
2708 __m128i s1 = zero;
2709 __m128i s2 = zero;
2710
2711 while (p != chunk_end) {
2712 __m128i s1_lo = zero, s1_hi = zero;
2713 __m128i tmp_lo = zero, tmp_hi = zero;
2714
2715 ufbxi_nounroll for (size_t i = 0; i < 256; i += 32) {
2716 __m128i d0 = _mm_load_si128((const __m128i*)(p + i + 0));
2717 __m128i d1 = _mm_load_si128((const __m128i*)(p + i + 16));
2718
2719 tmp_lo = _mm_add_epi16(tmp_lo, s1_lo);
2720 tmp_hi = _mm_add_epi16(tmp_hi, s1_hi);
2721 s1_lo = _mm_add_epi16(s1_lo, _mm_unpacklo_epi8(d0, zero));
2722 s1_hi = _mm_add_epi16(s1_hi, _mm_unpackhi_epi8(d0, zero));
2723
2724 tmp_lo = _mm_add_epi16(tmp_lo, s1_lo);
2725 tmp_hi = _mm_add_epi16(tmp_hi, s1_hi);
2726 s1_lo = _mm_add_epi16(s1_lo, _mm_unpacklo_epi8(d1, zero));
2727 s1_hi = _mm_add_epi16(s1_hi, _mm_unpackhi_epi8(d1, zero));
2728 }
2729
2730 s2 = _mm_add_epi32(s2, _mm_slli_epi32(s1, 8));
2731 s1 = _mm_add_epi32(s1, _mm_madd_epi16(s1_lo, factor_1));
2732 s1 = _mm_add_epi32(s1, _mm_madd_epi16(s1_hi, factor_1));
2733
2734 s2 = _mm_add_epi32(s2, _mm_madd_epi16(tmp_lo, factor_16));
2735 s2 = _mm_add_epi32(s2, _mm_madd_epi16(tmp_hi, factor_16));
2736 s2 = _mm_add_epi32(s2, _mm_madd_epi16(s1_lo, factor_lo));
2737 s2 = _mm_add_epi32(s2, _mm_madd_epi16(s1_hi, factor_hi));
2738
2739 p += 256;
2740 }
2741
2742 s1 = _mm_add_epi32(s1, _mm_shuffle_epi32(s1, _MM_SHUFFLE(2,3,0,1)));
2743 s2 = _mm_add_epi32(s2, _mm_shuffle_epi32(s2, _MM_SHUFFLE(2,3,0,1)));
2744 s1 = _mm_add_epi32(s1, _mm_shuffle_epi32(s1, _MM_SHUFFLE(1,0,3,2)));
2745 s2 = _mm_add_epi32(s2, _mm_shuffle_epi32(s2, _MM_SHUFFLE(1,0,3,2)));
2746
2747 b += chunk_size * a;
2748 a += (uint32_t)_mm_cvtsi128_si32(s1);
2749 b += (uint32_t)_mm_cvtsi128_si32(s2);
2750 }
2751 #elif UFBX_LITTLE_ENDIAN
2752 for (;;) {
2753 size_t chunk_size = ufbxi_min_sz(ufbxi_to_size(end - p), 256*8/4) & ~(size_t)0xf;
2754 if (chunk_size == 0) break;
2755 const char *chunk_end = p + chunk_size;
2756
2757 uint64_t s1_lo = 0, s1_hi = 0;
2758 uint64_t tmp, s2 = 0;
2759 uint64_t mask8 = UINT64_C(0x00ff00ff00ff00ff);
2760 uint64_t mask16 = UINT64_C(0x0000ffff0000ffff);
2761
2762 while (p != chunk_end) {
2763 uint64_t d0 = *(const uint64_t*)p;
2764 uint64_t d1 = *(const uint64_t*)(p + 8);
2765
2766 tmp = s1_lo + s1_hi;
2767 s1_lo += d0 & mask8;
2768 s1_hi += (d0 >> 8) & mask8;
2769
2770 tmp += s1_lo + s1_hi;
2771 s1_lo += d1 & mask8;
2772 s1_hi += (d1 >> 8) & mask8;
2773
2774 s2 += (tmp & mask16) + ((tmp >> 16) & mask16);
2775 p += 16;
2776 }
2777
2778 uint64_t s1 = s1_lo + s1_hi;
2779 s1 = (s1 & mask16) + ((s1 >> 16u) & mask16);
2780 ufbxi_fast_uint s1_sum = (ufbxi_fast_uint)(s1 + (s1 >> 32u));
2781
2782 ufbxi_fast_uint s2_sum = (ufbxi_fast_uint)(s2 + (s2 >> 32u)) * 8;
2783 s2_sum += ((ufbxi_fast_uint)(s1_lo >> 0) & 0xffff) * 8;
2784 s2_sum += ((ufbxi_fast_uint)(s1_hi >> 0) & 0xffff) * 7;
2785 s2_sum += ((ufbxi_fast_uint)(s1_lo >> 16) & 0xffff) * 6;
2786 s2_sum += ((ufbxi_fast_uint)(s1_hi >> 16) & 0xffff) * 5;
2787 s2_sum += ((ufbxi_fast_uint)(s1_lo >> 32) & 0xffff) * 4;
2788 s2_sum += ((ufbxi_fast_uint)(s1_hi >> 32) & 0xffff) * 3;
2789 s2_sum += ((ufbxi_fast_uint)(s1_lo >> 48) & 0xffff) * 2;
2790 s2_sum += ((ufbxi_fast_uint)(s1_hi >> 48) & 0xffff) * 1;
2791
2792 b += chunk_size * a;
2793 a += s1_sum & 0xffffffffu;
2794 b += s2_sum & 0xffffffffu;
2795 }
2796 #endif
2797
2798 while (p != end) {
2799 a += (size_t)(uint8_t)p[0]; b += a;
2800 p++;
2801 }
2802
2803 a %= 65521u;
2804 b %= 65521u;
2805 }
2806
2807 return (uint32_t)((b << 16) | (a & 0xffff));
2808 }
2809
2810 static ufbxi_noinline int
2811 ufbxi_inflate_block_slow(ufbxi_deflate_context *dc, ufbxi_trees *trees, size_t max_symbols)
2812 {
2813 char *out_ptr = dc->out_ptr;
2814 char *const out_begin = dc->out_begin;
2815 char *const out_end = dc->out_end;
2816
2817 uint32_t fast_bits = trees->fast_bits;
2818 uint32_t fast_mask = (1u << fast_bits) - 1;
2819
2820 uint64_t bits = dc->stream.bits;
2821 size_t left = dc->stream.left;
2822 const char *data = dc->stream.chunk_ptr;
2823
2824 for (;;) {
2825 if (max_symbols-- == 0) break;
2826
2827 ufbxi_bit_refill(&bits, &left, &data, &dc->stream);
2828 uint64_t sym_bits = bits;
2829
2830 ufbxi_huff_sym sym0 = ufbxi_huff_decode_bits(&trees->lit_length, bits, fast_bits, fast_mask);
2831 ufbxi_regression_assert(sym0 != UFBXI_HUFF_UNINITIALIZED_SYM);
2832
2833 uint32_t sym0_bits = ufbxi_huff_sym_total_bits(sym0);
2834
2835 bits >>= sym0_bits;
2836 left -= sym0_bits;
2837 if (sym0 & UFBXI_HUFF_SYM_END) {
2838 if (ufbxi_huff_sym_value(sym0) != 0) return -13;
2839
2840 dc->out_ptr = out_ptr;
2841 dc->stream.bits = bits;
2842 dc->stream.left = left;
2843 dc->stream.chunk_ptr = data;
2844 return 0;
2845 } else if ((sym0 & UFBXI_HUFF_SYM_MATCH) == 0) {
2846 if (out_ptr == out_end) return -10;
2847 *out_ptr++ = (char)ufbxi_huff_sym_value(sym0);
2848 continue;
2849 }
2850
2851 uint32_t sym0_value = ufbxi_huff_sym_value(sym0);
2852 uint32_t len_shift_base = trees->lit_length.extra_shift_base[sym0_value];
2853 uint16_t len_mask = trees->lit_length.extra_mask[sym0_value];
2854 uint32_t length = (len_shift_base >> 16) + (uint32_t)(ufbxi_wrap_shr64(sym_bits, len_shift_base) & len_mask);
2855
2856 ufbxi_huff_sym sym1 = ufbxi_huff_decode_bits(&trees->dist, bits, fast_bits, fast_mask);
2857 ufbxi_regression_assert(sym1 != UFBXI_HUFF_UNINITIALIZED_SYM);
2858 if (sym1 & UFBXI_HUFF_SYM_END) return -11;
2859
2860 uint32_t sym1_bits = ufbxi_huff_sym_total_bits(sym1);
2861
2862 bits >>= sym1_bits;
2863 left -= sym1_bits;
2864
2865 uint32_t sym1_value = ufbxi_huff_sym_value(sym1);
2866 uint32_t dist_shift_base = trees->dist.extra_shift_base[sym1_value];
2867 uint16_t dist_mask = trees->dist.extra_mask[sym1_value];
2868 uint32_t distance = (dist_shift_base >> 16) + (uint32_t)(ufbxi_wrap_shr64(sym_bits, dist_shift_base + sym0) & dist_mask);
2869
2870 // Bounds checking
2871 size_t out_space = ufbxi_to_size(out_end - out_ptr);
2872 if ((ptrdiff_t)distance > out_ptr - out_begin || length > out_space) {
2873 return -12;
2874 }
2875
2876 // Copy the match
2877 const char *src = out_ptr - distance;
2878 char *dst = out_ptr;
2879 char *end = dst + length;
2880 out_ptr += length;
2881
2882 if (out_space >= length + 16) {
2883 uint32_t min_dist = length < 16 ? length : 16;
2884 if (distance >= min_dist) {
2885 ufbxi_copy_16_bytes(dst, src);
2886 while (length > 16) {
2887 src += 16;
2888 dst += 16;
2889 length -= 16;
2890 ufbxi_copy_16_bytes(dst, src);
2891 }
2892 } else {
2893 while (dst != end) {
2894 *dst++ = *src++;
2895 }
2896 }
2897 } else {
2898 while (dst != end) {
2899 *dst++ = *src++;
2900 }
2901 }
2902 }
2903
2904 dc->out_ptr = out_ptr;
2905 dc->stream.bits = bits;
2906 dc->stream.left = left;
2907 dc->stream.chunk_ptr = data;
2908 return 1;
2909 }
2910
2911 ufbx_static_assert(inflate_huff_fast_bits, UFBXI_HUFF_FAST_BITS <= 11); // `fast lit, fast len, slow dist` in 56 bits
2912 ufbx_static_assert(inflate_huff_long_bits, UFBXI_HUFF_FAST_BITS + UFBXI_HUFF_MAX_LONG_BITS >= 15); // Largest code fits in a single long lookup
2913
2914 // Optimized version of `ufbxi_inflate_block_slow()`.
2915 // Has a lot of assumptions (see asserts) and does not call _any_ (even forceinlined) functions.
2916 static ufbxi_noinline int
2917 ufbxi_inflate_block_fast(ufbxi_deflate_context *dc, ufbxi_trees *trees)
2918 {
2919 ufbxi_dev_assert(!dc->stream.cancelled);
2920 ufbxi_dev_assert(trees->fast_bits == UFBXI_HUFF_FAST_BITS);
2921 ufbxi_dev_assert(dc->stream.chunk_yield - dc->stream.chunk_ptr >= UFBXI_INFLATE_FAST_MIN_IN);
2922 ufbxi_dev_assert(dc->out_end - dc->out_ptr >= UFBXI_INFLATE_FAST_MIN_OUT);
2923
2924 char *out_ptr = dc->out_ptr;
2925 char *const out_begin = dc->out_begin;
2926 char *const out_end = dc->out_end - UFBXI_INFLATE_FAST_MIN_OUT;
2927
2928 const ufbxi_huff_tree *tree_lit_length = &trees->lit_length;
2929 const ufbxi_huff_tree *tree_dist = &trees->dist;
2930
2931 uint64_t bits = dc->stream.bits;
2932 size_t left = dc->stream.left;
2933 const char *data = dc->stream.chunk_ptr;
2934 const char *data_end = dc->stream.chunk_yield - UFBXI_INFLATE_FAST_MIN_IN;
2935
2936 uint64_t sym01_bits;
2937 ufbxi_huff_sym sym0, sym1;
2938 uint64_t refill_bits = ufbxi_read_u64(data);
2939
2940 #define ufbxi_fast_inflate_refill_and_decode() do { \
2941 ufbxi_macro_bit_refill_fast(bits, left, data, refill_bits); \
2942 sym01_bits = bits; \
2943 sym0 = tree_lit_length->fast_sym[sym01_bits & UFBXI_HUFF_FAST_MASK]; \
2944 sym1 = ((sym0 & UFBXI_HUFF_SYM_MATCH) ? tree_dist : tree_lit_length)->fast_sym[ufbxi_wrap_shr64(sym01_bits, sym0) & UFBXI_HUFF_FAST_MASK]; \
2945 refill_bits = ufbxi_read_u64(data); \
2946 } while (0)
2947
2948 #define ufbxi_fast_inflate_should_continue() \
2949 (((data_end - data) | (out_end - out_ptr)) >= 0)
2950
2951 ufbxi_fast_inflate_refill_and_decode();
2952
2953 for (;;) {
2954 if ((sym0 & sym1) & UFBXI_HUFF_SYM_FAST) {
2955 bits = ufbxi_wrap_shr64(sym01_bits, sym0 + sym1);
2956 left -= (sym0 + sym1) & 0x3f;
2957
2958 if (((sym0 | sym1) & UFBXI_HUFF_SYM_MATCH) == 0) {
2959 // Literal, Literal
2960 // -> Output the two literals and loop back to start.
2961
2962 out_ptr[0] = (char)ufbxi_huff_sym_value(sym0);
2963 out_ptr[1] = (char)ufbxi_huff_sym_value(sym1);
2964 out_ptr += 2;
2965
2966 ufbxi_fast_inflate_refill_and_decode();
2967 if (ufbxi_fast_inflate_should_continue()) continue;
2968 break;
2969
2970 } else if ((sym0 & UFBXI_HUFF_SYM_MATCH) == 0) {
2971 // Literal, Match, (Distance)
2972 // -> Output a single literal, decode the missing distance and fall through to match.
2973
2974 out_ptr[0] = (char)ufbxi_huff_sym_value(sym0);
2975 out_ptr += 1;
2976
2977 sym01_bits = ufbxi_wrap_shr64(sym01_bits, sym0);
2978
2979 // This must fit as literals never have extra bits and the match length is fast so:
2980 // 10 (lit) + 10 (len code) + 5 (len extra) + 15 (dist code) + 13 (dist extra) = 53 <= 56
2981 sym0 = sym1;
2982 sym1 = tree_dist->fast_sym[bits & UFBXI_HUFF_FAST_MASK];
2983
2984 if ((sym1 & UFBXI_HUFF_SYM_FAST) == 0) {
2985 // Slow sym1
2986 if (sym1 & UFBXI_HUFF_SYM_END) return -11;
2987 uint32_t tail = (uint32_t)(bits >> UFBXI_HUFF_FAST_BITS);
2988 uint32_t long_mask = ufbxi_huff_sym_long_mask(sym1);
2989 sym1 = tree_dist->long_sym[ufbxi_huff_sym_long_offset(sym1) + (tail & long_mask)];
2990 if (sym1 & UFBXI_HUFF_SYM_END) return -11;
2991 }
2992
2993 bits = ufbxi_wrap_shr64(bits, sym1);
2994 left -= sym1 & 0x3f;
2995 } else {
2996 // Match, Distance
2997 // -> Fall through to match copy.
2998 }
2999
3000 } else {
3001 if ((sym0 & (UFBXI_HUFF_SYM_FAST|UFBXI_HUFF_SYM_END)) == 0) {
3002 // Slow sym0
3003 uint32_t tail = (uint32_t)(sym01_bits >> UFBXI_HUFF_FAST_BITS);
3004 uint32_t long_mask = ufbxi_huff_sym_long_mask(sym0);
3005 sym0 = tree_lit_length->long_sym[ufbxi_huff_sym_long_offset(sym0) + (tail & long_mask)];
3006 }
3007
3008 uint32_t sym0_bits = ufbxi_huff_sym_total_bits(sym0);
3009 bits >>= sym0_bits;
3010 left -= sym0_bits;
3011
3012 if (sym0 & UFBXI_HUFF_SYM_END) {
3013 if (ufbxi_huff_sym_value(sym0) != 0) return -13;
3014 dc->out_ptr = out_ptr;
3015 dc->stream.bits = bits;
3016 dc->stream.left = left;
3017 dc->stream.chunk_ptr = data;
3018 return 0;
3019 }
3020
3021 if (sym0 & UFBXI_HUFF_SYM_MATCH) {
3022 sym1 = tree_dist->fast_sym[bits & UFBXI_HUFF_FAST_MASK];
3023
3024 if ((sym1 & UFBXI_HUFF_SYM_FAST) == 0) {
3025 // Slow sym1
3026 if (sym1 & UFBXI_HUFF_SYM_END) return -11;
3027 uint32_t tail = (uint32_t)(bits >> UFBXI_HUFF_FAST_BITS);
3028 uint32_t long_mask = ufbxi_huff_sym_long_mask(sym1);
3029 sym1 = tree_dist->long_sym[ufbxi_huff_sym_long_offset(sym1) + (tail & long_mask)];
3030 if (sym1 & UFBXI_HUFF_SYM_END) return -11;
3031 }
3032
3033 bits = ufbxi_wrap_shr64(bits, sym1);
3034 left -= sym1 & 0x3f;
3035 } else {
3036 *out_ptr++ = (char)ufbxi_huff_sym_value(sym0);
3037
3038 ufbxi_fast_inflate_refill_and_decode();
3039 if (ufbxi_fast_inflate_should_continue()) continue;
3040 break;
3041 }
3042 }
3043
3044 uint32_t sym0_value = ufbxi_huff_sym_value(sym0);
3045 uint32_t len_shift_base = trees->lit_length.extra_shift_base[sym0_value];
3046 uint16_t len_mask = trees->lit_length.extra_mask[sym0_value];
3047 uint32_t length = (len_shift_base >> 16) + (uint32_t)(ufbxi_wrap_shr64(sym01_bits, len_shift_base) & len_mask);
3048
3049 uint32_t sym1_value = ufbxi_huff_sym_value(sym1);
3050 uint32_t dist_shift_base = trees->dist.extra_shift_base[sym1_value];
3051 uint16_t dist_mask = trees->dist.extra_mask[sym1_value];
3052 uint32_t distance = (dist_shift_base >> 16) + (uint32_t)(ufbxi_wrap_shr64(sym01_bits, dist_shift_base + sym0) & dist_mask);
3053
3054 ufbxi_fast_inflate_refill_and_decode();
3055
3056 // Bounds checking: We don't actually handle the error here, just bail out to the slow implementation
3057 ptrdiff_t dst_space = out_end - out_ptr - (ptrdiff_t)length + UFBXI_INFLATE_FAST_MIN_OUT;
3058 ptrdiff_t src_space = out_ptr - out_begin - (ptrdiff_t)distance;
3059 if ((dst_space | src_space) < 0) {
3060 return -12;
3061 }
3062
3063 const char *src = out_ptr - distance;
3064 char *dst = out_ptr;
3065 char *end = dst + length;
3066 out_ptr += length;
3067
3068 // Copy the match
3069
3070 uint32_t min_dist = length < 16 ? length : 16;
3071 if (distance >= min_dist && dst_space >= 16) {
3072 ufbxi_copy_16_bytes(dst, src);
3073 while (length > 16) {
3074 src += 16;
3075 dst += 16;
3076 length -= 16;
3077 ufbxi_copy_16_bytes(dst, src);
3078 }
3079 } else {
3080 while (dst != end) {
3081 *dst++ = *src++;
3082 }
3083 }
3084
3085 if (ufbxi_fast_inflate_should_continue()) continue;
3086 break;
3087 }
3088
3089 dc->out_ptr = out_ptr;
3090 dc->stream.bits = bits;
3091 dc->stream.left = left;
3092 dc->stream.chunk_ptr = data;
3093 return 1;
3094
3095 #undef ufbxi_fast_inflate_refill_and_decode
3096 #undef ufbxi_fast_inflate_should_continue
3097 }
3098
3099 static void ufbxi_inflate_init_retain(ufbx_inflate_retain *retain)
3100 {
3101 ufbxi_inflate_retain_imp *ret_imp = (ufbxi_inflate_retain_imp*)retain;
3102 if (!ret_imp->initialized) {
3103 ufbxi_init_static_huff(&ret_imp->static_trees, NULL);
3104 ret_imp->initialized = true;
3105 }
3106 }
3107
3108 // TODO: Error codes should have a quick test if the destination buffer overflowed
3109 // Returns actual number of decompressed bytes or negative error:
3110 // -1: Bad compression method (ZLIB header)
3111 // -2: Requires dictionary (ZLIB header)
3112 // -3: Bad FCHECK (ZLIB header)
3113 // -4: Bad NLEN (Uncompressed LEN != ~NLEN)
3114 // -5: Uncompressed source overflow
3115 // -6: Uncompressed destination overflow
3116 // -7: Bad block type
3117 // -8: Truncated checksum (deprecated, reported as -9)
3118 // -9: Checksum mismatch
3119 // -10: Literal destination overflow
3120 // -11: Bad distance code or distance of (30..31)
3121 // -12: Match out of bounds
3122 // -13: Bad lit/length code
3123 // -14: Codelen Huffman Overfull
3124 // -15: Codelen Huffman Underfull
3125 // -16 - -21: Litlen Huffman: Overfull / Underfull / Repeat 16/17/18 overflow / Bad length code
3126 // -22 - -27: Distance Huffman: Overfull / Underfull / Repeat 16/17/18 overflow / Bad length code
3127 // -28: Cancelled
3128 // -29: Invalid ufbx_inflate_input.internal_fast_bits value
3129 ufbxi_extern_c ptrdiff_t ufbx_inflate(void *dst, size_t dst_size, const ufbx_inflate_input *input, ufbx_inflate_retain *retain)
3130 {
3131 ufbxi_inflate_retain_imp *ret_imp = (ufbxi_inflate_retain_imp*)retain;
3132
3133 ptrdiff_t err;
3134 ufbxi_deflate_context dc;
3135 ufbxi_bit_stream_init(&dc.stream, input);
3136 dc.out_begin = (char*)dst;
3137 dc.out_ptr = (char*)dst;
3138 dc.out_end = (char*)dst + dst_size;
3139 if (input->internal_fast_bits != 0) {
3140 dc.fast_bits = (uint32_t)input->internal_fast_bits;
3141 if (dc.fast_bits < 1 || dc.fast_bits == 9 || dc.fast_bits > 10) return -29;
3142 } else {
3143 // TODO: Profile this
3144 dc.fast_bits = input->total_size > 2048 ? 10 : 8;
3145 }
3146
3147 uint64_t bits = dc.stream.bits;
3148 size_t left = dc.stream.left;
3149 const char *data = dc.stream.chunk_ptr;
3150
3151 ufbxi_bit_refill(&bits, &left, &data, &dc.stream);
3152 if (dc.stream.cancelled) return -28;
3153
3154 // Zlib header
3155 if (!input->no_header) {
3156 size_t cmf = (size_t)(bits & 0xff);
3157 size_t flg = (size_t)(bits >> 8) & 0xff;
3158 bits >>= 16;
3159 left -= 16;
3160
3161 if ((cmf & 0xf) != 0x8) return -1;
3162 if ((flg & 0x20) != 0) return -2;
3163 if ((cmf << 8 | flg) % 31u != 0) return -3;
3164 }
3165
3166 for (;;) {
3167 ufbxi_bit_refill(&bits, &left, &data, &dc.stream);
3168 if (dc.stream.cancelled) return -28;
3169
3170 // Block header: [0:1] BFINAL [1:3] BTYPE
3171 size_t header = (size_t)bits & 0x7;
3172 bits >>= 3;
3173 left -= 3;
3174
3175 size_t type = header >> 1;
3176 if (type == 0) {
3177
3178 // Round up to the next byte
3179 size_t align_bits = left & 0x7;
3180 bits >>= align_bits;
3181 left -= align_bits;
3182
3183 size_t len = (size_t)(bits & 0xffff);
3184 size_t nlen = (size_t)((bits >> 16) & 0xffff);
3185 if ((len ^ nlen) != 0xffff) return -4;
3186 if (dc.out_end - dc.out_ptr < (ptrdiff_t)len) return -6;
3187 bits >>= 32;
3188 left -= 32;
3189
3190 dc.stream.bits = bits;
3191 dc.stream.left = left;
3192 dc.stream.chunk_ptr = data;
3193
3194 // Copy `len` bytes of literal data
3195 if (!ufbxi_bit_copy_bytes(dc.out_ptr, &dc.stream, len)) return -5;
3196
3197 dc.out_ptr += len;
3198
3199 } else if (type <= 2) {
3200
3201 dc.stream.bits = bits;
3202 dc.stream.left = left;
3203 dc.stream.chunk_ptr = data;
3204
3205 ufbxi_trees tree_data; // ufbxi_uninit
3206 ufbxi_trees *trees; // ufbxi_uninit
3207 if (type == 1) {
3208 // Static Huffman: Initialize the trees once and cache them in `retain`.
3209 if (!ret_imp->initialized) {
3210 ufbxi_init_static_huff(&ret_imp->static_trees, input);
3211 ret_imp->initialized = true;
3212 }
3213 trees = &ret_imp->static_trees;
3214 } else {
3215 // Dynamic Huffman
3216 err = ufbxi_init_dynamic_huff(&dc, &tree_data);
3217 if (err) return err;
3218 trees = &tree_data;
3219 }
3220
3221 for (;;) {
3222 bool fast_viable = trees->fast_bits == UFBXI_HUFF_FAST_BITS && dc.out_end - dc.out_ptr >= UFBXI_INFLATE_FAST_MIN_OUT;
3223
3224 // `ufbxi_inflate_block_fast()` needs a bit more upfront setup, see asserts on top of the function
3225 if (fast_viable && dc.stream.chunk_yield - dc.stream.chunk_ptr >= UFBXI_INFLATE_FAST_MIN_IN) {
3226 err = ufbxi_inflate_block_fast(&dc, trees);
3227 } else {
3228 err = ufbxi_inflate_block_slow(&dc, trees, fast_viable ? 32 : SIZE_MAX);
3229 }
3230
3231 if (err < 0) return err;
3232
3233 // `ufbxi_inflate_block()` returns normally on cancel so check it here
3234 if (dc.stream.cancelled) return -28;
3235
3236 if (err == 0) break;
3237 }
3238
3239 } else {
3240 // 0b11 - reserved (error)
3241 return -7;
3242 }
3243
3244 bits = dc.stream.bits;
3245 left = dc.stream.left;
3246 data = dc.stream.chunk_ptr;
3247
3248 // BFINAL: End of stream
3249 if (header & 1) break;
3250 }
3251
3252 // Check Adler-32
3253 {
3254 // Round up to the next byte
3255 size_t align_bits = left & 0x7;
3256 bits >>= align_bits;
3257 left -= align_bits;
3258 ufbxi_bit_refill(&bits, &left, &data, &dc.stream);
3259 if (dc.stream.cancelled) return -28;
3260
3261 if (!input->no_checksum) {
3262 uint32_t ref = (uint32_t)bits;
3263 ref = (ref>>24) | ((ref>>8)&0xff00) | ((ref<<8)&0xff0000) | (ref<<24);
3264
3265 uint32_t checksum = ufbxi_adler32(dc.out_begin, ufbxi_to_size(dc.out_ptr - dc.out_begin));
3266 if (ref != checksum) {
3267 return -9;
3268 }
3269 }
3270 }
3271
3272 return dc.out_ptr - dc.out_begin;
3273 }
3274
3275 #endif // !defined(ufbx_inflate)
3276
3277 // -- Printf
3278
3279 typedef struct {
3280 char *dst;
3281 size_t length;
3282 size_t pos;
3283 } ufbxi_print_buffer;
3284
3285 #define UFBXI_PRINT_UNSIGNED 0x1
3286 #define UFBXI_PRINT_STRING 0x2
3287 #define UFBXI_PRINT_SIZE_T 0x10
3288
3289 static void ufbxi_print_append(ufbxi_print_buffer *buf, size_t min_width, size_t max_width, const char *str)
3290 {
3291 size_t width = 0;
3292 for (width = 0; width < max_width; width++) {
3293 if (!str[width]) break;
3294 }
3295 size_t pad = min_width > width ? min_width - width : 0;
3296 for (size_t i = 0; i < pad; i++) {
3297 if (buf->pos < buf->length) buf->dst[buf->pos++] = ' ';
3298 }
3299 for (size_t i = 0; i < width; i++) {
3300 if (buf->pos < buf->length) buf->dst[buf->pos++] = str[i];
3301 }
3302 }
3303
3304 static char *ufbxi_print_format_int(char *buffer, uint64_t value)
3305 {
3306 *--buffer = '\0';
3307 do {
3308 uint32_t digit = (uint32_t)(value % 10);
3309 value = value / 10;
3310 *--buffer = (char)('0' + digit);
3311 } while (value > 0);
3312 return buffer;
3313 }
3314
3315 static void ufbxi_vprint(ufbxi_print_buffer *buf, const char *fmt, va_list args)
3316 {
3317 char buffer[96]; // ufbxi_uninit
3318 for (const char *p = fmt; *p;) {
3319 if (*p == '%' && *++p != '%') {
3320 size_t min_width = 0, max_width = SIZE_MAX;
3321 if (*p == '*') {
3322 p++;
3323 min_width = (size_t)va_arg(args, int);
3324 }
3325 if (*p == '.') {
3326 ufbxi_dev_assert(p[1] == '*');
3327 p += 2;
3328 max_width = (size_t)va_arg(args, int);
3329 }
3330 uint32_t flags = 0;
3331 switch (*p) {
3332 case 'z': p++; flags |= UFBXI_PRINT_SIZE_T; break;
3333 default: break;
3334 }
3335 switch (*p++) {
3336 case 'u': flags |= UFBXI_PRINT_UNSIGNED; break;
3337 case 's': flags |= UFBXI_PRINT_STRING; break;
3338 default: break;
3339 }
3340 if (flags & UFBXI_PRINT_STRING) {
3341 const char *str = va_arg(args, const char*);
3342 ufbxi_print_append(buf, min_width, max_width, str);
3343 } else if (flags & UFBXI_PRINT_UNSIGNED) {
3344 uint64_t value = (flags & UFBXI_PRINT_SIZE_T) != 0 ? (uint64_t)va_arg(args, size_t) : (uint64_t)va_arg(args, uint32_t);
3345 char *str = ufbxi_print_format_int(buffer + sizeof(buffer), value);
3346 ufbxi_print_append(buf, min_width, max_width, str);
3347 } else {
3348 ufbxi_unreachable("Bad printf format");
3349 }
3350 } else {
3351 if (buf->pos < buf->length) buf->dst[buf->pos++] = *p;
3352 p++;
3353 }
3354 }
3355 if (buf->length && buf->dst) {
3356 size_t end = buf->pos <= buf->length - 1 ? buf->pos : buf->length - 1;
3357 buf->dst[end] = '\0';
3358 }
3359 }
3360
3361 // -- Errors
3362
3363 static const char ufbxi_empty_char[1] = { '\0' };
3364
3365 static ufbxi_noinline int ufbxi_vsnprintf(char *buf, size_t buf_size, const char *fmt, va_list args)
3366 {
3367 ufbxi_print_buffer buffer = { buf, buf_size };
3368 ufbxi_vprint(&buffer, fmt, args);
3369 return (int)ufbxi_min_sz(buffer.pos, buf_size - 1);
3370 }
3371
3372 static ufbxi_noinline int ufbxi_snprintf(char *buf, size_t buf_size, const char *fmt, ...)
3373 {
3374 va_list args; // ufbxi_uninit
3375 va_start(args, fmt);
3376 int result = ufbxi_vsnprintf(buf, buf_size, fmt, args);
3377 va_end(args);
3378 return result;
3379 }
3380
3381 static ufbxi_noinline void ufbxi_panicf_imp(ufbx_panic *panic, const char *fmt, ...)
3382 {
3383 if (panic && panic->did_panic) return;
3384
3385 va_list args; // ufbxi_uninit
3386
3387 if (panic) {
3388 va_start(args, fmt);
3389 panic->did_panic = true;
3390 panic->message_length = (size_t)ufbxi_vsnprintf(panic->message, sizeof(panic->message), fmt, args);
3391 va_end(args);
3392 } else {
3393 va_start(args, fmt);
3394 char message[UFBX_PANIC_MESSAGE_LENGTH];
3395 ufbxi_vsnprintf(message, sizeof(message), fmt, args);
3396 va_end(args);
3397
3398 ufbx_panic_handler(message);
3399 }
3400 }
3401
3402 #define ufbxi_panicf(panic, cond, ...) \
3403 ((cond) ? false : (ufbxi_panicf_imp((panic), __VA_ARGS__), true))
3404
3405 // Prefix the error condition with $Description\0 for a human readable description
3406 #define ufbxi_error_msg(cond, msg) "$" msg "\0" cond
3407
3408 static ufbxi_noinline int ufbxi_fail_imp_err(ufbx_error *err, const char *cond, const char *func, uint32_t line)
3409 {
3410 if (cond && cond[0] == '$') {
3411 if (!err->description.data) {
3412 err->description.data = cond + 1;
3413 err->description.length = strlen(err->description.data);
3414 }
3415
3416 #if UFBXI_FEATURE_ERROR_STACK
3417 // Skip the description part if adding to a stack
3418 cond = cond + strlen(cond) + 1;
3419 #endif
3420 }
3421
3422 // NOTE: This is the base function all fails boil down to, place a breakpoint here to
3423 // break at the first error
3424 #if UFBXI_FEATURE_ERROR_STACK
3425 ufbx_assert(cond);
3426 ufbx_assert(func);
3427 if (err->stack_size < UFBX_ERROR_STACK_MAX_DEPTH) {
3428 ufbx_error_frame *frame = &err->stack[err->stack_size++];
3429 frame->description.data = cond;
3430 frame->description.length = strlen(cond);
3431 frame->function.data = func;
3432 frame->function.length = strlen(func);
3433 frame->source_line = line;
3434 }
3435 #else
3436 ufbxi_ignore(func);
3437 ufbxi_ignore(line);
3438 #endif
3439
3440 return 0;
3441 }
3442
3443 ufbxi_nodiscard static ufbxi_noinline size_t ufbxi_utf8_valid_length(const char *str, size_t length)
3444 {
3445 size_t index = 0;
3446 while (index < length) {
3447 uint8_t c = (uint8_t)str[index];
3448 size_t left = length - index;
3449
3450 if ((c & 0x80) == 0) {
3451 if (c != 0) {
3452 index += 1;
3453 continue;
3454 }
3455 } else if ((c & 0xe0) == 0xc0 && left >= 2) {
3456 uint8_t t0 = (uint8_t)str[index + 1];
3457 uint32_t code = (uint32_t)c << 8 | (uint32_t)t0;
3458 if ((code & 0xc0) == 0x80 && code >= 0xc280) {
3459 index += 2;
3460 continue;
3461 }
3462 } else if ((c & 0xf0) == 0xe0 && left >= 3) {
3463 uint8_t t0 = (uint8_t)str[index + 1], t1 = (uint8_t)str[index + 2];
3464 uint32_t code = (uint32_t)c << 16 | (uint32_t)t0 << 8 | (uint32_t)t1;
3465 if ((code & 0xc0c0) == 0x8080 && code >= 0xe0a080 && (code < 0xeda080 || code >= 0xee8080)) {
3466 index += 3;
3467 continue;
3468 }
3469 } else if ((c & 0xf8) == 0xf0 && left >= 4) {
3470 uint8_t t0 = (uint8_t)str[index + 1], t1 = (uint8_t)str[index + 2], t2 = (uint8_t)str[index + 3];
3471 uint32_t code = (uint32_t)c << 24 | (uint32_t)t0 << 16 | (uint32_t)t1 << 8 | (uint32_t)t2;
3472 if ((code & 0xc0c0c0) == 0x808080 && code >= 0xf0908080u && code <= 0xf48fbfbfu) {
3473 index += 4;
3474 continue;
3475 }
3476 }
3477
3478 break;
3479 }
3480
3481 ufbx_assert(index <= length);
3482 return index;
3483 }
3484
3485 static ufbxi_noinline void ufbxi_clean_string_utf8(char *str, size_t length)
3486 {
3487 size_t pos = 0;
3488 for (;;) {
3489 pos += ufbxi_utf8_valid_length(str + pos, length);
3490 if (pos == length) break;
3491 str[pos++] = '?';
3492 }
3493 }
3494
3495 static ufbxi_noinline void ufbxi_set_err_info(ufbx_error *err, const char *data, size_t length)
3496 {
3497 if (!err) return;
3498
3499 if (length == SIZE_MAX) length = strlen(data);
3500 size_t to_copy = ufbxi_min_sz(sizeof(err->info) - 1, length);
3501 memcpy(err->info, data, to_copy);
3502 err->info[to_copy] = '\0';
3503 err->info_length = to_copy;
3504 ufbxi_clean_string_utf8(err->info, err->info_length);
3505 }
3506
3507 static ufbxi_noinline void ufbxi_fmt_err_info(ufbx_error *err, const char *fmt, ...)
3508 {
3509 if (!err) return;
3510
3511 va_list args; // ufbxi_uninit
3512 va_start(args, fmt);
3513 err->info_length = (size_t)ufbxi_vsnprintf(err->info, sizeof(err->info), fmt, args);
3514 va_end(args);
3515 ufbxi_clean_string_utf8(err->info, err->info_length);
3516 }
3517
3518 static ufbxi_noinline void ufbxi_clear_error(ufbx_error *err)
3519 {
3520 if (!err) return;
3521
3522 err->type = UFBX_ERROR_NONE;
3523 err->description.data = ufbxi_empty_char;
3524 err->description.length = 0;
3525 err->stack_size = 0;
3526 err->info[0] = '\0';
3527 err->info_length = 0;
3528 }
3529
3530 #if UFBXI_FEATURE_ERROR_STACK
3531 #define ufbxi_function __FUNCTION__
3532 #define ufbxi_line __LINE__
3533 #define ufbxi_cond_str(cond) #cond
3534 #else
3535 #define ufbxi_function NULL
3536 #define ufbxi_line 0
3537 #define ufbxi_cond_str(cond) ""
3538 #endif
3539
3540 #if UFBXI_FEATURE_ERROR_STACK
3541 #define ufbxi_fail_err_no_msg(err, cond, func, line) ufbxi_fail_imp_err((err), (cond), (func), (line))
3542 #else
3543 static ufbxi_noinline int ufbxi_fail_imp_err_no_stack(ufbx_error *err) { return ufbxi_fail_imp_err(err, NULL, NULL, 0); }
3544 #define ufbxi_fail_err_no_msg(err, cond, func, line) ufbxi_fail_imp_err_no_stack((err))
3545 #endif
3546
3547 #define ufbxi_check_err(err, cond) do { if (ufbxi_unlikely(!ufbxi_trace(cond))) { ufbxi_fail_err_no_msg((err), ufbxi_cond_str(cond), ufbxi_function, ufbxi_line); return 0; } } while (0)
3548 #define ufbxi_check_return_err(err, cond, ret) do { if (ufbxi_unlikely(!ufbxi_trace(cond))) { ufbxi_fail_err_no_msg((err), ufbxi_cond_str(cond), ufbxi_function, ufbxi_line); return ret; } } while (0)
3549 #define ufbxi_fail_err(err, desc) return ufbxi_fail_err_no_msg(err, desc, ufbxi_function, ufbxi_line)
3550
3551 #define ufbxi_check_err_msg(err, cond, msg) do { if (ufbxi_unlikely(!ufbxi_trace(cond))) { ufbxi_fail_imp_err((err), ufbxi_error_msg(ufbxi_cond_str(cond), msg), ufbxi_function, ufbxi_line); return 0; } } while (0)
3552 #define ufbxi_check_return_err_msg(err, cond, ret, msg) do { if (ufbxi_unlikely(!ufbxi_trace(cond))) { ufbxi_fail_imp_err((err), ufbxi_error_msg(ufbxi_cond_str(cond), msg), ufbxi_function, ufbxi_line); return ret; } } while (0)
3553 #define ufbxi_fail_err_msg(err, desc, msg) return ufbxi_fail_imp_err(err, ufbxi_error_msg(desc, msg), ufbxi_function, ufbxi_line)
3554 #define ufbxi_report_err_msg(err, desc, msg) (void)ufbxi_fail_imp_err(err, ufbxi_error_msg(desc, msg), ufbxi_function, ufbxi_line)
3555
3556 static ufbxi_noinline void ufbxi_fix_error_type(ufbx_error *error, const char *default_desc, ufbx_error *p_error)
3557 {
3558 const char *desc = error->description.data;
3559 if (!desc) desc = default_desc;
3560 error->type = UFBX_ERROR_UNKNOWN;
3561 if (!strcmp(desc, "Out of memory")) {
3562 error->type = UFBX_ERROR_OUT_OF_MEMORY;
3563 } else if (!strcmp(desc, "Memory limit exceeded")) {
3564 error->type = UFBX_ERROR_MEMORY_LIMIT;
3565 } else if (!strcmp(desc, "Allocation limit exceeded")) {
3566 error->type = UFBX_ERROR_ALLOCATION_LIMIT;
3567 } else if (!strcmp(desc, "Truncated file")) {
3568 error->type = UFBX_ERROR_TRUNCATED_FILE;
3569 } else if (!strcmp(desc, "IO error")) {
3570 error->type = UFBX_ERROR_IO;
3571 } else if (!strcmp(desc, "Cancelled")) {
3572 error->type = UFBX_ERROR_CANCELLED;
3573 } else if (!strcmp(desc, "Unrecognized file format")) {
3574 error->type = UFBX_ERROR_UNRECOGNIZED_FILE_FORMAT;
3575 } else if (!strcmp(desc, "File not found")) {
3576 error->type = UFBX_ERROR_FILE_NOT_FOUND;
3577 } else if (!strcmp(desc, "Empty file")) {
3578 error->type = UFBX_ERROR_EMPTY_FILE;
3579 } else if (!strcmp(desc, "External file not found")) {
3580 error->type = UFBX_ERROR_EXTERNAL_FILE_NOT_FOUND;
3581 } else if (!strcmp(desc, "Uninitialized options")) {
3582 error->type = UFBX_ERROR_UNINITIALIZED_OPTIONS;
3583 } else if (!strcmp(desc, "Zero vertex size")) {
3584 error->type = UFBX_ERROR_ZERO_VERTEX_SIZE;
3585 } else if (!strcmp(desc, "Truncated vertex stream")) {
3586 error->type = UFBX_ERROR_TRUNCATED_VERTEX_STREAM;
3587 } else if (!strcmp(desc, "Invalid UTF-8")) {
3588 error->type = UFBX_ERROR_INVALID_UTF8;
3589 } else if (!strcmp(desc, "Feature disabled")) {
3590 error->type = UFBX_ERROR_FEATURE_DISABLED;
3591 } else if (!strcmp(desc, "Bad NURBS geometry")) {
3592 error->type = UFBX_ERROR_BAD_NURBS;
3593 } else if (!strcmp(desc, "Bad index")) {
3594 error->type = UFBX_ERROR_BAD_INDEX;
3595 } else if (!strcmp(desc, "Node depth limit exceeded")) {
3596 error->type = UFBX_ERROR_NODE_DEPTH_LIMIT;
3597 } else if (!strcmp(desc, "Threaded ASCII parse error")) {
3598 error->type = UFBX_ERROR_THREADED_ASCII_PARSE;
3599 } else if (!strcmp(desc, "Unsafe options")) {
3600 error->type = UFBX_ERROR_UNSAFE_OPTIONS;
3601 } else if (!strcmp(desc, "Duplicate override")) {
3602 error->type = UFBX_ERROR_DUPLICATE_OVERRIDE;
3603 }
3604 error->description.data = desc;
3605 error->description.length = strlen(desc);
3606 if (p_error) {
3607 memcpy(p_error, error, sizeof(ufbx_error));
3608 }
3609 }
3610
3611 // -- Allocator
3612
3613 // Returned for zero size allocations, place in the constant data
3614 // to catch writes to bad allocations.
3615 #if defined(UFBX_REGRESSION)
3616 static const char ufbxi_zero_size_buffer[4096] = { 0 };
3617 #else
3618 static const char ufbxi_zero_size_buffer[64] = { 0 };
3619 #endif
3620
3621 static ufbxi_forceinline size_t ufbxi_align_to_mask(size_t value, size_t align_mask)
3622 {
3623 return value + (((size_t)0 - value) & align_mask);
3624 }
3625
3626 static ufbxi_forceinline size_t ufbxi_size_align_mask(size_t size)
3627 {
3628 // Align to the all bits below the lowest set one in `size` up to the maximum alignment.
3629 return ((size ^ (size - 1)) >> 1) & (UFBX_MAXIMUM_ALIGNMENT - 1);
3630 }
3631
3632 typedef struct {
3633 ufbx_error *error;
3634 size_t current_size;
3635 size_t max_size;
3636 size_t num_allocs;
3637 size_t max_allocs;
3638 size_t huge_size;
3639 size_t chunk_max;
3640 ufbx_allocator_opts ator;
3641 const char *name;
3642 } ufbxi_allocator;
3643
3644 static ufbxi_forceinline bool ufbxi_does_overflow(size_t total, size_t a, size_t b)
3645 {
3646 // If `a` and `b` have at most 4 bits per `size_t` byte, the product can't overflow.
3647 if (((a | b) >> sizeof(size_t)*4) != 0) {
3648 if (a != 0 && total / a != b) return true;
3649 }
3650 return false;
3651 }
3652
3653 static ufbxi_noinline void *ufbxi_alloc_size(ufbxi_allocator *ator, size_t size, size_t n)
3654 {
3655 // Always succeed with an empty non-NULL buffer for empty allocations
3656 ufbx_assert(size > 0);
3657 if (n == 0) return (void*)ufbxi_zero_size_buffer;
3658
3659 size_t total = size * n;
3660 ufbxi_check_return_err(ator->error, !ufbxi_does_overflow(total, size, n), NULL);
3661 ufbxi_check_return_err(ator->error, total <= SIZE_MAX / 2, NULL); // Make sure it's always safe to double allocations
3662 if (!(total < ator->max_size - ator->current_size)) {
3663 ufbxi_report_err_msg(ator->error, "total <= ator->max_size - ator->current_size", "Memory limit exceeded");
3664 ufbxi_fmt_err_info(ator->error, "%s", ator->name);
3665 return NULL;
3666 }
3667 if (!(ator->num_allocs < ator->max_allocs)) {
3668 ufbxi_report_err_msg(ator->error, "ator->num_allocs < ator->max_allocs", "Allocation limit exceeded");
3669 ufbxi_fmt_err_info(ator->error, "%s", ator->name);
3670 return NULL;
3671 }
3672 ator->num_allocs++;
3673
3674 void *ptr;
3675 if (ator->ator.allocator.alloc_fn) {
3676 ptr = ator->ator.allocator.alloc_fn(ator->ator.allocator.user, total);
3677 } else if (ator->ator.allocator.realloc_fn) {
3678 ptr = ator->ator.allocator.realloc_fn(ator->ator.allocator.user, NULL, 0, total);
3679 } else {
3680 ptr = ufbx_malloc(total);
3681 }
3682
3683 if (!ptr) {
3684 ufbxi_report_err_msg(ator->error, "ptr", "Out of memory");
3685 ufbxi_fmt_err_info(ator->error, "%s", ator->name);
3686 return NULL;
3687 }
3688 ufbx_assert(ufbxi_is_aligned_mask(ptr, ufbxi_size_align_mask(total)));
3689
3690 ator->current_size += total;
3691
3692 return ptr;
3693 }
3694
3695 static void ufbxi_free_size(ufbxi_allocator *ator, size_t size, void *ptr, size_t n);
3696 static ufbxi_noinline void *ufbxi_realloc_size(ufbxi_allocator *ator, size_t size, void *old_ptr, size_t old_n, size_t n)
3697 {
3698 ufbx_assert(size > 0);
3699 // realloc() with zero old/new size is equivalent to alloc()/free()
3700 if (old_n == 0) return ufbxi_alloc_size(ator, size, n);
3701 if (n == 0) { ufbxi_free_size(ator, size, old_ptr, old_n); return NULL; }
3702
3703 size_t old_total = size * old_n;
3704 size_t total = size * n;
3705
3706 // The old values have been checked by a previous allocate call
3707 ufbx_assert(!ufbxi_does_overflow(old_total, size, old_n));
3708 ufbx_assert(old_total <= ator->current_size);
3709
3710 ufbxi_check_return_err(ator->error, !ufbxi_does_overflow(total, size, n), NULL);
3711 ufbxi_check_return_err(ator->error, total <= SIZE_MAX / 2, NULL); // Make sure it's always safe to double allocations
3712 ufbxi_check_return_err_msg(ator->error, total <= ator->max_size - ator->current_size, NULL, "Memory limit exceeded");
3713 ufbxi_check_return_err_msg(ator->error, ator->num_allocs < ator->max_allocs, NULL, "Allocation limit exceeded");
3714 ator->num_allocs++;
3715
3716 void *ptr;
3717 if (ator->ator.allocator.realloc_fn) {
3718 ptr = ator->ator.allocator.realloc_fn(ator->ator.allocator.user, old_ptr, old_total, total);
3719 } else if (ator->ator.allocator.alloc_fn) {
3720 // Use user-provided alloc_fn() and free_fn()
3721 ptr = ator->ator.allocator.alloc_fn(ator->ator.allocator.user, total);
3722 if (ptr) memcpy(ptr, old_ptr, old_total);
3723 if (ator->ator.allocator.free_fn) {
3724 ator->ator.allocator.free_fn(ator->ator.allocator.user, old_ptr, old_total);
3725 }
3726 } else {
3727 ptr = ufbx_realloc(old_ptr, old_total, total);
3728 }
3729
3730 ufbxi_check_return_err_msg(ator->error, ptr, NULL, "Out of memory");
3731 ufbx_assert(ufbxi_is_aligned_mask(ptr, ufbxi_size_align_mask(total)));
3732
3733 ator->current_size += total;
3734 ator->current_size -= old_total;
3735
3736 return ptr;
3737 }
3738
3739 static ufbxi_noinline void ufbxi_free_size(ufbxi_allocator *ator, size_t size, void *ptr, size_t n)
3740 {
3741 ufbx_assert(size > 0);
3742 if (n == 0) return;
3743 ufbx_assert(ptr);
3744
3745 size_t total = size * n;
3746
3747 // The old values have been checked by a previous allocate call
3748 ufbx_assert(!ufbxi_does_overflow(total, size, n));
3749 ufbx_assert(total <= ator->current_size);
3750
3751 ator->current_size -= total;
3752
3753 if (ator->ator.allocator.alloc_fn || ator->ator.allocator.realloc_fn) {
3754 // Don't call default free() if there is an user-provided `alloc_fn()`
3755 if (ator->ator.allocator.free_fn) {
3756 ator->ator.allocator.free_fn(ator->ator.allocator.user, ptr, total);
3757 } else if (ator->ator.allocator.realloc_fn) {
3758 ator->ator.allocator.realloc_fn(ator->ator.allocator.user, ptr, total, 0);
3759 }
3760 } else {
3761 ufbx_free(ptr, total);
3762 }
3763 }
3764
3765 ufbxi_noinline ufbxi_nodiscard static bool ufbxi_grow_array_size(ufbxi_allocator *ator, size_t size, void *p_ptr, size_t *p_cap, size_t n)
3766 {
3767 #if defined(UFBX_REGRESSION)
3768 {
3769 ufbxi_check_return_err_msg(ator->error, ator->num_allocs < ator->max_allocs, false, "Allocation limit exceeded");
3770 ator->num_allocs++;
3771 }
3772 #endif
3773
3774 if (n <= *p_cap) return true;
3775 void *ptr = *(void**)p_ptr;
3776 size_t old_n = *p_cap;
3777 if (old_n >= n) return true;
3778 size_t new_n = ufbxi_max_sz(old_n * 2, n);
3779 void *new_ptr = ufbxi_realloc_size(ator, size, ptr, old_n, new_n);
3780 if (!new_ptr) return false;
3781 *(void**)p_ptr = new_ptr;
3782 *p_cap = new_n;
3783 return true;
3784 }
3785
3786 static ufbxi_noinline void ufbxi_free_ator(ufbxi_allocator *ator)
3787 {
3788 ufbx_assert(ator->current_size == 0);
3789
3790 ufbx_free_allocator_fn *free_fn = ator->ator.allocator.free_allocator_fn;
3791 if (free_fn) {
3792 void *user = ator->ator.allocator.user;
3793 free_fn(user);
3794 }
3795 }
3796
3797 #define ufbxi_alloc(ator, type, n) ufbxi_maybe_null((type*)ufbxi_alloc_size((ator), sizeof(type), (n)))
3798 #define ufbxi_alloc_zero(ator, type, n) ufbxi_maybe_null((type*)ufbxi_alloc_zero_size((ator), sizeof(type), (n)))
3799 #define ufbxi_realloc(ator, type, old_ptr, old_n, n) ufbxi_maybe_null((type*)ufbxi_realloc_size((ator), sizeof(type), (old_ptr), (old_n), (n)))
3800 #define ufbxi_realloc_zero(ator, type, old_ptr, old_n, n) ufbxi_maybe_null((type*)ufbxi_realloc_zero_size((ator), sizeof(type), (old_ptr), (old_n), (n)))
3801 #define ufbxi_free(ator, type, ptr, n) ufbxi_free_size((ator), sizeof(type), (ptr), (n))
3802
3803 #define ufbxi_grow_array(ator, p_ptr, p_cap, n) ufbxi_grow_array_size((ator), sizeof(**(p_ptr)), (p_ptr), (p_cap), (n))
3804
3805 #define UFBXI_SCENE_IMP_MAGIC 0x58424655
3806 #define UFBXI_MESH_IMP_MAGIC 0x48534d55
3807 #define UFBXI_LINE_CURVE_IMP_MAGIC 0x55434c55
3808 #define UFBXI_CACHE_IMP_MAGIC 0x48434355
3809 #define UFBXI_ANIM_IMP_MAGIC 0x494e4155
3810 #define UFBXI_BAKED_ANIM_IMP_MAGIC 0x4b414255
3811 #define UFBXI_REFCOUNT_IMP_MAGIC 0x46455255
3812 #define UFBXI_BUF_CHUNK_IMP_MAGIC 0x46554255
3813
3814 // -- Memory buffer
3815 //
3816 // General purpose memory buffer that can be used either as a chunked linear memory
3817 // allocator or a non-contiguous stack. You can convert the contents of `ufbxi_buf`
3818 // to a contiguous range of memory by calling `ufbxi_make_array[_all]()`
3819
3820 typedef struct ufbxi_buf_padding ufbxi_buf_padding;
3821 typedef struct ufbxi_buf_chunk ufbxi_buf_chunk;
3822
3823 struct ufbxi_buf_padding {
3824 size_t original_pos; // < Original position before aligning
3825 size_t prev_padding; // < Starting offset of the previous `ufbxi_buf_padding`
3826 };
3827
3828 struct ufbxi_buf_chunk {
3829
3830 // Linked list of nodes
3831 ufbxi_buf_chunk *root;
3832 ufbxi_buf_chunk *prev;
3833 ufbxi_buf_chunk *next;
3834
3835 union {
3836 size_t magic; // < Magic for debugging
3837 void *align_0; // < Align to 4x pointer size (16/32 bytes)
3838 };
3839
3840 size_t size; // < Size of the chunk `data`, excluding this header
3841 size_t pushed_pos; // < Size of valid data when pushed to the list
3842 size_t next_size; // < Next geometrically growing chunk size to allocate
3843 size_t padding_pos; // < One past the offset of the most recent `ufbxi_buf_padding`
3844
3845 char data[]; // < Must be aligned to 8 bytes
3846 };
3847
3848 ufbx_static_assert(buf_chunk_align, offsetof(ufbxi_buf_chunk, data) % 8 == 0);
3849
3850 typedef struct {
3851 ufbxi_allocator *ator;
3852
3853 // Current chunks for normal and huge allocations.
3854 // Ordered buffers (`!ufbxi_buf.unordered`) never use `chunks[1]`
3855 ufbxi_buf_chunk *chunks[2];
3856
3857 // Inline state for non-huge chunks
3858 size_t pos; // < Next offset to allocate from
3859 size_t size; // < Size of the current chunk ie. `chunks[0]->size` (or 0 if `chunks[0] == NULL`)
3860
3861 size_t num_items; // < Number of individual items pushed to the buffer
3862
3863 size_t pushed_size; // < Cumulative size of pushed chunks, not tracked across pops
3864
3865 bool unordered; // < Does not support popping from the buffer
3866 bool clearable; // < Supports clearing the whole buffer even if `unordered`
3867 } ufbxi_buf;
3868
3869 typedef struct {
3870 ufbxi_buf_chunk *chunk;
3871 size_t pos;
3872 size_t num_items;
3873 } ufbxi_buf_state;
3874
3875 static ufbxi_noinline void *ufbxi_push_size_new_block(ufbxi_buf *b, size_t size)
3876 {
3877 bool huge = size >= b->ator->huge_size;
3878
3879 // Use the second chunk "list" for huge unordered chunks.
3880 // The state of these chunks is not tracked by `ufbxi_buf.pos/size`.
3881 uint32_t list_ix = ((uint32_t)b->unordered & (uint32_t)huge);
3882
3883 ufbxi_buf_chunk *chunk = b->chunks[list_ix];
3884 if (chunk) {
3885 if (list_ix == 0) {
3886 // Store the final position for the retired chunk and scan free
3887 // chunks in case we find one the allocation fits in.
3888 b->pushed_size += b->pos;
3889 chunk->pushed_pos = b->pos;
3890 ufbxi_buf_chunk *next = chunk->next;
3891 while (next != NULL) {
3892 ufbx_assert(next->magic == UFBXI_BUF_CHUNK_IMP_MAGIC);
3893 chunk = next;
3894 ufbx_assert(b->unordered || chunk->pushed_pos == 0);
3895 chunk->pushed_pos = 0;
3896 if (size <= chunk->size) {
3897 b->chunks[0] = chunk;
3898 b->pos = (uint32_t)size;
3899 b->size = chunk->size;
3900 return chunk->data;
3901 }
3902 next = chunk->next;
3903 }
3904 } else if (b->clearable) {
3905 // Keep track of the `UFBXI_HUGE_MAX_SCAN` largest chunks and
3906 // retain them. Overflowing chunks are freed in `ufbxi_buf_clear()`
3907 size_t align_mask = ufbxi_size_align_mask(size);
3908 ufbxi_buf_chunk *next = chunk;
3909
3910 ufbxi_buf_chunk *best_chunk = NULL;
3911 size_t best_space = SIZE_MAX;
3912
3913 // Clearable huge chunks are sorted by descending size. Check the first N
3914 // chunks for reuse and find the place a new block should be inserted if
3915 // no suitable space is found. Chunk ordering in the tail doesn't matter
3916 // as those chunks are never reused.
3917 // Unreachable chunks in the tail are freed in `ufbxi_buf_clear()`.
3918 for (size_t i = 0; next && i < UFBXI_HUGE_MAX_SCAN; i++) {
3919 ufbx_assert(next->magic == UFBXI_BUF_CHUNK_IMP_MAGIC);
3920 if (next->size < size) break;
3921 chunk = next;
3922
3923 // Try to reuse chunks using a best-fit strategy.
3924 size_t pos = ufbxi_align_to_mask(chunk->pushed_pos, align_mask);
3925 size_t space = chunk->size - pos;
3926 if (size <= space) {
3927 if (space < best_space) {
3928 best_chunk = chunk;
3929 best_space = space;
3930 }
3931 }
3932
3933 next = chunk->next;
3934 }
3935
3936 // Early return if we found a slot.
3937 if (best_chunk) {
3938 size_t pos = ufbxi_align_to_mask(best_chunk->pushed_pos, align_mask);
3939 best_chunk->pushed_pos = pos + size;
3940 b->pushed_size += size;
3941 return best_chunk->data + pos;
3942 }
3943 }
3944 }
3945
3946 // Allocate a new chunk, grow `next_size` geometrically but don't double
3947 // the current or previous user sizes if they are larger.
3948 size_t chunk_size, next_size;
3949
3950 // If `size` is larger than `huge_size` don't grow `next_size` geometrically,
3951 // but use a dedicated allocation.
3952 if (huge) {
3953 next_size = chunk ? chunk->next_size : 4096;
3954 if (next_size > b->ator->chunk_max) next_size = b->ator->chunk_max;
3955 chunk_size = size;
3956 } else {
3957 next_size = chunk ? chunk->next_size * 2 : 4096;
3958 if (next_size > b->ator->chunk_max) next_size = b->ator->chunk_max;
3959 chunk_size = next_size - sizeof(ufbxi_buf_chunk);
3960 if (chunk_size < size) chunk_size = size;
3961 }
3962
3963 // Align chunk sizes to 16 bytes
3964 chunk_size = ufbxi_align_to_mask(chunk_size, 0xf);
3965
3966 ufbxi_buf_chunk *new_chunk = (ufbxi_buf_chunk*)ufbxi_alloc_size(b->ator, 1, sizeof(ufbxi_buf_chunk) + chunk_size);
3967 if (!new_chunk) return NULL;
3968
3969 new_chunk->prev = chunk;
3970 new_chunk->size = chunk_size;
3971 new_chunk->next_size = next_size;
3972 new_chunk->magic = UFBXI_BUF_CHUNK_IMP_MAGIC;
3973 new_chunk->padding_pos = 0;
3974 new_chunk->pushed_pos = 0;
3975
3976 // Link the chunk to the list and set it as the active one
3977 if (chunk) {
3978 ufbxi_buf_chunk *next = chunk->next;
3979 if (next) next->prev = new_chunk;
3980 new_chunk->next = next;
3981 chunk->next = new_chunk;
3982 new_chunk->root = chunk->root;
3983 } else {
3984 new_chunk->next = NULL;
3985 new_chunk->root = new_chunk;
3986 }
3987
3988 if (list_ix == 0) {
3989 b->chunks[0] = new_chunk;
3990 b->pos = size;
3991 b->size = chunk_size;
3992 } else {
3993 ufbxi_buf_chunk *root = b->chunks[1];
3994 b->pushed_size += size;
3995 if (!root) {
3996 b->chunks[1] = new_chunk;
3997 } else if (root->size < chunk_size) {
3998 // Swap root and self if necessary, we should have bailed out
3999 // in the search loop in the first iteration so `new_chunk` should
4000 // directly follow `root`.
4001 // HACK: This ends up with `chunks[1]` entries having inconsistent
4002 // `ufbxi_buf_chunk.root` pointers but other code only reads `chunks[1].root`
4003 // TODO: Move roots out of the chunks?
4004 ufbx_assert(root->next == new_chunk);
4005 ufbx_assert(new_chunk->prev == root);
4006 if (new_chunk->next) new_chunk->next->prev = root;
4007 root->next = new_chunk->next;
4008 new_chunk->next = root;
4009 new_chunk->prev = NULL;
4010 new_chunk->root = new_chunk;
4011 b->chunks[1] = new_chunk;
4012 }
4013 new_chunk->pushed_pos = size;
4014 }
4015
4016 return new_chunk->data;
4017 }
4018
4019 static ufbxi_noinline void *ufbxi_push_size(ufbxi_buf *b, size_t size, size_t n)
4020 {
4021 // Always succeed with an empty non-NULL buffer for empty allocations
4022 ufbx_assert(size > 0);
4023 if (n == 0) return (void*)ufbxi_zero_size_buffer;
4024
4025 size_t total = size * n;
4026 if (ufbxi_does_overflow(total, size, n)) return NULL;
4027
4028 #if defined(UFBX_REGRESSION)
4029 {
4030 ufbxi_allocator *ator = b->ator;
4031 ufbxi_check_return_err_msg(ator->error, ator->num_allocs < ator->max_allocs, NULL, "Allocation limit exceeded");
4032 ator->num_allocs++;
4033 }
4034 #endif
4035
4036 b->num_items += n;
4037
4038 // Align to the natural alignment based on the size
4039 size_t align_mask = ufbxi_size_align_mask(size);
4040 size_t pos = ufbxi_align_to_mask(b->pos, align_mask);
4041
4042 if (!b->unordered && pos != b->pos) {
4043 // Alignment mismatch in an unordered block. Align to 16 bytes to guarantee
4044 // sufficient alignment for anything afterwards and mark the padding.
4045 // If we overflow the current block we don't need to care as the block
4046 // boundaries are not contiguous.
4047 pos = ufbxi_align_to_mask(b->pos, 0xf);
4048 if (total < SIZE_MAX - 16 && total + 16 <= b->size - pos) {
4049 ufbxi_buf_chunk *chunk = b->chunks[0];
4050 ufbxi_buf_padding *padding = (ufbxi_buf_padding*)(chunk->data + pos);
4051 padding->original_pos = b->pos;
4052 padding->prev_padding = chunk->padding_pos;
4053 chunk->padding_pos = pos + 16 + 1;
4054 b->pos = pos + 16 + total;
4055 return (char*)padding + 16;
4056 } else {
4057 return ufbxi_push_size_new_block(b, total);
4058 }
4059 } else {
4060 // Try to push to the current block. Allocate a new block
4061 // if the aligned size doesn't fit.
4062 if (total <= b->size - pos) {
4063 b->pos = pos + total;
4064 return b->chunks[0]->data + pos;
4065 } else {
4066 return ufbxi_push_size_new_block(b, total);
4067 }
4068 }
4069 }
4070
4071 static ufbxi_forceinline void *ufbxi_push_size_fast(ufbxi_buf *b, size_t size, size_t n)
4072 {
4073 // Always succeed with an empty non-NULL buffer for empty allocations
4074 ufbxi_regression_assert(size > 0);
4075 ufbxi_regression_assert(n > 0);
4076
4077 size_t total = size * n;
4078 ufbxi_regression_assert(!ufbxi_does_overflow(total, size, n));
4079
4080 #if defined(UFBX_REGRESSION)
4081 {
4082 ufbxi_allocator *ator = b->ator;
4083 ufbxi_check_return_err_msg(ator->error, ator->num_allocs < ator->max_allocs, NULL, "Allocation limit exceeded");
4084 ator->num_allocs++;
4085 }
4086 #endif
4087
4088 b->num_items += n;
4089
4090 // Homogeneous arrays should always be aligned
4091 size_t pos = b->pos;
4092 ufbxi_regression_assert((pos & ufbxi_size_align_mask(size)) == 0);
4093
4094 // Try to push to the current block. Allocate a new block
4095 // if the aligned size doesn't fit.
4096 if (total <= b->size - pos) {
4097 b->pos = pos + total;
4098 return b->chunks[0]->data + pos;
4099 } else {
4100 return ufbxi_push_size_new_block(b, total);
4101 }
4102 }
4103
4104 static ufbxi_noinline void *ufbxi_push_size_zero(ufbxi_buf *b, size_t size, size_t n)
4105 {
4106 void *ptr = ufbxi_push_size(b, size, n);
4107 if (ptr) memset(ptr, 0, size * n);
4108 return ptr;
4109 }
4110
4111 ufbxi_nodiscard static ufbxi_noinline void *ufbxi_push_size_copy(ufbxi_buf *b, size_t size, size_t n, const void *data)
4112 {
4113 // Always succeed with an empty non-NULL buffer for empty allocations, even if `data == NULL`
4114 ufbx_assert(size > 0);
4115 if (n == 0) return (void*)ufbxi_zero_size_buffer;
4116
4117 ufbx_assert(data);
4118 void *ptr = ufbxi_push_size(b, size, n);
4119 if (ptr) memcpy(ptr, data, size * n);
4120 return ptr;
4121 }
4122
4123 ufbxi_nodiscard static ufbxi_forceinline void *ufbxi_push_size_copy_fast(ufbxi_buf *b, size_t size, size_t n, const void *data)
4124 {
4125 // Always succeed with an empty non-NULL buffer for empty allocations, even if `data == NULL`
4126 ufbx_assert(size > 0);
4127 if (n == 0) return (void*)ufbxi_zero_size_buffer;
4128
4129 ufbx_assert(data);
4130 void *ptr = ufbxi_push_size_fast(b, size, n);
4131 if (ptr) memcpy(ptr, data, size * n);
4132 return ptr;
4133 }
4134
4135 static ufbxi_noinline void ufbxi_buf_free_unused(ufbxi_buf *b)
4136 {
4137 ufbx_assert(!b->unordered);
4138
4139 ufbxi_buf_chunk *chunk = b->chunks[0];
4140 if (!chunk) return;
4141
4142 ufbxi_buf_chunk *next = chunk->next;
4143 while (next) {
4144 ufbxi_buf_chunk *to_free = next;
4145 next = next->next;
4146 ufbx_assert(to_free->magic == UFBXI_BUF_CHUNK_IMP_MAGIC);
4147 to_free->magic = 0;
4148 ufbxi_free_size(b->ator, 1, to_free, sizeof(ufbxi_buf_chunk) + to_free->size);
4149 }
4150 chunk->next = NULL;
4151
4152 while (b->pos == 0 && chunk) {
4153 ufbxi_buf_chunk *prev = chunk->prev;
4154 ufbx_assert(chunk->magic == UFBXI_BUF_CHUNK_IMP_MAGIC);
4155 chunk->magic = 0;
4156 ufbxi_free_size(b->ator, 1, chunk, sizeof(ufbxi_buf_chunk) + chunk->size);
4157 chunk = prev;
4158 b->chunks[0] = prev;
4159 if (prev) {
4160 prev->next = NULL;
4161 b->pos = prev->pushed_pos;
4162 b->size = prev->size;
4163 } else {
4164 b->pos = 0;
4165 b->size = 0;
4166 }
4167 }
4168 }
4169
4170 static ufbxi_noinline void ufbxi_pop_size(ufbxi_buf *b, size_t size, size_t n, void *dst, bool peek)
4171 {
4172 ufbx_assert(!b->unordered);
4173 ufbx_assert(size > 0);
4174 ufbx_assert(b->num_items >= n);
4175 if (!peek) b->num_items -= n;
4176
4177 char *ptr = (char*)dst;
4178 size_t bytes_left = size * n;
4179
4180 // We've already pushed this, it better not overflow
4181 ufbx_assert(!ufbxi_does_overflow(bytes_left, size, n));
4182
4183 if (ptr) {
4184 ptr += bytes_left;
4185 size_t pos = b->pos;
4186 ufbxi_buf_chunk *chunk = b->chunks[0];
4187 for (;;) {
4188 if (bytes_left <= pos) {
4189 // Rest of the data is in this single chunk
4190 pos -= bytes_left;
4191 if (!peek) b->pos = pos;
4192 ptr -= bytes_left;
4193 if (bytes_left > 0) {
4194 memcpy(ptr, chunk->data + pos, bytes_left);
4195 }
4196 break;
4197 } else {
4198 // Pop the whole chunk
4199 ptr -= pos;
4200 bytes_left -= pos;
4201 memcpy(ptr, chunk->data, pos);
4202 if (!peek) {
4203 chunk->pushed_pos = 0;
4204 chunk = chunk->prev;
4205 b->chunks[0] = chunk;
4206 b->size = chunk->size;
4207 } else {
4208 chunk = chunk->prev;
4209 }
4210 pos = chunk->pushed_pos;
4211 }
4212 }
4213 } else {
4214 size_t pos = b->pos;
4215 ufbxi_buf_chunk *chunk = b->chunks[0];
4216 for (;;) {
4217 if (bytes_left <= pos) {
4218 // Rest of the data is in this single chunk
4219 pos -= bytes_left;
4220 if (!peek) b->pos = pos;
4221 break;
4222 } else {
4223 // Pop the whole chunk
4224 bytes_left -= pos;
4225 if (!peek) {
4226 chunk->pushed_pos = 0;
4227 chunk = chunk->prev;
4228 b->chunks[0] = chunk;
4229 b->size = chunk->size;
4230 } else {
4231 chunk = chunk->prev;
4232 }
4233 pos = chunk->pushed_pos;
4234 }
4235 }
4236 }
4237
4238 if (!peek) {
4239 // Check if we need to rewind past some alignment padding
4240 ufbxi_buf_chunk *chunk = b->chunks[0];
4241 if (chunk) {
4242 size_t pos = b->pos, padding_pos = chunk->padding_pos;
4243 if (pos < padding_pos) {
4244 ufbx_assert(pos + 1 == padding_pos);
4245 ufbxi_buf_padding *padding = (ufbxi_buf_padding*)(chunk->data + padding_pos - 1 - 16);
4246 b->pos = padding->original_pos;
4247 chunk->padding_pos = padding->prev_padding;
4248 }
4249 }
4250
4251 // Immediately free popped items if all the allocations are huge
4252 // as it means we want to have dedicated allocations for each push.
4253 if (b->ator->huge_size <= 1) {
4254 ufbxi_buf_free_unused(b);
4255 }
4256 }
4257 }
4258
4259 static ufbxi_noinline void *ufbxi_push_pop_size(ufbxi_buf *dst, ufbxi_buf *src, size_t size, size_t n)
4260 {
4261 void *data = ufbxi_push_size(dst, size, n);
4262 if (!data) return NULL;
4263 ufbxi_pop_size(src, size, n, data, false);
4264 return data;
4265 }
4266
4267 static ufbxi_noinline void *ufbxi_push_peek_size(ufbxi_buf *dst, ufbxi_buf *src, size_t size, size_t n)
4268 {
4269 void *data = ufbxi_push_size(dst, size, n);
4270 if (!data) return NULL;
4271 ufbxi_pop_size(src, size, n, data, true);
4272 return data;
4273 }
4274
4275 static ufbxi_noinline void ufbxi_buf_free(ufbxi_buf *buf)
4276 {
4277 ufbxi_nounroll for (size_t i = 0; i < 2; i++) {
4278 ufbxi_buf_chunk *chunk = buf->chunks[i];
4279 if (chunk) {
4280 chunk = chunk->root;
4281 while (chunk) {
4282 ufbxi_buf_chunk *next = chunk->next;
4283 ufbx_assert(chunk->magic == UFBXI_BUF_CHUNK_IMP_MAGIC);
4284 chunk->magic = 0;
4285 ufbxi_free_size(buf->ator, 1, chunk, sizeof(ufbxi_buf_chunk) + chunk->size);
4286 chunk = next;
4287 }
4288 }
4289 buf->chunks[i] = NULL;
4290 }
4291 buf->pos = 0;
4292 buf->size = 0;
4293 buf->num_items = 0;
4294 }
4295
4296 static ufbxi_noinline void ufbxi_buf_clear(ufbxi_buf *buf)
4297 {
4298 // Only unordered or clearable buffers can be cleared
4299 ufbx_assert(!buf->unordered || buf->clearable);
4300
4301 // Free the memory if using ASAN
4302 if (buf->ator->huge_size <= 1) {
4303 ufbxi_buf_free(buf);
4304 return;
4305 }
4306
4307 // Reset the non-huge chunks as `chunk->next` is always free.
4308 ufbxi_buf_chunk *chunk = buf->chunks[0];
4309 if (chunk) {
4310 ufbxi_buf_chunk *root = chunk->root;
4311 buf->chunks[0] = root;
4312 buf->pos = 0;
4313 buf->size = root->size;
4314 }
4315 buf->num_items = 0;
4316 buf->pushed_size = 0;
4317
4318 // Huge chunks are always sorted by descending size and
4319 // `chunks[1]` points to the largest one.
4320 ufbxi_buf_chunk *huge = buf->chunks[1];
4321 if (huge) {
4322 // Reset the first N ones that are tracked.
4323 for (size_t i = 0; huge && i < UFBXI_HUGE_MAX_SCAN; i++) {
4324 huge->pushed_pos = 0;
4325 huge = huge->next;
4326 }
4327
4328 // Got unreachable tail that should be freed: Unlink from the last
4329 // tracked chunk and free the rest.
4330 if (huge) {
4331 huge->prev->next = NULL;
4332 while (huge) {
4333 ufbxi_buf_chunk *next = huge->next;
4334 ufbx_assert(huge->magic == UFBXI_BUF_CHUNK_IMP_MAGIC);
4335 huge->magic = 0;
4336 ufbxi_free_size(buf->ator, 1, huge, sizeof(ufbxi_buf_chunk) + huge->size);
4337 huge = next;
4338 }
4339 }
4340 }
4341 }
4342
4343 #define ufbxi_push(b, type, n) ufbxi_maybe_null((type*)ufbxi_push_size((b), sizeof(type), (n)))
4344 #define ufbxi_push_zero(b, type, n) ufbxi_maybe_null((type*)ufbxi_push_size_zero((b), sizeof(type), (n)))
4345 #define ufbxi_push_copy(b, type, n, data) ufbxi_maybe_null((type*)ufbxi_push_size_copy((b), sizeof(type), (n), (data)))
4346 #define ufbxi_push_copy_fast(b, type, n, data) ufbxi_maybe_null((type*)ufbxi_push_size_copy_fast((b), sizeof(type), (n), (data)))
4347 #define ufbxi_push_fast(b, type, n) ufbxi_maybe_null((type*)ufbxi_push_size_fast((b), sizeof(type), (n)))
4348 #define ufbxi_pop(b, type, n, dst) ufbxi_pop_size((b), sizeof(type), (n), (dst), false)
4349 #define ufbxi_peek(b, type, n, dst) ufbxi_pop_size((b), sizeof(type), (n), (dst), true)
4350 #define ufbxi_push_pop(dst, src, type, n) ufbxi_maybe_null((type*)ufbxi_push_pop_size((dst), (src), sizeof(type), (n)))
4351 #define ufbxi_push_peek(dst, src, type, n) ufbxi_maybe_null((type*)ufbxi_push_peek_size((dst), (src), sizeof(type), (n)))
4352
4353 // -- Hash map
4354 //
4355 // The actual element comparison is left to the user of `ufbxi_map`, see usage below.
4356 //
4357 // NOTES:
4358 // ufbxi_map_insert() does not support duplicate values, use find first if duplicates are possible!
4359 // Inserting duplicate elements fails with an assertion if `UFBX_REGRESSION` is enabled.
4360
4361 typedef struct ufbxi_aa_node ufbxi_aa_node;
4362
4363 typedef int ufbxi_cmp_fn(void *user, const void *a, const void *b);
4364
4365 struct ufbxi_aa_node {
4366 ufbxi_aa_node *left, *right;
4367 uint32_t level;
4368 uint32_t index;
4369 };
4370
4371 typedef struct {
4372 ufbxi_allocator *ator;
4373 size_t data_size;
4374
4375 void *items;
4376 uint64_t *entries;
4377 uint32_t mask;
4378
4379 uint32_t capacity;
4380 uint32_t size;
4381
4382 ufbxi_cmp_fn *cmp_fn;
4383 void *cmp_user;
4384
4385 ufbxi_buf aa_buf;
4386 ufbxi_aa_node *aa_root;
4387
4388 } ufbxi_map;
4389
4390 static ufbxi_noinline void ufbxi_map_init(ufbxi_map *map, ufbxi_allocator *ator, ufbxi_cmp_fn *cmp_fn, void *cmp_user)
4391 {
4392 map->ator = ator;
4393 #if defined(UFBX_REGRESSION)
4394 // HACK: Maps contain pointers that are not stable between runs, in regression
4395 // mode this causes instability in allocation patterns due to different AA trees
4396 // being built, which is a problem in fuzz checks that need to have deterministic
4397 // allocation counts. We can work around this using a local allocator that doesn't
4398 // count the allocations.
4399 {
4400 ufbxi_allocator *regression_ator = (ufbxi_allocator*)ufbx_malloc(sizeof(ufbxi_allocator));
4401 ufbx_assert(regression_ator);
4402 memset(regression_ator, 0, sizeof(ufbxi_allocator));
4403 regression_ator->name = "regression";
4404 regression_ator->error = ator->error;
4405 regression_ator->huge_size = ator->huge_size;
4406 regression_ator->max_size = SIZE_MAX;
4407 regression_ator->max_allocs = SIZE_MAX;
4408 regression_ator->chunk_max = 0x1000000;
4409 map->aa_buf.ator = regression_ator;
4410 }
4411 #else
4412 map->aa_buf.ator = ator;
4413 #endif
4414 map->cmp_fn = cmp_fn;
4415 map->cmp_user = cmp_user;
4416 }
4417
4418 static ufbxi_noinline void ufbxi_map_free(ufbxi_map *map)
4419 {
4420 #if defined(UFBX_REGRESSION)
4421 ufbxi_allocator *regression_ator = map->aa_buf.ator;
4422 #endif
4423
4424 ufbxi_buf_free(&map->aa_buf);
4425 ufbxi_free(map->ator, char, map->entries, map->data_size);
4426 map->entries = NULL;
4427 map->items = NULL;
4428 map->aa_root = NULL;
4429 map->mask = map->capacity = map->size = 0;
4430
4431 #if defined(UFBX_REGRESSION)
4432 if (regression_ator) {
4433 ufbxi_free_ator(regression_ator);
4434 ufbx_free(regression_ator, sizeof(ufbxi_allocator));
4435 }
4436 #endif
4437 }
4438
4439 // Recursion limit: log2(2^64 / sizeof(ufbxi_aa_node))
4440 static ufbxi_noinline ufbxi_aa_node *ufbxi_aa_tree_insert(ufbxi_map *map, ufbxi_aa_node *node, const void *value, uint32_t index, size_t item_size)
4441 ufbxi_recursive_function(ufbxi_aa_node *, ufbxi_aa_tree_insert, (map, node, value, index, item_size), 59,
4442 (ufbxi_map *map, ufbxi_aa_node *node, const void *value, uint32_t index, size_t item_size))
4443 {
4444 if (!node) {
4445 ufbxi_aa_node *new_node = ufbxi_push(&map->aa_buf, ufbxi_aa_node, 1);
4446 if (!new_node) return NULL;
4447 new_node->left = NULL;
4448 new_node->right = NULL;
4449 new_node->level = 1;
4450 new_node->index = index;
4451 return new_node;
4452 }
4453
4454 void *entry = (char*)map->items + node->index * item_size;
4455 int cmp = map->cmp_fn(map->cmp_user, value, entry);
4456 if (cmp < 0) {
4457 node->left = ufbxi_aa_tree_insert(map, node->left, value, index, item_size);
4458 } else if (cmp >= 0) {
4459 node->right = ufbxi_aa_tree_insert(map, node->right, value, index, item_size);
4460 }
4461
4462 if (node->left && node->left->level == node->level) {
4463 ufbxi_aa_node *left = node->left;
4464 node->left = left->right;
4465 left->right = node;
4466 node = left;
4467 }
4468
4469 if (node->right && node->right->right && node->right->right->level == node->level) {
4470 ufbxi_aa_node *right = node->right;
4471 node->right = right->left;
4472 right->left = node;
4473 right->level += 1;
4474 node = right;
4475 }
4476
4477 return node;
4478 }
4479
4480 static ufbxi_noinline void *ufbxi_aa_tree_find(ufbxi_map *map, const void *value, size_t item_size)
4481 {
4482 ufbxi_aa_node *node = map->aa_root;
4483 while (node) {
4484 void *entry = (char*)map->items + node->index * item_size;
4485 int cmp = map->cmp_fn(map->cmp_user, value, entry);
4486 if (cmp < 0) {
4487 node = node->left;
4488 } else if (cmp > 0) {
4489 node = node->right;
4490 } else {
4491 return entry;
4492 }
4493 }
4494 return NULL;
4495 }
4496
4497 static ufbxi_noinline bool ufbxi_map_grow_size_imp(ufbxi_map *map, size_t item_size, size_t min_size)
4498 {
4499 ufbx_assert(min_size > 0);
4500 const double load_factor = 0.7;
4501
4502 // Find the lowest power of two size that fits `min_size` within `load_factor`
4503 size_t num_entries = map->mask + 1;
4504 size_t new_size = (size_t)((double)num_entries * load_factor);
4505 if (min_size < map->capacity + 1) min_size = map->capacity + 1;
4506 while (new_size < min_size) {
4507 num_entries *= 2;
4508 new_size = (size_t)((double)num_entries * load_factor);
4509 }
4510
4511 // Check for overflow
4512 ufbxi_check_return_err(map->ator->error, SIZE_MAX / num_entries > sizeof(uint64_t), false);
4513 size_t alloc_size = num_entries * sizeof(uint64_t);
4514
4515 // Allocate a combined entry/item memory block
4516 ufbxi_check_return_err(map->ator->error, (SIZE_MAX - alloc_size) / new_size > item_size, false);
4517 size_t data_size = alloc_size + new_size * item_size;
4518
4519 char *data = ufbxi_alloc(map->ator, char, data_size);
4520 ufbxi_check_return_err(map->ator->error, data, false);
4521
4522 // Copy the previous user items over
4523 uint64_t *old_entries = map->entries;
4524 uint64_t *new_entries = (uint64_t*)data;
4525 void *new_items = data + alloc_size;
4526 if (map->size > 0) {
4527 memcpy(new_items, map->items, item_size * map->size);
4528 }
4529
4530 // Re-hash the entries
4531 uint32_t old_mask = map->mask;
4532 uint32_t new_mask = (uint32_t)(num_entries) - 1;
4533 memset(new_entries, 0, sizeof(uint64_t) * num_entries);
4534 if (old_mask) {
4535 for (uint32_t i = 0; i <= old_mask; i++) {
4536 uint64_t entry, new_entry = old_entries[i];
4537 if (!new_entry) continue;
4538
4539 // Reconstruct the hash of the old entry at `i`
4540 uint32_t old_scan = (uint32_t)(new_entry & old_mask) - 1;
4541 uint32_t hash = ((uint32_t)new_entry & ~old_mask) | ((i - old_scan) & old_mask);
4542 uint32_t slot = hash & new_mask;
4543 new_entry &= ~(uint64_t)new_mask;
4544
4545 // Scan forward until we find an empty slot, potentially swapping
4546 // `new_element` if it has a shorter scan distance (Robin Hood).
4547 uint32_t scan = 1;
4548 while ((entry = new_entries[slot]) != 0) {
4549 uint32_t entry_scan = (uint32_t)(entry & new_mask);
4550 if (entry_scan < scan) {
4551 new_entries[slot] = new_entry + scan;
4552 new_entry = (entry & ~(uint64_t)new_mask);
4553 scan = entry_scan;
4554 }
4555 scan += 1;
4556 slot = (slot + 1) & new_mask;
4557 }
4558 new_entries[slot] = new_entry + scan;
4559 }
4560 }
4561
4562 // And finally free the previous allocation
4563 ufbxi_free(map->ator, char, (char*)old_entries, map->data_size);
4564 map->items = new_items;
4565 map->data_size = data_size;
4566 map->entries = new_entries;
4567 map->mask = new_mask;
4568 map->capacity = (uint32_t)new_size;
4569
4570 return true;
4571 }
4572
4573 static ufbxi_forceinline bool ufbxi_map_grow_size(ufbxi_map *map, size_t size, size_t min_size)
4574 {
4575 #if defined(UFBX_REGRESSION)
4576 {
4577 ufbxi_allocator *ator = map->ator;
4578 ufbxi_check_return_err_msg(ator->error, ator->num_allocs < ator->max_allocs, false, "Allocation limit exceeded");
4579 ator->num_allocs++;
4580 }
4581 #endif
4582
4583 if (map->size < map->capacity && map->capacity >= min_size) return true;
4584 return ufbxi_map_grow_size_imp(map, size, min_size);
4585 }
4586
4587 static ufbxi_noinline void *ufbxi_map_find_size(ufbxi_map *map, size_t size, uint32_t hash, const void *value)
4588 {
4589 uint64_t *entries = map->entries;
4590 uint32_t mask = map->mask, scan = 0;
4591
4592 uint32_t ref = hash & ~mask;
4593 if (!mask || scan == UINT32_MAX) return 0;
4594
4595 // Scan entries until we find an exact match of the hash or until we hit
4596 // an element that has lower scan distance than our search (Robin Hood).
4597 // The encoding guarantees that zero slots also terminate with the same test.
4598 for (;;) {
4599 uint64_t entry = entries[(hash + scan) & mask];
4600 scan += 1;
4601 if ((uint32_t)entry == ref + scan) {
4602 uint32_t index = (uint32_t)(entry >> 32u);
4603 void *data = (char*)map->items + size * index;
4604 int cmp = map->cmp_fn(map->cmp_user, value, data);
4605 if (cmp == 0) return data;
4606 } else if ((entry & mask) < scan) {
4607 if (map->aa_root) {
4608 return ufbxi_aa_tree_find(map, value, size);
4609 } else {
4610 return NULL;
4611 }
4612 }
4613 }
4614 }
4615
4616 static ufbxi_noinline void *ufbxi_map_insert_size(ufbxi_map *map, size_t size, uint32_t hash, const void *value)
4617 {
4618 if (!ufbxi_map_grow_size(map, size, 64)) return NULL;
4619
4620 ufbxi_regression_assert(ufbxi_map_find_size(map, size, hash, value) == NULL);
4621
4622 uint32_t index = map->size++;
4623
4624 uint64_t *entries = map->entries;
4625 uint32_t mask = map->mask;
4626
4627 // Scan forward until we find an empty slot, potentially swapping
4628 // `new_element` if it has a shorter scan distance (Robin Hood).
4629 uint32_t slot = hash & mask;
4630 uint64_t entry, new_entry = (uint64_t)index << 32u | (hash & ~mask);
4631 uint32_t scan = 1;
4632 while ((entry = entries[slot]) != 0) {
4633 uint32_t entry_scan = (uint32_t)(entry & mask);
4634 if (entry_scan < scan) {
4635 entries[slot] = new_entry + scan;
4636 new_entry = (entry & ~(uint64_t)mask);
4637 scan = entry_scan;
4638 }
4639 scan += 1;
4640 slot = (slot + 1) & mask;
4641
4642 if (scan > UFBXI_MAP_MAX_SCAN) {
4643 uint32_t new_index = (uint32_t)(new_entry >> 32u);
4644 const void *new_value = new_index == index ? value : (const void*)((char*)map->items + size * new_index);
4645 map->aa_root = ufbxi_aa_tree_insert(map, map->aa_root, new_value, new_index, size);
4646 return (char*)map->items + size * index;
4647 }
4648 }
4649 entries[slot] = new_entry + scan;
4650
4651 return (char*)map->items + size * index;
4652 }
4653
4654 #define ufbxi_map_grow(map, type, min_size) ufbxi_map_grow_size((map), sizeof(type), (min_size))
4655 #define ufbxi_map_find(map, type, hash, value) ufbxi_maybe_null((type*)ufbxi_map_find_size((map), sizeof(type), (hash), (value)))
4656 #define ufbxi_map_insert(map, type, hash, value) ufbxi_maybe_null((type*)ufbxi_map_insert_size((map), sizeof(type), (hash), (value)))
4657
4658 static int ufbxi_map_cmp_uint64(void *user, const void *va, const void *vb)
4659 {
4660 (void)user;
4661 uint64_t a = *(const uint64_t*)va, b = *(const uint64_t*)vb;
4662 if (a < b) return -1;
4663 if (a > b) return +1;
4664 return 0;
4665 }
4666
4667 static int ufbxi_map_cmp_const_char_ptr(void *user, const void *va, const void *vb)
4668 {
4669 (void)user;
4670 const char *a = *(const char **)va, *b = *(const char **)vb;
4671 if (a < b) return -1;
4672 if (a > b) return +1;
4673 return 0;
4674 }
4675
4676 static int ufbxi_map_cmp_uintptr(void *user, const void *va, const void *vb)
4677 {
4678 (void)user;
4679 uintptr_t a = *(const uintptr_t*)va, b = *(const uintptr_t*)vb;
4680 if (a < b) return -1;
4681 if (a > b) return +1;
4682 return 0;
4683 }
4684
4685 typedef struct {
4686 uintptr_t ptr;
4687 uint64_t id;
4688 } ufbxi_ptr_id;
4689
4690 static int ufbxi_map_cmp_ptr_id(void *user, const void *va, const void *vb)
4691 {
4692 (void)user;
4693 ufbxi_ptr_id a = *(const ufbxi_ptr_id*)va, b = *(const ufbxi_ptr_id*)vb;
4694 if (a.id != b.id) return a.id < b.id ? -1 : +1;
4695 if (a.ptr != b.ptr) return a.ptr < b.ptr ? -1 : +1;
4696 return 0;
4697 }
4698
4699 // -- Hash functions
4700
4701 static ufbxi_noinline uint32_t ufbxi_hash_string(const char *str, size_t length)
4702 {
4703 uint32_t hash = (uint32_t)length;
4704 uint32_t seed = UINT32_C(0x9e3779b9);
4705 if (length >= 4) {
4706 do {
4707 uint32_t word = ufbxi_read_u32(str);
4708 hash = ((hash << 5u | hash >> 27u) ^ word) * seed;
4709 str += 4;
4710 length -= 4;
4711 } while (length >= 4);
4712
4713 uint32_t word = ufbxi_read_u32(str + length - 4);
4714 hash = ((hash << 5u | hash >> 27u) ^ word) * seed;
4715 } else {
4716 uint32_t word = 0;
4717 if (length >= 1) word |= (uint32_t)(uint8_t)str[0] << 0;
4718 if (length >= 2) word |= (uint32_t)(uint8_t)str[1] << 8;
4719 if (length >= 3) word |= (uint32_t)(uint8_t)str[2] << 16;
4720 hash = ((hash << 5u | hash >> 27u) ^ word) * seed;
4721 }
4722 hash ^= hash >> 16;
4723 hash *= UINT32_C(0x7feb352d);
4724 hash ^= hash >> 15;
4725 return hash;
4726 }
4727
4728 // NOTE: _Must_ match `ufbxi_hash_string()`
4729 static ufbxi_noinline uint32_t ufbxi_hash_string_check_ascii(const char *str, size_t length, bool *p_non_ascii)
4730 {
4731 uint32_t ascii_mask = 0;
4732 uint32_t zero_mask = 0;
4733
4734 ufbx_assert(length > 0);
4735
4736 uint32_t hash = (uint32_t)length;
4737 uint32_t seed = UINT32_C(0x9e3779b9);
4738 if (length >= 4) {
4739 do {
4740 uint32_t word = ufbxi_read_u32(str);
4741 ascii_mask |= word;
4742 zero_mask |= UINT32_C(0x80808080) - word;
4743
4744 hash = ((hash << 5u | hash >> 27u) ^ word) * seed;
4745 str += 4;
4746 length -= 4;
4747 } while (length >= 4);
4748
4749 uint32_t word = ufbxi_read_u32(str + length - 4);
4750 ascii_mask |= word;
4751 zero_mask |= UINT32_C(0x80808080) - word;
4752
4753 hash = ((hash << 5u | hash >> 27u) ^ word) * seed;
4754 } else {
4755 uint32_t word = 0;
4756 if (length >= 1) word |= (uint32_t)(uint8_t)str[0] << 0;
4757 if (length >= 2) word |= (uint32_t)(uint8_t)str[1] << 8;
4758 if (length >= 3) word |= (uint32_t)(uint8_t)str[2] << 16;
4759
4760 ascii_mask |= word;
4761 zero_mask |= (UINT32_C(0x80808080) >> ((4u - length) * 8u)) - word;
4762
4763 hash = ((hash << 5u | hash >> 27u) ^ word) * seed;
4764 }
4765
4766 // If any character has high bit set or is zero we're not ASCII
4767 if (((ascii_mask | zero_mask) & 0x80808080u) != 0) {
4768 *p_non_ascii = true;
4769 }
4770
4771 hash ^= hash >> 16;
4772 hash *= UINT32_C(0x7feb352d);
4773 hash ^= hash >> 15;
4774
4775 return hash;
4776 }
4777
4778 static ufbxi_unused ufbxi_forceinline uint32_t ufbxi_hash32(uint32_t x)
4779 {
4780 x ^= x >> 16;
4781 x *= UINT32_C(0x7feb352d);
4782 x ^= x >> 15;
4783 x *= UINT32_C(0x846ca68b);
4784 x ^= x >> 16;
4785 return x;
4786 }
4787
4788 static ufbxi_unused ufbxi_forceinline uint32_t ufbxi_hash64(uint64_t x)
4789 {
4790 x ^= x >> 32;
4791 x *= UINT64_C(0xd6e8feb86659fd93);
4792 x ^= x >> 32;
4793 x *= UINT64_C(0xd6e8feb86659fd93);
4794 x ^= x >> 32;
4795 return (uint32_t)x;
4796 }
4797
4798 static ufbxi_forceinline uint32_t ufbxi_hash_uptr(uintptr_t ptr)
4799 {
4800 #if UFBX_POINTER_SIZE == 8
4801 return ufbxi_hash64((uint64_t)ptr);
4802 #elif UFBX_POINTER_SIZE == 4
4803 return ufbxi_hash32((uint32_t)ptr);
4804 #else
4805 if (sizeof(ptr) == 8) return ufbxi_hash64((uint64_t)ptr);
4806 else if (sizeof(ptr) == 4) return ufbxi_hash32((uint32_t)ptr);
4807 else return ufbxi_hash_string((const char*)&ptr, sizeof(uintptr_t));
4808 #endif
4809 }
4810
4811 static ufbxi_forceinline uint32_t ufbxi_hash_ptr_id(ufbxi_ptr_id id)
4812 {
4813 // Trivial reduction is fine: Only `ptr` or `id` is defined.
4814 return ufbxi_hash_uptr(id.ptr) ^ ufbxi_hash64(id.id);
4815 }
4816
4817 #define ufbxi_hash_ptr(ptr) ufbxi_hash_uptr((uintptr_t)(ptr))
4818
4819 // -- Warnings
4820
4821 typedef struct {
4822 ufbx_error *error;
4823 ufbxi_buf *result;
4824 ufbxi_buf tmp_stack;
4825 uint32_t deferred_element_id_plus_one;
4826 // Separate lists for specific and non-specific warnings
4827 ufbx_warning *prev_warnings[UFBX_WARNING_TYPE_COUNT][2];
4828 } ufbxi_warnings;
4829
4830 ufbxi_nodiscard static ufbxi_noinline int ufbxi_vwarnf_imp(ufbxi_warnings *ws, ufbx_warning_type type, uint32_t element_id, const char *fmt, va_list args)
4831 {
4832 if (!ws) return 1;
4833
4834 // HACK(warning-element): Encode potential deferred element ID into `ufbx_warning.element_id`,
4835 // `ws->element_id_index_plus_one` contains index to `uc->tmp_element_id`.
4836 // Tag deferred indices with the high bit.
4837 if (element_id == ~0u && ws->deferred_element_id_plus_one > 0) {
4838 element_id = (ws->deferred_element_id_plus_one - 1) | 0x80000000u;
4839 }
4840
4841 uint32_t has_element_id = element_id != ~0u;
4842 if (type >= UFBX_WARNING_TYPE_FIRST_DEDUPLICATED) {
4843 ufbx_warning *prev = ws->prev_warnings[type][has_element_id];
4844 if (prev && prev->element_id == element_id) {
4845 prev->count++;
4846 return 1;
4847 }
4848 }
4849
4850 char desc[256];
4851 size_t desc_len = (size_t)ufbxi_vsnprintf(desc, sizeof(desc), fmt, args);
4852
4853 ufbxi_clean_string_utf8(desc, desc_len);
4854
4855 char *desc_copy = ufbxi_push_copy(ws->result, char, desc_len + 1, desc);
4856 ufbxi_check_err(ws->error, desc_copy);
4857
4858 ufbx_warning *warning = ufbxi_push(&ws->tmp_stack, ufbx_warning, 1);
4859 ufbxi_check_err(ws->error, warning);
4860
4861 warning->type = type;
4862 warning->description.data = desc_copy;
4863 warning->description.length = desc_len;
4864 warning->element_id = element_id;
4865 warning->count = 1;
4866 ws->prev_warnings[type][has_element_id] = warning;
4867
4868 return 1;
4869 }
4870
4871 ufbxi_nodiscard static ufbxi_noinline int ufbxi_warnf_imp(ufbxi_warnings *ws, ufbx_warning_type type, uint32_t element_id, const char *fmt, ...)
4872 {
4873 // NOTE: `ws` may be `NULL` here, handled by `ufbxi_vwarnf()`
4874 va_list args; // ufbxi_uninit
4875 va_start(args, fmt);
4876 int ok = ufbxi_vwarnf_imp(ws, type, element_id, fmt, args);
4877 va_end(args);
4878 return ok;
4879 }
4880
4881 ufbxi_nodiscard static ufbxi_noinline int ufbxi_pop_warnings(ufbxi_warnings *ws, ufbx_warning_list *warnings, bool *p_has_warning)
4882 {
4883 warnings->count = ws->tmp_stack.num_items;
4884 warnings->data = ufbxi_push_pop(ws->result, &ws->tmp_stack, ufbx_warning, warnings->count);
4885 ufbxi_check_err(ws->error, warnings->data);
4886 ufbxi_for_list(ufbx_warning, warning, *warnings) {
4887 p_has_warning[warning->type] = true;
4888 }
4889 return 1;
4890 }
4891
4892 // -- String pool
4893
4894 // All strings found in FBX files are interned for deduplication and fast
4895 // comparison. Our fixed internal strings (`ufbxi_String`) are considered the
4896 // canonical pointers for said strings so we can compare them by address.
4897
4898 typedef struct {
4899 ufbx_error *error;
4900 ufbxi_buf buf; // < Buffer for the actual string data
4901 ufbxi_map map; // < Map of `ufbxi_string`
4902 size_t initial_size; // < Number of initial entries
4903 char *temp_str; // < Temporary string buffer of `temp_cap`
4904 size_t temp_cap; // < Capacity of the temporary buffer
4905 ufbx_unicode_error_handling error_handling;
4906 ufbxi_warnings *warnings;
4907 } ufbxi_string_pool;
4908
4909 typedef struct {
4910 const char *raw_data; // < UTF-8 data follows at `raw_length+1` if `utf8_length > 0`
4911 uint32_t raw_length; // < Length of the non-sanitized original string
4912 uint32_t utf8_length; // < Length of sanitized UTF-8 string (or zero)
4913 } ufbxi_sanitized_string;
4914
4915 static ufbxi_forceinline bool ufbxi_str_equal(ufbx_string a, ufbx_string b)
4916 {
4917 return a.length == b.length && !memcmp(a.data, b.data, a.length);
4918 }
4919
4920 static ufbxi_forceinline bool ufbxi_str_less(ufbx_string a, ufbx_string b)
4921 {
4922 size_t len = ufbxi_min_sz(a.length, b.length);
4923 int cmp = memcmp(a.data, b.data, len);
4924 if (cmp != 0) return cmp < 0;
4925 return a.length < b.length;
4926 }
4927
4928 static ufbxi_forceinline int ufbxi_str_cmp(ufbx_string a, ufbx_string b)
4929 {
4930 size_t len = ufbxi_min_sz(a.length, b.length);
4931 int cmp = memcmp(a.data, b.data, len);
4932 if (cmp != 0) return cmp;
4933 if (a.length != b.length) return a.length < b.length ? -1 : 1;
4934 return 0;
4935 }
4936
4937 static ufbxi_forceinline ufbx_string ufbxi_str_c(const char *str)
4938 {
4939 ufbx_string s = { str, strlen(str) };
4940 return s;
4941 }
4942
4943 static ufbxi_noinline uint32_t ufbxi_get_concat_key(const ufbx_string *parts, size_t num_parts)
4944 {
4945 uint32_t key = 0, shift = 32;
4946 ufbxi_for(const ufbx_string, part, parts, num_parts) {
4947 size_t length = part->length != SIZE_MAX ? part->length : strlen(part->data);
4948 for (size_t i = 0; i < length; i++) {
4949 shift -= 8;
4950 key |= (uint32_t)(uint8_t)part->data[i] << shift;
4951 if (shift == 0) return key;
4952 }
4953 }
4954 return key;
4955 }
4956
4957 static ufbxi_noinline int ufbxi_concat_str_cmp(const ufbx_string *ref, const ufbx_string *parts, size_t num_parts)
4958 {
4959 const char *ptr = ref->data, *end = ptr + ref->length;
4960 ufbxi_for(const ufbx_string, part, parts, num_parts) {
4961 size_t length = part->length != SIZE_MAX ? part->length : strlen(part->data);
4962 size_t to_cmp = ufbxi_min_sz(ufbxi_to_size(end - ptr), length);
4963 int cmp = to_cmp > 0 ? memcmp(ptr, part->data, to_cmp) : 0;
4964 if (cmp != 0) return cmp;
4965 if (to_cmp != length) return -1;
4966 ptr += length;
4967 }
4968 return ptr == end ? 0 : +1;
4969 }
4970
4971 static ufbxi_forceinline bool ufbxi_starts_with(ufbx_string str, ufbx_string prefix)
4972 {
4973 return str.length >= prefix.length && !memcmp(str.data, prefix.data, prefix.length);
4974 }
4975
4976 static ufbxi_forceinline bool ufbxi_ends_with(ufbx_string str, ufbx_string suffix)
4977 {
4978 return str.length >= suffix.length && !memcmp(str.data + str.length - suffix.length, suffix.data, suffix.length);
4979 }
4980
4981 static ufbxi_noinline bool ufbxi_remove_prefix_len(ufbx_string *str, const char *prefix, size_t prefix_len)
4982 {
4983 ufbx_string prefix_str = { prefix, prefix_len };
4984 if (ufbxi_starts_with(*str, prefix_str)) {
4985 str->data += prefix_len;
4986 str->length -= prefix_len;
4987 return true;
4988 }
4989 return false;
4990 }
4991
4992 static ufbxi_noinline bool ufbxi_remove_suffix_len(ufbx_string *str, const char *suffix, size_t suffix_len)
4993 {
4994 ufbx_string suffix_str = { suffix, suffix_len };
4995 if (ufbxi_ends_with(*str, suffix_str)) {
4996 str->length -= suffix_len;
4997 return true;
4998 }
4999 return false;
5000 }
5001
5002 static ufbxi_forceinline bool ufbxi_remove_prefix_str(ufbx_string *str, ufbx_string prefix)
5003 {
5004 return ufbxi_remove_prefix_len(str, prefix.data, prefix.length);
5005 }
5006
5007 static ufbxi_forceinline bool ufbxi_remove_suffix_c(ufbx_string *str, const char *suffix)
5008 {
5009 return ufbxi_remove_suffix_len(str, suffix, strlen(suffix));
5010 }
5011
5012 static int ufbxi_map_cmp_string(void *user, const void *va, const void *vb)
5013 {
5014 (void)user;
5015 const ufbx_string *a = (const ufbx_string*)va, *b = (const ufbx_string*)vb;
5016 return ufbxi_str_cmp(*a, *b);
5017 }
5018
5019 static ufbxi_forceinline ufbx_string ufbxi_safe_string(const char *data, size_t length)
5020 {
5021 ufbx_string str = { length > 0 ? data : ufbxi_empty_char, length };
5022 return str;
5023 }
5024
5025 static void ufbxi_string_pool_temp_free(ufbxi_string_pool *pool)
5026 {
5027 ufbxi_free(pool->map.ator, char, pool->temp_str, pool->temp_cap);
5028 ufbxi_map_free(&pool->map);
5029 }
5030
5031 ufbxi_nodiscard static size_t ufbxi_add_replacement_char(ufbxi_string_pool *pool, char *dst, char c)
5032 {
5033 switch (pool->error_handling) {
5034
5035 case UFBX_UNICODE_ERROR_HANDLING_REPLACEMENT_CHARACTER:
5036 dst[0] = (char)(uint8_t)0xefu;
5037 dst[1] = (char)(uint8_t)0xbfu;
5038 dst[2] = (char)(uint8_t)0xbdu;
5039 return 3;
5040
5041 case UFBX_UNICODE_ERROR_HANDLING_UNDERSCORE:
5042 dst[0] = '_';
5043 return 1;
5044
5045 case UFBX_UNICODE_ERROR_HANDLING_QUESTION_MARK:
5046 dst[0] = '?';
5047 return 1;
5048
5049 case UFBX_UNICODE_ERROR_HANDLING_REMOVE:
5050 return 0;
5051
5052 case UFBX_UNICODE_ERROR_HANDLING_UNSAFE_IGNORE:
5053 dst[0] = c;
5054 return 1;
5055
5056 default:
5057 return 0;
5058
5059 }
5060 }
5061
5062 ufbxi_nodiscard static ufbxi_noinline int ufbxi_sanitize_string(ufbxi_string_pool *pool, ufbxi_sanitized_string *sanitized, const char *str, size_t length, size_t valid_length, bool push_both)
5063 {
5064 // Handle only invalid cases here
5065 ufbx_assert(valid_length < length);
5066 ufbxi_check_err_msg(pool->error, pool->error_handling != UFBX_UNICODE_ERROR_HANDLING_ABORT_LOADING, "Invalid UTF-8");
5067 ufbxi_check_err(pool->error, ufbxi_warnf_imp(pool->warnings, UFBX_WARNING_BAD_UNICODE, ~0u, "Bad UTF-8 string"));
5068
5069 size_t index = valid_length;
5070 size_t dst_len = index;
5071 if (push_both) {
5072 // Copy both the full raw string and the initial valid part
5073 ufbxi_check_err(pool->error, length <= SIZE_MAX / 2 - 64);
5074 ufbxi_check_err(pool->error, ufbxi_grow_array(pool->map.ator, &pool->temp_str, &pool->temp_cap, length * 2 + 64));
5075 memcpy(pool->temp_str, str, length);
5076 pool->temp_str[length] = '\0';
5077 memcpy(pool->temp_str + length + 1, str, index);
5078 dst_len += length + 1;
5079 } else {
5080
5081 // Copy the initial valid part
5082 ufbxi_check_err(pool->error, length <= SIZE_MAX - 64);
5083 ufbxi_check_err(pool->error, ufbxi_grow_array(pool->map.ator, &pool->temp_str, &pool->temp_cap, length + 64));
5084 memcpy(pool->temp_str, str, index);
5085 }
5086
5087 char *dst = pool->temp_str;
5088 while (index < length) {
5089 uint8_t c = (uint8_t)str[index];
5090 size_t left = length - index;
5091
5092 // Not optimal but not the worst thing ever
5093 if (pool->temp_cap - dst_len < 16) {
5094 ufbxi_check_err(pool->error, ufbxi_grow_array(pool->map.ator, &pool->temp_str, &pool->temp_cap, dst_len + 16));
5095 dst = pool->temp_str;
5096 }
5097
5098 if ((c & 0x80) == 0) {
5099 if (c != 0) {
5100 dst[dst_len] = (char)c;
5101 dst_len += 1;
5102 index += 1;
5103 continue;
5104 }
5105 } else if ((c & 0xe0) == 0xc0 && left >= 2) {
5106 uint8_t t0 = (uint8_t)str[index + 1];
5107 uint32_t code = (uint32_t)c << 8 | (uint32_t)t0 << 0;
5108 if ((code & 0xc0) == 0x80 && code >= 0xc280) {
5109 dst[dst_len + 0] = (char)c;
5110 dst[dst_len + 1] = (char)t0;
5111 dst_len += 2;
5112 index += 2;
5113 continue;
5114 }
5115 } else if ((c & 0xf0) == 0xe0 && left >= 3) {
5116 uint8_t t0 = (uint8_t)str[index + 1], t1 = (uint8_t)str[index + 2];
5117 uint32_t code = (uint32_t)c << 16 | (uint32_t)t0 << 8 | (uint32_t)t1;
5118 if ((code & 0xc0c0) == 0x8080 && code >= 0xe0a080 && (code < 0xeda080 || code >= 0xee8080)) {
5119 dst[dst_len + 0] = (char)c;
5120 dst[dst_len + 1] = (char)t0;
5121 dst[dst_len + 2] = (char)t1;
5122 dst_len += 3;
5123 index += 3;
5124 continue;
5125 }
5126 } else if ((c & 0xf8) == 0xf0 && left >= 4) {
5127 uint8_t t0 = (uint8_t)str[index + 1], t1 = (uint8_t)str[index + 2], t2 = (uint8_t)str[index + 3];
5128 uint32_t code = (uint32_t)c << 24 | (uint32_t)t0 << 16 | (uint32_t)t1 << 8 | (uint32_t)t2;
5129 if ((code & 0xc0c0c0) == 0x808080 && code >= 0xf0908080u && code <= 0xf48fbfbfu) {
5130 dst[dst_len + 0] = (char)c;
5131 dst[dst_len + 1] = (char)t0;
5132 dst[dst_len + 2] = (char)t1;
5133 dst[dst_len + 3] = (char)t2;
5134 dst_len += 4;
5135 index += 4;
5136 continue;
5137 }
5138 }
5139
5140 dst_len += ufbxi_add_replacement_char(pool, dst + dst_len, (char)c);
5141 index++;
5142 }
5143
5144 // Sanitized strings are packed to 32-bit integers, in practice this should be fine
5145 // as strings are limited to 32-bit length in FBX itself.
5146 // The only problem case is a massive string that is full of unicode errors, ie.
5147 // >1GB binary blob, but these should never be sanitized.
5148 ufbxi_check_err(pool->error, length <= UINT32_MAX);
5149 sanitized->raw_data = pool->temp_str;
5150 if (push_both) {
5151 // Reserve `UINT32_MAX` for invalid UTF-8 without sanitization
5152 size_t utf8_length = dst_len - (length + 1);
5153 ufbxi_check_err(pool->error, utf8_length < UINT32_MAX);
5154 sanitized->raw_length = (uint32_t)length;
5155 sanitized->utf8_length = (uint32_t)utf8_length;
5156 } else {
5157 ufbxi_check_err(pool->error, dst_len <= UINT32_MAX);
5158 sanitized->raw_length = (uint32_t)dst_len;
5159 sanitized->utf8_length = 0;
5160 }
5161
5162 return 1;
5163 }
5164
5165 ufbxi_nodiscard static ufbxi_noinline int ufbxi_push_sanitized_string(ufbxi_string_pool *pool, ufbxi_sanitized_string *sanitized, const char *str, size_t length, uint32_t hash, bool raw)
5166 {
5167 ufbxi_regression_assert(hash == ufbxi_hash_string(str, length));
5168
5169 ufbxi_check_err(pool->error, length <= UINT32_MAX);
5170 ufbxi_check_err(pool->error, ufbxi_map_grow(&pool->map, ufbx_string, pool->initial_size));
5171
5172 const char *total_data = str;
5173 size_t total_length = length;
5174
5175 sanitized->raw_length = (uint32_t)length;
5176 sanitized->utf8_length = 0;
5177
5178 if (!raw) {
5179 size_t valid_length = ufbxi_utf8_valid_length(str, length);
5180 if (valid_length != length) {
5181 ufbxi_check_err(pool->error, ufbxi_sanitize_string(pool, sanitized, str, length, valid_length, true));
5182 total_data = sanitized->raw_data;
5183 total_length = sanitized->raw_length + sanitized->utf8_length + 1;
5184 hash = ufbxi_hash_string(str, length);
5185 }
5186 }
5187
5188 ufbx_string ref = { total_data, total_length };
5189
5190 ufbx_string *entry = ufbxi_map_find(&pool->map, ufbx_string, hash, &ref);
5191 if (entry) {
5192 sanitized->raw_data = entry->data;
5193 } else {
5194 entry = ufbxi_map_insert(&pool->map, ufbx_string, hash, &ref);
5195 ufbxi_check_err(pool->error, entry);
5196 entry->length = total_length;
5197 char *dst = ufbxi_push(&pool->buf, char, total_length + 1);
5198 ufbxi_check_err(pool->error, dst);
5199 memcpy(dst, total_data, total_length);
5200 dst[total_length] = '\0';
5201 entry->data = dst;
5202 sanitized->raw_data = dst;
5203 }
5204
5205 return 1;
5206 }
5207
5208 ufbxi_nodiscard static ufbxi_noinline const char *ufbxi_push_string_imp(ufbxi_string_pool *pool, const char *str, size_t length, size_t *p_out_length, bool copy, bool raw)
5209 {
5210 if (length == 0) return ufbxi_empty_char;
5211
5212 ufbxi_check_return_err(pool->error, ufbxi_map_grow(&pool->map, ufbx_string, pool->initial_size), NULL);
5213
5214 uint32_t hash;
5215 if (raw) {
5216 hash = ufbxi_hash_string(str, length);
5217 } else {
5218 bool non_ascii = false;
5219 hash = ufbxi_hash_string_check_ascii(str, length, &non_ascii);
5220 if (non_ascii) {
5221 size_t valid_length = ufbxi_utf8_valid_length(str, length);
5222 if (valid_length < length) {
5223 ufbxi_sanitized_string sanitized;
5224 ufbxi_check_return_err(pool->error, ufbxi_sanitize_string(pool, &sanitized, str, length, valid_length, false), NULL);
5225 str = sanitized.raw_data;
5226 length = sanitized.raw_length;
5227 hash = ufbxi_hash_string(str, length);
5228 *p_out_length = length;
5229 }
5230 }
5231 }
5232
5233 ufbx_string ref = { str, length };
5234
5235 ufbx_string *entry = ufbxi_map_find(&pool->map, ufbx_string, hash, &ref);
5236 if (entry) return entry->data;
5237 entry = ufbxi_map_insert(&pool->map, ufbx_string, hash, &ref);
5238 ufbxi_check_return_err(pool->error, entry, NULL);
5239 entry->length = length;
5240 if (copy) {
5241 char *dst = ufbxi_push(&pool->buf, char, length + 1);
5242 ufbxi_check_return_err(pool->error, dst, NULL);
5243 memcpy(dst, str, length);
5244 dst[length] = '\0';
5245 entry->data = dst;
5246 } else {
5247 entry->data = str;
5248 }
5249 return entry->data;
5250 }
5251
5252 ufbxi_nodiscard static ufbxi_forceinline const char *ufbxi_push_string(ufbxi_string_pool *pool, const char *str, size_t length, size_t *p_out_length, bool raw)
5253 {
5254 return ufbxi_push_string_imp(pool, str, length, p_out_length, true, raw);
5255 }
5256
5257 ufbxi_nodiscard static ufbxi_forceinline int ufbxi_push_string_place(ufbxi_string_pool *pool, const char **p_str, size_t *p_length, bool raw)
5258 {
5259 const char *str = *p_str;
5260 size_t length = *p_length;
5261 ufbxi_check_err(pool->error, str || length == 0);
5262 str = ufbxi_push_string(pool, str, length, p_length, raw);
5263 ufbxi_check_err(pool->error, str);
5264 *p_str = str;
5265 return 1;
5266 }
5267
5268 ufbxi_nodiscard static ufbxi_noinline int ufbxi_push_string_place_str(ufbxi_string_pool *pool, ufbx_string *p_str, bool raw)
5269 {
5270 ufbxi_check_err(pool->error, p_str);
5271 return ufbxi_push_string_place(pool, &p_str->data, &p_str->length, raw);
5272 }
5273
5274 ufbxi_nodiscard static ufbxi_noinline int ufbxi_push_string_place_blob(ufbxi_string_pool *pool, ufbx_blob *p_blob, bool raw)
5275 {
5276 if (p_blob->size == 0) {
5277 p_blob->data = NULL;
5278 return 1;
5279 }
5280 p_blob->data = ufbxi_push_string(pool, (const char*)p_blob->data, p_blob->size, &p_blob->size, raw);
5281 ufbxi_check_err(pool->error, p_blob->data);
5282 return 1;
5283 }
5284
5285 // -- String constants
5286 //
5287 // All strings in FBX files are pooled so by having canonical string constant
5288 // addresses we can compare strings to these constants by comparing pointers.
5289 // Keep the list alphabetically sorted!
5290
5291 static const char ufbxi_AllSame[] = "AllSame";
5292 static const char ufbxi_Alphas[] = "Alphas";
5293 static const char ufbxi_AmbientColor[] = "AmbientColor";
5294 static const char ufbxi_AnimationCurveNode[] = "AnimationCurveNode";
5295 static const char ufbxi_AnimationCurve[] = "AnimationCurve";
5296 static const char ufbxi_AnimationLayer[] = "AnimationLayer";
5297 static const char ufbxi_AnimationStack[] = "AnimationStack";
5298 static const char ufbxi_ApertureFormat[] = "ApertureFormat";
5299 static const char ufbxi_ApertureMode[] = "ApertureMode";
5300 static const char ufbxi_AreaLightShape[] = "AreaLightShape";
5301 static const char ufbxi_AspectH[] = "AspectH";
5302 static const char ufbxi_AspectHeight[] = "AspectHeight";
5303 static const char ufbxi_AspectRatioMode[] = "AspectRatioMode";
5304 static const char ufbxi_AspectW[] = "AspectW";
5305 static const char ufbxi_AspectWidth[] = "AspectWidth";
5306 static const char ufbxi_Audio[] = "Audio";
5307 static const char ufbxi_AudioLayer[] = "AudioLayer";
5308 static const char ufbxi_BaseLayer[] = "BaseLayer";
5309 static const char ufbxi_BinaryData[] = "BinaryData";
5310 static const char ufbxi_BindPose[] = "BindPose";
5311 static const char ufbxi_BindingTable[] = "BindingTable";
5312 static const char ufbxi_Binormals[] = "Binormals";
5313 static const char ufbxi_BinormalsIndex[] = "BinormalsIndex";
5314 static const char ufbxi_BinormalsW[] = "BinormalsW";
5315 static const char ufbxi_BlendMode[] = "BlendMode";
5316 static const char ufbxi_BlendModes[] = "BlendModes";
5317 static const char ufbxi_BlendShapeChannel[] = "BlendShapeChannel";
5318 static const char ufbxi_BlendShape[] = "BlendShape";
5319 static const char ufbxi_BlendWeights[] = "BlendWeights";
5320 static const char ufbxi_BoundaryRule[] = "BoundaryRule";
5321 static const char ufbxi_Boundary[] = "Boundary";
5322 static const char ufbxi_ByEdge[] = "ByEdge";
5323 static const char ufbxi_ByPolygonVertex[] = "ByPolygonVertex";
5324 static const char ufbxi_ByPolygon[] = "ByPolygon";
5325 static const char ufbxi_ByVertex[] = "ByVertex";
5326 static const char ufbxi_ByVertice[] = "ByVertice";
5327 static const char ufbxi_Cache[] = "Cache";
5328 static const char ufbxi_CameraProjectionType[] = "CameraProjectionType";
5329 static const char ufbxi_CameraStereo[] = "CameraStereo";
5330 static const char ufbxi_CameraSwitcher[] = "CameraSwitcher";
5331 static const char ufbxi_Camera[] = "Camera";
5332 static const char ufbxi_CastLight[] = "CastLight";
5333 static const char ufbxi_CastShadows[] = "CastShadows";
5334 static const char ufbxi_Channel[] = "Channel";
5335 static const char ufbxi_Character[] = "Character";
5336 static const char ufbxi_Children[] = "Children";
5337 static const char ufbxi_Cluster[] = "Cluster";
5338 static const char ufbxi_CollectionExclusive[] = "CollectionExclusive";
5339 static const char ufbxi_Collection[] = "Collection";
5340 static const char ufbxi_ColorIndex[] = "ColorIndex";
5341 static const char ufbxi_Color[] = "Color";
5342 static const char ufbxi_Colors[] = "Colors";
5343 static const char ufbxi_Cone_angle[] = "Cone angle";
5344 static const char ufbxi_ConeAngle[] = "ConeAngle";
5345 static const char ufbxi_Connections[] = "Connections";
5346 static const char ufbxi_Constraint[] = "Constraint";
5347 static const char ufbxi_Content[] = "Content";
5348 static const char ufbxi_CoordAxisSign[] = "CoordAxisSign";
5349 static const char ufbxi_CoordAxis[] = "CoordAxis";
5350 static const char ufbxi_Count[] = "Count";
5351 static const char ufbxi_Creator[] = "Creator";
5352 static const char ufbxi_CurrentTextureBlendMode[] = "CurrentTextureBlendMode";
5353 static const char ufbxi_CurrentTimeMarker[] = "CurrentTimeMarker";
5354 static const char ufbxi_CustomFrameRate[] = "CustomFrameRate";
5355 static const char ufbxi_DecayType[] = "DecayType";
5356 static const char ufbxi_DefaultCamera[] = "DefaultCamera";
5357 static const char ufbxi_Default[] = "Default";
5358 static const char ufbxi_Definitions[] = "Definitions";
5359 static const char ufbxi_DeformPercent[] = "DeformPercent";
5360 static const char ufbxi_Deformer[] = "Deformer";
5361 static const char ufbxi_DiffuseColor[] = "DiffuseColor";
5362 static const char ufbxi_Dimension[] = "Dimension";
5363 static const char ufbxi_Dimensions[] = "Dimensions";
5364 static const char ufbxi_DisplayLayer[] = "DisplayLayer";
5365 static const char ufbxi_Document[] = "Document";
5366 static const char ufbxi_Documents[] = "Documents";
5367 static const char ufbxi_EdgeCrease[] = "EdgeCrease";
5368 static const char ufbxi_EdgeIndexArray[] = "EdgeIndexArray";
5369 static const char ufbxi_Edges[] = "Edges";
5370 static const char ufbxi_EmissiveColor[] = "EmissiveColor";
5371 static const char ufbxi_Entry[] = "Entry";
5372 static const char ufbxi_FBXHeaderExtension[] = "FBXHeaderExtension";
5373 static const char ufbxi_FBXHeaderVersion[] = "FBXHeaderVersion";
5374 static const char ufbxi_FBXVersion[] = "FBXVersion";
5375 static const char ufbxi_FKEffector[] = "FKEffector";
5376 static const char ufbxi_FarPlane[] = "FarPlane";
5377 static const char ufbxi_FbxPropertyEntry[] = "FbxPropertyEntry";
5378 static const char ufbxi_FbxSemanticEntry[] = "FbxSemanticEntry";
5379 static const char ufbxi_FieldOfViewX[] = "FieldOfViewX";
5380 static const char ufbxi_FieldOfViewY[] = "FieldOfViewY";
5381 static const char ufbxi_FieldOfView[] = "FieldOfView";
5382 static const char ufbxi_FileName[] = "FileName";
5383 static const char ufbxi_Filename[] = "Filename";
5384 static const char ufbxi_FilmHeight[] = "FilmHeight";
5385 static const char ufbxi_FilmSqueezeRatio[] = "FilmSqueezeRatio";
5386 static const char ufbxi_FilmWidth[] = "FilmWidth";
5387 static const char ufbxi_FlipNormals[] = "FlipNormals";
5388 static const char ufbxi_FocalLength[] = "FocalLength";
5389 static const char ufbxi_Form[] = "Form";
5390 static const char ufbxi_Freeze[] = "Freeze";
5391 static const char ufbxi_FrontAxisSign[] = "FrontAxisSign";
5392 static const char ufbxi_FrontAxis[] = "FrontAxis";
5393 static const char ufbxi_FullWeights[] = "FullWeights";
5394 static const char ufbxi_GateFit[] = "GateFit";
5395 static const char ufbxi_GeometricRotation[] = "GeometricRotation";
5396 static const char ufbxi_GeometricScaling[] = "GeometricScaling";
5397 static const char ufbxi_GeometricTranslation[] = "GeometricTranslation";
5398 static const char ufbxi_GeometryUVInfo[] = "GeometryUVInfo";
5399 static const char ufbxi_Geometry[] = "Geometry";
5400 static const char ufbxi_GlobalSettings[] = "GlobalSettings";
5401 static const char ufbxi_Hole[] = "Hole";
5402 static const char ufbxi_HotSpot[] = "HotSpot";
5403 static const char ufbxi_IKEffector[] = "IKEffector";
5404 static const char ufbxi_ImageData[] = "ImageData";
5405 static const char ufbxi_Implementation[] = "Implementation";
5406 static const char ufbxi_Indexes[] = "Indexes";
5407 static const char ufbxi_InheritType[] = "InheritType";
5408 static const char ufbxi_InnerAngle[] = "InnerAngle";
5409 static const char ufbxi_Intensity[] = "Intensity";
5410 static const char ufbxi_IsTheNodeInSet[] = "IsTheNodeInSet";
5411 static const char ufbxi_KeyAttrDataFloat[] = "KeyAttrDataFloat";
5412 static const char ufbxi_KeyAttrFlags[] = "KeyAttrFlags";
5413 static const char ufbxi_KeyAttrRefCount[] = "KeyAttrRefCount";
5414 static const char ufbxi_KeyCount[] = "KeyCount";
5415 static const char ufbxi_KeyTime[] = "KeyTime";
5416 static const char ufbxi_KeyValueFloat[] = "KeyValueFloat";
5417 static const char ufbxi_Key[] = "Key";
5418 static const char ufbxi_KnotVectorU[] = "KnotVectorU";
5419 static const char ufbxi_KnotVectorV[] = "KnotVectorV";
5420 static const char ufbxi_KnotVector[] = "KnotVector";
5421 static const char ufbxi_LayerElementBinormal[] = "LayerElementBinormal";
5422 static const char ufbxi_LayerElementColor[] = "LayerElementColor";
5423 static const char ufbxi_LayerElementEdgeCrease[] = "LayerElementEdgeCrease";
5424 static const char ufbxi_LayerElementHole[] = "LayerElementHole";
5425 static const char ufbxi_LayerElementMaterial[] = "LayerElementMaterial";
5426 static const char ufbxi_LayerElementNormal[] = "LayerElementNormal";
5427 static const char ufbxi_LayerElementPolygonGroup[] = "LayerElementPolygonGroup";
5428 static const char ufbxi_LayerElementSmoothing[] = "LayerElementSmoothing";
5429 static const char ufbxi_LayerElementTangent[] = "LayerElementTangent";
5430 static const char ufbxi_LayerElementUV[] = "LayerElementUV";
5431 static const char ufbxi_LayerElementVertexCrease[] = "LayerElementVertexCrease";
5432 static const char ufbxi_LayerElementVisibility[] = "LayerElementVisibility";
5433 static const char ufbxi_LayerElement[] = "LayerElement";
5434 static const char ufbxi_Layer[] = "Layer";
5435 static const char ufbxi_LayeredTexture[] = "LayeredTexture";
5436 static const char ufbxi_Lcl_Rotation[] = "Lcl Rotation";
5437 static const char ufbxi_Lcl_Scaling[] = "Lcl Scaling";
5438 static const char ufbxi_Lcl_Translation[] = "Lcl Translation";
5439 static const char ufbxi_LeftCamera[] = "LeftCamera";
5440 static const char ufbxi_LightType[] = "LightType";
5441 static const char ufbxi_Light[] = "Light";
5442 static const char ufbxi_LimbLength[] = "LimbLength";
5443 static const char ufbxi_LimbNode[] = "LimbNode";
5444 static const char ufbxi_Limb[] = "Limb";
5445 static const char ufbxi_Line[] = "Line";
5446 static const char ufbxi_Link[] = "Link";
5447 static const char ufbxi_LocalStart[] = "LocalStart";
5448 static const char ufbxi_LocalStop[] = "LocalStop";
5449 static const char ufbxi_LocalTime[] = "LocalTime";
5450 static const char ufbxi_LodGroup[] = "LodGroup";
5451 static const char ufbxi_MappingInformationType[] = "MappingInformationType";
5452 static const char ufbxi_Marker[] = "Marker";
5453 static const char ufbxi_MaterialAssignation[] = "MaterialAssignation";
5454 static const char ufbxi_Material[] = "Material";
5455 static const char ufbxi_Materials[] = "Materials";
5456 static const char ufbxi_Matrix[] = "Matrix";
5457 static const char ufbxi_Media[] = "Media";
5458 static const char ufbxi_Mesh[] = "Mesh";
5459 static const char ufbxi_Model[] = "Model";
5460 static const char ufbxi_Name[] = "Name";
5461 static const char ufbxi_NearPlane[] = "NearPlane";
5462 static const char ufbxi_NodeAttributeName[] = "NodeAttributeName";
5463 static const char ufbxi_NodeAttribute[] = "NodeAttribute";
5464 static const char ufbxi_Node[] = "Node";
5465 static const char ufbxi_Normals[] = "Normals";
5466 static const char ufbxi_NormalsIndex[] = "NormalsIndex";
5467 static const char ufbxi_NormalsW[] = "NormalsW";
5468 static const char ufbxi_Null[] = "Null";
5469 static const char ufbxi_NurbsCurve[] = "NurbsCurve";
5470 static const char ufbxi_NurbsSurfaceOrder[] = "NurbsSurfaceOrder";
5471 static const char ufbxi_NurbsSurface[] = "NurbsSurface";
5472 static const char ufbxi_Nurbs[] = "Nurbs";
5473 static const char ufbxi_OO[] = "OO\0";
5474 static const char ufbxi_OP[] = "OP\0";
5475 static const char ufbxi_ObjectMetaData[] = "ObjectMetaData";
5476 static const char ufbxi_ObjectType[] = "ObjectType";
5477 static const char ufbxi_Objects[] = "Objects";
5478 static const char ufbxi_Order[] = "Order";
5479 static const char ufbxi_OriginalUnitScaleFactor[] = "OriginalUnitScaleFactor";
5480 static const char ufbxi_OriginalUpAxis[] = "OriginalUpAxis";
5481 static const char ufbxi_OriginalUpAxisSign[] = "OriginalUpAxisSign";
5482 static const char ufbxi_OrthoZoom[] = "OrthoZoom";
5483 static const char ufbxi_OtherFlags[] = "OtherFlags";
5484 static const char ufbxi_OuterAngle[] = "OuterAngle";
5485 static const char ufbxi_PO[] = "PO\0";
5486 static const char ufbxi_PP[] = "PP\0";
5487 static const char ufbxi_PointsIndex[] = "PointsIndex";
5488 static const char ufbxi_Points[] = "Points";
5489 static const char ufbxi_PolygonGroup[] = "PolygonGroup";
5490 static const char ufbxi_PolygonIndexArray[] = "PolygonIndexArray";
5491 static const char ufbxi_PolygonVertexIndex[] = "PolygonVertexIndex";
5492 static const char ufbxi_PoseNode[] = "PoseNode";
5493 static const char ufbxi_Pose[] = "Pose";
5494 static const char ufbxi_Post_Extrapolation[] = "Post-Extrapolation";
5495 static const char ufbxi_PostRotation[] = "PostRotation";
5496 static const char ufbxi_Pre_Extrapolation[] = "Pre-Extrapolation";
5497 static const char ufbxi_PreRotation[] = "PreRotation";
5498 static const char ufbxi_PreviewDivisionLevels[] = "PreviewDivisionLevels";
5499 static const char ufbxi_Properties60[] = "Properties60";
5500 static const char ufbxi_Properties70[] = "Properties70";
5501 static const char ufbxi_PropertyTemplate[] = "PropertyTemplate";
5502 static const char ufbxi_R[] = "R\0\0";
5503 static const char ufbxi_ReferenceStart[] = "ReferenceStart";
5504 static const char ufbxi_ReferenceStop[] = "ReferenceStop";
5505 static const char ufbxi_ReferenceTime[] = "ReferenceTime";
5506 static const char ufbxi_RelativeFileName[] = "RelativeFileName";
5507 static const char ufbxi_RelativeFilename[] = "RelativeFilename";
5508 static const char ufbxi_RenderDivisionLevels[] = "RenderDivisionLevels";
5509 static const char ufbxi_Repetition[] = "Repetition";
5510 static const char ufbxi_RightCamera[] = "RightCamera";
5511 static const char ufbxi_RootNode[] = "RootNode";
5512 static const char ufbxi_Root[] = "Root";
5513 static const char ufbxi_RotationAccumulationMode[] = "RotationAccumulationMode";
5514 static const char ufbxi_RotationOffset[] = "RotationOffset";
5515 static const char ufbxi_RotationOrder[] = "RotationOrder";
5516 static const char ufbxi_RotationPivot[] = "RotationPivot";
5517 static const char ufbxi_Rotation[] = "Rotation";
5518 static const char ufbxi_S[] = "S\0\0";
5519 static const char ufbxi_ScaleAccumulationMode[] = "ScaleAccumulationMode";
5520 static const char ufbxi_ScalingOffset[] = "ScalingOffset";
5521 static const char ufbxi_ScalingPivot[] = "ScalingPivot";
5522 static const char ufbxi_Scaling[] = "Scaling";
5523 static const char ufbxi_SceneInfo[] = "SceneInfo";
5524 static const char ufbxi_SelectionNode[] = "SelectionNode";
5525 static const char ufbxi_SelectionSet[] = "SelectionSet";
5526 static const char ufbxi_ShadingModel[] = "ShadingModel";
5527 static const char ufbxi_Shape[] = "Shape";
5528 static const char ufbxi_Shininess[] = "Shininess";
5529 static const char ufbxi_Show[] = "Show";
5530 static const char ufbxi_Size[] = "Size";
5531 static const char ufbxi_Skin[] = "Skin";
5532 static const char ufbxi_SkinningType[] = "SkinningType";
5533 static const char ufbxi_Smoothing[] = "Smoothing";
5534 static const char ufbxi_Smoothness[] = "Smoothness";
5535 static const char ufbxi_SnapOnFrameMode[] = "SnapOnFrameMode";
5536 static const char ufbxi_SpecularColor[] = "SpecularColor";
5537 static const char ufbxi_Step[] = "Step";
5538 static const char ufbxi_SubDeformer[] = "SubDeformer";
5539 static const char ufbxi_T[] = "T\0\0";
5540 static const char ufbxi_TCDefinition[] = "TCDefinition";
5541 static const char ufbxi_Take[] = "Take";
5542 static const char ufbxi_Takes[] = "Takes";
5543 static const char ufbxi_Tangents[] = "Tangents";
5544 static const char ufbxi_TangentsIndex[] = "TangentsIndex";
5545 static const char ufbxi_TangentsW[] = "TangentsW";
5546 static const char ufbxi_Texture[] = "Texture";
5547 static const char ufbxi_Texture_alpha[] = "Texture alpha";
5548 static const char ufbxi_TextureId[] = "TextureId";
5549 static const char ufbxi_TextureRotationPivot[] = "TextureRotationPivot";
5550 static const char ufbxi_TextureScalingPivot[] = "TextureScalingPivot";
5551 static const char ufbxi_TextureUV[] = "TextureUV";
5552 static const char ufbxi_TextureUVVerticeIndex[] = "TextureUVVerticeIndex";
5553 static const char ufbxi_Thumbnail[] = "Thumbnail";
5554 static const char ufbxi_TimeMarker[] = "TimeMarker";
5555 static const char ufbxi_TimeMode[] = "TimeMode";
5556 static const char ufbxi_TimeProtocol[] = "TimeProtocol";
5557 static const char ufbxi_TimeSpanStart[] = "TimeSpanStart";
5558 static const char ufbxi_TimeSpanStop[] = "TimeSpanStop";
5559 static const char ufbxi_TransformLink[] = "TransformLink";
5560 static const char ufbxi_Transform[] = "Transform";
5561 static const char ufbxi_Translation[] = "Translation";
5562 static const char ufbxi_TrimNurbsSurface[] = "TrimNurbsSurface";
5563 static const char ufbxi_Type[] = "Type";
5564 static const char ufbxi_TypedIndex[] = "TypedIndex";
5565 static const char ufbxi_UVIndex[] = "UVIndex";
5566 static const char ufbxi_UVSet[] = "UVSet";
5567 static const char ufbxi_UVSwap[] = "UVSwap";
5568 static const char ufbxi_UV[] = "UV\0";
5569 static const char ufbxi_UnitScaleFactor[] = "UnitScaleFactor";
5570 static const char ufbxi_UpAxisSign[] = "UpAxisSign";
5571 static const char ufbxi_UpAxis[] = "UpAxis";
5572 static const char ufbxi_Version5[] = "Version5";
5573 static const char ufbxi_VertexCacheDeformer[] = "VertexCacheDeformer";
5574 static const char ufbxi_VertexCrease[] = "VertexCrease";
5575 static const char ufbxi_VertexCreaseIndex[] = "VertexCreaseIndex";
5576 static const char ufbxi_VertexIndexArray[] = "VertexIndexArray";
5577 static const char ufbxi_Vertices[] = "Vertices";
5578 static const char ufbxi_Video[] = "Video";
5579 static const char ufbxi_Visibility[] = "Visibility";
5580 static const char ufbxi_Weight[] = "Weight";
5581 static const char ufbxi_Weights[] = "Weights";
5582 static const char ufbxi_WrapModeU[] = "WrapModeU";
5583 static const char ufbxi_WrapModeV[] = "WrapModeV";
5584 static const char ufbxi_X[] = "X\0\0";
5585 static const char ufbxi_Y[] = "Y\0\0";
5586 static const char ufbxi_Z[] = "Z\0\0";
5587 static const char ufbxi_d_X[] = "d|X";
5588 static const char ufbxi_d_Y[] = "d|Y";
5589 static const char ufbxi_d_Z[] = "d|Z";
5590
5591 static const ufbx_string ufbxi_strings[] = {
5592 { ufbxi_AllSame, 7 },
5593 { ufbxi_Alphas, 6 },
5594 { ufbxi_AmbientColor, 12 },
5595 { ufbxi_AnimationCurve, 14 },
5596 { ufbxi_AnimationCurveNode, 18 },
5597 { ufbxi_AnimationLayer, 14 },
5598 { ufbxi_AnimationStack, 14 },
5599 { ufbxi_ApertureFormat, 14 },
5600 { ufbxi_ApertureMode, 12 },
5601 { ufbxi_AreaLightShape, 14 },
5602 { ufbxi_AspectH, 7 },
5603 { ufbxi_AspectHeight, 12 },
5604 { ufbxi_AspectRatioMode, 15 },
5605 { ufbxi_AspectW, 7 },
5606 { ufbxi_AspectWidth, 11 },
5607 { ufbxi_Audio, 5 },
5608 { ufbxi_AudioLayer, 10 },
5609 { ufbxi_BaseLayer, 9 },
5610 { ufbxi_BinaryData, 10 },
5611 { ufbxi_BindPose, 8 },
5612 { ufbxi_BindingTable, 12 },
5613 { ufbxi_Binormals, 9 },
5614 { ufbxi_BinormalsIndex, 14 },
5615 { ufbxi_BinormalsW, 10 },
5616 { ufbxi_BlendMode, 9 },
5617 { ufbxi_BlendModes, 10 },
5618 { ufbxi_BlendShape, 10 },
5619 { ufbxi_BlendShapeChannel, 17 },
5620 { ufbxi_BlendWeights, 12 },
5621 { ufbxi_Boundary, 8 },
5622 { ufbxi_BoundaryRule, 12 },
5623 { ufbxi_ByEdge, 6 },
5624 { ufbxi_ByPolygon, 9 },
5625 { ufbxi_ByPolygonVertex, 15 },
5626 { ufbxi_ByVertex, 8 },
5627 { ufbxi_ByVertice, 9 },
5628 { ufbxi_Cache, 5 },
5629 { ufbxi_Camera, 6 },
5630 { ufbxi_CameraProjectionType, 20 },
5631 { ufbxi_CameraStereo, 12 },
5632 { ufbxi_CameraSwitcher, 14 },
5633 { ufbxi_CastLight, 9 },
5634 { ufbxi_CastShadows, 11 },
5635 { ufbxi_Channel, 7 },
5636 { ufbxi_Character, sizeof(ufbxi_Character) - 1 },
5637 { ufbxi_Children, 8 },
5638 { ufbxi_Cluster, 7 },
5639 { ufbxi_Collection, 10 },
5640 { ufbxi_CollectionExclusive, 19 },
5641 { ufbxi_Color, 5 },
5642 { ufbxi_ColorIndex, 10 },
5643 { ufbxi_Colors, 6 },
5644 { ufbxi_Cone_angle, 10 },
5645 { ufbxi_ConeAngle, 9 },
5646 { ufbxi_Connections, 11 },
5647 { ufbxi_Constraint, sizeof(ufbxi_Constraint) - 1 },
5648 { ufbxi_Content, 7 },
5649 { ufbxi_CoordAxis, 9 },
5650 { ufbxi_CoordAxisSign, 13 },
5651 { ufbxi_Count, 5 },
5652 { ufbxi_Creator, 7 },
5653 { ufbxi_CurrentTextureBlendMode, 23 },
5654 { ufbxi_CurrentTimeMarker, 17 },
5655 { ufbxi_CustomFrameRate, 15 },
5656 { ufbxi_DecayType, 9 },
5657 { ufbxi_Default, 7 },
5658 { ufbxi_DefaultCamera, 13 },
5659 { ufbxi_Definitions, 11 },
5660 { ufbxi_DeformPercent, 13 },
5661 { ufbxi_Deformer, 8 },
5662 { ufbxi_DiffuseColor, 12 },
5663 { ufbxi_Dimension, 9 },
5664 { ufbxi_Dimensions, 10 },
5665 { ufbxi_DisplayLayer, 12 },
5666 { ufbxi_Document, 8 },
5667 { ufbxi_Documents, 9 },
5668 { ufbxi_EdgeCrease, 10 },
5669 { ufbxi_EdgeIndexArray, 14 },
5670 { ufbxi_Edges, 5 },
5671 { ufbxi_EmissiveColor, 13 },
5672 { ufbxi_Entry, 5 },
5673 { ufbxi_FBXHeaderExtension, 18 },
5674 { ufbxi_FBXHeaderVersion, 16 },
5675 { ufbxi_FBXVersion, 10 },
5676 { ufbxi_FKEffector, 10 },
5677 { ufbxi_FarPlane, 8 },
5678 { ufbxi_FbxPropertyEntry, 16 },
5679 { ufbxi_FbxSemanticEntry, 16 },
5680 { ufbxi_FieldOfView, 11 },
5681 { ufbxi_FieldOfViewX, 12 },
5682 { ufbxi_FieldOfViewY, 12 },
5683 { ufbxi_FileName, 8 },
5684 { ufbxi_Filename, 8 },
5685 { ufbxi_FilmHeight, 10 },
5686 { ufbxi_FilmSqueezeRatio, 16 },
5687 { ufbxi_FilmWidth, 9 },
5688 { ufbxi_FlipNormals, 11 },
5689 { ufbxi_FocalLength, 11 },
5690 { ufbxi_Form, 4 },
5691 { ufbxi_Freeze, 6 },
5692 { ufbxi_FrontAxis, 9 },
5693 { ufbxi_FrontAxisSign, 13 },
5694 { ufbxi_FullWeights, 11 },
5695 { ufbxi_GateFit, 7 },
5696 { ufbxi_GeometricRotation, 17 },
5697 { ufbxi_GeometricScaling, 16 },
5698 { ufbxi_GeometricTranslation, 20 },
5699 { ufbxi_Geometry, 8 },
5700 { ufbxi_GeometryUVInfo, 14 },
5701 { ufbxi_GlobalSettings, 14 },
5702 { ufbxi_Hole, 4 },
5703 { ufbxi_HotSpot, 7 },
5704 { ufbxi_IKEffector, 10 },
5705 { ufbxi_ImageData, 9 },
5706 { ufbxi_Implementation, 14 },
5707 { ufbxi_Indexes, 7 },
5708 { ufbxi_InheritType, 11 },
5709 { ufbxi_InnerAngle, 10 },
5710 { ufbxi_Intensity, 9 },
5711 { ufbxi_IsTheNodeInSet, 14 },
5712 { ufbxi_Key, 3 },
5713 { ufbxi_KeyAttrDataFloat, 16 },
5714 { ufbxi_KeyAttrFlags, 12 },
5715 { ufbxi_KeyAttrRefCount, 15 },
5716 { ufbxi_KeyCount, 8 },
5717 { ufbxi_KeyTime, 7 },
5718 { ufbxi_KeyValueFloat, 13 },
5719 { ufbxi_KnotVector, 10 },
5720 { ufbxi_KnotVectorU, 11 },
5721 { ufbxi_KnotVectorV, 11 },
5722 { ufbxi_Layer, 5 },
5723 { ufbxi_LayerElement, 12 },
5724 { ufbxi_LayerElementBinormal, 20 },
5725 { ufbxi_LayerElementColor, 17 },
5726 { ufbxi_LayerElementEdgeCrease, 22 },
5727 { ufbxi_LayerElementHole, 16 },
5728 { ufbxi_LayerElementMaterial, 20 },
5729 { ufbxi_LayerElementNormal, 18 },
5730 { ufbxi_LayerElementPolygonGroup, 24 },
5731 { ufbxi_LayerElementSmoothing, 21 },
5732 { ufbxi_LayerElementTangent, 19 },
5733 { ufbxi_LayerElementUV, 14 },
5734 { ufbxi_LayerElementVertexCrease, 24 },
5735 { ufbxi_LayerElementVisibility, 22 },
5736 { ufbxi_LayeredTexture, 14 },
5737 { ufbxi_Lcl_Rotation, 12 },
5738 { ufbxi_Lcl_Scaling, 11 },
5739 { ufbxi_Lcl_Translation, 15 },
5740 { ufbxi_LeftCamera, 10 },
5741 { ufbxi_Light, 5 },
5742 { ufbxi_LightType, 9 },
5743 { ufbxi_Limb, 4 },
5744 { ufbxi_LimbLength, 10 },
5745 { ufbxi_LimbNode, 8 },
5746 { ufbxi_Line, 4 },
5747 { ufbxi_Link, 4 },
5748 { ufbxi_LocalStart, 10 },
5749 { ufbxi_LocalStop, 9 },
5750 { ufbxi_LocalTime, 9 },
5751 { ufbxi_LodGroup, 8 },
5752 { ufbxi_MappingInformationType, 22 },
5753 { ufbxi_Marker, 6 },
5754 { ufbxi_Material, 8 },
5755 { ufbxi_MaterialAssignation, 19 },
5756 { ufbxi_Materials, 9 },
5757 { ufbxi_Matrix, 6 },
5758 { ufbxi_Media, 5 },
5759 { ufbxi_Mesh, 4 },
5760 { ufbxi_Model, 5 },
5761 { ufbxi_Name, 4 },
5762 { ufbxi_NearPlane, 9 },
5763 { ufbxi_Node, 4 },
5764 { ufbxi_NodeAttribute, 13 },
5765 { ufbxi_NodeAttributeName, 17 },
5766 { ufbxi_Normals, 7 },
5767 { ufbxi_NormalsIndex, 12 },
5768 { ufbxi_NormalsW, 8 },
5769 { ufbxi_Null, 4 },
5770 { ufbxi_Nurbs, 5 },
5771 { ufbxi_NurbsCurve, 10 },
5772 { ufbxi_NurbsSurface, 12 },
5773 { ufbxi_NurbsSurfaceOrder, 17 },
5774 { ufbxi_OO, 2 },
5775 { ufbxi_OP, 2 },
5776 { ufbxi_ObjectMetaData, 14 },
5777 { ufbxi_ObjectType, 10 },
5778 { ufbxi_Objects, 7 },
5779 { ufbxi_Order, 5 },
5780 { ufbxi_OriginalUnitScaleFactor, 23 },
5781 { ufbxi_OriginalUpAxis, 14 },
5782 { ufbxi_OriginalUpAxisSign, 18 },
5783 { ufbxi_OrthoZoom, 9 },
5784 { ufbxi_OtherFlags, 10 },
5785 { ufbxi_OuterAngle, 10 },
5786 { ufbxi_PO, 2 },
5787 { ufbxi_PP, 2 },
5788 { ufbxi_Points, 6 },
5789 { ufbxi_PointsIndex, 11 },
5790 { ufbxi_PolygonGroup, 12 },
5791 { ufbxi_PolygonIndexArray, 17 },
5792 { ufbxi_PolygonVertexIndex, 18 },
5793 { ufbxi_Pose, 4 },
5794 { ufbxi_PoseNode, 8 },
5795 { ufbxi_Post_Extrapolation, 18 },
5796 { ufbxi_PostRotation, 12 },
5797 { ufbxi_Pre_Extrapolation, 17 },
5798 { ufbxi_PreRotation, 11 },
5799 { ufbxi_PreviewDivisionLevels, 21 },
5800 { ufbxi_Properties60, 12 },
5801 { ufbxi_Properties70, 12 },
5802 { ufbxi_PropertyTemplate, 16 },
5803 { ufbxi_R, 1 },
5804 { ufbxi_ReferenceStart, 14 },
5805 { ufbxi_ReferenceStop, 13 },
5806 { ufbxi_ReferenceTime, 13 },
5807 { ufbxi_RelativeFileName, 16 },
5808 { ufbxi_RelativeFilename, 16 },
5809 { ufbxi_RenderDivisionLevels, 20 },
5810 { ufbxi_Repetition, 10 },
5811 { ufbxi_RightCamera, 11 },
5812 { ufbxi_Root, 4 },
5813 { ufbxi_RootNode, 8 },
5814 { ufbxi_Rotation, 8 },
5815 { ufbxi_RotationAccumulationMode, 24 },
5816 { ufbxi_RotationOffset, 14 },
5817 { ufbxi_RotationOrder, 13 },
5818 { ufbxi_RotationPivot, 13 },
5819 { ufbxi_S, 1 },
5820 { ufbxi_ScaleAccumulationMode, 21 },
5821 { ufbxi_Scaling, 7 },
5822 { ufbxi_ScalingOffset, 13 },
5823 { ufbxi_ScalingPivot, 12 },
5824 { ufbxi_SceneInfo, 9 },
5825 { ufbxi_SelectionNode, 13 },
5826 { ufbxi_SelectionSet, 12 },
5827 { ufbxi_ShadingModel, 12 },
5828 { ufbxi_Shape, 5 },
5829 { ufbxi_Shininess, 9 },
5830 { ufbxi_Show, 4 },
5831 { ufbxi_Size, 4 },
5832 { ufbxi_Skin, 4 },
5833 { ufbxi_SkinningType, 12 },
5834 { ufbxi_Smoothing, 9 },
5835 { ufbxi_Smoothness, 10 },
5836 { ufbxi_SnapOnFrameMode, 15 },
5837 { ufbxi_SpecularColor, 13 },
5838 { ufbxi_Step, 4 },
5839 { ufbxi_SubDeformer, 11 },
5840 { ufbxi_T, 1 },
5841 { ufbxi_TCDefinition, 12 },
5842 { ufbxi_Take, 4 },
5843 { ufbxi_Takes, 5 },
5844 { ufbxi_Tangents, 8 },
5845 { ufbxi_TangentsIndex, 13 },
5846 { ufbxi_TangentsW, 9 },
5847 { ufbxi_Texture, 7 },
5848 { ufbxi_Texture_alpha, 13 },
5849 { ufbxi_TextureId, 9 },
5850 { ufbxi_TextureRotationPivot, 20 },
5851 { ufbxi_TextureScalingPivot, 19 },
5852 { ufbxi_TextureUV, 9 },
5853 { ufbxi_TextureUVVerticeIndex, 21 },
5854 { ufbxi_Thumbnail, 9 },
5855 { ufbxi_TimeMarker, 10 },
5856 { ufbxi_TimeMode, 8 },
5857 { ufbxi_TimeProtocol, 12 },
5858 { ufbxi_TimeSpanStart, 13 },
5859 { ufbxi_TimeSpanStop, 12 },
5860 { ufbxi_Transform, 9 },
5861 { ufbxi_TransformLink, 13 },
5862 { ufbxi_Translation, 11 },
5863 { ufbxi_TrimNurbsSurface, 16 },
5864 { ufbxi_Type, 4 },
5865 { ufbxi_TypedIndex, 10 },
5866 { ufbxi_UV, 2 },
5867 { ufbxi_UVIndex, 7 },
5868 { ufbxi_UVSet, 5 },
5869 { ufbxi_UVSwap, 6 },
5870 { ufbxi_UnitScaleFactor, 15 },
5871 { ufbxi_UpAxis, 6 },
5872 { ufbxi_UpAxisSign, 10 },
5873 { ufbxi_Version5, 8 },
5874 { ufbxi_VertexCacheDeformer, 19 },
5875 { ufbxi_VertexCrease, 12 },
5876 { ufbxi_VertexCreaseIndex, 17 },
5877 { ufbxi_VertexIndexArray, 16 },
5878 { ufbxi_Vertices, 8 },
5879 { ufbxi_Video, 5 },
5880 { ufbxi_Visibility, 10 },
5881 { ufbxi_Weight, 6 },
5882 { ufbxi_Weights, 7 },
5883 { ufbxi_WrapModeU, 9 },
5884 { ufbxi_WrapModeV, 9 },
5885 { ufbxi_X, 1 },
5886 { ufbxi_Y, 1 },
5887 { ufbxi_Z, 1 },
5888 { ufbxi_d_X, 3 },
5889 { ufbxi_d_Y, 3 },
5890 { ufbxi_d_Z, 3 },
5891 };
5892
5893 static const ufbx_vec3 ufbxi_one_vec3 = { 1.0f, 1.0f, 1.0f };
5894
5895 #define UFBXI_PI ((ufbx_real)3.14159265358979323846)
5896 #define UFBXI_DPI (3.14159265358979323846)
5897 #define UFBXI_DEG_TO_RAD ((ufbx_real)(UFBXI_PI / 180.0))
5898 #define UFBXI_RAD_TO_DEG ((ufbx_real)(180.0 / UFBXI_PI))
5899 #define UFBXI_DEG_TO_RAD_DOUBLE (UFBXI_DPI / 180.0)
5900 #define UFBXI_RAD_TO_DEG_DOUBLE (180.0 / UFBXI_DPI)
5901 #define UFBXI_MM_TO_INCH ((ufbx_real)0.0393700787)
5902
5903 ufbx_inline ufbx_vec3 ufbxi_add3(ufbx_vec3 a, ufbx_vec3 b) {
5904 ufbx_vec3 v = { a.x + b.x, a.y + b.y, a.z + b.z };
5905 return v;
5906 }
5907
5908 ufbx_inline ufbx_vec3 ufbxi_sub3(ufbx_vec3 a, ufbx_vec3 b) {
5909 ufbx_vec3 v = { a.x - b.x, a.y - b.y, a.z - b.z };
5910 return v;
5911 }
5912
5913 ufbx_inline ufbx_vec3 ufbxi_mul3(ufbx_vec3 a, ufbx_real b) {
5914 ufbx_vec3 v = { a.x * b, a.y * b, a.z * b };
5915 return v;
5916 }
5917
5918 ufbx_inline ufbx_vec3 ufbxi_lerp3(ufbx_vec3 a, ufbx_vec3 b, ufbx_real t) {
5919 ufbx_real u = 1.0f - t;
5920 ufbx_vec3 v = { a.x*u + b.x*t, a.y*u + b.y*t, a.z*u + b.z*t };
5921 return v;
5922 }
5923
5924 ufbx_inline ufbx_real ufbxi_dot3(ufbx_vec3 a, ufbx_vec3 b) {
5925 return a.x*b.x + a.y*b.y + a.z*b.z;
5926 }
5927
5928 ufbx_inline ufbx_real ufbxi_length3(ufbx_vec3 v)
5929 {
5930 return (ufbx_real)ufbx_sqrt(v.x*v.x + v.y*v.y + v.z*v.z);
5931 }
5932
5933 ufbx_inline ufbx_real ufbxi_min3(ufbx_vec3 v)
5934 {
5935 return ufbxi_min_real(ufbxi_min_real(v.x, v.y), v.z);
5936 }
5937
5938 ufbx_inline ufbx_vec3 ufbxi_cross3(ufbx_vec3 a, ufbx_vec3 b) {
5939 ufbx_vec3 v = { a.y*b.z - a.z*b.y, a.z*b.x - a.x*b.z, a.x*b.y - a.y*b.x };
5940 return v;
5941 }
5942
5943 ufbx_inline ufbx_vec3 ufbxi_normalize3(ufbx_vec3 a) {
5944 ufbx_real len = (ufbx_real)ufbx_sqrt(ufbxi_dot3(a, a));
5945 if (len > UFBX_EPSILON) {
5946 return ufbxi_mul3(a, (ufbx_real)1.0 / len);
5947 } else {
5948 ufbx_vec3 zero = { (ufbx_real)0 };
5949 return zero;
5950 }
5951 }
5952
5953 ufbx_inline ufbx_vec3 ufbxi_neg3(ufbx_vec3 a) {
5954 ufbx_vec3 v = { -a.x, -a.y, -a.z };
5955 return v;
5956 }
5957
5958 ufbx_inline ufbx_real ufbxi_distsq2(ufbx_vec2 a, ufbx_vec2 b) {
5959 ufbx_real dx = a.x - b.x, dy = a.y - b.y;
5960 return dx*dx + dy*dy;
5961 }
5962
5963 static ufbxi_noinline ufbx_vec3 ufbxi_slow_normalize3(const ufbx_vec3 *a) {
5964 return ufbxi_normalize3(*a);
5965 }
5966
5967 static ufbxi_noinline ufbx_vec3 ufbxi_slow_normalized_cross3(const ufbx_vec3 *a, const ufbx_vec3 *b) {
5968 return ufbxi_normalize3(ufbxi_cross3(*a, *b));
5969 }
5970
5971 // -- Threading
5972
5973 typedef struct ufbxi_task ufbxi_task;
5974 typedef struct ufbxi_thread_pool ufbxi_thread_pool;
5975
5976 typedef bool ufbxi_task_fn(ufbxi_task *task);
5977
5978 struct ufbxi_task {
5979 void *data;
5980 const char *error;
5981 };
5982
5983 typedef struct {
5984 ufbxi_task task;
5985 ufbxi_task_fn *fn;
5986 } ufbxi_task_imp;
5987
5988 typedef struct {
5989 uint32_t max_index;
5990 uint32_t wait_index;
5991 } ufbxi_task_group;
5992
5993 struct ufbxi_thread_pool {
5994 ufbx_thread_opts opts;
5995 ufbxi_allocator *ator;
5996 ufbx_error *error;
5997 void *user_ptr;
5998
5999 bool enabled;
6000 bool failed;
6001 const char *error_desc;
6002
6003 uint32_t start_index;
6004 uint32_t execute_index;
6005 uint32_t wait_index;
6006
6007 ufbxi_task_group groups[UFBX_THREAD_GROUP_COUNT];
6008 uint32_t group;
6009
6010 uint32_t num_tasks;
6011 ufbxi_task_imp *tasks;
6012 };
6013
6014 static void ufbxi_thread_pool_execute(ufbxi_thread_pool *pool, uint32_t index)
6015 {
6016 ufbxi_task_imp *imp = &pool->tasks[index % pool->num_tasks];
6017 if (imp->fn(&imp->task)) {
6018 imp->task.error = NULL;
6019 } else if (!imp->task.error) {
6020 imp->task.error = "";
6021 }
6022 }
6023
6024 ufbxi_noinline static void ufbxi_thread_pool_update_finished(ufbxi_thread_pool *pool, uint32_t max_index)
6025 {
6026 while (pool->wait_index < max_index) {
6027 ufbxi_task_imp *task = &pool->tasks[pool->wait_index % pool->num_tasks];
6028 if (!pool->failed && task->task.error) {
6029 pool->failed = true;
6030 pool->error_desc = task->task.error;
6031 }
6032 pool->wait_index += 1;
6033 }
6034 }
6035
6036 ufbxi_nodiscard ufbxi_noinline static int ufbxi_thread_pool_wait_imp(ufbxi_thread_pool *pool, uint32_t group, bool can_fail)
6037 {
6038 uint32_t max_index = pool->groups[group].max_index;
6039
6040 if (pool->groups[group].wait_index < max_index) {
6041 pool->opts.pool.wait_fn(pool->opts.pool.user, (ufbx_thread_pool_context)pool, group, max_index);
6042 pool->groups[group].wait_index = max_index;
6043 }
6044 ufbxi_thread_pool_update_finished(pool, max_index);
6045
6046 if (pool->failed && can_fail) {
6047 ufbx_error *error = pool->error;
6048 if (pool->error_desc) {
6049 error->description.data = pool->error_desc;
6050 error->description.length = strlen(pool->error_desc);
6051 }
6052 ufbxi_fail_err(error, "Task failed");
6053 }
6054 return 1;
6055 }
6056
6057 ufbxi_nodiscard ufbxi_noinline static int ufbxi_thread_pool_wait_group(ufbxi_thread_pool *pool)
6058 {
6059 ufbxi_check_err(pool->error, ufbxi_thread_pool_wait_imp(pool, pool->group, true));
6060 return 1;
6061 }
6062
6063 ufbxi_nodiscard ufbxi_noinline static int ufbxi_thread_pool_wait_all(ufbxi_thread_pool *pool)
6064 {
6065 for (uint32_t i = 0; i < UFBX_THREAD_GROUP_COUNT; i++) {
6066 ufbxi_check_err(pool->error, ufbxi_thread_pool_wait_imp(pool, pool->group, true));
6067 pool->group = (pool->group + 1) % UFBX_THREAD_GROUP_COUNT;
6068 }
6069 return 1;
6070 }
6071
6072 ufbxi_nodiscard ufbxi_noinline static int ufbxi_thread_pool_init(ufbxi_thread_pool *pool, ufbx_error *error, ufbxi_allocator *ator, const ufbx_thread_opts *opts)
6073 {
6074 if (!(opts->pool.run_fn && opts->pool.wait_fn)) return 1;
6075 pool->enabled = true;
6076
6077 uint32_t num_tasks = (uint32_t)ufbxi_min_sz(opts->num_tasks, INT32_MAX);
6078 if (num_tasks == 0) {
6079 num_tasks = 2048;
6080 }
6081
6082 pool->opts = *opts;
6083 if (pool->opts.pool.init_fn) {
6084 ufbx_thread_pool_info info; // ufbxi_uninit
6085 info.max_concurrent_tasks = num_tasks;
6086 ufbxi_check_err(error, pool->opts.pool.init_fn(pool->opts.pool.user, (ufbx_thread_pool_context)pool, &info));
6087 }
6088 pool->ator = ator;
6089 pool->error = error;
6090
6091 pool->num_tasks = num_tasks;
6092 pool->tasks = ufbxi_alloc(ator, ufbxi_task_imp, num_tasks);
6093 ufbxi_check_err(error, pool->tasks);
6094
6095 return 1;
6096 }
6097
6098 ufbxi_noinline static void ufbxi_thread_pool_free(ufbxi_thread_pool *pool)
6099 {
6100 if (!pool->enabled) return;
6101
6102 // Wait for all pending tasks
6103 for (uint32_t i = 0; i < UFBX_THREAD_GROUP_COUNT; i++) {
6104 pool->group = (pool->group + 1) % UFBX_THREAD_GROUP_COUNT;
6105 ufbxi_ignore(ufbxi_thread_pool_wait_imp(pool, pool->group, false));
6106 }
6107
6108 if (pool->opts.pool.free_fn) {
6109 pool->opts.pool.free_fn(pool->opts.pool.user, (ufbx_thread_pool_context)pool);
6110 }
6111
6112 ufbxi_free(pool->ator, ufbxi_task_imp, pool->tasks, pool->num_tasks);
6113 }
6114
6115 ufbxi_nodiscard ufbxi_noinline static uint32_t ufbxi_thread_pool_available_tasks(ufbxi_thread_pool *pool)
6116 {
6117 return pool->num_tasks - (pool->start_index - pool->wait_index);
6118 }
6119
6120 ufbxi_noinline static void ufbxi_thread_pool_flush_group(ufbxi_thread_pool *pool)
6121 {
6122 uint32_t group = pool->group;
6123 uint32_t start_index = pool->execute_index;
6124 uint32_t count = pool->start_index - start_index;
6125 if (count > 0) {
6126 if (pool->opts.pool.run_fn) {
6127 pool->opts.pool.run_fn(pool->opts.pool.user, (ufbx_thread_pool_context)pool, group, start_index, count);
6128 }
6129 pool->groups[group].max_index = start_index + count;
6130 pool->execute_index = start_index + count;
6131 }
6132 pool->group = (group + 1) % UFBX_THREAD_GROUP_COUNT;
6133 }
6134
6135 ufbxi_nodiscard ufbxi_noinline static ufbxi_task *ufbxi_thread_pool_create_task(ufbxi_thread_pool *pool, ufbxi_task_fn *fn)
6136 {
6137 uint32_t index = pool->start_index;
6138 if (index - pool->wait_index >= pool->num_tasks) {
6139 if (index - pool->wait_index >= pool->num_tasks) {
6140 // No space left
6141 return NULL;
6142 }
6143 } else if (index == INT32_MAX) {
6144 // TODO: Expand to 64 bits if possible?
6145 return NULL;
6146 }
6147
6148 ufbxi_task_imp *imp = &pool->tasks[index % pool->num_tasks];
6149 if (index < pool->num_tasks) {
6150 memset(imp, 0, sizeof(ufbxi_task_imp));
6151 }
6152
6153 imp->fn = fn;
6154
6155 return &imp->task;
6156 }
6157
6158 static void ufbxi_thread_pool_run_task(ufbxi_thread_pool *pool, ufbxi_task *task)
6159 {
6160 (void)task;
6161 uint32_t index = pool->start_index;
6162 ufbx_assert(task == &pool->tasks[index % pool->num_tasks].task);
6163 pool->start_index = index + 1;
6164 }
6165
6166 // -- Type definitions
6167
6168 typedef struct ufbxi_node ufbxi_node;
6169
6170 typedef enum {
6171 UFBXI_VALUE_NONE,
6172 UFBXI_VALUE_NUMBER,
6173 UFBXI_VALUE_STRING,
6174 UFBXI_VALUE_ARRAY,
6175 } ufbxi_value_type;
6176
6177 typedef union {
6178 struct { double f; int64_t i; }; // < if `UFBXI_PROP_NUMBER`
6179 ufbxi_sanitized_string s; // < if `UFBXI_PROP_STRING`
6180 } ufbxi_value;
6181
6182 typedef struct {
6183 void *data; // < Pointer to `size` bool/int32_t/int64_t/float/double elements
6184 size_t size; // < Number of elements
6185 char type; // < FBX type code: b/i/l/f/d
6186 } ufbxi_value_array;
6187
6188 struct ufbxi_node {
6189 const char *name; // < Name of the node (pooled, compare with == to ufbxi_* strings)
6190 uint32_t num_children; // < Number of child nodes
6191 uint8_t name_len; // < Length of `name` in bytes
6192
6193 // If `value_type_mask == UFBXI_PROP_ARRAY` then the node is an array
6194 // (`array` field is valid) otherwise the node has N values in `vals`
6195 // where the type of each value is stored in 2 bits per value from LSB.
6196 // ie. `vals[ix]` type is `(value_type_mask >> (ix*2)) & 0x3`
6197 uint16_t value_type_mask;
6198
6199 ufbxi_node *children;
6200 union {
6201 ufbxi_value_array *array; // if `prop_type_mask == UFBXI_PROP_ARRAY`
6202 ufbxi_value *vals; // otherwise
6203 };
6204 };
6205
6206 typedef struct ufbxi_refcount ufbxi_refcount;
6207
6208 struct ufbxi_refcount {
6209 ufbxi_refcount *parent;
6210 void *align_0;
6211 uint32_t self_magic;
6212 uint32_t type_magic;
6213 ufbxi_buf buf;
6214 ufbxi_allocator ator;
6215 uint64_t zero_pad_pre[8];
6216 ufbxi_atomic_counter refcount;
6217 uint64_t zero_pad_post[8];
6218 };
6219
6220 static ufbxi_noinline void ufbxi_init_ref(ufbxi_refcount *refcount, uint32_t magic, ufbxi_refcount *parent);
6221 static ufbxi_noinline void ufbxi_retain_ref(ufbxi_refcount *refcount);
6222
6223 #define ufbxi_get_imp(type, ptr) ((type*)((char*)ptr - sizeof(ufbxi_refcount)))
6224
6225 typedef struct {
6226 ufbxi_refcount refcount;
6227 ufbx_scene scene;
6228 uint32_t magic;
6229
6230 ufbxi_buf string_buf;
6231 } ufbxi_scene_imp;
6232
6233 ufbx_static_assert(scene_imp_offset, offsetof(ufbxi_scene_imp, scene) == sizeof(ufbxi_refcount));
6234
6235 typedef struct {
6236 ufbxi_refcount refcount;
6237 ufbx_mesh mesh;
6238 uint32_t magic;
6239 } ufbxi_mesh_imp;
6240
6241 ufbx_static_assert(mesh_imp_offset, offsetof(ufbxi_mesh_imp, mesh) == sizeof(ufbxi_refcount));
6242
6243 typedef struct {
6244 // Semantic string data and length eg. for a string token
6245 // this string doesn't include the quotes.
6246 char *str_data;
6247 size_t str_len;
6248 size_t str_cap;
6249
6250 // Type of the token, either single character such as '{' or ':'
6251 // or one of UFBXI_ASCII_* defines.
6252 char type;
6253
6254 // Sign for integer if negative.
6255 bool negative;
6256
6257 // Parsed semantic value
6258 union {
6259 double f64;
6260 int64_t i64;
6261 size_t name_len;
6262 } value;
6263 } ufbxi_ascii_token;
6264
6265 typedef struct {
6266 size_t max_token_length;
6267
6268 const char *src;
6269 const char *src_yield;
6270 const char *src_end;
6271
6272 bool read_first_comment;
6273 bool found_version;
6274 bool parse_as_f32;
6275 bool src_is_retained;
6276
6277 ufbxi_buf *retain_buf;
6278 ufbxi_buf *src_buf;
6279
6280 ufbxi_ascii_token prev_token;
6281 ufbxi_ascii_token token;
6282 } ufbxi_ascii;
6283
6284 typedef struct {
6285 const char *type;
6286 ufbx_string sub_type;
6287 ufbx_props props;
6288 } ufbxi_template;
6289
6290 typedef struct {
6291 uint64_t fbx_id;
6292 uint32_t element_id;
6293 uint32_t user_id;
6294 } ufbxi_fbx_id_entry;
6295
6296 typedef struct {
6297 ufbxi_ptr_id ptr_id;
6298 uint64_t fbx_id;
6299 } ufbxi_ptr_fbx_id_entry;
6300
6301 typedef struct {
6302 uint64_t node_fbx_id;
6303 uint64_t attr_fbx_id;
6304 } ufbxi_fbx_attr_entry;
6305
6306 // Temporary connection before we resolve the element pointers
6307 typedef struct {
6308 uint64_t src, dst;
6309 ufbx_string src_prop;
6310 ufbx_string dst_prop;
6311 } ufbxi_tmp_connection;
6312
6313 typedef struct {
6314 uint64_t fbx_id;
6315 ufbx_string name;
6316 ufbx_props props;
6317 ufbx_dom_node *dom_node;
6318 } ufbxi_element_info;
6319
6320 typedef struct {
6321 uint64_t bone_fbx_id;
6322 ufbx_matrix bone_to_world;
6323 } ufbxi_tmp_bone_pose;
6324
6325 typedef struct {
6326 ufbx_string prop_name;
6327 uint32_t *face_texture;
6328 size_t num_faces;
6329 bool all_same;
6330 } ufbxi_tmp_mesh_texture;
6331
6332 typedef struct {
6333 ufbxi_tmp_mesh_texture *texture_arr;
6334 size_t texture_count;
6335 } ufbxi_mesh_extra;
6336
6337 typedef struct {
6338 int32_t material_id;
6339 int32_t texture_id;
6340 ufbx_string prop_name;
6341 } ufbxi_tmp_material_texture;
6342
6343 typedef struct {
6344 int32_t *blend_modes;
6345 size_t num_blend_modes;
6346
6347 ufbx_real *alphas;
6348 size_t num_alphas;
6349 } ufbxi_texture_extra;
6350
6351 typedef enum {
6352 UFBXI_OBJ_ATTRIB_POSITION,
6353 UFBXI_OBJ_ATTRIB_UV,
6354 UFBXI_OBJ_ATTRIB_NORMAL,
6355 UFBXI_OBJ_ATTRIB_COLOR,
6356 } ufbxi_obj_attrib;
6357
6358 #define UFBXI_OBJ_NUM_ATTRIBS 3
6359 #define UFBXI_OBJ_NUM_ATTRIBS_EXT 4
6360
6361 typedef struct {
6362 uint64_t min_ix, max_ix;
6363 } ufbxi_obj_index_range;
6364
6365 typedef struct {
6366 size_t num_faces;
6367 size_t num_indices;
6368 ufbxi_obj_index_range vertex_range[UFBXI_OBJ_NUM_ATTRIBS];
6369
6370 ufbx_node *fbx_node;
6371 ufbx_mesh *fbx_mesh;
6372
6373 uint64_t fbx_node_id;
6374 uint64_t fbx_mesh_id;
6375
6376 uint32_t usemtl_base;
6377
6378 uint32_t num_groups;
6379 } ufbxi_obj_mesh;
6380
6381 typedef struct {
6382 const char *name;
6383 uint32_t local_id;
6384 uint32_t mesh_id;
6385 } ufbxi_obj_group_entry;
6386
6387 typedef struct {
6388 uint64_t *indices;
6389 size_t num_left;
6390 } ufbxi_obj_fast_indices;
6391
6392 // Temporary pointer to a `ufbx_anim_stack` by name used to patch start/stop
6393 // time from "Takes" if necessary.
6394 typedef struct {
6395 const char *name;
6396 ufbx_anim_stack *stack;
6397 } ufbxi_tmp_anim_stack;
6398
6399 typedef struct {
6400 ufbx_string absolute_filename;
6401 ufbx_blob content;
6402 } ufbxi_file_content;
6403
6404 typedef struct {
6405
6406 // Current line and tokens.
6407 // NOTE: `line` and `tokens` are not NULL-terminated nor UTF-8!
6408 // `line` is guaranteed to be terminated by a `\n`
6409 ufbx_string line;
6410 ufbx_string *tokens;
6411 size_t tokens_cap;
6412 size_t num_tokens;
6413
6414 ufbxi_obj_fast_indices fast_indices[UFBXI_OBJ_NUM_ATTRIBS];
6415
6416 size_t vertex_count[UFBXI_OBJ_NUM_ATTRIBS_EXT];
6417 ufbxi_buf tmp_vertices[UFBXI_OBJ_NUM_ATTRIBS_EXT];
6418 ufbxi_buf tmp_indices[UFBXI_OBJ_NUM_ATTRIBS_EXT];
6419 ufbxi_buf tmp_color_valid;
6420 ufbxi_buf tmp_faces;
6421 ufbxi_buf tmp_face_smoothing;
6422 ufbxi_buf tmp_face_group;
6423 ufbxi_buf tmp_face_group_infos;
6424 ufbxi_buf tmp_face_material;
6425 ufbxi_buf tmp_meshes;
6426 ufbxi_buf tmp_props;
6427
6428 ufbxi_map group_map;
6429
6430 size_t read_progress;
6431
6432 ufbxi_obj_mesh *mesh;
6433
6434 uint64_t usemtl_fbx_id;
6435 uint32_t usemtl_index;
6436
6437 uint32_t face_material;
6438
6439 uint32_t face_group;
6440 bool has_face_group;
6441
6442 bool face_smoothing;
6443 bool has_face_smoothing;
6444
6445 bool has_vertex_color;
6446 size_t mrgb_vertex_count;
6447
6448 bool eof;
6449 bool initialized;
6450
6451 ufbx_blob mtllib_relative_path;
6452
6453 ufbx_material **tmp_materials;
6454 size_t tmp_materials_cap;
6455
6456 ufbx_string object;
6457 ufbx_string group;
6458 bool material_dirty;
6459 bool object_dirty;
6460 bool group_dirty;
6461 bool face_group_dirty;
6462
6463 } ufbxi_obj_context;
6464
6465 typedef struct {
6466
6467 ufbx_error error;
6468 uint32_t version;
6469 ufbx_exporter exporter;
6470 uint32_t exporter_version;
6471 bool from_ascii;
6472 bool local_big_endian;
6473 bool file_big_endian;
6474 bool sure_fbx;
6475 bool retain_mesh_parts;
6476 bool read_legacy_settings;
6477 uint32_t double_parse_flags;
6478
6479 ufbx_load_opts opts;
6480
6481 // IO
6482 uint64_t data_offset;
6483 ufbx_read_fn *read_fn;
6484 ufbx_skip_fn *skip_fn;
6485 void *read_user;
6486
6487 char *read_buffer;
6488 size_t read_buffer_size;
6489
6490 const char *data_begin;
6491 const char *data;
6492 size_t yield_size;
6493 size_t data_size;
6494
6495 // Allocators
6496 ufbxi_allocator ator_result;
6497 ufbxi_allocator ator_tmp;
6498
6499 // Temporary maps
6500 ufbxi_map prop_type_map; // < `ufbxi_prop_type_name` Property type to enum
6501 ufbxi_map fbx_id_map; // < `ufbxi_fbx_id_entry` FBX ID to local ID
6502 ufbxi_map ptr_fbx_id_map; // < `ufbxi_ptr_fbx_id_entry` Pointer/negative ID to FBX ID
6503 ufbxi_map texture_file_map; // < `ufbxi_texture_file_entry` absolute raw filename to element ID
6504 ufbxi_map anim_stack_map; // < `ufbxi_tmp_anim_stack` anim stacks by name before finalization
6505
6506 // 6x00 specific maps
6507 ufbxi_map fbx_attr_map; // < `ufbxi_fbx_attr_entry` Node ID to attrib ID
6508 ufbxi_map node_prop_set; // < `const char*` Node property names
6509
6510 // DOM nodes
6511 ufbxi_map dom_node_map; // < `const char*` Node property names
6512
6513 // Temporary array
6514 char *tmp_arr;
6515 size_t tmp_arr_size;
6516 char *swap_arr;
6517 size_t swap_arr_size;
6518
6519 // Generated index buffers
6520 size_t max_zero_indices;
6521 size_t max_consecutive_indices;
6522
6523 // Temporary buffers
6524 ufbxi_buf tmp;
6525 ufbxi_buf tmp_parse;
6526 ufbxi_buf tmp_stack;
6527 ufbxi_buf tmp_connections;
6528 ufbxi_buf tmp_node_ids;
6529 ufbxi_buf tmp_elements;
6530 ufbxi_buf tmp_element_offsets;
6531 ufbxi_buf tmp_element_fbx_ids;
6532 ufbxi_buf tmp_element_ptrs;
6533 ufbxi_buf tmp_typed_element_offsets[UFBX_ELEMENT_TYPE_COUNT];
6534 ufbxi_buf tmp_mesh_textures;
6535 ufbxi_buf tmp_full_weights;
6536 ufbxi_buf tmp_dom_nodes;
6537 ufbxi_buf tmp_element_id;
6538 ufbxi_buf tmp_ascii_spans;
6539 ufbxi_buf tmp_thread_parse[UFBX_THREAD_GROUP_COUNT];
6540 size_t tmp_element_byte_offset;
6541
6542 ufbxi_template *templates;
6543 size_t num_templates;
6544
6545 ufbx_dom_node *dom_parse_toplevel;
6546 size_t dom_parse_num_children;
6547
6548 uint32_t *p_element_id;
6549
6550 // String pool
6551 ufbxi_string_pool string_pool;
6552
6553 // Result buffers, these are retained in `ufbx_scene` returned to user.
6554 ufbxi_buf result;
6555
6556 // Top-level state
6557 ufbxi_node *top_nodes;
6558 size_t top_nodes_len, top_nodes_cap;
6559 bool parsed_to_end;
6560
6561 // "Focused" top-level node and child index, if `top_child_index == SIZE_MAX`
6562 // the children are parsed on demand.
6563 ufbxi_node *top_node;
6564 size_t top_child_index;
6565 ufbxi_node top_child;
6566 bool has_next_child;
6567
6568 // Shared consecutive and all-zero index buffers
6569 uint32_t *zero_indices;
6570 uint32_t *consecutive_indices;
6571
6572 // Call progress function periodically
6573 ptrdiff_t progress_timer;
6574 uint64_t progress_bytes_total;
6575 uint64_t latest_progress_bytes;
6576 size_t progress_interval;
6577
6578 // Extra data on the side of elements
6579 void **element_extra_arr;
6580 size_t element_extra_cap;
6581
6582 // Temporary per-element flags
6583 uint8_t *tmp_element_flag;
6584
6585 // IO (cold)
6586 ufbx_close_fn *close_fn;
6587 ufbx_size_fn *size_fn;
6588
6589 ufbxi_ascii ascii;
6590
6591 uint64_t synthetic_id_counter;
6592
6593 bool has_geometry_transform_nodes;
6594 bool has_scale_helper_nodes;
6595 bool retain_vertex_w;
6596 bool blender_full_weights;
6597
6598 ufbx_mirror_axis mirror_axis;
6599
6600 ufbxi_node root;
6601
6602 ufbx_scene scene;
6603 ufbxi_scene_imp *scene_imp;
6604
6605 ufbx_inflate_retain *inflate_retain;
6606
6607 // Per-mesh consecutive indices used by `ufbxi_flip_winding()`.
6608 uint32_t *tmp_mesh_consecutive_indices;
6609
6610 uint64_t root_id;
6611 uint32_t num_elements;
6612
6613 ufbxi_node legacy_node;
6614 uint64_t legacy_implicit_anim_layer_id;
6615
6616 ufbxi_file_content *file_content;
6617 size_t num_file_content;
6618
6619 int64_t ktime_sec;
6620 double ktime_sec_double;
6621
6622 bool eof;
6623 ufbxi_obj_context obj;
6624
6625 ufbx_matrix axis_matrix;
6626 ufbx_real unit_scale;
6627
6628 ufbxi_warnings warnings;
6629
6630 bool deferred_failure;
6631 bool deferred_load;
6632
6633 const char *load_filename;
6634 size_t load_filename_len;
6635
6636 bool parse_threaded;
6637 ufbxi_thread_pool thread_pool;
6638
6639 uint8_t *base64_table;
6640
6641 } ufbxi_context;
6642
6643 static ufbxi_noinline int ufbxi_fail_imp(ufbxi_context *uc, const char *cond, const char *func, uint32_t line)
6644 {
6645 return ufbxi_fail_imp_err(&uc->error, cond, func, line);
6646 }
6647
6648 #if UFBXI_FEATURE_ERROR_STACK
6649 #define ufbxi_fail_no_msg(uc, cond, func, line) ufbxi_fail_imp((uc), (cond), (func), (line))
6650 #else
6651 static ufbxi_noinline int ufbxi_fail_imp_no_stack(ufbxi_context *uc) { return ufbxi_fail_imp_err(&uc->error, NULL, NULL, 0); }
6652 #define ufbxi_fail_no_msg(uc, cond, func, line) ufbxi_fail_imp_no_stack((uc))
6653 #endif
6654
6655 #define ufbxi_check(cond) if (ufbxi_unlikely(!ufbxi_trace(cond))) return ufbxi_fail_no_msg(uc, ufbxi_cond_str(cond), ufbxi_function, ufbxi_line)
6656 #define ufbxi_check_return(cond, ret) do { if (ufbxi_unlikely(!ufbxi_trace(cond))) { ufbxi_fail_no_msg(uc, ufbxi_cond_str(cond), ufbxi_function, ufbxi_line); return ret; } } while (0)
6657 #define ufbxi_fail(desc) return ufbxi_fail_no_msg(uc, desc, ufbxi_function, ufbxi_line)
6658 #define ufbxi_fail_return(desc, ret) do { ufbxi_fail_no_msg(uc, desc, ufbxi_function, ufbxi_line); return ret; } while (0)
6659
6660 #define ufbxi_check_msg(cond, msg) if (ufbxi_unlikely(!ufbxi_trace(cond))) return ufbxi_fail_imp(uc, ufbxi_error_msg(ufbxi_cond_str(cond), msg), ufbxi_function, ufbxi_line)
6661 #define ufbxi_check_return_msg(cond, ret, msg) do { if (ufbxi_unlikely(!ufbxi_trace(cond))) { ufbxi_fail_imp(uc, ufbxi_error_msg(ufbxi_cond_str(cond), msg), ufbxi_function, ufbxi_line); return ret; } } while (0)
6662 #define ufbxi_fail_msg(desc, msg) return ufbxi_fail_imp(uc, ufbxi_error_msg(desc, msg), ufbxi_function, ufbxi_line)
6663
6664 #define ufbxi_warnf(type, ...) ufbxi_warnf_imp(&uc->warnings, type, ~0u, __VA_ARGS__)
6665 #define ufbxi_warnf_tag(type, element_id, ...) ufbxi_warnf_imp(&uc->warnings, type, (element_id), __VA_ARGS__)
6666
6667 // -- Progress
6668
6669 static ufbxi_forceinline uint64_t ufbxi_get_read_offset(ufbxi_context *uc)
6670 {
6671 return uc->data_offset + ufbxi_to_size(uc->data - uc->data_begin);
6672 }
6673
6674 ufbxi_nodiscard static ufbxi_noinline int ufbxi_report_progress(ufbxi_context *uc)
6675 {
6676 if (!uc->opts.progress_cb.fn) return 1;
6677
6678 uint64_t read_offset = ufbxi_get_read_offset(uc);
6679 uc->latest_progress_bytes = read_offset;
6680
6681 ufbx_progress progress = { 0 };
6682 progress.bytes_read = read_offset;
6683 progress.bytes_total = uc->progress_bytes_total;
6684 if (progress.bytes_total < progress.bytes_read) {
6685 progress.bytes_total = progress.bytes_read;
6686 }
6687
6688 uc->progress_timer = 1024;
6689 uint32_t result = (uint32_t)uc->opts.progress_cb.fn(uc->opts.progress_cb.user, &progress);
6690 ufbx_assert(result == UFBX_PROGRESS_CONTINUE || result == UFBX_PROGRESS_CANCEL);
6691 ufbxi_check_msg(result != UFBX_PROGRESS_CANCEL, "Cancelled");
6692 return 1;
6693 }
6694
6695 // TODO: Remove `ufbxi_unused` when it's not needed anymore
6696 ufbxi_unused ufbxi_nodiscard static ufbxi_forceinline int ufbxi_progress(ufbxi_context *uc, size_t work_units)
6697 {
6698 if (!uc->opts.progress_cb.fn) return 1;
6699 ptrdiff_t left = uc->progress_timer - (ptrdiff_t)work_units;
6700 uc->progress_timer = left;
6701 if (left > 0) return 1;
6702 return ufbxi_report_progress(uc);
6703 }
6704
6705 // -- IO
6706
6707 static ufbxi_noinline const char *ufbxi_refill(ufbxi_context *uc, size_t size, bool require_size)
6708 {
6709 ufbx_assert(uc->data_size < size);
6710 ufbxi_check_return(!uc->eof, NULL);
6711 if (require_size) {
6712 ufbxi_check_return_msg(uc->read_fn || uc->data_size > 0, NULL, "Empty file");
6713 ufbxi_check_return_msg(uc->read_fn, NULL, "Truncated file");
6714 } else if (!uc->read_fn) {
6715 uc->eof = true;
6716 return uc->data;
6717 }
6718
6719 void *data_to_free = NULL;
6720 size_t size_to_free = 0;
6721
6722 // Grow the read buffer if necessary, data is copied over below with the
6723 // usual path so the free is deferred (`size_to_free`, `data_to_free`)
6724 if (size > uc->read_buffer_size) {
6725 size_t new_size = ufbxi_max_sz(size, uc->opts.read_buffer_size);
6726 new_size = ufbxi_max_sz(new_size, uc->read_buffer_size * 2);
6727 size_to_free = uc->read_buffer_size;
6728 data_to_free = uc->read_buffer;
6729 char *new_buffer = ufbxi_alloc(&uc->ator_tmp, char, new_size);
6730 ufbxi_check_return(new_buffer, NULL);
6731 uc->read_buffer = new_buffer;
6732 uc->read_buffer_size = new_size;
6733 }
6734
6735 // Copy the remains of the previous buffer to the beginning of the new one
6736 size_t data_size = uc->data_size;
6737 if (data_size > 0) {
6738 ufbx_assert(uc->read_buffer != NULL && uc->data != NULL);
6739 memmove(uc->read_buffer, uc->data, data_size);
6740 }
6741
6742 if (size_to_free) {
6743 ufbxi_free(&uc->ator_tmp, char, data_to_free, size_to_free);
6744 }
6745
6746 // Fill the rest of the buffer with user data
6747 size_t data_capacity = uc->read_buffer_size;
6748 while (data_size < data_capacity) {
6749 size_t to_read = data_capacity - data_size;
6750 size_t read_result = uc->read_fn(uc->read_user, uc->read_buffer + data_size, to_read);
6751 ufbxi_check_return_msg(read_result != SIZE_MAX, NULL, "IO error");
6752 ufbxi_check_return(read_result <= to_read, NULL);
6753 data_size += read_result;
6754 if (read_result == 0) {
6755 uc->eof = true;
6756 break;
6757 }
6758 }
6759
6760 if (require_size) {
6761 if (uc->data_offset == 0) {
6762 ufbxi_check_return_msg(data_size > 0, NULL, "Empty file");
6763 }
6764 ufbxi_check_return_msg(data_size >= size, NULL, "Truncated file");
6765 }
6766
6767 uc->data_offset += ufbxi_to_size(uc->data - uc->data_begin);
6768 uc->data_begin = uc->data = uc->read_buffer;
6769 uc->data_size = data_size;
6770
6771 return uc->read_buffer;
6772 }
6773
6774 static ufbxi_forceinline void ufbxi_pause_progress(ufbxi_context *uc)
6775 {
6776 uc->data_size += uc->yield_size;
6777 uc->yield_size = 0;
6778 }
6779
6780 static ufbxi_noinline int ufbxi_resume_progress(ufbxi_context *uc)
6781 {
6782 uc->yield_size = ufbxi_min_sz(uc->data_size, uc->progress_interval);
6783 uc->data_size -= uc->yield_size;
6784
6785 if (ufbxi_get_read_offset(uc) - uc->latest_progress_bytes >= uc->progress_interval) {
6786 ufbxi_check(ufbxi_report_progress(uc));
6787 }
6788
6789 return 1;
6790 }
6791
6792 static ufbxi_noinline const char *ufbxi_yield(ufbxi_context *uc, size_t size)
6793 {
6794 const char *ret;
6795 uc->data_size += uc->yield_size;
6796 if (uc->data_size >= size) {
6797 ret = uc->data;
6798 } else {
6799 ret = ufbxi_refill(uc, size, true);
6800 }
6801 uc->yield_size = ufbxi_min_sz(uc->data_size, ufbxi_max_sz(size, uc->progress_interval));
6802 uc->data_size -= uc->yield_size;
6803
6804 ufbxi_check_return(ufbxi_report_progress(uc), NULL);
6805 return ret;
6806 }
6807
6808 static ufbxi_forceinline const char *ufbxi_peek_bytes(ufbxi_context *uc, size_t size)
6809 {
6810 if (uc->yield_size >= size) {
6811 return uc->data;
6812 } else {
6813 return ufbxi_yield(uc, size);
6814 }
6815 }
6816
6817 static ufbxi_forceinline const char *ufbxi_read_bytes(ufbxi_context *uc, size_t size)
6818 {
6819 // Refill the current buffer if necessary
6820 const char *ret;
6821 if (uc->yield_size >= size) {
6822 ret = uc->data;
6823 } else {
6824 ret = ufbxi_yield(uc, size);
6825 if (!ret) return NULL;
6826 }
6827
6828 // Advance the read position inside the current buffer
6829 uc->yield_size -= size;
6830 uc->data = ret + size;
6831 return ret;
6832 }
6833
6834 static ufbxi_forceinline void ufbxi_consume_bytes(ufbxi_context *uc, size_t size)
6835 {
6836 // Bytes must have been checked first with `ufbxi_peek_bytes()`
6837 ufbx_assert(size <= uc->yield_size);
6838 uc->yield_size -= size;
6839 uc->data += size;
6840 }
6841
6842 ufbxi_nodiscard static ufbxi_noinline int ufbxi_skip_bytes(ufbxi_context *uc, uint64_t size)
6843 {
6844 if (uc->skip_fn) {
6845 ufbxi_pause_progress(uc);
6846
6847 if (size > uc->data_size) {
6848 size -= uc->data_size;
6849 uc->data += uc->data_size;
6850 uc->data_size = 0;
6851
6852 uc->data_offset += size;
6853 while (size >= UFBXI_MAX_SKIP_SIZE) {
6854 size -= UFBXI_MAX_SKIP_SIZE;
6855 ufbxi_check_msg(uc->skip_fn(uc->read_user, UFBXI_MAX_SKIP_SIZE - 1), "Truncated file");
6856
6857 // Check that we can read at least one byte in case the file is broken
6858 // and causes us to seek indefinitely forwards as `fseek()` does not
6859 // report if we hit EOF...
6860 char single_byte[1]; // ufbxi_uninit
6861 size_t num_read = uc->read_fn(uc->read_user, single_byte, 1);
6862 ufbxi_check_msg(num_read <= 1, "IO error");
6863 ufbxi_check_msg(num_read == 1, "Truncated file");
6864 }
6865
6866 if (size > 0) {
6867 ufbxi_check_msg(uc->skip_fn(uc->read_user, (size_t)size), "Truncated file");
6868 }
6869
6870 } else {
6871 uc->data += (size_t)size;
6872 uc->data_size -= (size_t)size;
6873 }
6874
6875 ufbxi_check(ufbxi_resume_progress(uc));
6876 } else {
6877 // Read and discard bytes in reasonable chunks
6878 uint64_t skip_size = ufbxi_max64(uc->read_buffer_size, uc->opts.read_buffer_size);
6879 while (size > 0) {
6880 uint64_t to_skip = ufbxi_min64(size, skip_size);
6881 ufbxi_check(ufbxi_read_bytes(uc, (size_t)to_skip));
6882 size -= to_skip;
6883 }
6884 }
6885
6886 return 1;
6887 }
6888
6889 ufbxi_nodiscard static ufbxi_noinline int ufbxi_read_to(ufbxi_context *uc, void *dst, size_t size)
6890 {
6891 char *ptr = (char*)dst;
6892
6893 ufbxi_pause_progress(uc);
6894
6895 // Copy data from the current buffer first
6896 size_t len = ufbxi_min_sz(uc->data_size, size);
6897 memcpy(ptr, uc->data, len);
6898 uc->data += len;
6899 uc->data_size -= len;
6900 ptr += len;
6901 size -= len;
6902
6903 // If there's data left to copy try to read from user IO
6904 if (size > 0) {
6905 uc->data_offset += ufbxi_to_size(uc->data - uc->data_begin);
6906
6907 uc->data_begin = uc->data = NULL;
6908 uc->data_size = 0;
6909 ufbxi_check(uc->read_fn);
6910
6911 while (size > 0) {
6912 size_t read_result = uc->read_fn(uc->read_user, ptr, size);
6913 ufbxi_check_msg(read_result != SIZE_MAX, "IO error");
6914 ufbxi_check(read_result != 0);
6915
6916 ptr += read_result;
6917 size -= read_result;
6918 uc->data_offset += read_result;
6919 }
6920 }
6921
6922 ufbxi_check(ufbxi_resume_progress(uc));
6923
6924 return 1;
6925 }
6926
6927 static ufbxi_noinline void ufbxi_init_ator(ufbx_error *error, ufbxi_allocator *ator, const ufbx_allocator_opts *opts, const char *name)
6928 {
6929 ufbx_allocator_opts zero_opts;
6930 if (!opts) {
6931 memset(&zero_opts, 0, sizeof(zero_opts));
6932 opts = &zero_opts;
6933 }
6934
6935 // `opts` is either passed in or `zero_opts`.
6936 // cppcheck-suppress uninitvar
6937 ator->ator = *opts;
6938 ator->error = error;
6939 ator->max_size = opts->memory_limit ? opts->memory_limit : SIZE_MAX;
6940 ator->max_allocs = opts->allocation_limit ? opts->allocation_limit : SIZE_MAX;
6941 ator->huge_size = opts->huge_threshold ? opts->huge_threshold : 0x100000;
6942 ator->chunk_max = opts->max_chunk_size ? opts->max_chunk_size : 0x1000000;
6943 ator->name = name;
6944 }
6945
6946 typedef struct {
6947 ufbx_error error;
6948
6949 ufbxi_allocator *parent_ator;
6950 ufbxi_allocator ator;
6951 } ufbxi_file_context;
6952
6953 static ufbxi_noinline void ufbxi_begin_file_context(ufbxi_file_context *fc, ufbx_open_file_context ctx, const ufbx_allocator_opts *ator_opts)
6954 {
6955 memset(fc, 0, sizeof(ufbxi_file_context));
6956 if (ctx) {
6957 fc->parent_ator = (ufbxi_allocator*)ctx;
6958 fc->ator = *fc->parent_ator;
6959 fc->ator.error = &fc->error;
6960 } else {
6961 ufbxi_init_ator(&fc->error, &fc->ator, ator_opts, "file");
6962 }
6963 }
6964
6965 static ufbxi_noinline void ufbxi_end_file_context(ufbxi_file_context *fc, ufbx_error *error, bool ok)
6966 {
6967 if (fc->parent_ator) {
6968 fc->ator.error = fc->parent_ator->error;
6969 *fc->parent_ator = fc->ator;
6970 } else {
6971 ufbxi_free_ator(&fc->ator);
6972 }
6973 if (error) {
6974 if (!ok) {
6975 ufbxi_fix_error_type(&fc->error, "Failed to open file", error);
6976 } else {
6977 ufbxi_clear_error(error);
6978 }
6979 }
6980 }
6981
6982 // -- File IO
6983
6984 #if !defined(UFBX_NO_STDIO) && !defined(UFBX_EXTERNAL_STDIO)
6985
6986 static ufbxi_noinline FILE *ufbxi_fopen(ufbxi_file_context *fc, const char *path, size_t path_len, bool null_terminated)
6987 {
6988 FILE *file = NULL;
6989 #if !defined(UFBX_STANDARD_C) && defined(_WIN32)
6990 (void)null_terminated;
6991 wchar_t wpath_buf[256], *wpath = NULL; // ufbxi_uninit
6992 if (path_len < ufbxi_arraycount(wpath_buf) - 1) {
6993 wpath = wpath_buf;
6994 } else {
6995 wpath = ufbxi_alloc(&fc->ator, wchar_t, path_len + 1);
6996 if (!wpath) return NULL;
6997 }
6998
6999 // Convert UTF-8 to UTF-16 but allow stray surrogate pairs as the Windows
7000 // file system encoding allows them as well..
7001 size_t wlen = 0;
7002 for (size_t i = 0; i < path_len; ) {
7003 uint32_t code = UINT32_MAX;
7004 char c = path[i++];
7005 if ((c & 0x80) == 0) {
7006 code = (uint32_t)c;
7007 } else if ((c & 0xe0) == 0xc0) {
7008 code = (uint32_t)(c & 0x1f);
7009 if (i < path_len) code = code << 6 | (uint32_t)(path[i++] & 0x3f);
7010 } else if ((c & 0xf0) == 0xe0) {
7011 code = (uint32_t)(c & 0x0f);
7012 if (i < path_len) code = code << 6 | (uint32_t)(path[i++] & 0x3f);
7013 if (i < path_len) code = code << 6 | (uint32_t)(path[i++] & 0x3f);
7014 } else if ((c & 0xf8) == 0xf0) {
7015 code = (uint32_t)(c & 0x07);
7016 if (i < path_len) code = code << 6 | (uint32_t)(path[i++] & 0x3f);
7017 if (i < path_len) code = code << 6 | (uint32_t)(path[i++] & 0x3f);
7018 if (i < path_len) code = code << 6 | (uint32_t)(path[i++] & 0x3f);
7019 }
7020 if (code < 0x10000) {
7021 wpath[wlen++] = (wchar_t)code;
7022 } else {
7023 code -= 0x10000;
7024 wpath[wlen++] = (wchar_t)(0xd800 + (code >> 10));
7025 wpath[wlen++] = (wchar_t)(0xdc00 + (code & 0x3ff));
7026 }
7027 }
7028 wpath[wlen] = 0;
7029
7030 #if UFBXI_MSC_VER >= 1400
7031 if (_wfopen_s(&file, wpath, L"rb") != 0) file = NULL;
7032 #else
7033 file = _wfopen(wpath, L"rb");
7034 #endif
7035 if (wpath != wpath_buf) {
7036 ufbxi_free(&fc->ator, wchar_t, wpath, path_len + 1);
7037 }
7038 #else
7039 char copy_buf[256], *copy = NULL; // ufbxi_uninit
7040 if (null_terminated) {
7041 copy = (char*)path;
7042 } else {
7043 if (path_len < ufbxi_arraycount(copy_buf) - 1) {
7044 copy = copy_buf;
7045 } else {
7046 copy = ufbxi_alloc(&fc->ator, char, path_len + 1);
7047 if (!copy) return NULL;
7048 }
7049 memcpy(copy, path, path_len);
7050 copy[path_len] = '\0';
7051 }
7052 file = fopen(copy, "rb");
7053 if (!null_terminated && copy != copy_buf) {
7054 ufbxi_free(&fc->ator, char, copy, path_len + 1);
7055 }
7056 #endif
7057 if (!file) {
7058 ufbxi_set_err_info(&fc->error, path, path_len);
7059 ufbxi_report_err_msg(&fc->error, "file", "File not found");
7060 }
7061 return file;
7062 }
7063
7064 static uint64_t ufbxi_ftell(FILE *file)
7065 {
7066 #if !defined(UFBX_STANDARD_C) && defined(UFBX_HAS_FTELLO)
7067 off_t result = ftello(file);
7068 if (result >= 0) return (uint64_t)result;
7069 #elif !defined(UFBX_STANDARD_C) && defined(_MSC_VER)
7070 int64_t result = _ftelli64(file);
7071 if (result >= 0) return (uint64_t)result;
7072 #else
7073 int64_t result = ftell(file);
7074 if (result >= 0) return (uint64_t)result;
7075 #endif
7076 return UINT64_MAX;
7077 }
7078
7079 static size_t ufbxi_stdio_read(void *user, void *data, size_t max_size)
7080 {
7081 FILE *file = (FILE*)user;
7082 if (ferror(file)) return SIZE_MAX;
7083 return fread(data, 1, max_size, file);
7084 }
7085
7086 static bool ufbxi_stdio_skip(void *user, size_t size)
7087 {
7088 FILE *file = (FILE*)user;
7089 ufbx_assert(size <= UFBXI_MAX_SKIP_SIZE);
7090 if (fseek(file, (long)size, SEEK_CUR) != 0) return false;
7091 if (ferror(file)) return false;
7092 return true;
7093 }
7094
7095 static uint64_t ufbxi_stdio_size(void *user)
7096 {
7097 FILE *file = (FILE*)user;
7098 uint64_t result = 0;
7099 uint64_t begin = ufbxi_ftell(file);
7100 if (begin < UINT64_MAX) {
7101 fpos_t pos; // ufbxi_uninit
7102 if (fgetpos(file, &pos) == 0) {
7103 if (fseek(file, 0, SEEK_END) == 0) {
7104 uint64_t end = ufbxi_ftell(file);
7105 if (end != UINT64_MAX && begin < end) {
7106 result = end - begin;
7107 }
7108 // Both `rewind()` and `fsetpos()` to reset error and EOF
7109 rewind(file);
7110 fsetpos(file, &pos);
7111 }
7112 }
7113 }
7114 return result;
7115 }
7116
7117 static void ufbxi_stdio_close(void *user)
7118 {
7119 FILE *file = (FILE*)user;
7120 fclose(file);
7121 }
7122
7123 static ufbxi_noinline void ufbxi_stdio_init(ufbx_stream *stream, void *file, bool close)
7124 {
7125 stream->read_fn = &ufbxi_stdio_read;
7126 stream->skip_fn = &ufbxi_stdio_skip;
7127 stream->size_fn = &ufbxi_stdio_size;
7128 stream->close_fn = close ? &ufbxi_stdio_close : NULL;
7129 stream->user = file;
7130 }
7131
7132 static ufbxi_noinline bool ufbxi_stdio_open(ufbxi_file_context *fc, ufbx_stream *stream, const char *path, size_t path_len, bool null_terminated)
7133 {
7134 FILE *file = ufbxi_fopen(fc, path, path_len, null_terminated);
7135 if (!file) return false;
7136 ufbxi_stdio_init(stream, file, true);
7137 return true;
7138 }
7139
7140 #elif defined(UFBX_EXTERNAL_STDIO)
7141
7142 static ufbxi_noinline void ufbxi_stdio_init(ufbx_stream *stream, void *file, bool close)
7143 {
7144 stream->read_fn = &ufbx_stdio_read;
7145 stream->skip_fn = &ufbx_stdio_skip;
7146 stream->size_fn = &ufbx_stdio_size;
7147 stream->close_fn = close ? &ufbx_stdio_close : NULL;
7148 stream->user = file;
7149 }
7150
7151 static ufbxi_noinline bool ufbxi_stdio_open(ufbxi_file_context *fc, ufbx_stream *stream, const char *path, size_t path_len, bool null_terminated)
7152 {
7153 char copy_buf[256], *copy = NULL; // ufbxi_uninit
7154 if (null_terminated) {
7155 copy = (char*)path;
7156 } else {
7157 if (path_len < ufbxi_arraycount(copy_buf) - 1) {
7158 copy = copy_buf;
7159 } else {
7160 copy = ufbxi_alloc(&fc->ator, char, path_len + 1);
7161 if (!copy) return false;
7162 }
7163 memcpy(copy, path, path_len);
7164 copy[path_len] = '\0';
7165 }
7166 void *file = ufbx_stdio_open(copy, path_len);
7167 if (!null_terminated && copy != copy_buf) {
7168 ufbxi_free(&fc->ator, char, copy, path_len + 1);
7169 }
7170 if (!file) {
7171 ufbxi_set_err_info(&fc->error, path, path_len);
7172 ufbxi_report_err_msg(&fc->error, "file", "File not found");
7173 return false;
7174 }
7175 ufbxi_stdio_init(stream, file, true);
7176 return true;
7177 }
7178
7179 #endif
7180
7181 // -- Memory IO
7182
7183 typedef struct {
7184 const void *data;
7185 size_t size;
7186 size_t position;
7187 ufbx_close_memory_cb close_cb;
7188
7189 // Own allocation information
7190 size_t self_size;
7191 ufbxi_allocator *parent_ator;
7192 ufbxi_allocator local_ator;
7193 ufbx_error error;
7194 char data_copy[];
7195 } ufbxi_memory_stream;
7196
7197 static size_t ufbxi_memory_read(void *user, void *data, size_t max_size)
7198 {
7199 ufbxi_memory_stream *stream = (ufbxi_memory_stream*)user;
7200 size_t to_read = ufbxi_min_sz(stream->size - stream->position, max_size);
7201 memcpy(data, (const char*)stream->data + stream->position, to_read);
7202 stream->position += to_read;
7203 return to_read;
7204 }
7205
7206 static bool ufbxi_memory_skip(void *user, size_t size)
7207 {
7208 ufbxi_memory_stream *stream = (ufbxi_memory_stream*)user;
7209 if (stream->size - stream->position < size) return false;
7210 stream->position += size;
7211 return true;
7212 }
7213
7214 static uint64_t ufbxi_memory_size(void *user)
7215 {
7216 ufbxi_memory_stream *stream = (ufbxi_memory_stream*)user;
7217 return stream->size;
7218 }
7219
7220 static void ufbxi_memory_close(void *user)
7221 {
7222 ufbxi_memory_stream *stream = (ufbxi_memory_stream*)user;
7223 if (stream->close_cb.fn) {
7224 stream->close_cb.fn(stream->close_cb.user, (void*)stream->data, stream->size);
7225 }
7226
7227 if (stream->parent_ator) {
7228 ufbxi_free(stream->parent_ator, char, stream, stream->self_size);
7229 } else {
7230 ufbxi_allocator ator = stream->local_ator;
7231 ufbxi_free(&ator, char, stream, stream->self_size);
7232 ufbxi_free_ator(&ator);
7233 }
7234 }
7235
7236 // -- XML
7237
7238 #if UFBXI_FEATURE_XML
7239
7240 typedef struct ufbxi_xml_tag ufbxi_xml_tag;
7241 typedef struct ufbxi_xml_attrib ufbxi_xml_attrib;
7242 typedef struct ufbxi_xml_document ufbxi_xml_document;
7243
7244 struct ufbxi_xml_attrib {
7245 ufbx_string name;
7246 ufbx_string value;
7247 };
7248
7249 struct ufbxi_xml_tag {
7250 ufbx_string name;
7251 ufbx_string text;
7252
7253 ufbxi_xml_attrib *attribs;
7254 size_t num_attribs;
7255
7256 ufbxi_xml_tag *children;
7257 size_t num_children;
7258 };
7259
7260 struct ufbxi_xml_document {
7261 ufbxi_xml_tag *root;
7262 ufbxi_buf buf;
7263 };
7264
7265 typedef struct {
7266 ufbx_error error;
7267
7268 ufbxi_allocator *ator;
7269
7270 ufbxi_buf tmp_stack;
7271 ufbxi_buf result;
7272
7273 ufbxi_xml_document *doc;
7274
7275 ufbx_read_fn *read_fn;
7276 void *read_user;
7277
7278 char *tok;
7279 size_t tok_cap;
7280 size_t tok_len;
7281
7282 const char *pos, *pos_end;
7283 char data[4096];
7284
7285 bool io_error;
7286 } ufbxi_xml_context;
7287
7288 enum {
7289 UFBXI_XML_CTYPE_WHITESPACE = 0x1,
7290 UFBXI_XML_CTYPE_SINGLE_QUOTE = 0x2,
7291 UFBXI_XML_CTYPE_DOUBLE_QUOTE = 0x4,
7292 UFBXI_XML_CTYPE_NAME_END = 0x8,
7293 UFBXI_XML_CTYPE_TAG_START = 0x10,
7294 UFBXI_XML_CTYPE_END_OF_FILE = 0x20,
7295 };
7296
7297 // Generated by `misc/gen_xml_ctype.py`
7298 static const uint8_t ufbxi_xml_ctype[256] = {
7299 32,0,0,0,0,0,0,0,0,9,9,0,0,9,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
7300 9,0,12,0,0,0,0,10,0,0,0,0,0,0,0,8,0,0,0,0,0,0,0,0,0,0,0,0,16,8,8,8,
7301 };
7302
7303 static ufbxi_noinline void ufbxi_xml_refill(ufbxi_xml_context *xc)
7304 {
7305 size_t num = xc->read_fn(xc->read_user, xc->data, sizeof(xc->data));
7306 if (num == SIZE_MAX || num < sizeof(xc->data)) xc->io_error = true;
7307 if (num < sizeof(xc->data)) {
7308 xc->data[num++] = '\0';
7309 }
7310 xc->pos = xc->data;
7311 xc->pos_end = xc->data + num;
7312 }
7313
7314 static ufbxi_forceinline void ufbxi_xml_advance(ufbxi_xml_context *xc)
7315 {
7316 if (++xc->pos == xc->pos_end) ufbxi_xml_refill(xc);
7317 }
7318
7319 ufbxi_nodiscard static ufbxi_noinline int ufbxi_xml_push_token_char(ufbxi_xml_context *xc, char c)
7320 {
7321 if (xc->tok_len == xc->tok_cap || UFBXI_IS_REGRESSION) {
7322 ufbxi_check_err(&xc->error, ufbxi_grow_array(xc->ator, &xc->tok, &xc->tok_cap, xc->tok_len + 1));
7323 }
7324 xc->tok[xc->tok_len++] = c;
7325 return 1;
7326 }
7327
7328 static ufbxi_noinline int ufbxi_xml_accept(ufbxi_xml_context *xc, char ch)
7329 {
7330 if (*xc->pos == ch) {
7331 ufbxi_xml_advance(xc);
7332 return 1;
7333 } else {
7334 return 0;
7335 }
7336 }
7337
7338 static ufbxi_noinline void ufbxi_xml_skip_while(ufbxi_xml_context *xc, uint32_t ctypes)
7339 {
7340 while (ufbxi_xml_ctype[(uint8_t)*xc->pos] & ctypes) {
7341 ufbxi_xml_advance(xc);
7342 }
7343 }
7344
7345 ufbxi_nodiscard static ufbxi_noinline int ufbxi_xml_skip_until_string(ufbxi_xml_context *xc, ufbx_string *dst, const char *suffix)
7346 {
7347 xc->tok_len = 0;
7348 size_t match_len = 0, ix = 0, suffix_len = strlen(suffix);
7349 char buf[16] = { 0 };
7350 size_t wrap_mask = sizeof(buf) - 1;
7351 ufbx_assert(suffix_len < sizeof(buf));
7352 for (;;) {
7353 char c = *xc->pos;
7354 ufbxi_check_err_msg(&xc->error, c != 0, "Truncated file");
7355 ufbxi_xml_advance(xc);
7356 if (ix >= suffix_len) {
7357 ufbxi_check_err(&xc->error, ufbxi_xml_push_token_char(xc, buf[(ix - suffix_len) & wrap_mask]));
7358 }
7359
7360 buf[ix++ & wrap_mask] = c;
7361 for (match_len = 0; match_len < suffix_len; match_len++) {
7362 if (buf[(ix - suffix_len + match_len) & wrap_mask] != suffix[match_len]) {
7363 break;
7364 }
7365 }
7366 if (match_len == suffix_len) break;
7367 }
7368
7369 ufbxi_check_err(&xc->error, ufbxi_xml_push_token_char(xc, '\0'));
7370 if (dst) {
7371 dst->length = xc->tok_len - 1;
7372 dst->data = ufbxi_push_copy(&xc->result, char, xc->tok_len, xc->tok);
7373 ufbxi_check_err(&xc->error, dst->data);
7374 }
7375
7376 return 1;
7377 }
7378
7379 static ufbxi_noinline int ufbxi_xml_read_until(ufbxi_xml_context *xc, ufbx_string *dst, uint32_t ctypes)
7380 {
7381 xc->tok_len = 0;
7382 for (;;) {
7383 char c = *xc->pos;
7384
7385 if (c == '&') {
7386 size_t entity_begin = xc->tok_len;
7387 for (;;) {
7388 ufbxi_xml_advance(xc);
7389 c = *xc->pos;
7390 ufbxi_check_err(&xc->error, c != '\0');
7391 if (c == ';') break;
7392 ufbxi_check_err(&xc->error, ufbxi_xml_push_token_char(xc, c));
7393 }
7394 ufbxi_xml_advance(xc);
7395 ufbxi_check_err(&xc->error, ufbxi_xml_push_token_char(xc, '\0'));
7396
7397 char *entity = xc->tok + entity_begin;
7398 xc->tok_len = entity_begin;
7399
7400 if (entity[0] == '#') {
7401 unsigned long code = 0;
7402 if (entity[1] == 'x') {
7403 code = ufbxi_parse_uint32_radix(entity + 2, 16);
7404 } else {
7405 code = ufbxi_parse_uint32_radix(entity + 1, 10);
7406 }
7407
7408 char bytes[5] = { 0 };
7409 if (code < 0x80) {
7410 bytes[0] = (char)code;
7411 } else if (code < 0x800) {
7412 bytes[0] = (char)(0xc0 | (code>>6));
7413 bytes[1] = (char)(0x80 | (code & 0x3f));
7414 } else if (code < 0x10000) {
7415 bytes[0] = (char)(0xe0 | (code>>12));
7416 bytes[1] = (char)(0x80 | ((code>>6) & 0x3f));
7417 bytes[2] = (char)(0x80 | (code & 0x3f));
7418 } else {
7419 bytes[0] = (char)(0xf0 | (code>>18));
7420 bytes[1] = (char)(0x80 | ((code>>12) & 0x3f));
7421 bytes[2] = (char)(0x80 | ((code>>6) & 0x3f));
7422 bytes[3] = (char)(0x80 | (code & 0x3f));
7423 }
7424 for (char *b = bytes; *b; b++) {
7425 ufbxi_check_err(&xc->error, ufbxi_xml_push_token_char(xc, *b));
7426 }
7427 } else {
7428 char ch = '\0';
7429 if (!strcmp(entity, "lt")) ch = '<';
7430 else if (!strcmp(entity, "quot")) ch = '"';
7431 else if (!strcmp(entity, "amp")) ch = '&';
7432 else if (!strcmp(entity, "apos")) ch = '\'';
7433 else if (!strcmp(entity, "gt")) ch = '>';
7434 if (ch) {
7435 ufbxi_check_err(&xc->error, ufbxi_xml_push_token_char(xc, ch));
7436 }
7437 }
7438 } else {
7439 if ((ufbxi_xml_ctype[(uint8_t)c] & ctypes) != 0) break;
7440 ufbxi_check_err_msg(&xc->error, c != 0, "Truncated file");
7441 ufbxi_check_err(&xc->error, ufbxi_xml_push_token_char(xc, c));
7442 ufbxi_xml_advance(xc);
7443 }
7444 }
7445
7446 ufbxi_check_err(&xc->error, ufbxi_xml_push_token_char(xc, '\0'));
7447 if (dst) {
7448 dst->length = xc->tok_len - 1;
7449 dst->data = ufbxi_push_copy(&xc->result, char, xc->tok_len, xc->tok);
7450 ufbxi_check_err(&xc->error, dst->data);
7451 }
7452
7453 return 1;
7454 }
7455
7456 // Recursion limited by check at the start
7457 static ufbxi_noinline int ufbxi_xml_parse_tag(ufbxi_xml_context *xc, size_t depth, bool *p_closing, const char *opening)
7458 ufbxi_recursive_function(int, ufbxi_xml_parse_tag, (xc, depth, p_closing, opening), UFBXI_MAX_XML_DEPTH + 1,
7459 (ufbxi_xml_context *xc, size_t depth, bool *p_closing, const char *opening))
7460 {
7461 ufbxi_check_err(&xc->error, depth < UFBXI_MAX_XML_DEPTH);
7462
7463 if (!ufbxi_xml_accept(xc, '<')) {
7464 if (*xc->pos == '\0') {
7465 *p_closing = true;
7466 } else {
7467 ufbxi_check_err(&xc->error, ufbxi_xml_read_until(xc, NULL, UFBXI_XML_CTYPE_TAG_START | UFBXI_XML_CTYPE_END_OF_FILE));
7468 bool has_text = false;
7469 for (size_t i = 0; i < xc->tok_len; i++) {
7470 if ((ufbxi_xml_ctype[(uint8_t)xc->tok[i]] & UFBXI_XML_CTYPE_WHITESPACE) == 0) {
7471 has_text = true;
7472 break;
7473 }
7474 }
7475
7476 if (has_text) {
7477 ufbxi_xml_tag *tag = ufbxi_push_zero(&xc->tmp_stack, ufbxi_xml_tag, 1);
7478 ufbxi_check_err(&xc->error, tag);
7479 tag->name.data = ufbxi_empty_char;
7480
7481 tag->text.length = xc->tok_len - 1;
7482 tag->text.data = ufbxi_push_copy(&xc->result, char, xc->tok_len, xc->tok);
7483 ufbxi_check_err(&xc->error, tag->text.data);
7484 }
7485 }
7486 return 1;
7487 }
7488
7489 if (ufbxi_xml_accept(xc, '/')) {
7490 ufbxi_check_err(&xc->error, ufbxi_xml_read_until(xc, NULL, UFBXI_XML_CTYPE_NAME_END));
7491 ufbxi_check_err(&xc->error, opening && !strcmp(xc->tok, opening));
7492 ufbxi_xml_skip_while(xc, UFBXI_XML_CTYPE_WHITESPACE);
7493 if (!ufbxi_xml_accept(xc, '>')) return 0;
7494 *p_closing = true;
7495 return 1;
7496 } else if (ufbxi_xml_accept(xc, '!')) {
7497 if (ufbxi_xml_accept(xc, '[')) {
7498 for (const char *ch = "CDATA["; *ch; ch++) {
7499 if (!ufbxi_xml_accept(xc, *ch)) return 0;
7500 }
7501
7502 ufbxi_xml_tag *tag = ufbxi_push_zero(&xc->tmp_stack, ufbxi_xml_tag, 1);
7503 ufbxi_check_err(&xc->error, tag);
7504 ufbxi_check_err(&xc->error, ufbxi_xml_skip_until_string(xc, &tag->text, "]]>"));
7505 tag->name.data = ufbxi_empty_char;
7506
7507 } else if (ufbxi_xml_accept(xc, '-')) {
7508 if (!ufbxi_xml_accept(xc, '-')) return 0;
7509 ufbxi_check_err(&xc->error, ufbxi_xml_skip_until_string(xc, NULL, "-->"));
7510 } else {
7511 // TODO: !DOCTYPE
7512 ufbxi_check_err(&xc->error, ufbxi_xml_skip_until_string(xc, NULL, ">"));
7513 }
7514 return 1;
7515 } else if (ufbxi_xml_accept(xc, '?')) {
7516 ufbxi_check_err(&xc->error, ufbxi_xml_skip_until_string(xc, NULL, "?>"));
7517 return 1;
7518 }
7519
7520 ufbxi_xml_tag *tag = ufbxi_push_zero(&xc->tmp_stack, ufbxi_xml_tag, 1);
7521 ufbxi_check_err(&xc->error, tag);
7522 ufbxi_check_err(&xc->error, ufbxi_xml_read_until(xc, &tag->name, UFBXI_XML_CTYPE_NAME_END));
7523 tag->text.data = ufbxi_empty_char;
7524
7525 bool has_children = false;
7526
7527 size_t num_attribs = 0;
7528 for (;;) {
7529 ufbxi_xml_skip_while(xc, UFBXI_XML_CTYPE_WHITESPACE);
7530 if (ufbxi_xml_accept(xc, '/')) {
7531 if (!ufbxi_xml_accept(xc, '>')) return 0;
7532 break;
7533 } else if (ufbxi_xml_accept(xc, '>')) {
7534 has_children = true;
7535 break;
7536 } else {
7537 ufbxi_xml_attrib *attrib = ufbxi_push_zero(&xc->tmp_stack, ufbxi_xml_attrib, 1);
7538 ufbxi_check_err(&xc->error, attrib);
7539 ufbxi_check_err(&xc->error, ufbxi_xml_read_until(xc, &attrib->name, UFBXI_XML_CTYPE_NAME_END));
7540 ufbxi_xml_skip_while(xc, UFBXI_XML_CTYPE_WHITESPACE);
7541 if (!ufbxi_xml_accept(xc, '=')) return 0;
7542 ufbxi_xml_skip_while(xc, UFBXI_XML_CTYPE_WHITESPACE);
7543 uint32_t quote_ctype = 0;
7544 if (ufbxi_xml_accept(xc, '"')) {
7545 quote_ctype = UFBXI_XML_CTYPE_DOUBLE_QUOTE;
7546 } else if (ufbxi_xml_accept(xc, '\'')) {
7547 quote_ctype = UFBXI_XML_CTYPE_SINGLE_QUOTE;
7548 } else {
7549 ufbxi_fail_err(&xc->error, "Bad attrib value");
7550 }
7551 ufbxi_check_err(&xc->error, ufbxi_xml_read_until(xc, &attrib->value, quote_ctype));
7552 ufbxi_xml_advance(xc);
7553 num_attribs++;
7554 }
7555 }
7556
7557 tag->num_attribs = num_attribs;
7558 tag->attribs = ufbxi_push_pop(&xc->result, &xc->tmp_stack, ufbxi_xml_attrib, num_attribs);
7559 ufbxi_check_err(&xc->error, tag->attribs);
7560
7561 if (has_children) {
7562 size_t children_begin = xc->tmp_stack.num_items;
7563 for (;;) {
7564 bool closing = false;
7565 ufbxi_check_err(&xc->error, ufbxi_xml_parse_tag(xc, depth + 1, &closing, tag->name.data));
7566 if (closing) break;
7567 }
7568
7569 tag->num_children = xc->tmp_stack.num_items - children_begin;
7570 tag->children = ufbxi_push_pop(&xc->result, &xc->tmp_stack, ufbxi_xml_tag, tag->num_children);
7571 ufbxi_check_err(&xc->error, tag->children);
7572 }
7573
7574 return 1;
7575 }
7576
7577 static ufbxi_noinline int ufbxi_xml_parse_root(ufbxi_xml_context *xc)
7578 {
7579 ufbxi_xml_tag *tag = ufbxi_push_zero(&xc->result, ufbxi_xml_tag, 1);
7580 ufbxi_check_err(&xc->error, tag);
7581 tag->name.data = ufbxi_empty_char;
7582 tag->text.data = ufbxi_empty_char;
7583
7584 for (;;) {
7585 bool closing = false;
7586 ufbxi_check_err(&xc->error, ufbxi_xml_parse_tag(xc, 0, &closing, NULL));
7587 if (closing) break;
7588 }
7589
7590 tag->num_children = xc->tmp_stack.num_items;
7591 tag->children = ufbxi_push_pop(&xc->result, &xc->tmp_stack, ufbxi_xml_tag, tag->num_children);
7592 ufbxi_check_err(&xc->error, tag->children);
7593
7594 xc->doc = ufbxi_push(&xc->result, ufbxi_xml_document, 1);
7595 ufbxi_check_err(&xc->error, xc->doc);
7596
7597 xc->doc->root = tag;
7598 xc->doc->buf = xc->result;
7599
7600 return 1;
7601 }
7602
7603 typedef struct {
7604 ufbxi_allocator *ator;
7605 ufbx_read_fn *read_fn;
7606 void *read_user;
7607 const char *prefix;
7608 size_t prefix_length;
7609 } ufbxi_xml_load_opts;
7610
7611 static ufbxi_noinline ufbxi_xml_document *ufbxi_load_xml(ufbxi_xml_load_opts *opts, ufbx_error *error)
7612 {
7613 ufbxi_xml_context xc = { UFBX_ERROR_NONE };
7614 xc.ator = opts->ator;
7615 xc.read_fn = opts->read_fn;
7616 xc.read_user = opts->read_user;
7617
7618 xc.tmp_stack.ator = xc.ator;
7619 xc.result.ator = xc.ator;
7620
7621 xc.result.unordered = true;
7622
7623 if (opts->prefix_length > 0) {
7624 xc.pos = opts->prefix;
7625 xc.pos_end = opts->prefix + opts->prefix_length;
7626 } else {
7627 ufbxi_xml_refill(&xc);
7628 }
7629
7630 int ok = ufbxi_xml_parse_root(&xc);
7631
7632 ufbxi_buf_free(&xc.tmp_stack);
7633 ufbxi_free(xc.ator, char, xc.tok, xc.tok_cap);
7634
7635 if (ok) {
7636 return xc.doc;
7637 } else {
7638 ufbxi_buf_free(&xc.result);
7639 if (error) {
7640 *error = xc.error;
7641 }
7642
7643 return NULL;
7644 }
7645 }
7646
7647 static ufbxi_noinline void ufbxi_free_xml(ufbxi_xml_document *doc)
7648 {
7649 ufbxi_buf buf = doc->buf;
7650 ufbxi_buf_free(&buf);
7651 }
7652
7653 static ufbxi_noinline ufbxi_xml_tag *ufbxi_xml_find_child(ufbxi_xml_tag *tag, const char *name)
7654 {
7655 ufbxi_for(ufbxi_xml_tag, child, tag->children, tag->num_children) {
7656 if (!strcmp(child->name.data, name)) {
7657 return child;
7658 }
7659 }
7660 return NULL;
7661 }
7662
7663 static ufbxi_noinline ufbxi_xml_attrib *ufbxi_xml_find_attrib(ufbxi_xml_tag *tag, const char *name)
7664 {
7665 ufbxi_for(ufbxi_xml_attrib, attrib, tag->attribs, tag->num_attribs) {
7666 if (!strcmp(attrib->name.data, name)) {
7667 return attrib;
7668 }
7669 }
7670 return NULL;
7671 }
7672
7673 #endif
7674
7675 // -- FBX value type information
7676
7677 static char ufbxi_normalize_array_type(char type, char bool_type) {
7678 switch (type) {
7679 case 'r': return sizeof(ufbx_real) == sizeof(float) ? 'f' : 'd';
7680 case 'b': return bool_type;
7681 default: return type;
7682 }
7683 }
7684
7685 static ufbxi_noinline size_t ufbxi_array_type_size(char type)
7686 {
7687 switch (type) {
7688 case 'r': return sizeof(ufbx_real);
7689 case 'b': return sizeof(bool);
7690 case 'c': return sizeof(uint8_t);
7691 case 'i': return sizeof(int32_t);
7692 case 'l': return sizeof(int64_t);
7693 case 'f': return sizeof(float);
7694 case 'd': return sizeof(double);
7695 case 's': return sizeof(ufbx_string);
7696 case 'S': return sizeof(ufbx_string);
7697 case 'C': return sizeof(ufbx_string);
7698 default: return 1;
7699 }
7700 }
7701
7702 // -- Node operations
7703
7704 static ufbxi_noinline ufbxi_node *ufbxi_find_child(ufbxi_node *node, const char *name)
7705 {
7706 ufbxi_for(ufbxi_node, c, node->children, node->num_children) {
7707 if (c->name == name) return c;
7708 }
7709 return NULL;
7710 }
7711
7712 // Retrieve the type of a given value
7713 ufbxi_forceinline static ufbxi_value_type ufbxi_get_val_type(ufbxi_node *node, size_t ix)
7714 {
7715 return (ufbxi_value_type)((node->value_type_mask >> (ix*2)) & 0x3);
7716 }
7717
7718 // Retrieve values from nodes with type codes:
7719 // Any: '_' (ignore)
7720 // NUMBER: 'I' int32_t 'L' int64_t 'F' float 'D' double 'R' ufbxi_real 'B' bool 'Z' size_t
7721 // STRING: 'S' ufbx_string 'C' const char* (checked) 's' ufbx_string 'c' const char * (unchecked) 'b' ufbx_blob
7722 ufbxi_nodiscard ufbxi_forceinline static int ufbxi_get_val_at(ufbxi_node *node, size_t ix, char fmt, void *v)
7723 {
7724 ufbxi_dev_assert(ix < UFBXI_MAX_NON_ARRAY_VALUES);
7725 ufbxi_value_type type = (ufbxi_value_type)((node->value_type_mask >> (ix*2)) & 0x3);
7726 switch (fmt) {
7727 case '_': return 1;
7728 case 'I': if (type == UFBXI_VALUE_NUMBER) { *(int32_t*)v = (int32_t)node->vals[ix].i; return 1; } else return 0;
7729 case 'L': if (type == UFBXI_VALUE_NUMBER) { *(int64_t*)v = (int64_t)node->vals[ix].i; return 1; } else return 0;
7730 case 'F': if (type == UFBXI_VALUE_NUMBER) { *(float*)v = (float)node->vals[ix].f; return 1; } else return 0;
7731 case 'D': if (type == UFBXI_VALUE_NUMBER) { *(double*)v = (double)node->vals[ix].f; return 1; } else return 0;
7732 case 'R': if (type == UFBXI_VALUE_NUMBER) { *(ufbx_real*)v = (ufbx_real)node->vals[ix].f; return 1; } else return 0;
7733 case 'B': if (type == UFBXI_VALUE_NUMBER) { *(bool*)v = node->vals[ix].i != 0; return 1; } else return 0;
7734 case 'Z': if (type == UFBXI_VALUE_NUMBER) { if (node->vals[ix].i < 0) return 0; *(size_t*)v = (size_t)node->vals[ix].i; return 1; } else return 0;
7735 case 'S': if (type == UFBXI_VALUE_STRING) {
7736 ufbxi_sanitized_string src = node->vals[ix].s;
7737 ufbx_string *dst = (ufbx_string*)v;
7738 if (src.utf8_length > 0) {
7739 if (src.utf8_length == UINT32_MAX) return 0;
7740 dst->data = src.raw_data + src.raw_length + 1;
7741 dst->length = src.utf8_length;
7742 } else {
7743 dst->data = src.raw_data;
7744 dst->length = src.raw_length;
7745 }
7746 return 1;
7747 } else return 0;
7748 case 's': if (type == UFBXI_VALUE_STRING) {
7749 ufbxi_sanitized_string src = node->vals[ix].s;
7750 ufbx_string *dst = (ufbx_string*)v;
7751 dst->data = src.raw_data;
7752 dst->length = src.raw_length;
7753 return 1;
7754 } else return 0;
7755 case 'C': if (type == UFBXI_VALUE_STRING) {
7756 ufbxi_sanitized_string src = node->vals[ix].s;
7757 const char **dst = (const char **)v;
7758 if (src.utf8_length > 0) {
7759 if (src.utf8_length == UINT32_MAX) return 0;
7760 *dst = src.raw_data + src.raw_length + 1;
7761 } else {
7762 *dst = src.raw_data;
7763 }
7764 return 1;
7765 } else return 0;
7766 case 'c': if (type == UFBXI_VALUE_STRING) {
7767 ufbxi_sanitized_string src = node->vals[ix].s;
7768 const char **dst = (const char **)v;
7769 *dst = src.raw_data;
7770 return 1;
7771 } else return 0;
7772 case 'b': if (type == UFBXI_VALUE_STRING) {
7773 ufbxi_sanitized_string src = node->vals[ix].s;
7774 ufbx_blob *dst = (ufbx_blob*)v;
7775 dst->data = src.raw_data;
7776 dst->size = src.raw_length;
7777 return 1;
7778 } else return 0;
7779 default:
7780 ufbxi_unreachable("Bad format char");
7781 return 0;
7782 }
7783 }
7784
7785 ufbxi_nodiscard ufbxi_noinline static ufbxi_value_array *ufbxi_get_array(ufbxi_node *node, char fmt)
7786 {
7787 if (node->value_type_mask != UFBXI_VALUE_ARRAY) return NULL;
7788 ufbxi_value_array *array = node->array;
7789 if (fmt != '?') {
7790 fmt = ufbxi_normalize_array_type(fmt, 'b');
7791 if (array->type != fmt) return NULL;
7792 }
7793 return array;
7794 }
7795
7796 ufbxi_nodiscard static ufbxi_forceinline int ufbxi_get_val1(ufbxi_node *node, const char *fmt, void *v0)
7797 {
7798 if (!ufbxi_get_val_at(node, 0, fmt[0], v0)) return 0;
7799 return 1;
7800 }
7801
7802 ufbxi_nodiscard static ufbxi_forceinline int ufbxi_get_val2(ufbxi_node *node, const char *fmt, void *v0, void *v1)
7803 {
7804 if (!ufbxi_get_val_at(node, 0, fmt[0], v0)) return 0;
7805 if (!ufbxi_get_val_at(node, 1, fmt[1], v1)) return 0;
7806 return 1;
7807 }
7808
7809 ufbxi_nodiscard static ufbxi_forceinline int ufbxi_get_val3(ufbxi_node *node, const char *fmt, void *v0, void *v1, void *v2)
7810 {
7811 if (!ufbxi_get_val_at(node, 0, fmt[0], v0)) return 0;
7812 if (!ufbxi_get_val_at(node, 1, fmt[1], v1)) return 0;
7813 if (!ufbxi_get_val_at(node, 2, fmt[2], v2)) return 0;
7814 return 1;
7815 }
7816
7817 ufbxi_nodiscard static ufbxi_forceinline int ufbxi_get_val4(ufbxi_node *node, const char *fmt, void *v0, void *v1, void *v2, void *v3)
7818 {
7819 if (!ufbxi_get_val_at(node, 0, fmt[0], v0)) return 0;
7820 if (!ufbxi_get_val_at(node, 1, fmt[1], v1)) return 0;
7821 if (!ufbxi_get_val_at(node, 2, fmt[2], v2)) return 0;
7822 if (!ufbxi_get_val_at(node, 3, fmt[3], v3)) return 0;
7823 return 1;
7824 }
7825
7826 ufbxi_nodiscard static ufbxi_forceinline int ufbxi_get_val5(ufbxi_node *node, const char *fmt, void *v0, void *v1, void *v2, void *v3, void *v4)
7827 {
7828 if (!ufbxi_get_val_at(node, 0, fmt[0], v0)) return 0;
7829 if (!ufbxi_get_val_at(node, 1, fmt[1], v1)) return 0;
7830 if (!ufbxi_get_val_at(node, 2, fmt[2], v2)) return 0;
7831 if (!ufbxi_get_val_at(node, 3, fmt[3], v3)) return 0;
7832 if (!ufbxi_get_val_at(node, 4, fmt[4], v4)) return 0;
7833 return 1;
7834 }
7835
7836 ufbxi_nodiscard static ufbxi_forceinline int ufbxi_find_val1(ufbxi_node *node, const char *name, const char *fmt, void *v0)
7837 {
7838 ufbxi_node *child = ufbxi_find_child(node, name);
7839 if (!child) return 0;
7840 if (!ufbxi_get_val_at(child, 0, fmt[0], v0)) return 0;
7841 return 1;
7842 }
7843
7844 ufbxi_nodiscard static ufbxi_forceinline int ufbxi_find_val2(ufbxi_node *node, const char *name, const char *fmt, void *v0, void *v1)
7845 {
7846 ufbxi_node *child = ufbxi_find_child(node, name);
7847 if (!child) return 0;
7848 if (!ufbxi_get_val_at(child, 0, fmt[0], v0)) return 0;
7849 if (!ufbxi_get_val_at(child, 1, fmt[1], v1)) return 0;
7850 return 1;
7851 }
7852
7853 ufbxi_nodiscard static ufbxi_noinline ufbxi_value_array *ufbxi_find_array(ufbxi_node *node, const char *name, char fmt)
7854 {
7855 ufbxi_node *child = ufbxi_find_child(node, name);
7856 if (!child) return NULL;
7857 return ufbxi_get_array(child, fmt);
7858 }
7859
7860 static ufbxi_node *ufbxi_find_child_strcmp(ufbxi_node *node, const char *name)
7861 {
7862 char leading = name[0];
7863 ufbxi_for(ufbxi_node, c, node->children, node->num_children) {
7864 if (c->name[0] != leading) continue;
7865 if (!strcmp(c->name, name)) return c;
7866 }
7867 return NULL;
7868 }
7869
7870 // -- Element extra data allocation
7871
7872 ufbxi_nodiscard static ufbxi_noinline void *ufbxi_push_element_extra_size(ufbxi_context *uc, uint32_t id, size_t size)
7873 {
7874 if (uc->element_extra_cap <= id) {
7875 size_t old_cap = uc->element_extra_cap;
7876 ufbxi_check_return(ufbxi_grow_array(&uc->ator_tmp, &uc->element_extra_arr, &uc->element_extra_cap, id + 1), NULL);
7877 memset(uc->element_extra_arr + old_cap, 0, (uc->element_extra_cap - old_cap) * sizeof(void*));
7878 }
7879
7880 if (uc->element_extra_arr[id]) return uc->element_extra_arr[id];
7881
7882 void *extra = ufbxi_push_size_zero(&uc->tmp, size, 1);
7883 ufbxi_check_return(extra, NULL);
7884 uc->element_extra_arr[id] = extra;
7885
7886 return extra;
7887 }
7888
7889 static ufbxi_noinline void *ufbxi_get_element_extra(ufbxi_context *uc, uint32_t id)
7890 {
7891 if (id < uc->element_extra_cap) {
7892 return uc->element_extra_arr[id];
7893 } else {
7894 return NULL;
7895 }
7896 }
7897
7898 #define ufbxi_push_element_extra(uc, id, type) (type*)ufbxi_push_element_extra_size((uc), (id), sizeof(type))
7899
7900 // -- Parsing state machine
7901 //
7902 // When reading the file we maintain a coarse representation of the structure so
7903 // that we can resolve array info (type, included in result, etc). Using this info
7904 // we can often read/decompress the contents directly into the right memory area.
7905
7906 typedef enum {
7907 UFBXI_PARSE_ROOT,
7908 UFBXI_PARSE_FBX_HEADER_EXTENSION,
7909 UFBXI_PARSE_SCENE_INFO,
7910 UFBXI_PARSE_THUMBNAIL,
7911 UFBXI_PARSE_DEFINITIONS,
7912 UFBXI_PARSE_OBJECTS,
7913 UFBXI_PARSE_CONNECTIONS,
7914 UFBXI_PARSE_RELATIONS,
7915 UFBXI_PARSE_TAKES,
7916 UFBXI_PARSE_FBX_VERSION,
7917 UFBXI_PARSE_MODEL,
7918 UFBXI_PARSE_GEOMETRY,
7919 UFBXI_PARSE_NODE_ATTRIBUTE,
7920 UFBXI_PARSE_LEGACY_MODEL,
7921 UFBXI_PARSE_LEGACY_MEDIA,
7922 UFBXI_PARSE_LEGACY_VIDEO,
7923 UFBXI_PARSE_LEGACY_SWITCHER,
7924 UFBXI_PARSE_LEGACY_SCENE_PERSISTENCE,
7925 UFBXI_PARSE_REFERENCES,
7926 UFBXI_PARSE_REFERENCE,
7927 UFBXI_PARSE_ANIMATION_CURVE,
7928 UFBXI_PARSE_DEFORMER,
7929 UFBXI_PARSE_ASSOCIATE_MODEL,
7930 UFBXI_PARSE_LEGACY_LINK,
7931 UFBXI_PARSE_POSE,
7932 UFBXI_PARSE_POSE_NODE,
7933 UFBXI_PARSE_TEXTURE,
7934 UFBXI_PARSE_VIDEO,
7935 UFBXI_PARSE_LAYERED_TEXTURE,
7936 UFBXI_PARSE_SELECTION_NODE,
7937 UFBXI_PARSE_COLLECTION,
7938 UFBXI_PARSE_AUDIO,
7939 UFBXI_PARSE_UNKNOWN_OBJECT,
7940 UFBXI_PARSE_LAYER_ELEMENT_NORMAL,
7941 UFBXI_PARSE_LAYER_ELEMENT_BINORMAL,
7942 UFBXI_PARSE_LAYER_ELEMENT_TANGENT,
7943 UFBXI_PARSE_LAYER_ELEMENT_UV,
7944 UFBXI_PARSE_LAYER_ELEMENT_COLOR,
7945 UFBXI_PARSE_LAYER_ELEMENT_VERTEX_CREASE,
7946 UFBXI_PARSE_LAYER_ELEMENT_EDGE_CREASE,
7947 UFBXI_PARSE_LAYER_ELEMENT_SMOOTHING,
7948 UFBXI_PARSE_LAYER_ELEMENT_VISIBILITY,
7949 UFBXI_PARSE_LAYER_ELEMENT_POLYGON_GROUP,
7950 UFBXI_PARSE_LAYER_ELEMENT_HOLE,
7951 UFBXI_PARSE_LAYER_ELEMENT_MATERIAL,
7952 UFBXI_PARSE_LAYER_ELEMENT_OTHER,
7953 UFBXI_PARSE_GEOMETRY_UV_INFO,
7954 UFBXI_PARSE_SHAPE,
7955 UFBXI_PARSE_TAKE,
7956 UFBXI_PARSE_TAKE_OBJECT,
7957 UFBXI_PARSE_CHANNEL,
7958 UFBXI_PARSE_UNKNOWN,
7959 } ufbxi_parse_state;
7960
7961 typedef enum {
7962 UFBXI_ARRAY_FLAG_RESULT = 0x1, // < Allocate the array from the result buffer
7963 UFBXI_ARRAY_FLAG_TMP_BUF = 0x2, // < Allocate the array from the long-term temporary buffer
7964 UFBXI_ARRAY_FLAG_PAD_BEGIN = 0x4, // < Pad the begin of the array with 4 zero elements to guard from invalid -1 index accesses
7965 UFBXI_ARRAY_FLAG_ACCURATE_F32 = 0x8, // < Must be parsed as bit-accurate 32-bit floats
7966 } ufbxi_array_flags;
7967
7968 typedef struct {
7969 char type; // < FBX type code of the array: b,i,l,f,d (or 'r' meaning ufbx_real '-' ignore, 's'/'S' for strings, 'C' for content)
7970 uint8_t flags; // < Combination of `ufbxi_array_flags`
7971 } ufbxi_array_info;
7972
7973 static ufbxi_noinline ufbxi_parse_state ufbxi_update_parse_state(ufbxi_parse_state parent, const char *name)
7974 {
7975 switch (parent) {
7976
7977 case UFBXI_PARSE_ROOT:
7978 if (name == ufbxi_FBXHeaderExtension) return UFBXI_PARSE_FBX_HEADER_EXTENSION;
7979 if (name == ufbxi_Definitions) return UFBXI_PARSE_DEFINITIONS;
7980 if (name == ufbxi_Objects) return UFBXI_PARSE_OBJECTS;
7981 if (name == ufbxi_Connections) return UFBXI_PARSE_CONNECTIONS;
7982 if (name == ufbxi_Takes) return UFBXI_PARSE_TAKES;
7983 if (name == ufbxi_Model) return UFBXI_PARSE_LEGACY_MODEL;
7984 if (!strcmp(name, "References")) return UFBXI_PARSE_REFERENCES;
7985 if (!strcmp(name, "Relations")) return UFBXI_PARSE_RELATIONS;
7986 if (name == ufbxi_Media) return UFBXI_PARSE_LEGACY_MEDIA;
7987 if (!strcmp(name, "Switcher")) return UFBXI_PARSE_LEGACY_SWITCHER;
7988 if (!strcmp(name, "SceneGenericPersistence")) return UFBXI_PARSE_LEGACY_SCENE_PERSISTENCE;
7989 break;
7990
7991 case UFBXI_PARSE_FBX_HEADER_EXTENSION:
7992 if (name == ufbxi_FBXVersion) return UFBXI_PARSE_FBX_VERSION;
7993 if (name == ufbxi_SceneInfo) return UFBXI_PARSE_SCENE_INFO;
7994 break;
7995
7996 case UFBXI_PARSE_SCENE_INFO:
7997 if (name == ufbxi_Thumbnail) return UFBXI_PARSE_THUMBNAIL;
7998 break;
7999
8000 case UFBXI_PARSE_OBJECTS:
8001 if (name == ufbxi_Model) return UFBXI_PARSE_MODEL;
8002 if (name == ufbxi_Geometry) return UFBXI_PARSE_GEOMETRY;
8003 if (name == ufbxi_NodeAttribute) return UFBXI_PARSE_NODE_ATTRIBUTE;
8004 if (name == ufbxi_AnimationCurve) return UFBXI_PARSE_ANIMATION_CURVE;
8005 if (name == ufbxi_Deformer) return UFBXI_PARSE_DEFORMER;
8006 if (name == ufbxi_Pose) return UFBXI_PARSE_POSE;
8007 if (name == ufbxi_Texture) return UFBXI_PARSE_TEXTURE;
8008 if (name == ufbxi_Video) return UFBXI_PARSE_VIDEO;
8009 if (name == ufbxi_LayeredTexture) return UFBXI_PARSE_LAYERED_TEXTURE;
8010 if (name == ufbxi_SelectionNode) return UFBXI_PARSE_SELECTION_NODE;
8011 if (name == ufbxi_Collection) return UFBXI_PARSE_COLLECTION;
8012 if (name == ufbxi_Audio) return UFBXI_PARSE_AUDIO;
8013 return UFBXI_PARSE_UNKNOWN_OBJECT;
8014
8015 case UFBXI_PARSE_MODEL:
8016 case UFBXI_PARSE_GEOMETRY:
8017 if (name[0] == 'L') {
8018 if (name == ufbxi_LayerElementNormal) return UFBXI_PARSE_LAYER_ELEMENT_NORMAL;
8019 if (name == ufbxi_LayerElementBinormal) return UFBXI_PARSE_LAYER_ELEMENT_BINORMAL;
8020 if (name == ufbxi_LayerElementTangent) return UFBXI_PARSE_LAYER_ELEMENT_TANGENT;
8021 if (name == ufbxi_LayerElementUV) return UFBXI_PARSE_LAYER_ELEMENT_UV;
8022 if (name == ufbxi_LayerElementColor) return UFBXI_PARSE_LAYER_ELEMENT_COLOR;
8023 if (name == ufbxi_LayerElementVertexCrease) return UFBXI_PARSE_LAYER_ELEMENT_VERTEX_CREASE;
8024 if (name == ufbxi_LayerElementEdgeCrease) return UFBXI_PARSE_LAYER_ELEMENT_EDGE_CREASE;
8025 if (name == ufbxi_LayerElementSmoothing) return UFBXI_PARSE_LAYER_ELEMENT_SMOOTHING;
8026 if (name == ufbxi_LayerElementVisibility) return UFBXI_PARSE_LAYER_ELEMENT_VISIBILITY;
8027 if (name == ufbxi_LayerElementPolygonGroup) return UFBXI_PARSE_LAYER_ELEMENT_POLYGON_GROUP;
8028 if (name == ufbxi_LayerElementHole) return UFBXI_PARSE_LAYER_ELEMENT_HOLE;
8029 if (name == ufbxi_LayerElementMaterial) return UFBXI_PARSE_LAYER_ELEMENT_MATERIAL;
8030 if (!strncmp(name, "LayerElement", 12)) return UFBXI_PARSE_LAYER_ELEMENT_OTHER;
8031 }
8032 if (name == ufbxi_Shape) return UFBXI_PARSE_SHAPE;
8033 break;
8034
8035 case UFBXI_PARSE_DEFORMER:
8036 if (!strcmp(name, "AssociateModel")) return UFBXI_PARSE_ASSOCIATE_MODEL;
8037 break;
8038
8039 case UFBXI_PARSE_LEGACY_MEDIA:
8040 if (name == ufbxi_Video) return UFBXI_PARSE_LEGACY_VIDEO;
8041 break;
8042
8043 case UFBXI_PARSE_LEGACY_VIDEO:
8044 return UFBXI_PARSE_VIDEO;
8045
8046 case UFBXI_PARSE_LEGACY_MODEL:
8047 if (name == ufbxi_GeometryUVInfo) return UFBXI_PARSE_GEOMETRY_UV_INFO;
8048 if (name == ufbxi_Link) return UFBXI_PARSE_LEGACY_LINK;
8049 if (name == ufbxi_Channel) return UFBXI_PARSE_CHANNEL;
8050 if (name == ufbxi_Shape) return UFBXI_PARSE_SHAPE;
8051 break;
8052
8053 case UFBXI_PARSE_POSE:
8054 if (name == ufbxi_PoseNode) return UFBXI_PARSE_POSE_NODE;
8055 break;
8056
8057 case UFBXI_PARSE_TAKES:
8058 if (name == ufbxi_Take) return UFBXI_PARSE_TAKE;
8059 break;
8060
8061 case UFBXI_PARSE_TAKE:
8062 return UFBXI_PARSE_TAKE_OBJECT;
8063
8064 case UFBXI_PARSE_TAKE_OBJECT:
8065 if (name == ufbxi_Channel) return UFBXI_PARSE_CHANNEL;
8066 break;
8067
8068 case UFBXI_PARSE_CHANNEL:
8069 if (name == ufbxi_Channel) return UFBXI_PARSE_CHANNEL;
8070 break;
8071
8072 case UFBXI_PARSE_REFERENCES:
8073 return UFBXI_PARSE_REFERENCE;
8074
8075 default:
8076 break;
8077
8078 }
8079
8080 return UFBXI_PARSE_UNKNOWN;
8081 }
8082
8083 static bool ufbxi_is_array_node(ufbxi_context *uc, ufbxi_parse_state parent, const char *name, ufbxi_array_info *info)
8084 {
8085 info->flags = 0;
8086
8087 // Retain all arrays if user wants the DOM representation
8088 if (uc->opts.retain_dom) {
8089 info->flags |= UFBXI_ARRAY_FLAG_RESULT;
8090 }
8091
8092 switch (parent) {
8093
8094 case UFBXI_PARSE_THUMBNAIL:
8095 if (name == ufbxi_ImageData) {
8096 info->type = 'c';
8097 info->flags = UFBXI_ARRAY_FLAG_RESULT;
8098 return true;
8099 }
8100 break;
8101
8102 case UFBXI_PARSE_GEOMETRY:
8103 case UFBXI_PARSE_MODEL:
8104 if (name == ufbxi_Vertices) {
8105 info->type = uc->opts.ignore_geometry ? '-' : 'r';
8106 info->flags = UFBXI_ARRAY_FLAG_RESULT | UFBXI_ARRAY_FLAG_PAD_BEGIN;
8107 return true;
8108 } else if (name == ufbxi_PolygonVertexIndex) {
8109 info->type = uc->opts.ignore_geometry ? '-' : 'i';
8110 info->flags = UFBXI_ARRAY_FLAG_RESULT;
8111 return true;
8112 } else if (name == ufbxi_Edges) {
8113 info->type = uc->opts.ignore_geometry ? '-' : 'i';
8114 return true;
8115 } else if (name == ufbxi_Indexes) {
8116 info->type = uc->opts.ignore_geometry ? '-' : 'i';
8117 info->flags = UFBXI_ARRAY_FLAG_RESULT;
8118 return true;
8119 } else if (name == ufbxi_Points) {
8120 info->type = uc->opts.ignore_geometry ? '-' : 'r';
8121 info->flags = UFBXI_ARRAY_FLAG_RESULT;
8122 return true;
8123 } else if (name == ufbxi_KnotVector) {
8124 info->type = uc->opts.ignore_geometry ? '-' : 'r';
8125 info->flags = UFBXI_ARRAY_FLAG_RESULT;
8126 return true;
8127 } else if (name == ufbxi_KnotVectorU) {
8128 info->type = uc->opts.ignore_geometry ? '-' : 'r';
8129 info->flags = UFBXI_ARRAY_FLAG_RESULT;
8130 return true;
8131 } else if (name == ufbxi_KnotVectorV) {
8132 info->type = uc->opts.ignore_geometry ? '-' : 'r';
8133 info->flags = UFBXI_ARRAY_FLAG_RESULT;
8134 return true;
8135 } else if (name == ufbxi_PointsIndex) {
8136 info->type = uc->opts.ignore_geometry ? '-' : 'i';
8137 info->flags = UFBXI_ARRAY_FLAG_RESULT;
8138 return true;
8139 } else if (name == ufbxi_Normals) {
8140 info->type = uc->opts.ignore_geometry ? '-' : 'r';
8141 info->flags = UFBXI_ARRAY_FLAG_RESULT | UFBXI_ARRAY_FLAG_PAD_BEGIN;
8142 return true;
8143 }
8144 break;
8145
8146 case UFBXI_PARSE_LEGACY_MODEL:
8147 if (name == ufbxi_Vertices) {
8148 info->type = uc->opts.ignore_geometry ? '-' : 'r';
8149 info->flags = UFBXI_ARRAY_FLAG_RESULT | UFBXI_ARRAY_FLAG_PAD_BEGIN;
8150 return true;
8151 } else if (name == ufbxi_Normals) {
8152 info->type = uc->opts.ignore_geometry ? '-' : 'r';
8153 info->flags = UFBXI_ARRAY_FLAG_RESULT | UFBXI_ARRAY_FLAG_PAD_BEGIN;
8154 return true;
8155 } else if (name == ufbxi_Materials) {
8156 info->type = uc->opts.ignore_geometry ? '-' : 'i';
8157 info->flags = UFBXI_ARRAY_FLAG_RESULT;
8158 return true;
8159 } else if (name == ufbxi_PolygonVertexIndex) {
8160 info->type = uc->opts.ignore_geometry ? '-' : 'i';
8161 info->flags = UFBXI_ARRAY_FLAG_RESULT;
8162 return true;
8163 } else if (name == ufbxi_Children) {
8164 info->type = 's';
8165 return true;
8166 }
8167 break;
8168
8169 case UFBXI_PARSE_ANIMATION_CURVE:
8170 if (name == ufbxi_KeyTime) {
8171 info->type = uc->opts.ignore_animation ? '-' : 'l';
8172 return true;
8173 } else if (name == ufbxi_KeyValueFloat) {
8174 info->type = uc->opts.ignore_animation ? '-' : 'r';
8175 return true;
8176 } else if (name == ufbxi_KeyAttrFlags) {
8177 info->type = uc->opts.ignore_animation ? '-' : 'i';
8178 return true;
8179 } else if (name == ufbxi_KeyAttrDataFloat) {
8180 // The float data in a keyframe attribute array is represented as integers
8181 // in versions >= 7200 as some of the elements aren't actually floats (!)
8182 info->type = uc->from_ascii && uc->version >= 7200 ? 'i' : 'f';
8183 if (uc->opts.ignore_animation) info->type = '-';
8184 if (uc->from_ascii && uc->version < 7200) {
8185 info->flags |= UFBXI_ARRAY_FLAG_ACCURATE_F32;
8186 }
8187 return true;
8188 } else if (name == ufbxi_KeyAttrRefCount) {
8189 info->type = uc->opts.ignore_animation ? '-' : 'i';
8190 return true;
8191 }
8192 break;
8193
8194 case UFBXI_PARSE_TEXTURE:
8195 if (!strcmp(name, "ModelUVTranslation") || !strcmp(name, "ModelUVScaling") || !strcmp(name, "Cropping")) {
8196 info->type = uc->opts.retain_dom ? 'r' : '-';
8197 return true;
8198 }
8199 break;
8200
8201 case UFBXI_PARSE_VIDEO:
8202 if (name == ufbxi_Content) {
8203 info->type = uc->opts.ignore_embedded ? '-' : 'C';
8204 return true;
8205 }
8206 break;
8207
8208 case UFBXI_PARSE_LAYERED_TEXTURE:
8209 if (name == ufbxi_BlendModes) {
8210 info->type = 'i';
8211 info->flags |= UFBXI_ARRAY_FLAG_TMP_BUF;
8212 return true;
8213 } else if (name == ufbxi_Alphas) {
8214 info->type = 'r';
8215 info->flags |= UFBXI_ARRAY_FLAG_TMP_BUF;
8216 return true;
8217 }
8218 break;
8219
8220 case UFBXI_PARSE_SELECTION_NODE:
8221 if (name == ufbxi_VertexIndexArray) {
8222 info->type = 'i';
8223 info->flags = UFBXI_ARRAY_FLAG_RESULT;
8224 return true;
8225 } else if (name == ufbxi_EdgeIndexArray) {
8226 info->type = 'i';
8227 info->flags = UFBXI_ARRAY_FLAG_RESULT;
8228 return true;
8229 } else if (name == ufbxi_PolygonIndexArray) {
8230 info->type = 'i';
8231 info->flags = UFBXI_ARRAY_FLAG_RESULT;
8232 return true;
8233 }
8234 break;
8235
8236 case UFBXI_PARSE_LAYER_ELEMENT_NORMAL:
8237 if (name == ufbxi_Normals) {
8238 info->type = uc->opts.ignore_geometry ? '-' : 'r';
8239 info->flags = UFBXI_ARRAY_FLAG_RESULT | UFBXI_ARRAY_FLAG_PAD_BEGIN;
8240 return true;
8241 } else if (name == ufbxi_NormalsIndex) {
8242 info->type = uc->opts.ignore_geometry ? '-' : 'i';
8243 info->flags = UFBXI_ARRAY_FLAG_RESULT;
8244 return true;
8245 } else if (name == ufbxi_NormalsW) {
8246 info->type = uc->retain_vertex_w ? 'r' : '-';
8247 info->flags = UFBXI_ARRAY_FLAG_RESULT | UFBXI_ARRAY_FLAG_PAD_BEGIN;
8248 return true;
8249 }
8250 break;
8251
8252 case UFBXI_PARSE_LAYER_ELEMENT_BINORMAL:
8253 if (name == ufbxi_Binormals) {
8254 info->type = uc->opts.ignore_geometry ? '-' : 'r';
8255 info->flags = UFBXI_ARRAY_FLAG_RESULT | UFBXI_ARRAY_FLAG_PAD_BEGIN;
8256 return true;
8257 } else if (name == ufbxi_BinormalsIndex) {
8258 info->type = uc->opts.ignore_geometry ? '-' : 'i';
8259 info->flags = UFBXI_ARRAY_FLAG_RESULT;
8260 return true;
8261 } else if (name == ufbxi_BinormalsW) {
8262 info->type = uc->retain_vertex_w ? 'r' : '-';
8263 info->flags = UFBXI_ARRAY_FLAG_RESULT | UFBXI_ARRAY_FLAG_PAD_BEGIN;
8264 return true;
8265 }
8266 break;
8267
8268 case UFBXI_PARSE_LAYER_ELEMENT_TANGENT:
8269 if (name == ufbxi_Tangents) {
8270 info->type = uc->opts.ignore_geometry ? '-' : 'r';
8271 info->flags = UFBXI_ARRAY_FLAG_RESULT | UFBXI_ARRAY_FLAG_PAD_BEGIN;
8272 return true;
8273 } else if (name == ufbxi_TangentsIndex) {
8274 info->type = uc->opts.ignore_geometry ? '-' : 'i';
8275 info->flags = UFBXI_ARRAY_FLAG_RESULT;
8276 return true;
8277 } else if (name == ufbxi_TangentsW) {
8278 info->type = uc->retain_vertex_w ? 'r' : '-';
8279 info->flags = UFBXI_ARRAY_FLAG_RESULT | UFBXI_ARRAY_FLAG_PAD_BEGIN;
8280 return true;
8281 }
8282 break;
8283
8284 case UFBXI_PARSE_LAYER_ELEMENT_UV:
8285 if (name == ufbxi_UV) {
8286 info->type = uc->opts.ignore_geometry ? '-' : 'r';
8287 info->flags = UFBXI_ARRAY_FLAG_RESULT | UFBXI_ARRAY_FLAG_PAD_BEGIN;
8288 return true;
8289 } else if (name == ufbxi_UVIndex) {
8290 info->type = uc->opts.ignore_geometry ? '-' : 'i';
8291 info->flags = UFBXI_ARRAY_FLAG_RESULT;
8292 return true;
8293 }
8294 break;
8295
8296 case UFBXI_PARSE_LAYER_ELEMENT_COLOR:
8297 if (name == ufbxi_Colors) {
8298 info->type = uc->opts.ignore_geometry ? '-' : 'r';
8299 info->flags = UFBXI_ARRAY_FLAG_RESULT | UFBXI_ARRAY_FLAG_PAD_BEGIN;
8300 return true;
8301 } else if (name == ufbxi_ColorIndex) {
8302 info->type = uc->opts.ignore_geometry ? '-' : 'i';
8303 info->flags = UFBXI_ARRAY_FLAG_RESULT;
8304 return true;
8305 }
8306 break;
8307
8308 case UFBXI_PARSE_LAYER_ELEMENT_VERTEX_CREASE:
8309 if (name == ufbxi_VertexCrease) {
8310 info->type = uc->opts.ignore_geometry ? '-' : 'r';
8311 info->flags = UFBXI_ARRAY_FLAG_RESULT | UFBXI_ARRAY_FLAG_PAD_BEGIN;
8312 return true;
8313 } else if (name == ufbxi_VertexCreaseIndex) {
8314 info->type = uc->opts.ignore_geometry ? '-' : 'i';
8315 info->flags = UFBXI_ARRAY_FLAG_RESULT;
8316 return true;
8317 }
8318 break;
8319
8320 case UFBXI_PARSE_LAYER_ELEMENT_EDGE_CREASE:
8321 if (name == ufbxi_EdgeCrease) {
8322 info->type = uc->opts.ignore_geometry ? '-' : 'r';
8323 info->flags = UFBXI_ARRAY_FLAG_RESULT;
8324 return true;
8325 }
8326 break;
8327
8328 case UFBXI_PARSE_LAYER_ELEMENT_SMOOTHING:
8329 if (name == ufbxi_Smoothing) {
8330 info->type = uc->opts.ignore_geometry ? '-' : 'b';
8331 info->flags = UFBXI_ARRAY_FLAG_RESULT;
8332 return true;
8333 }
8334 break;
8335
8336 case UFBXI_PARSE_LAYER_ELEMENT_VISIBILITY:
8337 if (name == ufbxi_Visibility) {
8338 info->type = uc->opts.ignore_geometry ? '-' : 'b';
8339 info->flags = UFBXI_ARRAY_FLAG_RESULT;
8340 return true;
8341 }
8342 break;
8343
8344 case UFBXI_PARSE_LAYER_ELEMENT_POLYGON_GROUP:
8345 if (name == ufbxi_PolygonGroup) {
8346 info->type = uc->opts.ignore_geometry ? '-' : 'i';
8347 info->flags = UFBXI_ARRAY_FLAG_RESULT;
8348 return true;
8349 }
8350 break;
8351
8352 case UFBXI_PARSE_LAYER_ELEMENT_HOLE:
8353 if (name == ufbxi_Hole) {
8354 info->type = uc->opts.ignore_geometry ? '-' : 'b';
8355 info->flags = UFBXI_ARRAY_FLAG_RESULT;
8356 return true;
8357 }
8358 break;
8359
8360 case UFBXI_PARSE_LAYER_ELEMENT_MATERIAL:
8361 if (name == ufbxi_Materials) {
8362 info->type = uc->opts.ignore_geometry ? '-' : 'i';
8363 info->flags = UFBXI_ARRAY_FLAG_RESULT;
8364 return true;
8365 }
8366 break;
8367
8368 case UFBXI_PARSE_LAYER_ELEMENT_OTHER:
8369 if (name == ufbxi_TextureId) {
8370 info->type = uc->opts.ignore_geometry ? '-' : 'i';
8371 info->flags |= UFBXI_ARRAY_FLAG_TMP_BUF;
8372 return true;
8373 } else if (name == ufbxi_UV) {
8374 info->type = uc->opts.retain_dom ? 'r' : '-';
8375 return true;
8376 } else if (name == ufbxi_UVIndex) {
8377 info->type = uc->opts.retain_dom ? 'i' : '-';
8378 return true;
8379 }
8380 break;
8381
8382 case UFBXI_PARSE_GEOMETRY_UV_INFO:
8383 if (name == ufbxi_TextureUV) {
8384 info->type = uc->opts.ignore_geometry ? '-' : 'r';
8385 info->flags = UFBXI_ARRAY_FLAG_RESULT | UFBXI_ARRAY_FLAG_PAD_BEGIN;
8386 return true;
8387 } else if (name == ufbxi_TextureUVVerticeIndex) {
8388 info->type = uc->opts.ignore_geometry ? '-' : 'i';
8389 info->flags = UFBXI_ARRAY_FLAG_RESULT | UFBXI_ARRAY_FLAG_PAD_BEGIN;
8390 return true;
8391 }
8392 break;
8393
8394 case UFBXI_PARSE_SHAPE:
8395 if (name == ufbxi_Indexes) {
8396 info->type = uc->opts.ignore_geometry ? '-' : 'i';
8397 info->flags = UFBXI_ARRAY_FLAG_RESULT;
8398 return true;
8399 }
8400 if (name == ufbxi_Vertices) {
8401 info->type = uc->opts.ignore_geometry ? '-' : 'r';
8402 info->flags = UFBXI_ARRAY_FLAG_RESULT | UFBXI_ARRAY_FLAG_PAD_BEGIN;
8403 return true;
8404 }
8405 if (name == ufbxi_Normals) {
8406 info->type = uc->opts.ignore_geometry ? '-' : 'r';
8407 info->flags = UFBXI_ARRAY_FLAG_RESULT | UFBXI_ARRAY_FLAG_PAD_BEGIN;
8408 return true;
8409 }
8410 break;
8411
8412 case UFBXI_PARSE_DEFORMER:
8413 if (name == ufbxi_Transform) {
8414 info->type = 'r';
8415 return true;
8416 } else if (name == ufbxi_TransformLink) {
8417 info->type = 'r';
8418 return true;
8419 } else if (name == ufbxi_Indexes) {
8420 info->type = uc->opts.ignore_geometry ? '-' : 'i';
8421 info->flags = UFBXI_ARRAY_FLAG_RESULT;
8422 return true;
8423 } else if (name == ufbxi_Weights) {
8424 info->type = uc->opts.ignore_geometry ? '-' : 'r';
8425 info->flags = UFBXI_ARRAY_FLAG_RESULT;
8426 return true;
8427 } else if (name == ufbxi_BlendWeights) {
8428 info->type = uc->opts.ignore_geometry ? '-' : 'r';
8429 info->flags = UFBXI_ARRAY_FLAG_RESULT;
8430 return true;
8431 } else if (name == ufbxi_FullWeights) {
8432 info->type = 'r';
8433 info->flags = (uint8_t)(info->flags | (uc->blender_full_weights ? UFBXI_ARRAY_FLAG_RESULT : UFBXI_ARRAY_FLAG_TMP_BUF));
8434 return true;
8435 } else if (!strcmp(name, "TransformAssociateModel")) {
8436 info->type = uc->opts.retain_dom ? 'r' : '-';
8437 return true;
8438 }
8439 break;
8440
8441 case UFBXI_PARSE_ASSOCIATE_MODEL:
8442 if (name == ufbxi_Transform) {
8443 info->type = uc->opts.retain_dom ? 'r' : '-';
8444 return true;
8445 }
8446 break;
8447
8448 case UFBXI_PARSE_LEGACY_LINK:
8449 if (name == ufbxi_Transform) {
8450 info->type = 'r';
8451 return true;
8452 } else if (name == ufbxi_TransformLink) {
8453 info->type = 'r';
8454 return true;
8455 } else if (name == ufbxi_Indexes) {
8456 info->type = uc->opts.ignore_geometry ? '-' : 'i';
8457 info->flags = UFBXI_ARRAY_FLAG_RESULT;
8458 return true;
8459 } else if (name == ufbxi_Weights) {
8460 info->type = uc->opts.ignore_geometry ? '-' : 'r';
8461 info->flags = UFBXI_ARRAY_FLAG_RESULT;
8462 return true;
8463 }
8464 break;
8465
8466 case UFBXI_PARSE_POSE_NODE:
8467 if (name == ufbxi_Matrix) {
8468 info->type = 'r';
8469 return true;
8470 }
8471 break;
8472
8473 case UFBXI_PARSE_CHANNEL:
8474 if (name == ufbxi_Key) {
8475 info->type = uc->opts.ignore_animation ? '-' : 'd';
8476 return true;
8477 }
8478 break;
8479
8480 case UFBXI_PARSE_AUDIO:
8481 if (name == ufbxi_Content) {
8482 info->type = uc->opts.ignore_embedded ? '-' : 'C';
8483 return true;
8484 }
8485 break;
8486
8487 default:
8488 if (name == ufbxi_BinaryData) {
8489 info->type = uc->opts.ignore_embedded ? '-' : 'C';
8490 return true;
8491 }
8492 break;
8493
8494 }
8495
8496 return false;
8497 }
8498
8499 static ufbxi_noinline bool ufbxi_is_raw_string(ufbxi_context *uc, ufbxi_parse_state parent, const char *name, size_t index)
8500 {
8501 (void)index;
8502
8503 switch (parent) {
8504
8505 case UFBXI_PARSE_ROOT:
8506 if (name == ufbxi_Model) return true;
8507 if (!strcmp(name, "FileId")) return true;
8508 break;
8509
8510 case UFBXI_PARSE_FBX_HEADER_EXTENSION:
8511 if (name == ufbxi_SceneInfo) return true;
8512 break;
8513
8514 case UFBXI_PARSE_OBJECTS:
8515 return true;
8516
8517 case UFBXI_PARSE_CONNECTIONS:
8518 case UFBXI_PARSE_RELATIONS:
8519 // Pre-7000 needs raw strings for "Name\x00\x01Type" pairs, post-7000 uses it only
8520 // for properties that are non-raw by default.
8521 return uc->version < 7000;
8522
8523 case UFBXI_PARSE_MODEL:
8524 if (name == ufbxi_NodeAttributeName) return true;
8525 if (name == ufbxi_Name) return true;
8526 break;
8527
8528 case UFBXI_PARSE_VIDEO:
8529 if (name == ufbxi_Content) return true;
8530 break;
8531
8532 case UFBXI_PARSE_TEXTURE:
8533 if (!strcmp(name, "TextureName")) return true;
8534 if (name == ufbxi_Media) return true;
8535 break;
8536
8537 case UFBXI_PARSE_GEOMETRY:
8538 if (name == ufbxi_NodeAttributeName) return true;
8539 if (name == ufbxi_Name) return true;
8540 break;
8541
8542 case UFBXI_PARSE_NODE_ATTRIBUTE:
8543 if (name == ufbxi_NodeAttributeName) return true;
8544 if (name == ufbxi_Name) return true;
8545 break;
8546
8547 case UFBXI_PARSE_POSE_NODE:
8548 if (name == ufbxi_Node) return true;
8549 break;
8550
8551 case UFBXI_PARSE_SELECTION_NODE:
8552 if (name == ufbxi_Node) return true;
8553 break;
8554
8555 case UFBXI_PARSE_UNKNOWN_OBJECT:
8556 if (name == ufbxi_NodeAttributeName) return true;
8557 if (name == ufbxi_Name) return true;
8558 break;
8559
8560 case UFBXI_PARSE_COLLECTION:
8561 if (!strcmp(name, "Member")) return true;
8562 break;
8563
8564 case UFBXI_PARSE_AUDIO:
8565 if (name == ufbxi_Content) return true;
8566 break;
8567
8568 case UFBXI_PARSE_LEGACY_MODEL:
8569 if (name == ufbxi_Material) return true;
8570 if (name == ufbxi_Link) return true;
8571 if (name == ufbxi_Name) return true;
8572 break;
8573
8574 case UFBXI_PARSE_LEGACY_SWITCHER:
8575 if (!strcmp(name, "CameraIndexName")) return true;
8576 break;
8577
8578 case UFBXI_PARSE_LEGACY_SCENE_PERSISTENCE:
8579 if (name == ufbxi_SceneInfo) return true;
8580 break;
8581
8582 case UFBXI_PARSE_REFERENCE:
8583 if (!strcmp(name, "Object")) return true;
8584 break;
8585
8586 case UFBXI_PARSE_TAKE:
8587 if (name == ufbxi_Model) return true;
8588 break;
8589
8590 default:
8591 break;
8592
8593 }
8594
8595 return false;
8596 }
8597
8598 // -- Binary parsing
8599
8600 ufbxi_nodiscard static ufbxi_noinline char *ufbxi_swap_endian(ufbxi_context *uc, const void *src, size_t count, size_t elem_size)
8601 {
8602 ufbxi_dev_assert(elem_size > 1);
8603 size_t total_size = count * elem_size;
8604 ufbxi_check_return(!ufbxi_does_overflow(total_size, count, elem_size), NULL);
8605 if (uc->swap_arr_size < total_size) {
8606 ufbxi_check_return(ufbxi_grow_array(&uc->ator_tmp, &uc->swap_arr, &uc->swap_arr_size, total_size), NULL);
8607 }
8608 char *dst = uc->swap_arr, *d = dst;
8609
8610 const char *s = (const char*)src;
8611 switch (elem_size) {
8612 case 2:
8613 ufbxi_nounroll for (size_t i = 0; i < count; i++) {
8614 d[0] = s[1]; d[1] = s[0];
8615 d += 2; s += 2;
8616 }
8617 break;
8618 case 4:
8619 ufbxi_nounroll for (size_t i = 0; i < count; i++) {
8620 d[0] = s[3]; d[1] = s[2]; d[2] = s[1]; d[3] = s[0];
8621 d += 4; s += 4;
8622 }
8623 break;
8624 case 8:
8625 ufbxi_nounroll for (size_t i = 0; i < count; i++) {
8626 d[0] = s[7]; d[1] = s[6]; d[2] = s[5]; d[3] = s[4];
8627 d[4] = s[3]; d[5] = s[2]; d[6] = s[1]; d[7] = s[0];
8628 d += 8; s += 8;
8629 }
8630 break;
8631 default:
8632 ufbxi_unreachable("Bad endian swap size");
8633 }
8634
8635 return dst;
8636 }
8637
8638 // Swap the endianness of an array typed with a lowercase letter
8639 ufbxi_nodiscard static ufbxi_noinline const char *ufbxi_swap_endian_array(ufbxi_context *uc, const void *src, size_t count, char type)
8640 {
8641 switch (type) {
8642 case 'i': case 'f': return ufbxi_swap_endian(uc, src, count, 4);
8643 case 'l': case 'd': return ufbxi_swap_endian(uc, src, count, 8);
8644 default: return (const char*)src;
8645 }
8646 }
8647
8648 // Swap the endianness of a single value (shallow, swaps string/array header words)
8649 ufbxi_nodiscard static ufbxi_noinline const char *ufbxi_swap_endian_value(ufbxi_context *uc, const void *src, char type)
8650 {
8651 switch (type) {
8652 case 'Y': return ufbxi_swap_endian(uc, src, 1, 2);
8653 case 'I': case 'F': return ufbxi_swap_endian(uc, src, 1, 4);
8654 case 'L': case 'D': return ufbxi_swap_endian(uc, src, 1, 8);
8655 case 'S': case 'R': return ufbxi_swap_endian(uc, src, 1, 4);
8656 case 'i': case 'l': case 'f': case 'd': case 'b': return ufbxi_swap_endian(uc, src, 3, 4);
8657 default: return (const char*)src;
8658 }
8659 }
8660
8661 // Read and convert a post-7000 FBX data array into a different format. `src_type` may be equal to `dst_type`
8662 // if the platform is not binary compatible with the FBX data representation.
8663 ufbxi_nodiscard static ufbxi_noinline int ufbxi_binary_convert_array(ufbxi_context *maybe_uc, char src_type, char dst_type, const void *src, void *dst, size_t size)
8664 {
8665 // TODO: We might want to use the slow path if the machine float/double doesn't match IEEE 754!
8666 // Convert commented out lines under some `#if UFBX_NON_IEE754` define or something.
8667 if (src_type == dst_type) {
8668 ufbx_assert(maybe_uc && maybe_uc->file_big_endian != maybe_uc->local_big_endian);
8669 src = ufbxi_swap_endian_array(maybe_uc, src, size, src_type);
8670 ufbxi_check_err(&maybe_uc->error, src);
8671 memcpy(dst, src, size * ufbxi_array_type_size(dst_type));
8672 return 1;
8673 }
8674
8675 if (maybe_uc && maybe_uc->file_big_endian) {
8676 src = ufbxi_swap_endian_array(maybe_uc, src, size, src_type);
8677 ufbxi_check_err(&maybe_uc->error, src);
8678 }
8679
8680 switch (dst_type)
8681 {
8682
8683 #define ufbxi_convert_loop_fast(m_dst, m_cast, m_size, m_expr) do { \
8684 const char *val = (const char*)src, *val_end = val + size*m_size; \
8685 m_dst *d = (m_dst*)dst; \
8686 while (val != val_end) { *d++ = m_cast(m_expr); val += m_size; } \
8687 } while (0)
8688
8689 #define ufbxi_convert_loop_slow(m_dst, m_cast, m_size, m_expr) do { \
8690 const char *val = (const char*)src, *val_end = val + size*m_size; \
8691 m_dst *d = (m_dst*)dst; \
8692 ufbxi_nounroll while (val != val_end) { *d++ = m_cast(m_expr); val += m_size; } \
8693 } while (0)
8694
8695 case 'c':
8696 switch (src_type) {
8697 // case 'c': ufbxi_convert_loop_fast(char, (char), 1, *val != 0); break;
8698 case 'i': ufbxi_convert_loop_slow(uint8_t, (uint8_t), 4, (uint8_t)ufbxi_read_i32(val)); break;
8699 case 'l': ufbxi_convert_loop_slow(uint8_t, (uint8_t), 8, (uint8_t)ufbxi_read_i64(val)); break;
8700 case 'f': ufbxi_convert_loop_slow(uint8_t, (uint8_t), 4, (uint8_t)ufbxi_read_f32(val)); break;
8701 case 'd': ufbxi_convert_loop_slow(uint8_t, (uint8_t), 8, (uint8_t)ufbxi_read_f64(val)); break;
8702 default: if (maybe_uc) ufbxi_fail_err(&maybe_uc->error, "Bad array source type"); return 0;
8703 }
8704 break;
8705
8706 case 'i':
8707 switch (src_type) {
8708 case 'c': ufbxi_convert_loop_slow(int32_t, (int32_t), 1, *val); break;
8709 // case 'i': ufbxi_convert_loop_slow(int32_t, (int32_t), 4, ufbxi_read_i32(val)); break;
8710 case 'l': ufbxi_convert_loop_slow(int32_t, (int32_t), 8, ufbxi_read_i64(val)); break;
8711 case 'f': ufbxi_convert_loop_slow(int32_t, ufbxi_f64_to_i32, 4, ufbxi_read_f32(val)); break;
8712 case 'd': ufbxi_convert_loop_slow(int32_t, ufbxi_f64_to_i32, 8, ufbxi_read_f64(val)); break;
8713 default: if (maybe_uc) ufbxi_fail_err(&maybe_uc->error, "Bad array source type"); return 0;
8714 }
8715 break;
8716
8717 case 'l':
8718 switch (src_type) {
8719 case 'c': ufbxi_convert_loop_slow(int64_t, (int64_t), 1, *val); break;
8720 case 'i': ufbxi_convert_loop_slow(int64_t, (int64_t), 4, ufbxi_read_i32(val)); break;
8721 // case 'l': ufbxi_convert_loop_slow(int64_t, (int64_t), 8, ufbxi_read_i64(val)); break;
8722 case 'f': ufbxi_convert_loop_slow(int64_t, ufbxi_f64_to_i64, 4, ufbxi_read_f32(val)); break;
8723 case 'd': ufbxi_convert_loop_slow(int64_t, ufbxi_f64_to_i64, 8, ufbxi_read_f64(val)); break;
8724 default: if (maybe_uc) ufbxi_fail_err(&maybe_uc->error, "Bad array source type"); return 0;
8725 }
8726 break;
8727
8728 case 'f':
8729 switch (src_type) {
8730 case 'c': ufbxi_convert_loop_slow(float, (float), 1, *val); break;
8731 case 'i': ufbxi_convert_loop_slow(float, (float), 4, ufbxi_read_i32(val)); break;
8732 case 'l': ufbxi_convert_loop_slow(float, (float), 8, ufbxi_read_i64(val)); break;
8733 // case 'f': ufbxi_convert_loop_slow(float, (float), 4, ufbxi_read_f32(val)); break;
8734 case 'd': ufbxi_convert_loop_fast(float, (float), 8, ufbxi_read_f64(val)); break;
8735 default: if (maybe_uc) ufbxi_fail_err(&maybe_uc->error, "Bad array source type"); return 0;
8736 }
8737 break;
8738
8739 case 'd':
8740 switch (src_type) {
8741 case 'c': ufbxi_convert_loop_slow(double, (double), 1, *val); break;
8742 case 'i': ufbxi_convert_loop_slow(double, (double), 4, ufbxi_read_i32(val)); break;
8743 case 'l': ufbxi_convert_loop_slow(double, (double), 8, ufbxi_read_i64(val)); break;
8744 case 'f': ufbxi_convert_loop_fast(double, (double), 4, ufbxi_read_f32(val)); break;
8745 // case 'd': ufbxi_convert_loop_slow(double, (double), 8, ufbxi_read_f64(val)); break;
8746 default: if (maybe_uc) ufbxi_fail_err(&maybe_uc->error, "Bad array source type"); return 0;
8747 }
8748 break;
8749
8750 default: return 0;
8751
8752 }
8753
8754 return 1;
8755 }
8756
8757 // Read pre-7000 separate properties as an array.
8758 ufbxi_nodiscard static ufbxi_noinline int ufbxi_binary_parse_multivalue_array(ufbxi_context *uc, char dst_type, void *dst, size_t size, ufbxi_buf *tmp_buf)
8759 {
8760 if (size == 0) return 1;
8761 const char *val;
8762 size_t val_size;
8763
8764 bool file_big_endian = uc->file_big_endian;
8765
8766 #define ufbxi_convert_parse_fast(m_dst, m_type, m_expr) do { \
8767 m_dst *d = (m_dst*)dst; \
8768 for (; base < size; base++) { \
8769 val = ufbxi_peek_bytes(uc, 13); \
8770 ufbxi_check(val); \
8771 if (*val != m_type) break; \
8772 val++; \
8773 *d++ = (m_dst)(m_expr); \
8774 ufbxi_consume_bytes(uc, 1 + sizeof(m_dst)); \
8775 } \
8776 } while (0)
8777
8778 // String array special case
8779 if (dst_type == 's' || dst_type == 'S' || dst_type == 'C') {
8780 bool raw = dst_type == 's';
8781 ufbx_string *d = (ufbx_string*)dst;
8782 for (size_t i = 0; i < size; i++) {
8783 val = ufbxi_peek_bytes(uc, 13);
8784 ufbxi_check(val);
8785 char type = *val++;
8786 ufbxi_check(type == 'S' || type == 'R');
8787 if (file_big_endian) {
8788 val = ufbxi_swap_endian_value(uc, val, type);
8789 ufbxi_check(val);
8790 }
8791 size_t len = ufbxi_read_u32(val);
8792 ufbxi_consume_bytes(uc, 5);
8793 d->data = ufbxi_read_bytes(uc, len);
8794 d->length = len;
8795 ufbxi_check(d->data);
8796 if (dst_type == 'C') {
8797 ufbxi_buf *buf = size == 1 || uc->opts.retain_dom ? &uc->result : tmp_buf;
8798 d->data = ufbxi_push_copy(buf, char, len, d->data);
8799 ufbxi_check(d->data);
8800 } else {
8801 ufbxi_check(ufbxi_push_string_place_str(&uc->string_pool, d, raw));
8802 }
8803 d++;
8804 }
8805 return 1;
8806 }
8807
8808 // Optimize a couple of common cases
8809 size_t base = 0;
8810 if (!file_big_endian) {
8811 switch (dst_type) {
8812 case 'i': ufbxi_convert_parse_fast(int32_t, 'I', ufbxi_read_i32(val)); break;
8813 case 'l': ufbxi_convert_parse_fast(int64_t, 'L', ufbxi_read_i64(val)); break;
8814 case 'f': ufbxi_convert_parse_fast(float, 'F', ufbxi_read_f32(val)); break;
8815 case 'd': ufbxi_convert_parse_fast(double, 'D', ufbxi_read_f64(val)); break;
8816 default: break; // Fallthrough to rest
8817 }
8818
8819 // Early return if we handled everything
8820 if (base == size) return 1;
8821 }
8822
8823 switch (dst_type)
8824 {
8825
8826 #define ufbxi_convert_parse(m_cast, m_size, m_expr) \
8827 *d++ = m_cast(m_expr); val_size = m_size + 1; \
8828
8829 #define ufbxi_convert_parse_switch(m_dst, m_cast_int, m_cast_float) do { \
8830 m_dst *d = (m_dst*)dst + base; \
8831 for (size_t i = base; i < size; i++) { \
8832 val = ufbxi_peek_bytes(uc, 13); \
8833 ufbxi_check(val); \
8834 char type = *val++; \
8835 if (file_big_endian) { \
8836 val = ufbxi_swap_endian_value(uc, val, type); \
8837 ufbxi_check(val); \
8838 } \
8839 switch (type) { \
8840 case 'C': \
8841 case 'B': ufbxi_convert_parse(m_cast_int, 1, *val); break; \
8842 case 'Y': ufbxi_convert_parse(m_cast_int, 2, ufbxi_read_i16(val)); break; \
8843 case 'I': ufbxi_convert_parse(m_cast_int, 4, ufbxi_read_i32(val)); break; \
8844 case 'L': ufbxi_convert_parse(m_cast_int, 8, ufbxi_read_i64(val)); break; \
8845 case 'F': ufbxi_convert_parse(m_cast_float, 4, ufbxi_read_f32(val)); break; \
8846 case 'D': ufbxi_convert_parse(m_cast_float, 8, ufbxi_read_f64(val)); break; \
8847 default: ufbxi_fail("Bad multivalue array type"); \
8848 } \
8849 ufbxi_consume_bytes(uc, val_size); \
8850 } \
8851 } while (0)
8852
8853 case 'c': ufbxi_convert_parse_switch(uint8_t, (uint8_t), (uint8_t)); break;
8854 case 'i': ufbxi_convert_parse_switch(int32_t, (int32_t), ufbxi_f64_to_i32); break;
8855 case 'l': ufbxi_convert_parse_switch(int64_t, (int64_t), ufbxi_f64_to_i64); break;
8856 case 'f': ufbxi_convert_parse_switch(float, (float), (float)); break;
8857 case 'd': ufbxi_convert_parse_switch(double, (double), (double)); break;
8858
8859 default: return 0;
8860
8861 }
8862
8863 return 1;
8864 }
8865
8866 ufbxi_nodiscard ufbxi_noinline static void *ufbxi_push_array_data(ufbxi_context *uc, const ufbxi_array_info *info, size_t size, ufbxi_buf *tmp_buf)
8867 {
8868 size_t elem_size = ufbxi_array_type_size(info->type);
8869 uint32_t flags = info->flags;
8870 if (flags & UFBXI_ARRAY_FLAG_PAD_BEGIN) size += 4;
8871
8872 // The array may be pushed either to the result or temporary buffer depending
8873 // if it's already in the right format
8874 ufbxi_buf *arr_buf = tmp_buf;
8875 if (flags & UFBXI_ARRAY_FLAG_RESULT) arr_buf = &uc->result;
8876 else if (flags & UFBXI_ARRAY_FLAG_TMP_BUF) arr_buf = &uc->tmp;
8877 char *data = (char*)ufbxi_push_size(arr_buf, elem_size, size);
8878 ufbxi_check_return(data, NULL);
8879
8880 if (flags & UFBXI_ARRAY_FLAG_PAD_BEGIN) {
8881 memset(data, 0, elem_size * 4);
8882 data += elem_size * 4;
8883 }
8884
8885 return data;
8886 }
8887
8888 ufbxi_noinline static void ufbxi_postprocess_bool_array(char *data, size_t size)
8889 {
8890 ufbxi_for(char, b, (char*)data, size) {
8891 *b = (char)(*b != 0);
8892 }
8893 }
8894
8895 typedef struct {
8896 size_t encoded_size;
8897 size_t src_elem_size;
8898 size_t array_size;
8899 char src_type;
8900 char dst_type;
8901 char arr_type;
8902 const void *encoded_data;
8903 void *decoded_data;
8904 void *dst_data;
8905 ufbx_inflate_retain *inflate_retain;
8906 } ufbxi_deflate_task;
8907
8908 static bool ufbxi_deflate_task_fn(ufbxi_task *task)
8909 {
8910 ufbxi_deflate_task *t = (ufbxi_deflate_task*)task->data;
8911
8912 ufbx_inflate_input input; // ufbxi_uninit
8913 input.total_size = t->encoded_size;
8914 input.data = t->encoded_data;
8915 input.data_size = t->encoded_size;
8916 input.no_header = false;
8917 input.no_checksum = false;
8918 input.internal_fast_bits = 0;
8919 input.progress_cb.fn = NULL;
8920 input.progress_cb.user = NULL;
8921 input.progress_size_before = 0;
8922 input.progress_size_after = 0;
8923 input.progress_interval_hint = 0;
8924 input.buffer = NULL;
8925 input.buffer_size = 0;
8926 input.read_fn = NULL;
8927 input.read_user = NULL;
8928
8929 size_t decoded_data_size = t->src_elem_size * t->array_size;
8930 ptrdiff_t res = ufbx_inflate(t->decoded_data, decoded_data_size, &input, t->inflate_retain);
8931 if (res == -28) {
8932 task->error = "Cancelled";
8933 return false;
8934 } else if (res != (ptrdiff_t)decoded_data_size) {
8935 task->error = "Bad DEFLATE data";
8936 return false;
8937 }
8938
8939 if (t->decoded_data != t->dst_data) {
8940 int ok = ufbxi_binary_convert_array(NULL, t->src_type, t->dst_type, t->decoded_data, t->dst_data, t->array_size);
8941 if (!ok) {
8942 task->error = "Failed to convert array";
8943 return false;
8944 }
8945 }
8946
8947 if (t->arr_type == 'b') {
8948 ufbxi_postprocess_bool_array((char*)t->dst_data, t->array_size);
8949 }
8950
8951 return true;
8952 }
8953
8954 // Recursion limited by check at the start
8955 ufbxi_nodiscard ufbxi_noinline static int ufbxi_binary_parse_node(ufbxi_context *uc, uint32_t depth, ufbxi_parse_state parent_state, bool *p_end, ufbxi_buf *tmp_buf, bool recursive)
8956 ufbxi_recursive_function(int, ufbxi_binary_parse_node, (uc, depth, parent_state, p_end, tmp_buf, recursive), UFBXI_MAX_NODE_DEPTH + 1,
8957 (ufbxi_context *uc, uint32_t depth, ufbxi_parse_state parent_state, bool *p_end, ufbxi_buf *tmp_buf, bool recursive))
8958 {
8959 // https://code.blender.org/2013/08/fbx-binary-file-format-specification
8960 // Parse an FBX document node in the binary format
8961 ufbxi_check(depth < UFBXI_MAX_NODE_DEPTH);
8962
8963 // Parse the node header, post-7500 versions use 64-bit values for most
8964 // header fields.
8965 uint64_t end_offset, num_values64, values_len;
8966 uint8_t name_len;
8967 size_t header_size = (uc->version >= 7500) ? 25 : 13;
8968 const char *header = ufbxi_read_bytes(uc, header_size), *header_words = header;
8969 ufbxi_check(header);
8970 if (uc->version >= 7500) {
8971 if (uc->file_big_endian) {
8972 header_words = ufbxi_swap_endian(uc, header_words, 3, 8);
8973 ufbxi_check(header_words);
8974 }
8975 end_offset = ufbxi_read_u64(header_words + 0);
8976 num_values64 = ufbxi_read_u64(header_words + 8);
8977 values_len = ufbxi_read_u64(header_words + 16);
8978 name_len = ufbxi_read_u8(header + 24);
8979 } else {
8980 if (uc->file_big_endian) {
8981 header_words = ufbxi_swap_endian(uc, header_words, 3, 4);
8982 ufbxi_check(header_words);
8983 }
8984 end_offset = ufbxi_read_u32(header_words + 0);
8985 num_values64 = ufbxi_read_u32(header_words + 4);
8986 values_len = ufbxi_read_u32(header_words + 8);
8987 name_len = ufbxi_read_u8(header + 12);
8988 }
8989
8990 ufbxi_check(num_values64 <= UINT32_MAX);
8991 uint32_t num_values = (uint32_t)num_values64;
8992
8993 // If `end_offset` and `name_len` is zero we treat as the node as a NULL-sentinel
8994 // that terminates a node list.
8995 if (end_offset == 0 && name_len == 0) {
8996 *p_end = true;
8997 return 1;
8998 }
8999
9000 // Update estimated end offset if possible
9001 if (end_offset > uc->progress_bytes_total) {
9002 uc->progress_bytes_total = end_offset;
9003 }
9004
9005 // Push the parsed node into the `tmp_stack` buffer, the nodes will be popped by
9006 // calling code after its done parsing all of it's children.
9007 ufbxi_node *node = ufbxi_push_zero(&uc->tmp_stack, ufbxi_node, 1);
9008 ufbxi_check(node);
9009
9010 // Parse and intern the name to the string pool.
9011 const char *name = ufbxi_read_bytes(uc, name_len);
9012 ufbxi_check(name);
9013 name = ufbxi_push_string(&uc->string_pool, name, name_len, NULL, true);
9014 ufbxi_check(name);
9015 node->name_len = name_len;
9016 node->name = name;
9017
9018 uint64_t values_end_offset = ufbxi_get_read_offset(uc) + values_len;
9019
9020 // Check if the values of the node we're parsing currently should be
9021 // treated as an array.
9022 ufbxi_array_info arr_info;
9023 if (ufbxi_is_array_node(uc, parent_state, name, &arr_info)) {
9024
9025 // Normalize the array type (eg. 'r' to 'f'/'d' depending on the build)
9026 // and get the per-element size of the array.
9027 // Boolean arrays 'b' are normalized to 'c' as they are postprocessed
9028 // below based on `arr_info.type`.
9029 char dst_type = ufbxi_normalize_array_type(arr_info.type, 'c');
9030
9031 ufbxi_value_array *arr = ufbxi_push(tmp_buf, ufbxi_value_array, 1);
9032 ufbxi_check(arr);
9033
9034 node->value_type_mask = UFBXI_VALUE_ARRAY;
9035 node->array = arr;
9036 arr->type = ufbxi_normalize_array_type(arr_info.type, 'b');
9037
9038 // Peek the first bytes of the array. We can always look at least 13 bytes
9039 // ahead safely as valid FBX files must end in a 13/25 byte NULL record.
9040 const char *data = ufbxi_peek_bytes(uc, 13);
9041 ufbxi_check(data);
9042
9043 // Check if the data type is one of the explicit array types (post-7000).
9044 // Otherwise we form the array by concatenating all the normal values of the
9045 // node (pre-7000)
9046 char c = data[0];
9047
9048 // HACK: Override the "type" if either the array is empty or we want to
9049 // specifically ignore the contents.
9050 if (num_values == 0) c = '0';
9051 if (dst_type == '-') c = '-';
9052
9053 bool deferred = false;
9054
9055 if (c=='c' || c=='b' || c=='i' || c=='l' || c =='f' || c=='d') {
9056
9057 const char *arr_words = data + 1;
9058 if (uc->file_big_endian) {
9059 arr_words = ufbxi_swap_endian(uc, arr_words, 3, 4);
9060 ufbxi_check(arr_words);
9061 }
9062
9063 // Parse the array header from the prefix we already peeked above.
9064 char src_type = data[0];
9065 uint32_t size = ufbxi_read_u32(arr_words + 0);
9066 uint32_t encoding = ufbxi_read_u32(arr_words + 4);
9067 uint32_t encoded_size = ufbxi_read_u32(arr_words + 8);
9068 ufbxi_consume_bytes(uc, 13);
9069
9070 // Normalize the source type as well, but don't convert UFBX-specific
9071 // 'r' to 'f'/'d', but fail later instead.
9072 if (src_type != 'r') src_type = ufbxi_normalize_array_type(src_type, 'c');
9073 size_t src_elem_size = ufbxi_array_type_size(src_type);
9074 size_t decoded_data_size = src_elem_size * size;
9075
9076 // Allocate `size` elements for the array.
9077 char *arr_data = (char*)ufbxi_push_array_data(uc, &arr_info, size, tmp_buf);
9078 ufbxi_check(arr_data);
9079
9080 uint64_t arr_begin = ufbxi_get_read_offset(uc);
9081 ufbxi_check(UINT64_MAX - encoded_size > arr_begin);
9082 uint64_t arr_end = arr_begin + encoded_size;
9083 if (arr_end > uc->progress_bytes_total) {
9084 uc->progress_bytes_total = arr_end;
9085 }
9086
9087 // Threading
9088 if (uc->parse_threaded && encoding == 1 && encoded_size >= UFBXI_MIN_THREADED_DEFLATE_BYTES && !uc->file_big_endian && !uc->local_big_endian) {
9089 ufbxi_task *task = ufbxi_thread_pool_create_task(&uc->thread_pool, &ufbxi_deflate_task_fn);
9090 if (task) {
9091 ufbxi_deflate_task *t = ufbxi_push_zero(tmp_buf, ufbxi_deflate_task, 1);
9092 ufbxi_check(t);
9093
9094 ufbxi_inflate_init_retain(uc->inflate_retain);
9095
9096 t->src_elem_size = src_elem_size;
9097 t->encoded_size = encoded_size;
9098 t->array_size = size;
9099 t->src_type = src_type;
9100 t->dst_type = dst_type;
9101 t->arr_type = arr->type;
9102 t->dst_data = arr_data;
9103 t->inflate_retain = uc->inflate_retain;
9104
9105 if (!uc->read_fn) {
9106 // From memory, no need to copy
9107 t->encoded_data = uc->data;
9108 } else {
9109 void *encoded_data = ufbxi_push(tmp_buf, char, encoded_size);
9110 ufbxi_check(encoded_data);
9111 ufbxi_check(ufbxi_read_to(uc, encoded_data, encoded_size));
9112 t->encoded_data = encoded_data;
9113 }
9114
9115 if (src_type != dst_type) {
9116 t->decoded_data = ufbxi_push_size(tmp_buf, src_elem_size, size);
9117 ufbxi_check(t->decoded_data);
9118 } else {
9119 t->decoded_data = arr_data;
9120 }
9121
9122 task->data = t;
9123 ufbxi_thread_pool_run_task(&uc->thread_pool, task);
9124 deferred = true;
9125 }
9126 }
9127
9128 // If the source and destination types are equal and our build is binary-compatible
9129 // with the FBX format we can read the decoded data directly into the array buffer.
9130 // Otherwise we need a temporary buffer to decode the array into before conversion.
9131 void *decoded_data = arr_data;
9132 if (!deferred && (src_type != dst_type || uc->local_big_endian != uc->file_big_endian)) {
9133 ufbxi_check(ufbxi_grow_array(&uc->ator_tmp, &uc->tmp_arr, &uc->tmp_arr_size, decoded_data_size));
9134 decoded_data = uc->tmp_arr;
9135 }
9136
9137 if (deferred) {
9138 // Nop
9139 } else if (encoding == 0) {
9140 // Encoding 0: Plain binary data.
9141 ufbxi_check(encoded_size == decoded_data_size);
9142
9143 // If the array is contained in the current read buffer and we need to convert
9144 // the data anyway we can use the read buffer as the decoded array source, otherwise
9145 // do a plain byte copy to the array/conversion buffer.
9146 if (uc->yield_size + uc->data_size >= encoded_size && decoded_data != arr_data) {
9147 // Yield right after this if we crossed the yield threshold
9148 if (encoded_size > uc->yield_size) {
9149 uc->data_size += uc->yield_size;
9150 uc->yield_size = encoded_size;
9151 uc->data_size -= uc->yield_size;
9152 }
9153
9154 decoded_data = (void*)uc->data;
9155 ufbxi_consume_bytes(uc, encoded_size);
9156 } else {
9157 ufbxi_check(ufbxi_read_to(uc, decoded_data, encoded_size));
9158 }
9159 } else if (encoding == 1) {
9160 // Encoding 1: DEFLATE
9161
9162 ufbxi_pause_progress(uc);
9163
9164 // Inflate the data from the user-provided IO buffer / read callbacks
9165 ufbx_inflate_input input;
9166 input.total_size = encoded_size;
9167 input.data = uc->data;
9168 input.data_size = uc->data_size;
9169 input.no_header = false;
9170 input.no_checksum = false;
9171 input.internal_fast_bits = 0;
9172
9173 if (uc->opts.progress_cb.fn) {
9174 input.progress_cb = uc->opts.progress_cb;
9175 input.progress_size_before = arr_begin;
9176 input.progress_size_after = uc->progress_bytes_total - arr_end;
9177 input.progress_interval_hint = uc->progress_interval;
9178 } else {
9179 input.progress_cb.fn = NULL;
9180 input.progress_cb.user = NULL;
9181 input.progress_size_before = 0;
9182 input.progress_size_after = 0;
9183 input.progress_interval_hint = 0;
9184 }
9185
9186 // If the encoded array is larger than the data we have currently buffered
9187 // we need to allow `ufbx_inflate()` to read from the IO callback. We can
9188 // let `ufbx_inflate()` freely clobber our `read_buffer` as all the data
9189 // in the buffer will be consumed. `ufbx_inflate()` always reads exactly
9190 // the amount of bytes needed so we can continue reading from `read_fn` as
9191 // usual (given that we clear the `uc->data/_size` buffer below).
9192 // NOTE: We _cannot_ share `read_buffer` if we plan to read later from it
9193 // as `ufbx_inflate()` overwrites parts of it with zeroes.
9194 if (encoded_size > input.data_size) {
9195 input.buffer = uc->read_buffer;
9196 input.buffer_size = uc->read_buffer_size;
9197 input.read_fn = uc->read_fn;
9198 input.read_user = uc->read_user;
9199 uc->data_offset += encoded_size - input.data_size;
9200 uc->data += input.data_size;
9201 uc->data_size = 0;
9202 } else {
9203 input.buffer = NULL;
9204 input.buffer_size = 0;
9205 input.read_fn = NULL;
9206 input.read_user = NULL;
9207 uc->data += encoded_size;
9208 uc->data_size -= encoded_size;
9209 ufbxi_check(ufbxi_resume_progress(uc));
9210 }
9211
9212 ptrdiff_t res = ufbx_inflate(decoded_data, decoded_data_size, &input, uc->inflate_retain);
9213 ufbxi_check_msg(res != -28, "Cancelled");
9214 ufbxi_check_msg(res == (ptrdiff_t)decoded_data_size, "Bad DEFLATE data");
9215
9216 } else {
9217 ufbxi_fail("Bad array encoding");
9218 }
9219
9220 // Convert the decoded array if necessary.
9221 if (!deferred && decoded_data != arr_data) {
9222 ufbxi_check(ufbxi_binary_convert_array(uc, src_type, dst_type, decoded_data, arr_data, size));
9223 }
9224
9225 arr->data = arr_data;
9226 arr->size = size;
9227
9228 } else if (c == '0' || c == '-') {
9229 // Ignore the array
9230 arr->type = c == '-' ? '-' : dst_type;
9231 arr->data = (char*)ufbxi_zero_size_buffer + 32;
9232 arr->size = 0;
9233 } else {
9234 // Allocate `num_values` elements for the array and parse single values into it.
9235 char *arr_data = (char*)ufbxi_push_array_data(uc, &arr_info, num_values, tmp_buf);
9236 ufbxi_check(arr_data);
9237 ufbxi_check(ufbxi_binary_parse_multivalue_array(uc, dst_type, arr_data, num_values, tmp_buf));
9238 arr->data = arr_data;
9239 arr->size = num_values;
9240 }
9241
9242 // Post-process boolean arrays
9243 if (!deferred && arr_info.type == 'b') {
9244 ufbxi_postprocess_bool_array((char*)arr->data, arr->size);
9245 }
9246
9247 } else {
9248 // Parse up to UFBXI_MAX_NON_ARRAY_VALUES as plain values
9249 num_values = ufbxi_min32(num_values, UFBXI_MAX_NON_ARRAY_VALUES);
9250 ufbxi_value *vals = ufbxi_push(tmp_buf, ufbxi_value, num_values);
9251 ufbxi_check(vals);
9252 node->vals = vals;
9253
9254 uint32_t type_mask = 0;
9255 for (size_t i = 0; i < (size_t)num_values; i++) {
9256 // The file must end in a 13/25 byte NULL record, so we can peek
9257 // up to 13 bytes safely here.
9258 const char *data = ufbxi_peek_bytes(uc, 13);
9259 ufbxi_check(data);
9260
9261 const char *value = data + 1;
9262
9263 char type = data[0];
9264 if (uc->file_big_endian) {
9265 value = ufbxi_swap_endian_value(uc, value, type);
9266 ufbxi_check(value);
9267 }
9268
9269 switch (type) {
9270
9271 case 'C': case 'B': case 'Z':
9272 type_mask |= (uint32_t)UFBXI_VALUE_NUMBER << (i*2);
9273 vals[i].f = (double)(vals[i].i = (int64_t)(uint8_t)value[0]);
9274 ufbxi_consume_bytes(uc, 2);
9275 break;
9276
9277 case 'Y':
9278 type_mask |= (uint32_t)UFBXI_VALUE_NUMBER << (i*2);
9279 vals[i].f = (double)(vals[i].i = ufbxi_read_i16(value));
9280 ufbxi_consume_bytes(uc, 3);
9281 break;
9282
9283 case 'I':
9284 type_mask |= (uint32_t)UFBXI_VALUE_NUMBER << (i*2);
9285 vals[i].f = (double)(vals[i].i = ufbxi_read_i32(value));
9286 ufbxi_consume_bytes(uc, 5);
9287 break;
9288
9289 case 'L':
9290 type_mask |= (uint32_t)UFBXI_VALUE_NUMBER << (i*2);
9291 vals[i].f = (double)(vals[i].i = ufbxi_read_i64(value));
9292 ufbxi_consume_bytes(uc, 9);
9293 break;
9294
9295 case 'F':
9296 type_mask |= (uint32_t)UFBXI_VALUE_NUMBER << (i*2);
9297 vals[i].i = ufbxi_f64_to_i64(vals[i].f = ufbxi_read_f32(value));
9298 ufbxi_consume_bytes(uc, 5);
9299 break;
9300
9301 case 'D':
9302 type_mask |= (uint32_t)UFBXI_VALUE_NUMBER << (i*2);
9303 vals[i].i = ufbxi_f64_to_i64(vals[i].f = ufbxi_read_f64(value));
9304 ufbxi_consume_bytes(uc, 9);
9305 break;
9306
9307 case 'S': case 'R':
9308 {
9309 uint32_t length = ufbxi_read_u32(value);
9310 ufbxi_consume_bytes(uc, 5);
9311 const char *str = ufbxi_read_bytes(uc, length);
9312 ufbxi_check(str);
9313
9314 if (length == 0) {
9315 vals[i].s.raw_data = ufbxi_empty_char;
9316 vals[i].s.raw_length = 0;
9317 vals[i].s.utf8_length = 0;
9318 } else {
9319 bool non_ascii = false;
9320 uint32_t hash = ufbxi_hash_string_check_ascii(str, length, &non_ascii);
9321 bool raw = !non_ascii || ufbxi_is_raw_string(uc, parent_state, name, i);
9322 ufbxi_check(ufbxi_push_sanitized_string(&uc->string_pool, &vals[i].s, str, length, hash, raw));
9323
9324 // Mark the data as invalid UTF-8
9325 if (non_ascii && raw) vals[i].s.utf8_length = UINT32_MAX;
9326 }
9327
9328 type_mask |= (uint32_t)UFBXI_VALUE_STRING << (i*2);
9329 }
9330 break;
9331
9332 // Treat arrays as non-values and skip them
9333 case 'c': case 'b': case 'i': case 'l': case 'f': case 'd':
9334 {
9335 uint32_t encoded_size = ufbxi_read_u32(value + 8);
9336 ufbxi_consume_bytes(uc, 13);
9337 ufbxi_check(ufbxi_skip_bytes(uc, encoded_size));
9338 }
9339 break;
9340
9341 default:
9342 ufbxi_fail("Bad value type");
9343
9344 }
9345 }
9346
9347 node->value_type_mask = (uint16_t)type_mask;
9348 }
9349
9350 // Skip over remaining values if necessary if we for example truncated
9351 // the list of values or if there are values after an array
9352 uint64_t offset = ufbxi_get_read_offset(uc);
9353 ufbxi_check(offset <= values_end_offset);
9354 if (offset < values_end_offset) {
9355 ufbxi_check(ufbxi_skip_bytes(uc, values_end_offset - offset));
9356 }
9357
9358 if (recursive) {
9359 // Recursively parse the children of this node. Update the parse state
9360 // to provide context for child node parsing.
9361 ufbxi_parse_state parse_state = ufbxi_update_parse_state(parent_state, node->name);
9362 uint32_t num_children = 0;
9363 for (;;) {
9364 // Stop at end offset
9365 uint64_t current_offset = ufbxi_get_read_offset(uc);
9366 if (current_offset >= end_offset) {
9367 ufbxi_check(current_offset == end_offset || end_offset == 0);
9368 break;
9369 }
9370
9371 bool end = false;
9372 ufbxi_check(ufbxi_binary_parse_node(uc, depth + 1, parse_state, &end, tmp_buf, true));
9373 if (end) break;
9374 num_children++;
9375 }
9376
9377 // Pop children from `tmp_stack` to a contiguous array
9378 node->num_children = num_children;
9379 if (num_children > 0) {
9380 node->children = ufbxi_push_pop(tmp_buf, &uc->tmp_stack, ufbxi_node, num_children);
9381 ufbxi_check(node->children);
9382 }
9383 } else {
9384 uint64_t current_offset = ufbxi_get_read_offset(uc);
9385 uc->has_next_child = (current_offset < end_offset);
9386 }
9387
9388 return 1;
9389 }
9390
9391 #define UFBXI_BINARY_MAGIC_SIZE 22
9392 #define UFBXI_BINARY_HEADER_SIZE 27
9393 static const char ufbxi_binary_magic[] = "Kaydara FBX Binary \x00\x1a";
9394
9395 // -- ASCII parsing
9396
9397 #define UFBXI_ASCII_END '\0'
9398 #define UFBXI_ASCII_NAME 'N'
9399 #define UFBXI_ASCII_BARE_WORD 'B'
9400 #define UFBXI_ASCII_INT 'I'
9401 #define UFBXI_ASCII_FLOAT 'F'
9402 #define UFBXI_ASCII_STRING 'S'
9403
9404 static ufbxi_noinline char ufbxi_ascii_refill(ufbxi_context *uc)
9405 {
9406 ufbxi_ascii *ua = &uc->ascii;
9407 uc->data_offset += ufbxi_to_size(ua->src - uc->data_begin);
9408 if (uc->read_fn) {
9409 char *dst_buffer = NULL;
9410 size_t dst_size = 0;
9411
9412 if (ua->retain_buf != NULL) {
9413 dst_size = uc->opts.read_buffer_size;
9414 dst_buffer = ufbxi_push(ua->retain_buf, char, dst_size);
9415 ufbxi_check_return(dst_buffer, '\0');
9416 ua->src_is_retained = true;
9417 ua->src_buf = ua->retain_buf;
9418 } else {
9419 // Grow the read buffer if necessary
9420 if (uc->read_buffer_size < uc->opts.read_buffer_size) {
9421 size_t new_size = uc->opts.read_buffer_size;
9422 ufbxi_check_return(ufbxi_grow_array(&uc->ator_tmp, &uc->read_buffer, &uc->read_buffer_size, new_size), '\0');
9423 }
9424 dst_buffer = uc->read_buffer;
9425 dst_size = uc->read_buffer_size;
9426 ua->src_is_retained = false;
9427 ua->src_buf = NULL;
9428 }
9429
9430 // Read user data, return '\0' on EOF
9431 // TODO: Very unoptimal for non-full-size reads in some cases
9432 size_t num_read = uc->read_fn(uc->read_user, dst_buffer, dst_size);
9433 ufbxi_check_return_msg(num_read != SIZE_MAX, '\0', "IO error");
9434 ufbxi_check_return(num_read <= dst_size, '\0');
9435 if (num_read == 0) return '\0';
9436
9437 uc->data = uc->data_begin = ua->src = dst_buffer;
9438 ua->src_end = dst_buffer + num_read;
9439 return *ua->src;
9440 } else {
9441 // If the user didn't specify a `read_fn()` treat anything
9442 // past the initial data buffer as EOF.
9443 uc->data = uc->data_begin = ua->src = "";
9444 ua->src_end = ua->src + 1;
9445 return '\0';
9446 }
9447 }
9448
9449 static ufbxi_noinline char ufbxi_ascii_yield(ufbxi_context *uc)
9450 {
9451 ufbxi_ascii *ua = &uc->ascii;
9452
9453 char ret;
9454 if (ua->src == ua->src_end) {
9455 ret = ufbxi_ascii_refill(uc);
9456 } else {
9457 ret = *ua->src;
9458 }
9459
9460 if (ufbxi_to_size(ua->src_end - ua->src) < uc->progress_interval) {
9461 ua->src_yield = ua->src_end;
9462 } else {
9463 ua->src_yield = ua->src + uc->progress_interval;
9464 }
9465
9466 // TODO: Unify these properly
9467 uc->data = ua->src;
9468 ufbxi_check_return(ufbxi_report_progress(uc), '\0');
9469 return ret;
9470 }
9471
9472 static ufbxi_forceinline char ufbxi_ascii_peek(ufbxi_context *uc)
9473 {
9474 ufbxi_ascii *ua = &uc->ascii;
9475 if (ua->src == ua->src_yield) return ufbxi_ascii_yield(uc);
9476 return *ua->src;
9477 }
9478
9479 static ufbxi_forceinline char ufbxi_ascii_next(ufbxi_context *uc)
9480 {
9481 ufbxi_ascii *ua = &uc->ascii;
9482 if (ua->src == ua->src_yield) return ufbxi_ascii_yield(uc);
9483 ua->src++;
9484 if (ua->src == ua->src_yield) return ufbxi_ascii_yield(uc);
9485 return *ua->src;
9486 }
9487
9488 static ufbxi_noinline uint32_t ufbxi_ascii_parse_version(ufbxi_context *uc)
9489 {
9490 uint8_t digits[3];
9491 uint32_t num_digits = 0;
9492
9493 char c = ufbxi_ascii_next(uc);
9494
9495 const char fmt[] = " FBX ?.?.?";
9496 uint32_t ix = 0;
9497 while (num_digits < 3) {
9498 char ref = fmt[ix++];
9499 switch (ref) {
9500
9501 // Digit
9502 case '?':
9503 if (c < '0' || c > '9') return 0;
9504 digits[num_digits++] = (uint8_t)(c - '0');
9505 c = ufbxi_ascii_next(uc);
9506 break;
9507
9508 // Whitespace
9509 case ' ':
9510 while (c == ' ' || c == '\t') {
9511 c = ufbxi_ascii_next(uc);
9512 }
9513 break;
9514
9515 // Literal character
9516 default:
9517 if (c != ref) return 0;
9518 c = ufbxi_ascii_next(uc);
9519 break;
9520 }
9521 }
9522
9523 if (num_digits != 3) return 0;
9524 return 1000u*(uint32_t)digits[0] + 100u*(uint32_t)digits[1] + 10u*(uint32_t)digits[2];
9525 }
9526
9527 static const uint32_t ufbxi_space_mask =
9528 (1u << ((uint32_t)' ' - 1)) |
9529 (1u << ((uint32_t)'\t' - 1)) |
9530 (1u << ((uint32_t)'\r' - 1)) |
9531 (1u << ((uint32_t)'\n' - 1)) ;
9532
9533 ufbx_static_assert(space_codepoint,
9534 (uint32_t)' ' <= 32u && (uint32_t)'\t' <= 32u &&
9535 (uint32_t)'\r' <= 32u && (uint32_t)'\n' <= 32u);
9536
9537 static ufbxi_forceinline bool ufbxi_is_space(char c)
9538 {
9539 uint32_t v = (uint32_t)(uint8_t)c - 1;
9540 return v < 32 && ((ufbxi_space_mask >> v) & 0x1) != 0;
9541 }
9542
9543 static ufbxi_noinline char ufbxi_ascii_skip_whitespace(ufbxi_context *uc)
9544 {
9545 ufbxi_ascii *ua = &uc->ascii;
9546
9547 // Ignore whitespace
9548 char c = ufbxi_ascii_peek(uc);
9549 for (;;) {
9550 while (ufbxi_is_space(c)) {
9551 c = ufbxi_ascii_next(uc);
9552 }
9553
9554 // Line comment
9555 if (c == ';') {
9556
9557 bool read_magic = false;
9558 // FBX ASCII files begin with a magic comment of form "; FBX 7.7.0 project file"
9559 // Try to extract the version number from the magic comment
9560 if (!ua->read_first_comment) {
9561 ua->read_first_comment = true;
9562 uint32_t version = ufbxi_ascii_parse_version(uc);
9563 if (version) {
9564 uc->version = version;
9565 ua->found_version = true;
9566 read_magic = true;
9567 }
9568 }
9569
9570 c = ufbxi_ascii_next(uc);
9571 while (c != '\n' && c != '\0') {
9572 c = ufbxi_ascii_next(uc);
9573 }
9574 c = ufbxi_ascii_next(uc);
9575
9576 // Try to determine if this is a Blender 6100 ASCII file
9577 if (read_magic) {
9578 if (c == ';') {
9579 char line[32];
9580 size_t line_len = 0;
9581
9582 c = ufbxi_ascii_next(uc);
9583 while (c != '\n' && c != '\0') {
9584 if (line_len < sizeof(line)) {
9585 line[line_len++] = c;
9586 }
9587 c = ufbxi_ascii_next(uc);
9588 }
9589
9590 if (line_len >= 19 && !memcmp(line, " Created by Blender", 19)) {
9591 uc->exporter = UFBX_EXPORTER_BLENDER_ASCII;
9592 }
9593 }
9594 }
9595
9596 } else {
9597 break;
9598 }
9599 }
9600 return c;
9601 }
9602
9603 ufbxi_nodiscard static ufbxi_forceinline int ufbxi_ascii_push_token_char(ufbxi_context *uc, ufbxi_ascii_token *token, char c)
9604 {
9605 // Grow the string data buffer if necessary
9606 if (token->str_len == token->str_cap) {
9607 size_t len = ufbxi_max_sz(token->str_len + 1, 256);
9608 ufbxi_check(ufbxi_grow_array(&uc->ator_tmp, &token->str_data, &token->str_cap, len));
9609 }
9610
9611 token->str_data[token->str_len++] = c;
9612
9613 return 1;
9614 }
9615
9616 ufbxi_nodiscard static ufbxi_forceinline int ufbxi_ascii_push_token_string(ufbxi_context *uc, ufbxi_ascii_token *token, const char *data, size_t length)
9617 {
9618 // Grow the string data buffer if necessary
9619 if (token->str_len + length >= token->str_cap) {
9620 size_t len = ufbxi_max_sz(token->str_len + length, 256);
9621 ufbxi_check(ufbxi_grow_array(&uc->ator_tmp, &token->str_data, &token->str_cap, len));
9622 }
9623
9624 memcpy(token->str_data + token->str_len, data, length);
9625 token->str_len += length;
9626
9627 return 1;
9628 }
9629
9630 ufbxi_nodiscard ufbxi_noinline static int ufbxi_ascii_skip_until(ufbxi_context *uc, char dst)
9631 {
9632 ufbxi_ascii *ua = &uc->ascii;
9633
9634 for (;;) {
9635 size_t buffered = ufbxi_to_size(ua->src_yield - ua->src);
9636 const char *match = (const char*)memchr(ua->src, dst, buffered);
9637 if (match) {
9638 ua->src = match;
9639 break;
9640 } else {
9641 ua->src += buffered;
9642 }
9643 if (buffered == 0) {
9644 char c = ufbxi_ascii_yield(uc);
9645 ufbxi_check(c != '\0');
9646 }
9647 }
9648
9649 return 1;
9650 }
9651
9652 typedef struct {
9653 const char *source;
9654 size_t length;
9655 } ufbxi_ascii_span;
9656
9657 ufbxi_nodiscard ufbxi_noinline static int ufbxi_ascii_store_array(ufbxi_context *uc, ufbxi_buf *tmp_buf)
9658 {
9659 ufbxi_ascii *ua = &uc->ascii;
9660
9661 ua->retain_buf = tmp_buf;
9662
9663 for (;;) {
9664 size_t buffered = ufbxi_to_size(ua->src_yield - ua->src);
9665 if (buffered == 0) {
9666 char c = ufbxi_ascii_yield(uc);
9667 ufbxi_check(c != '\0');
9668 continue;
9669 }
9670
9671 const char *begin = ua->src, *end;
9672 const char *match = (const char*)memchr(begin, '}', buffered);
9673 if (match) {
9674 end = match;
9675 } else {
9676 end = begin + buffered;
9677 }
9678 ua->src = end;
9679
9680 size_t length = ufbxi_to_size(end - begin);
9681 ufbxi_ascii_span *span = ufbxi_push(&uc->tmp_ascii_spans, ufbxi_ascii_span, 1);
9682 ufbxi_check(span);
9683 // Store the trailing '}' for parsing
9684 if (match) length += 1;
9685 span->length = length;
9686 if (ua->src_is_retained || !uc->read_fn) {
9687 span->source = begin;
9688 } else {
9689 span->source = ufbxi_push_copy(tmp_buf, char, length, begin);
9690 ufbxi_check(span->source);
9691 }
9692
9693 if (match) break;
9694 }
9695
9696 ua->retain_buf = NULL;
9697
9698 return 1;
9699 }
9700
9701 ufbxi_nodiscard ufbxi_noinline static int ufbxi_ascii_try_ignore_string(ufbxi_context *uc, ufbxi_ascii_token *token)
9702 {
9703 ufbxi_ascii *ua = &uc->ascii;
9704
9705 char c = ufbxi_ascii_skip_whitespace(uc);
9706 token->str_len = 0;
9707
9708 if (c == '"') {
9709 // Replace `prev_token` with `token` but swap the buffers so `token` uses
9710 // the now-unused string buffer of the old `prev_token`.
9711 char *swap_data = ua->prev_token.str_data;
9712 size_t swap_cap = ua->prev_token.str_cap;
9713 ua->prev_token = ua->token;
9714 ua->token.str_data = swap_data;
9715 ua->token.str_cap = swap_cap;
9716
9717 token->type = UFBXI_ASCII_STRING;
9718 // Skip opening quote
9719 ufbxi_ascii_next(uc);
9720 ufbxi_check(ufbxi_ascii_skip_until(uc, '"'));
9721 // Skip closing quote
9722 ufbxi_ascii_next(uc);
9723 return true;
9724 }
9725
9726 return false;
9727 }
9728
9729 ufbxi_nodiscard ufbxi_noinline static int ufbxi_ascii_next_token(ufbxi_context *uc, ufbxi_ascii_token *token)
9730 {
9731 ufbxi_ascii *ua = &uc->ascii;
9732
9733 // Replace `prev_token` with `token` but swap the buffers so `token` uses
9734 // the now-unused string buffer of the old `prev_token`.
9735 char *swap_data = ua->prev_token.str_data;
9736 size_t swap_cap = ua->prev_token.str_cap;
9737 ua->prev_token = ua->token;
9738 ua->token.str_data = swap_data;
9739 ua->token.str_cap = swap_cap;
9740
9741 char c = ufbxi_ascii_skip_whitespace(uc);
9742 token->str_len = 0;
9743
9744 if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '_') {
9745 token->type = UFBXI_ASCII_BARE_WORD;
9746 while ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')
9747 || (c >= '0' && c <= '9') || c == '_' || c == '-' || c == '(' || c == ')') {
9748 ufbxi_check(ufbxi_ascii_push_token_char(uc, token, c));
9749 c = ufbxi_ascii_next(uc);
9750 }
9751
9752 // Skip whitespace to find if there's a following ':'
9753 c = ufbxi_ascii_skip_whitespace(uc);
9754 if (c == ':') {
9755 token->value.name_len = token->str_len;
9756 token->type = UFBXI_ASCII_NAME;
9757 ufbxi_ascii_next(uc);
9758 }
9759 } else if ((c >= '0' && c <= '9') || c == '-' || c == '+' || c == '.') {
9760 token->type = UFBXI_ASCII_INT;
9761
9762 token->negative = c == '-';
9763 while ((c >= '0' && c <= '9') || c == '-' || c == '+' || c == '.' || c == 'e' || c == 'E') {
9764 if (c == '.' || c == 'e' || c == 'E') {
9765 token->type = UFBXI_ASCII_FLOAT;
9766 }
9767 ufbxi_check(ufbxi_ascii_push_token_char(uc, token, c));
9768 c = ufbxi_ascii_next(uc);
9769 }
9770
9771 bool nan_like = false;
9772 while ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '#' || c == '(' || c == ')') {
9773 nan_like = true;
9774 ufbxi_check(ufbxi_ascii_push_token_char(uc, token, c));
9775 c = ufbxi_ascii_next(uc);
9776 }
9777 ufbxi_check(ufbxi_ascii_push_token_char(uc, token, '\0'));
9778 if (nan_like) {
9779 token->type = UFBXI_ASCII_FLOAT;
9780 }
9781
9782 char *end;
9783 if (token->type == UFBXI_ASCII_INT) {
9784 token->value.i64 = ufbxi_parse_int64(token->str_data, &end);
9785 ufbxi_check(end == token->str_data + token->str_len - 1);
9786 } else if (token->type == UFBXI_ASCII_FLOAT) {
9787 uint32_t flags = uc->double_parse_flags;
9788 if (ua->parse_as_f32) flags = UFBXI_PARSE_DOUBLE_AS_BINARY32;
9789 token->value.f64 = ufbxi_parse_double(token->str_data, token->str_len, &end, flags);
9790 ufbxi_check(end == token->str_data + token->str_len - 1);
9791 }
9792 } else if (c == '"') {
9793 token->type = UFBXI_ASCII_STRING;
9794 c = ufbxi_ascii_next(uc);
9795 while (c != '"') {
9796
9797 // Optimized string parsing for non-special characters
9798 if (ua->src + 1 < ua->src_yield) {
9799 const char *begin = ua->src;
9800 const char *end = ua->src_yield;
9801 const char *quot = (const char*)memchr(begin, '"', ufbxi_to_size(end - begin));
9802 if (quot) end = quot;
9803 const char *esc = (const char*)memchr(begin, '&', ufbxi_to_size(end - begin));
9804 if (esc) end = esc;
9805
9806 if (begin < end) {
9807 ufbxi_check(ufbxi_ascii_push_token_string(uc, token, begin, ufbxi_to_size(end - begin)));
9808 ua->src = end;
9809 c = ufbxi_ascii_peek(uc);
9810 continue;
9811 }
9812 }
9813
9814 // Escape XML-like elements, funny enough there is no way to escape '&' itself, there is no `&amp`.
9815 // '&quot;' -> '"'
9816 // '&cr;' -> '\r'
9817 // '&lf;' -> '\n'
9818 if (c == '&') {
9819 const char *entity = NULL;
9820 char replacement = '\0';
9821
9822 c = ufbxi_ascii_next(uc);
9823 switch (c) {
9824 case 'q':
9825 entity = "&quot;";
9826 replacement = '"';
9827 break;
9828 case 'c':
9829 entity = "&cr;";
9830 replacement = '\r';
9831 break;
9832 case 'l':
9833 entity = "&lf;";
9834 replacement = '\n';
9835 break;
9836 default:
9837 // As '&' is not escaped in any way just map '&' -> '&'
9838 entity = "&";
9839 replacement = '&';
9840 break;
9841 }
9842
9843 size_t step = 1;
9844
9845 ufbxi_dev_assert(entity && *entity);
9846 // `entity` is a NULL terminated string longer than a single character
9847 // cppcheck-suppress arrayIndexOutOfBounds
9848 for (; entity[step]; step++) {
9849 if (c != entity[step]) break;
9850 c = ufbxi_ascii_next(uc);
9851 }
9852
9853 if (entity[step] == '\0') {
9854 // Full match: Push the replacement character
9855 ufbxi_check(ufbxi_ascii_push_token_char(uc, token, replacement));
9856 } else {
9857 // Partial match: Push the prefix we have skipped already
9858 for (size_t i = 0; i < step; i++) {
9859 ufbxi_check(ufbxi_ascii_push_token_char(uc, token, entity[i]));
9860 }
9861 }
9862 continue;
9863 }
9864
9865 ufbxi_check(c != '\0');
9866 ufbxi_check(ufbxi_ascii_push_token_char(uc, token, c));
9867 c = ufbxi_ascii_next(uc);
9868 }
9869 // Skip closing quote
9870 ufbxi_ascii_next(uc);
9871 } else {
9872 // Single character token
9873 token->type = c;
9874 ufbxi_ascii_next(uc);
9875 }
9876
9877 return 1;
9878 }
9879
9880 ufbxi_nodiscard static int ufbxi_ascii_accept(ufbxi_context *uc, char type)
9881 {
9882 ufbxi_ascii *ua = &uc->ascii;
9883
9884 if (ua->token.type == type) {
9885 ufbxi_check(ufbxi_ascii_next_token(uc, &ua->token));
9886 return 1;
9887 } else {
9888 return 0;
9889 }
9890 }
9891
9892 ufbxi_nodiscard static ufbxi_noinline int ufbxi_ascii_read_int_array(ufbxi_context *uc, char type, size_t *p_num_read)
9893 {
9894 ufbxi_ascii *ua = &uc->ascii;
9895 if (ua->parse_as_f32) return 1;
9896 size_t initial_items = uc->tmp_stack.num_items;
9897
9898 int64_t val;
9899 if (ua->token.type == UFBXI_ASCII_INT) {
9900 val = ua->token.value.i64;
9901 } else {
9902 return 1;
9903 }
9904
9905 const char *src = ua->src;
9906 const char *end = ua->src_yield;
9907 const char *src_scan = src;
9908
9909 for (;;) {
9910
9911 // Skip '\s*,\s*' between array elements. If we don't find a comma after an element
9912 // don't push it as we can't be 100% certain whether it's a part of the array.
9913 while (src_scan != end && ufbxi_is_space(*src_scan)) src_scan++;
9914 if (src_scan == end || *src_scan != ',') break;
9915 src_scan++;
9916 while (src_scan != end && ufbxi_is_space(*src_scan)) src_scan++;
9917
9918 // Found comma, commit to the position and push the previous value to the array
9919 src = src_scan;
9920 if (type == 'i') {
9921 int32_t *v = ufbxi_push_fast(&uc->tmp_stack, int32_t, 1);
9922 ufbxi_check(v);
9923 *v = (int32_t)val;
9924 } else if (type == 'l') {
9925 int64_t *v = ufbxi_push_fast(&uc->tmp_stack, int64_t, 1);
9926 ufbxi_check(v);
9927 *v = (int64_t)val;
9928 }
9929
9930 // Try to parse the next value, we don't commit this until we find a comma after it above.
9931 size_t left = ufbxi_to_size(end - src_scan);
9932 if (left < 32) break;
9933
9934 val = ufbxi_parse_int64(src_scan, (char**)&src_scan);
9935 if (!src_scan) break;
9936 }
9937
9938 // Resume conventional parsing if we moved `src`.
9939 if (src != ua->src) {
9940 ua->src = src;
9941 ufbxi_check(ufbxi_ascii_next_token(uc, &ua->token));
9942 }
9943
9944 *p_num_read = uc->tmp_stack.num_items - initial_items;
9945 return 1;
9946 }
9947
9948 typedef struct {
9949 void *arr_data;
9950 char arr_type;
9951 size_t arr_size;
9952 const ufbxi_ascii_span *spans;
9953 size_t num_spans;
9954 size_t offset;
9955 } ufbxi_ascii_array_task;
9956
9957 ufbxi_noinline static const char *ufbxi_ascii_array_task_parse_floats(ufbxi_ascii_array_task *t, const char *src, const char *src_end, uint32_t parse_flags)
9958 {
9959 size_t offset = t->offset;
9960 float *dst_float = t->arr_type == 'f' ? (float*)t->arr_data + offset : NULL;
9961 double *dst_double = t->arr_type == 'd' ? (double*)t->arr_data + offset : NULL;
9962 ufbx_assert(dst_float || dst_double);
9963 const char *src_begin = src;
9964
9965 while (src != src_end) {
9966 while (ufbxi_is_space(*src)) src++;
9967
9968 // Try to parse the next value, we don't commit this until we find a comma after it above.
9969 char *num_end = NULL;
9970 double val = ufbxi_parse_double(src, ufbxi_to_size(src_end - src), &num_end, parse_flags);
9971 if (!num_end) return src_begin;
9972 src = num_end;
9973
9974 while (ufbxi_is_space(*src)) src++;
9975 if (*src != ',') break;
9976 src++;
9977 src_begin = src;
9978
9979 if (offset >= t->arr_size) return NULL;
9980 if (dst_double) {
9981 *dst_double++ = val;
9982 } else {
9983 *dst_float++ = (float)val;
9984 }
9985 offset++;
9986 }
9987
9988 t->offset = offset;
9989 return src_begin;
9990 }
9991
9992 ufbxi_noinline static const char *ufbxi_ascii_array_task_parse_ints(ufbxi_ascii_array_task *t, const char *src, const char *src_end)
9993 {
9994 size_t offset = t->offset;
9995 int32_t *dst32 = t->arr_type == 'i' ? (int32_t*)t->arr_data + offset : NULL;
9996 int64_t *dst64 = t->arr_type == 'l' ? (int64_t*)t->arr_data + offset : NULL;
9997 ufbx_assert(dst32 || dst64);
9998 const char *src_begin = src;
9999
10000 while (src != src_end) {
10001 while (ufbxi_is_space(*src)) src++;
10002
10003 int64_t val = ufbxi_parse_int64(src, (char**)&src);
10004 if (!src) return NULL;
10005
10006 while (ufbxi_is_space(*src)) src++;
10007 if (*src != ',') break;
10008 src++;
10009 src_begin = src;
10010
10011 if (offset >= t->arr_size) return NULL;
10012 if (dst32) {
10013 *dst32++ = (int32_t)val;
10014 } else {
10015 *dst64++ = val;
10016 }
10017 offset++;
10018 }
10019
10020 t->offset = offset;
10021 return src_begin;
10022 }
10023
10024 ufbxi_noinline static const char *ufbxi_ascii_array_task_parse(ufbxi_ascii_array_task *t, const char *src, const char *src_end)
10025 {
10026 if (t->arr_type == 'f' || t->arr_type == 'd') {
10027 uint32_t flags = ufbxi_parse_double_init_flags();
10028 return ufbxi_ascii_array_task_parse_floats(t, src, src_end, flags);
10029 } else {
10030 return ufbxi_ascii_array_task_parse_ints(t, src, src_end);
10031 }
10032 }
10033
10034 typedef enum {
10035 UFBXI_ASCII_SCAN_STATE_VALUE,
10036 UFBXI_ASCII_SCAN_STATE_WHITESPACE,
10037 UFBXI_ASCII_SCAN_STATE_COMMENT,
10038 UFBXI_ASCII_SCAN_STATE_COMMA,
10039 } ufbxi_ascii_scan_state;
10040
10041 ufbxi_noinline static bool ufbxi_ascii_array_task_imp(ufbxi_ascii_array_task *t)
10042 {
10043 // Temporary buffer for parsing between spans
10044 char buffer[128]; // ufbxi_uninit
10045 size_t buffer_len = 0;
10046 bool buffer_value = false;
10047
10048 ufbxi_ascii_scan_state state = UFBXI_ASCII_SCAN_STATE_WHITESPACE;
10049 ufbxi_for(const ufbxi_ascii_span, span, t->spans, t->num_spans) {
10050 const char *src = span->source;
10051 const char *end = src + span->length;
10052
10053 while (src != end) {
10054
10055 // State machine for skipping whitespace and comments, potentially
10056 // between multiple spans.
10057 while (src != end) {
10058 char c = *src;
10059 if (state == UFBXI_ASCII_SCAN_STATE_VALUE) {
10060 if (buffer_len >= sizeof(buffer) - 1) return false;
10061 if (c == '"') {
10062 return false;
10063 } else if (c == ';' || ufbxi_is_space(c)) {
10064 state = UFBXI_ASCII_SCAN_STATE_WHITESPACE;
10065 buffer[buffer_len] = ' ';
10066 buffer_len++;
10067 } else if (c == ',' || c == '}') {
10068 state = UFBXI_ASCII_SCAN_STATE_COMMA;
10069 buffer[buffer_len] = ',';
10070 buffer_len++;
10071 src++;
10072 break;
10073 } else {
10074 buffer_value = true;
10075 buffer[buffer_len] = c;
10076 buffer_len++;
10077 src++;
10078 }
10079 } else if (state == UFBXI_ASCII_SCAN_STATE_WHITESPACE) {
10080 if (c == ';') {
10081 state = UFBXI_ASCII_SCAN_STATE_COMMENT;
10082 } else if (ufbxi_is_space(c)) {
10083 src++;
10084 } else {
10085 state = UFBXI_ASCII_SCAN_STATE_VALUE;
10086 }
10087 } else if (state == UFBXI_ASCII_SCAN_STATE_COMMENT) {
10088 if (c == '\n') {
10089 state = UFBXI_ASCII_SCAN_STATE_WHITESPACE;
10090 } else {
10091 src++;
10092 }
10093 } else if (state == UFBXI_ASCII_SCAN_STATE_COMMA) {
10094 state = UFBXI_ASCII_SCAN_STATE_WHITESPACE;
10095 }
10096 }
10097
10098 if (state == UFBXI_ASCII_SCAN_STATE_COMMA) {
10099 // Parse a value from the buffer
10100 if (buffer_value) {
10101 const char *buffer_end = ufbxi_ascii_array_task_parse(t, buffer, buffer + buffer_len);
10102 if (buffer_end == NULL || buffer_end == buffer) {
10103 return false;
10104 }
10105 }
10106
10107 // If not at end, we are past the last comma, so try to find a
10108 // safe range to parse.
10109 if (src != end) {
10110 const char *parse_end = end;
10111 while (parse_end > src) {
10112 if (parse_end[-1] == ',') break;
10113 parse_end--;
10114 }
10115 if (src < parse_end) {
10116 src = ufbxi_ascii_array_task_parse(t, src, parse_end);
10117 if (src == NULL) return false;
10118 }
10119 }
10120
10121 buffer_len = 0;
10122 buffer_value = false;
10123 }
10124 }
10125 }
10126
10127 if (t->offset != t->arr_size) return false;
10128
10129 return true;
10130 }
10131
10132 ufbxi_noinline static bool ufbxi_ascii_array_task_fn(ufbxi_task *task)
10133 {
10134 ufbxi_ascii_array_task *t = (ufbxi_ascii_array_task *)task->data;
10135 if (!ufbxi_ascii_array_task_imp(t)) {
10136 task->error = "Threaded ASCII parse error";
10137 return false;
10138 }
10139 return true;
10140 }
10141
10142 ufbxi_nodiscard static ufbxi_noinline int ufbxi_ascii_read_float_array(ufbxi_context *uc, char type, size_t *p_num_read)
10143 {
10144 ufbxi_ascii *ua = &uc->ascii;
10145 if (ua->parse_as_f32) return 1;
10146
10147 double val;
10148 if (ua->token.type == UFBXI_ASCII_FLOAT) {
10149 val = ua->token.value.f64;
10150 } else if (ua->token.type == UFBXI_ASCII_INT) {
10151 double fsign = !ua->token.value.i64 && ua->token.negative ? -1.0 : 1.0;
10152 val = (double)ua->token.value.i64 * fsign;
10153 } else {
10154 return 1;
10155 }
10156
10157 const char *src = ua->src;
10158 const char *end = ua->src_yield;
10159
10160 uint32_t parse_flags = uc->double_parse_flags;
10161
10162 size_t initial_items = uc->tmp_stack.num_items;
10163 const char *src_scan = src;
10164 for (;;) {
10165
10166 // Skip '\s*,\s*' between array elements. If we don't find a comma after an element
10167 // don't push it as we can't be 100% certain whether it's a part of the array.
10168 while (src_scan != end && ufbxi_is_space(*src_scan)) src_scan++;
10169 if (src_scan == end || *src_scan != ',') break;
10170 src_scan++;
10171 while (src_scan != end && ufbxi_is_space(*src_scan)) src_scan++;
10172
10173 // Found comma, commit to the position and push the previous value to the array
10174 src = src_scan;
10175 if (type == 'd') {
10176 double *v = ufbxi_push_fast(&uc->tmp_stack, double, 1);
10177 ufbxi_check(v);
10178 *v = (double)val;
10179 } else if (type == 'f') {
10180 float *v = ufbxi_push_fast(&uc->tmp_stack, float, 1);
10181 ufbxi_check(v);
10182 *v = (float)val;
10183 }
10184
10185 // Try to parse the next value, we don't commit this until we find a comma after it above.
10186 char *num_end = NULL;
10187 size_t left = ufbxi_to_size(end - src_scan);
10188 val = ufbxi_parse_double(src_scan, left, &num_end, parse_flags);
10189 if (!num_end || num_end == src_scan || num_end >= end) {
10190 break;
10191 }
10192
10193 src_scan = num_end;
10194 }
10195
10196 // Resume conventional parsing if we moved `src`.
10197 if (src != ua->src) {
10198 ua->src = src;
10199 ufbxi_check(ufbxi_ascii_next_token(uc, &ua->token));
10200 }
10201
10202 *p_num_read = uc->tmp_stack.num_items - initial_items;
10203 return 1;
10204 }
10205
10206 ufbxi_noinline static int ufbxi_setup_base64(ufbxi_context *uc)
10207 {
10208 uint8_t *table = ufbxi_push(&uc->tmp, uint8_t, 256);
10209 ufbxi_check(table);
10210 uc->base64_table = table;
10211
10212 memset(table, 0x80, 256);
10213 ufbxi_nounroll for (char c = 'A'; c <= 'Z'; c++) table[(size_t)c] = (uint8_t)(c - 'A');
10214 ufbxi_nounroll for (char c = 'a'; c <= 'z'; c++) table[(size_t)c] = (uint8_t)(26 + (c - 'a'));
10215 ufbxi_nounroll for (char c = '0'; c <= '9'; c++) table[(size_t)c] = (uint8_t)(52 + (c - '0'));
10216 table[(size_t)'+'] = 62;
10217 table[(size_t)'/'] = 63;
10218 table[(size_t)'='] = 0x40;
10219
10220 return 1;
10221 }
10222
10223 ufbxi_noinline static int ufbxi_decode_base64(ufbxi_context *uc, ufbx_string *p_result, const char *src, size_t src_length, bool *p_failed)
10224 {
10225 if (!uc->base64_table) ufbxi_check(ufbxi_setup_base64(uc));
10226
10227 uint8_t *table = uc->base64_table;
10228 uint32_t error_mask = 0, pad_error = 0;
10229
10230 char *p = (char*)p_result->data;
10231 for (size_t i = 0; i + 4 <= src_length; i += 4) {
10232 uint32_t a = table[(size_t)(uint8_t)src[i + 0]];
10233 uint32_t b = table[(size_t)(uint8_t)src[i + 1]];
10234 uint32_t c = table[(size_t)(uint8_t)src[i + 2]];
10235 uint32_t d = table[(size_t)(uint8_t)src[i + 3]];
10236 pad_error = error_mask;
10237 error_mask |= a | b | c | d;
10238
10239 p[0] = (char)(uint8_t)(a << 2 | b >> 4);
10240 p[1] = (char)(uint8_t)(b << 4 | c >> 2);
10241 p[2] = (char)(uint8_t)(c << 6 | d);
10242 p += 3;
10243 }
10244
10245 if (src_length >= 4) {
10246 const char *end = src + src_length - 4;
10247 uint32_t padding = 0;
10248 padding |= end[0] == '=' ? 0x8 : 0x0;
10249 padding |= end[1] == '=' ? 0x4 : 0x0;
10250 padding |= end[2] == '=' ? 0x2 : 0x0;
10251 padding |= end[3] == '=' ? 0x1 : 0x0;
10252 if (padding <= 0x1) p -= padding; // "xxx=" or "xxxx"
10253 else if (padding == 0x3) p -= 2; // "xx=="
10254 else pad_error |= 0x40; // anything else
10255 }
10256
10257 if (((error_mask & 0x80) != 0 || (pad_error & 0x40) != 0 || src_length % 4 != 0) && !*p_failed) {
10258 ufbxi_check(ufbxi_warnf(UFBX_WARNING_BAD_BASE64_CONTENT, "Ignored bad base64 embedded content"));
10259 *p_failed = true;
10260 }
10261
10262 p_result->length = ufbxi_to_size(p - p_result->data);
10263 return 1;
10264 }
10265
10266 // Recursion limited by check at the start
10267 ufbxi_nodiscard ufbxi_noinline static int ufbxi_ascii_parse_node(ufbxi_context *uc, uint32_t depth, ufbxi_parse_state parent_state, bool *p_end, ufbxi_buf *tmp_buf, bool recursive)
10268 ufbxi_recursive_function(int, ufbxi_ascii_parse_node, (uc, depth, parent_state, p_end, tmp_buf, recursive), UFBXI_MAX_NODE_DEPTH + 1,
10269 (ufbxi_context *uc, uint32_t depth, ufbxi_parse_state parent_state, bool *p_end, ufbxi_buf *tmp_buf, bool recursive))
10270 {
10271 ufbxi_ascii *ua = &uc->ascii;
10272
10273 if (ua->token.type == '}') {
10274 ufbxi_check(ufbxi_ascii_next_token(uc, &ua->token));
10275 *p_end = true;
10276 return 1;
10277 }
10278
10279 if (ua->token.type == UFBXI_ASCII_END) {
10280 ufbxi_check_msg(depth == 0, "Truncated file");
10281 *p_end = true;
10282 return 1;
10283 }
10284
10285 // Parse the name eg. "Node:" token and intern the name
10286 ufbxi_check(depth < UFBXI_MAX_NODE_DEPTH);
10287 if (!uc->sure_fbx && depth == 0 && ua->token.type != UFBXI_ASCII_NAME) {
10288 ufbxi_fail_msg("Expected a 'Name:' token", "Not an FBX file");
10289 }
10290 ufbxi_check(ufbxi_ascii_accept(uc, UFBXI_ASCII_NAME));
10291 size_t name_len = ua->prev_token.value.name_len;
10292 ufbxi_check(name_len <= 0xff);
10293 const char *name = ufbxi_push_string(&uc->string_pool, ua->prev_token.str_data, ua->prev_token.str_len, NULL, true);
10294 ufbxi_check(name);
10295
10296 // Push the parsed node into the `tmp_stack` buffer, the nodes will be popped by
10297 // calling code after its done parsing all of it's children.
10298 ufbxi_node *node = ufbxi_push_zero(&uc->tmp_stack, ufbxi_node, 1);
10299 ufbxi_check(node);
10300 node->name = name;
10301 node->name_len = (uint8_t)name_len;
10302
10303 bool in_ascii_array = false;
10304
10305 uint32_t num_values = 0;
10306 uint32_t type_mask = 0;
10307
10308 int arr_type = 0;
10309 ufbxi_buf *arr_buf = NULL;
10310 size_t arr_elem_size = 0;
10311 bool arr_error = false;
10312
10313 // Check if the values of the node we're parsing currently should be
10314 // treated as an array.
10315 ufbxi_array_info arr_info;
10316 if (ufbxi_is_array_node(uc, parent_state, name, &arr_info)) {
10317 uint32_t flags = arr_info.flags;
10318 arr_type = ufbxi_normalize_array_type(arr_info.type, 'b');
10319 arr_buf = tmp_buf;
10320 if (flags & UFBXI_ARRAY_FLAG_RESULT) arr_buf = &uc->result;
10321 else if (flags & UFBXI_ARRAY_FLAG_TMP_BUF) arr_buf = &uc->tmp;
10322
10323 ufbxi_value_array *arr = ufbxi_push(tmp_buf, ufbxi_value_array, 1);
10324 ufbxi_check(arr);
10325 node->value_type_mask = UFBXI_VALUE_ARRAY;
10326 node->array = arr;
10327 arr->type = (char)arr_type;
10328
10329 // Parse array values using strtof() if the array destination is 32-bit float
10330 // since KeyAttrDataFloat packs integer data (!) into floating point values so we
10331 // should try to be as exact as possible.
10332 if (arr_info.flags & UFBXI_ARRAY_FLAG_ACCURATE_F32) {
10333 ua->parse_as_f32 = true;
10334 }
10335
10336 arr_elem_size = ufbxi_array_type_size((char)arr_type);
10337
10338 if (arr_type != '-') {
10339 // Force alignment for array contents: This allows us to use `ufbxi_push_fast()`
10340 // in fast parsing functions.
10341 ufbxi_check(ufbxi_push_size_zero(&uc->tmp_stack, 8, 1));
10342
10343 // Pad with 4 zero elements to make indexing with `-1` safe.
10344 if ((flags & UFBXI_ARRAY_FLAG_PAD_BEGIN) != 0) {
10345 ufbxi_check(ufbxi_push_size_zero(&uc->tmp_stack, arr_elem_size, 4));
10346 num_values += 4;
10347 }
10348 }
10349 }
10350
10351 // Some fields in ASCII may have leading commas eg. `Content: , "base64-string"`
10352 if (ua->token.type == ',') {
10353 // HACK: If we are parsing an "array" that should be ignored, ie. `Content` when
10354 // `opts.ignore_embedded == true` try to skip the next token string if possible.
10355 if (arr_type == '-') {
10356 if (!ufbxi_ascii_try_ignore_string(uc, &ua->token)) {
10357 ufbxi_check(ufbxi_ascii_next_token(uc, &ua->token));
10358 }
10359 } else {
10360 ufbxi_check(ufbxi_ascii_next_token(uc, &ua->token));
10361 }
10362 }
10363
10364 ufbxi_parse_state parse_state = ufbxi_update_parse_state(parent_state, node->name);
10365 ufbxi_value vals[UFBXI_MAX_NON_ARRAY_VALUES];
10366
10367 uint32_t deferred_size = 0;
10368
10369 // NOTE: Infinite loop to allow skipping the comma parsing via `continue`.
10370 for (;;) {
10371 ufbxi_ascii_token *tok = &ua->prev_token;
10372
10373 if (arr_type) {
10374 size_t num_read = 0;
10375 if (arr_type == 'f' || arr_type == 'd') {
10376 ufbxi_check(ufbxi_ascii_read_float_array(uc, (char)arr_type, &num_read));
10377 } else if (arr_type == 'i' || arr_type == 'l') {
10378 ufbxi_check(ufbxi_ascii_read_int_array(uc, (char)arr_type, &num_read));
10379 }
10380 ufbxi_check(UINT32_MAX - num_values > num_read);
10381 num_values += (uint32_t)num_read;
10382 }
10383
10384 if (ufbxi_ascii_accept(uc, UFBXI_ASCII_STRING)) {
10385
10386 if (arr_type) {
10387
10388 if (arr_type == 's' || arr_type == 'S' || arr_type == 'C') {
10389 bool raw = arr_type == 's';
10390 ufbx_string *v = ufbxi_push(&uc->tmp_stack, ufbx_string, 1);
10391 ufbxi_check(v);
10392 if (arr_type == 'C') {
10393 ufbxi_buf *buf = uc->opts.retain_dom ? &uc->result : tmp_buf;
10394 size_t capacity = tok->str_len / 4 * 3 + 3;
10395 v->data = ufbxi_push(buf, char, capacity);
10396 ufbxi_check(v->data);
10397 ufbxi_check(ufbxi_decode_base64(uc, v, tok->str_data, tok->str_len, &arr_error));
10398 ufbx_assert(v->length <= capacity);
10399 } else {
10400 v->data = tok->str_data;
10401 v->length = tok->str_len;
10402 ufbxi_check(ufbxi_push_string_place_str(&uc->string_pool, v, raw));
10403 }
10404 } else {
10405 // Ignore strings in non-string arrays, decrement `num_values` as it will be
10406 // incremented after the loop iteration is done to ignore it.
10407 num_values--;
10408 }
10409
10410 } else if (num_values < UFBXI_MAX_NON_ARRAY_VALUES) {
10411 type_mask |= (uint32_t)UFBXI_VALUE_STRING << (num_values*2);
10412 ufbxi_value *v = &vals[num_values];
10413
10414 const char *str = tok->str_data;
10415 size_t length = tok->str_len;
10416 ufbxi_check(str);
10417
10418 if (length == 0) {
10419 v->s.raw_data = ufbxi_empty_char;
10420 v->s.raw_length = 0;
10421 v->s.utf8_length = 0;
10422 } else {
10423 bool non_ascii = false;
10424 uint32_t hash = ufbxi_hash_string_check_ascii(str, length, &non_ascii);
10425 bool raw = !non_ascii || ufbxi_is_raw_string(uc, parent_state, name, num_values);
10426 ufbxi_check(ufbxi_push_sanitized_string(&uc->string_pool, &v->s, str, length, hash, raw));
10427 if (non_ascii && raw) v->s.utf8_length = UINT32_MAX;
10428 }
10429 }
10430
10431 } else if (ufbxi_ascii_accept(uc, UFBXI_ASCII_INT)) {
10432 int64_t val = tok->value.i64;
10433 ufbx_real fsign = !val && tok->negative ? (ufbx_real)-1.0f : (ufbx_real)1.0f;
10434
10435 switch (arr_type) {
10436
10437 case 0:
10438 // Parse version from comment if there was no magic comment
10439 if (!ua->found_version && parse_state == UFBXI_PARSE_FBX_VERSION && num_values == 0) {
10440 if (val >= 6000 && val <= 10000) {
10441 ua->found_version = true;
10442 uc->version = (uint32_t)val;
10443 }
10444 }
10445
10446 if (num_values < UFBXI_MAX_NON_ARRAY_VALUES) {
10447 type_mask |= (uint32_t)UFBXI_VALUE_NUMBER << (num_values*2);
10448 ufbxi_value *v = &vals[num_values];
10449 // False positive: `v->f` and `v->i` do not overlap in the union.
10450 // cppcheck-suppress overlappingWriteUnion
10451 v->f = (double)(v->i = val) * (double)fsign;
10452 }
10453 break;
10454
10455 case 'b': { bool *v = ufbxi_push(&uc->tmp_stack, bool, 1); ufbxi_check(v); *v = val != 0; } break;
10456 case 'c': { uint8_t *v = ufbxi_push(&uc->tmp_stack, uint8_t, 1); ufbxi_check(v); *v = (uint8_t)val; } break;
10457 case 'i': { int32_t *v = ufbxi_push(&uc->tmp_stack, int32_t, 1); ufbxi_check(v); *v = (int32_t)val; } break;
10458 case 'l': { int64_t *v = ufbxi_push(&uc->tmp_stack, int64_t, 1); ufbxi_check(v); *v = (int64_t)val; } break;
10459 case 'f': { float *v = ufbxi_push(&uc->tmp_stack, float, 1); ufbxi_check(v); *v = (float)val * (float)fsign; } break;
10460 case 'd': { double *v = ufbxi_push(&uc->tmp_stack, double, 1); ufbxi_check(v); *v = (double)val * (double)fsign; } break;
10461 case '-': num_values--; break;
10462
10463 default:
10464 ufbxi_fail("Bad array dst type");
10465
10466 }
10467
10468 } else if (ufbxi_ascii_accept(uc, UFBXI_ASCII_FLOAT)) {
10469 double val = tok->value.f64;
10470
10471 switch (arr_type) {
10472
10473 case 0:
10474 if (num_values < UFBXI_MAX_NON_ARRAY_VALUES) {
10475 type_mask |= (uint32_t)UFBXI_VALUE_NUMBER << (num_values*2);
10476 ufbxi_value *v = &vals[num_values];
10477 // False positive: `v->f` and `v->i` do not overlap in the union.
10478 // cppcheck-suppress overlappingWriteUnion
10479 v->i = ufbxi_f64_to_i64(v->f = val);
10480 }
10481 break;
10482
10483 case 'b': { bool *v = ufbxi_push(&uc->tmp_stack, bool, 1); ufbxi_check(v); *v = val != 0; } break;
10484 case 'c': { uint8_t *v = ufbxi_push(&uc->tmp_stack, uint8_t, 1); ufbxi_check(v); *v = (uint8_t)val; } break;
10485 case 'i': { int32_t *v = ufbxi_push(&uc->tmp_stack, int32_t, 1); ufbxi_check(v); *v = ufbxi_f64_to_i32(val); } break;
10486 case 'l': { int64_t *v = ufbxi_push(&uc->tmp_stack, int64_t, 1); ufbxi_check(v); *v = ufbxi_f64_to_i64(val); } break;
10487 case 'f': { float *v = ufbxi_push(&uc->tmp_stack, float, 1); ufbxi_check(v); *v = (float)val; } break;
10488 case 'd': { double *v = ufbxi_push(&uc->tmp_stack, double, 1); ufbxi_check(v); *v = (double)val; } break;
10489 case '-': num_values--; break;
10490
10491 default:
10492 ufbxi_fail("Bad array dst type");
10493
10494 }
10495
10496 } else if (ufbxi_ascii_accept(uc, UFBXI_ASCII_BARE_WORD)) {
10497
10498 int64_t val = 0;
10499 double val_f = 0.0;
10500 if (tok->str_len >= 1) {
10501 val = (int64_t)tok->str_data[0];
10502 val_f = (double)val;
10503 if (tok->str_len > 1 && tok->str_len < 64) {
10504 // Try to parse the bare word as NAN/INF
10505 char str_data[64]; // ufbxi_uninit
10506 size_t str_len = tok->str_len;
10507 memcpy(str_data, tok->str_data, str_len);
10508 str_data[str_len] = '\0';
10509 double inf_nan;
10510 char *end = NULL;
10511 if (ufbxi_parse_inf_nan(&inf_nan, str_data, str_len, &end) && end == str_data + str_len) {
10512 val = 0;
10513 val_f = inf_nan;
10514 }
10515 }
10516 }
10517
10518 switch (arr_type) {
10519
10520 case 0:
10521 if (num_values < UFBXI_MAX_NON_ARRAY_VALUES) {
10522 type_mask |= (uint32_t)UFBXI_VALUE_NUMBER << (num_values*2);
10523 ufbxi_value *v = &vals[num_values];
10524 // False positive: `v->f` and `v->i` do not overlap in the union.
10525 // cppcheck-suppress overlappingWriteUnion
10526 v->i = val;
10527 v->f = val_f;
10528 }
10529 break;
10530
10531 case 'b': { bool *v = ufbxi_push(&uc->tmp_stack, bool, 1); ufbxi_check(v); *v = val != 0; } break;
10532 case 'c': { uint8_t *v = ufbxi_push(&uc->tmp_stack, uint8_t, 1); ufbxi_check(v); *v = (uint8_t)val; } break;
10533 case 'i': { int32_t *v = ufbxi_push(&uc->tmp_stack, int32_t, 1); ufbxi_check(v); *v = (int32_t)val; } break;
10534 case 'l': { int64_t *v = ufbxi_push(&uc->tmp_stack, int64_t, 1); ufbxi_check(v); *v = (int64_t)val; } break;
10535 case 'f': { float *v = ufbxi_push(&uc->tmp_stack, float, 1); ufbxi_check(v); *v = (float)val_f; } break;
10536 case 'd': { double *v = ufbxi_push(&uc->tmp_stack, double, 1); ufbxi_check(v); *v = (double)val_f; } break;
10537 case '-': num_values--; break;
10538
10539 default:
10540 ufbxi_fail("Bad array dst type");
10541 }
10542
10543 } else if (ufbxi_ascii_accept(uc, '*')) {
10544 // Parse a post-7000 ASCII array eg. "*3 { 1,2,3 }"
10545 ufbxi_check(!in_ascii_array);
10546 ufbxi_check(ufbxi_ascii_accept(uc, UFBXI_ASCII_INT));
10547 int64_t count = ua->prev_token.value.i64;
10548
10549 if (ufbxi_ascii_accept(uc, '{')) {
10550 ufbxi_check(ufbxi_ascii_accept(uc, UFBXI_ASCII_NAME));
10551 in_ascii_array = true;
10552
10553 // Optimized array skipping and threaded parsing
10554 if (arr_type == '-') {
10555 ufbxi_check(ufbxi_ascii_skip_until(uc, '}'));
10556 } else if (uc->parse_threaded && !uc->opts.force_single_thread_ascii_parsing
10557 && !ua->parse_as_f32
10558 && (arr_type == 'i' || arr_type == 'l' || arr_type == 'f' || arr_type == 'd')) {
10559 // Don't bother with small arrays due to fixed overhead
10560 if (count >= UFBXI_MIN_THREADED_ASCII_VALUES && count <= UINT32_MAX) {
10561 deferred_size = (uint32_t)count - 1;
10562 ufbxi_check(ufbxi_ascii_store_array(uc, tmp_buf));
10563 }
10564 }
10565 }
10566
10567 // NOTE: This `continue` skips incrementing `num_values` and parsing
10568 // a comma, continuing to parse the values in the array.
10569 continue;
10570 } else {
10571 break;
10572 }
10573
10574 // Add value and keep parsing if there's a comma. This part may be
10575 // skipped if we enter an array block.
10576 num_values++;
10577 ufbxi_check(num_values < UINT32_MAX);
10578 if (!ufbxi_ascii_accept(uc, ',')) break;
10579 }
10580
10581 // Close the ASCII array if we are in one
10582 if (in_ascii_array) {
10583 ufbxi_check(ufbxi_ascii_accept(uc, '}'));
10584 }
10585
10586 ua->parse_as_f32 = false;
10587
10588 if (arr_type) {
10589 if (arr_type == '-') {
10590 node->array->data = NULL;
10591 node->array->size = 0;
10592 } else {
10593 void *arr_data = NULL;
10594
10595 if (deferred_size > 0) {
10596 arr_data = ufbxi_push_size(arr_buf, arr_elem_size, num_values + deferred_size);
10597 // Pop any previously pushed values
10598 if (num_values > 0) {
10599 ufbxi_pop_size(&uc->tmp_stack, arr_elem_size, num_values, arr_data, false);
10600 }
10601 } else if (arr_error) {
10602 ufbxi_pop_size(&uc->tmp_stack, arr_elem_size, num_values, NULL, false);
10603 num_values = 0;
10604 arr_data = (void*)ufbxi_zero_size_buffer;
10605 } else {
10606 arr_data = ufbxi_push_pop_size(arr_buf, &uc->tmp_stack, arr_elem_size, num_values);
10607 }
10608 ufbxi_check(arr_data);
10609 if (arr_info.flags & UFBXI_ARRAY_FLAG_PAD_BEGIN) {
10610 node->array->data = (char*)arr_data + 4*arr_elem_size;
10611 node->array->size = num_values + deferred_size - 4;
10612 } else {
10613 node->array->data = arr_data;
10614 node->array->size = num_values + deferred_size;
10615 }
10616
10617 // Pop alignment helper
10618 ufbxi_pop_size(&uc->tmp_stack, 8, 1, NULL, false);
10619
10620 // Deferred parsing
10621 if (deferred_size > 0) {
10622 size_t num_spans = uc->tmp_ascii_spans.num_items;
10623 ufbxi_ascii_span *spans = ufbxi_push_pop(tmp_buf, &uc->tmp_ascii_spans, ufbxi_ascii_span, num_spans);
10624 ufbxi_check(spans);
10625
10626 ufbxi_ascii_array_task t; // ufbxi_uninit
10627 t.arr_data = (char*)arr_data + num_values * arr_elem_size;
10628 t.arr_type = (char)arr_type;
10629 t.arr_size = deferred_size;
10630 t.num_spans = num_spans;
10631 t.spans = spans;
10632 t.offset = 0;
10633
10634 // TODO: Split these further
10635 ufbxi_task *task = ufbxi_thread_pool_create_task(&uc->thread_pool, &ufbxi_ascii_array_task_fn);
10636 if (task) {
10637 task->data = ufbxi_push_copy(tmp_buf, ufbxi_ascii_array_task, 1, &t);
10638 ufbxi_check(task->data);
10639 ufbxi_thread_pool_run_task(&uc->thread_pool, task);
10640 } else {
10641 ufbxi_check_msg(ufbxi_ascii_array_task_imp(&t), "Threaded ASCII parse error");
10642 }
10643 }
10644 }
10645 } else {
10646 num_values = ufbxi_min32(num_values, UFBXI_MAX_NON_ARRAY_VALUES);
10647 node->value_type_mask = (uint16_t)type_mask;
10648 node->vals = ufbxi_push_copy(tmp_buf, ufbxi_value, num_values, vals);
10649 ufbxi_check(node->vals);
10650 }
10651
10652 // Recursively parse the children of this node. Update the parse state
10653 // to provide context for child node parsing.
10654 if (ufbxi_ascii_accept(uc, '{')) {
10655 if (recursive) {
10656 size_t num_children = 0;
10657 for (;;) {
10658 bool end = false;
10659 ufbxi_check(ufbxi_ascii_parse_node(uc, depth + 1, parse_state, &end, tmp_buf, recursive));
10660 if (end) break;
10661 num_children++;
10662 }
10663
10664 // Pop children from `tmp_stack` to a contiguous array
10665 node->children = ufbxi_push_pop(tmp_buf, &uc->tmp_stack, ufbxi_node, num_children);
10666 ufbxi_check(node->children);
10667 node->num_children = (uint32_t)num_children;
10668 }
10669
10670 uc->has_next_child = true;
10671 } else {
10672 uc->has_next_child = false;
10673 }
10674
10675 return 1;
10676 }
10677
10678 // -- DOM retention
10679
10680 typedef struct {
10681 uintptr_t node_ptr;
10682 ufbx_dom_node *dom_node;
10683 } ufbxi_dom_mapping;
10684
10685 ufbxi_nodiscard static ufbxi_noinline ufbx_dom_node *ufbxi_get_dom_node_imp(ufbxi_context *uc, ufbxi_node *node)
10686 {
10687 if (!node) return NULL;
10688 ufbxi_dom_mapping mapping = { (uintptr_t)node, NULL };
10689 uint32_t hash = ufbxi_hash_uptr(mapping.node_ptr);
10690 ufbxi_dom_mapping *result = ufbxi_map_find(&uc->dom_node_map, ufbxi_dom_mapping, hash, &mapping);
10691 return result ? result->dom_node : NULL;
10692 }
10693
10694 ufbxi_nodiscard static ufbxi_forceinline ufbx_dom_node *ufbxi_get_dom_node(ufbxi_context *uc, ufbxi_node *node)
10695 {
10696 if (!uc->opts.retain_dom) return NULL;
10697 return ufbxi_get_dom_node_imp(uc, node);
10698 }
10699
10700 // Recursion limited by check in ufbxi_[binary/ascii]_parse_node()
10701 ufbxi_nodiscard static ufbxi_noinline int ufbxi_retain_dom_node(ufbxi_context *uc, ufbxi_node *node, ufbx_dom_node **p_dom_node)
10702 ufbxi_recursive_function(int, ufbxi_retain_dom_node, (uc, node, p_dom_node), UFBXI_MAX_NODE_DEPTH + 1,
10703 (ufbxi_context *uc, ufbxi_node *node, ufbx_dom_node **p_dom_node))
10704 {
10705 ufbx_dom_node *dst = ufbxi_push_zero(&uc->result, ufbx_dom_node, 1);
10706 ufbxi_check(dst);
10707 ufbxi_check(ufbxi_push_copy(&uc->tmp_dom_nodes, ufbx_dom_node*, 1, &dst));
10708
10709 if (p_dom_node) {
10710 *p_dom_node = dst;
10711 }
10712
10713 dst->name.data = node->name;
10714 dst->name.length = node->name_len;
10715
10716 {
10717 ufbxi_dom_mapping mapping = { (uintptr_t)node, NULL };
10718 uint32_t hash = ufbxi_hash_uptr(mapping.node_ptr);
10719 ufbxi_dom_mapping *result = ufbxi_map_find(&uc->dom_node_map, ufbxi_dom_mapping, hash, &mapping);
10720 if (!result) {
10721 result = ufbxi_map_insert(&uc->dom_node_map, ufbxi_dom_mapping, hash, &mapping);
10722 ufbxi_check(result);
10723 }
10724 result->node_ptr = (uintptr_t)node;
10725 result->dom_node = dst;
10726 }
10727
10728 ufbxi_check(ufbxi_push_string_place_str(&uc->string_pool, &dst->name, false));
10729
10730 if (node->value_type_mask == UFBXI_VALUE_ARRAY) {
10731 ufbxi_value_array *arr = node->array;
10732 ufbx_dom_value *val = ufbxi_push_zero(&uc->result, ufbx_dom_value, 1);
10733 ufbxi_check(val);
10734
10735 dst->values.data = val;
10736 dst->values.count = 1;
10737
10738 size_t elem_size = ufbxi_array_type_size(arr->type);
10739 val->value_str.data = ufbxi_empty_char;
10740 val->value_blob.data = arr->data;
10741 val->value_blob.size = arr->size * elem_size;
10742 val->value_float = (double)(val->value_int = (int64_t)arr->size);
10743
10744 switch (arr->type) {
10745 case 'c': val->type = UFBX_DOM_VALUE_BLOB; break;
10746 case 'b': val->type = UFBX_DOM_VALUE_BLOB; break;
10747 case 'i': val->type = UFBX_DOM_VALUE_ARRAY_I32; break;
10748 case 'l': val->type = UFBX_DOM_VALUE_ARRAY_I64; break;
10749 case 'f': val->type = UFBX_DOM_VALUE_ARRAY_F32; break;
10750 case 'd': val->type = UFBX_DOM_VALUE_ARRAY_F64; break;
10751 case 's': val->type = UFBX_DOM_VALUE_ARRAY_BLOB; break;
10752 case 'C': val->type = UFBX_DOM_VALUE_ARRAY_BLOB; break;
10753 case '-': val->type = UFBX_DOM_VALUE_ARRAY_IGNORED; break;
10754 default: ufbxi_fail("Bad array type");
10755 }
10756 } else {
10757 size_t ix;
10758 for (ix = 0; ix < UFBXI_MAX_NON_ARRAY_VALUES; ix++) {
10759 uint32_t mask = (node->value_type_mask >> (2*ix)) & 0x3;
10760 if (!mask) break;
10761 ufbx_dom_value *val = ufbxi_push_zero(&uc->tmp_stack, ufbx_dom_value, 1);
10762 ufbxi_check(val);
10763 val->value_str.data = ufbxi_empty_char;
10764
10765 if (mask == UFBXI_VALUE_STRING) {
10766 val->type = UFBX_DOM_VALUE_STRING;
10767 ufbxi_ignore(ufbxi_get_val_at(node, ix, 'S', &val->value_str));
10768 ufbxi_ignore(ufbxi_get_val_at(node, ix, 'b', &val->value_blob));
10769 } else {
10770 ufbx_assert(mask == UFBXI_VALUE_NUMBER);
10771 val->type = UFBX_DOM_VALUE_NUMBER;
10772 val->value_int = node->vals[ix].i;
10773 val->value_float = node->vals[ix].f;
10774 }
10775 }
10776
10777 dst->values.count = ix;
10778 dst->values.data = ufbxi_push_pop(&uc->result, &uc->tmp_stack, ufbx_dom_value, ix);
10779 ufbxi_check(dst->values.data);
10780 }
10781
10782 if (node->num_children > 0) {
10783 ufbxi_for(ufbxi_node, child, node->children, node->num_children) {
10784 ufbxi_check(ufbxi_retain_dom_node(uc, child, NULL));
10785 }
10786
10787 dst->children.count = node->num_children;
10788 dst->children.data = ufbxi_push_pop(&uc->result, &uc->tmp_dom_nodes, ufbx_dom_node*, node->num_children);
10789 ufbxi_check(dst->children.data);
10790 }
10791
10792 return 1;
10793 }
10794
10795 ufbxi_nodiscard static ufbxi_noinline int ufbxi_retain_toplevel(ufbxi_context *uc, ufbxi_node *node)
10796 {
10797 if (uc->dom_parse_num_children > 0) {
10798 ufbx_dom_node **children = ufbxi_push_pop(&uc->result, &uc->tmp_dom_nodes, ufbx_dom_node*, uc->dom_parse_num_children);
10799 ufbxi_check(children);
10800 uc->dom_parse_toplevel->children.data = children;
10801 uc->dom_parse_toplevel->children.count = uc->dom_parse_num_children;
10802 uc->dom_parse_num_children = 0;
10803 }
10804
10805 if (node) {
10806 ufbxi_check(ufbxi_retain_dom_node(uc, node, &uc->dom_parse_toplevel));
10807 } else {
10808 uc->dom_parse_toplevel = NULL;
10809
10810 // Called with NULL argument to finish retaining DOM, collect the final nodes to `ufbx_scene`.
10811 size_t num_top_nodes = uc->tmp_dom_nodes.num_items;
10812 ufbx_dom_node **nodes = ufbxi_push_pop(&uc->result, &uc->tmp_dom_nodes, ufbx_dom_node*, num_top_nodes);
10813 ufbxi_check(nodes);
10814
10815 ufbx_dom_node *dom_root = ufbxi_push_zero(&uc->result, ufbx_dom_node, 1);
10816 ufbxi_check(dom_root);
10817
10818 dom_root->name.data = ufbxi_empty_char;
10819 dom_root->children.data = nodes;
10820 dom_root->children.count = num_top_nodes;
10821
10822 uc->scene.dom_root = dom_root;
10823 }
10824
10825 return 1;
10826 }
10827
10828 ufbxi_nodiscard static ufbxi_noinline int ufbxi_retain_toplevel_child(ufbxi_context *uc, ufbxi_node *child)
10829 {
10830 ufbx_assert(uc->dom_parse_toplevel);
10831 ufbxi_check(ufbxi_retain_dom_node(uc, child, NULL));
10832 uc->dom_parse_num_children++;
10833
10834 return 1;
10835 }
10836
10837 // -- General parsing
10838
10839 static ufbxi_noinline bool ufbxi_next_line(ufbx_string *line, ufbx_string *buf, bool skip_space)
10840 {
10841 if (buf->length == 0) return false;
10842 const char *newline = (const char*)memchr(buf->data, '\n', buf->length);
10843 size_t length = newline ? ufbxi_to_size(newline - buf->data) + 1 : buf->length;
10844
10845 line->data = buf->data;
10846 line->length = length;
10847 buf->data += length;
10848 buf->length -= length;
10849
10850 if (skip_space) {
10851 while (line->length > 0 && ufbxi_is_space(line->data[0])) {
10852 line->data++;
10853 line->length--;
10854 }
10855 while (line->length > 0 && ufbxi_is_space(line->data[line->length - 1])) {
10856 line->length--;
10857 }
10858 }
10859
10860 return true;
10861 }
10862
10863 // Recursion limited by compile time patterns
10864 static ufbxi_noinline const char *ufbxi_match_skip(const char *fmt, bool alternation)
10865 ufbxi_recursive_function(const char *, ufbxi_match_skip, (fmt, alternation), 4,
10866 (const char *fmt, bool alternation))
10867 {
10868 for (;;) {
10869 char c = *fmt++;
10870 switch (c) {
10871 case '(':
10872 fmt = ufbxi_match_skip(fmt, false) + 1;
10873 break;
10874 case '\\':
10875 fmt++;
10876 break;
10877 case '[':
10878 c = *fmt;
10879 while (c != ']') {
10880 c = *fmt++;
10881 if (c == '\\') {
10882 c = *fmt++;
10883 }
10884 }
10885 fmt++;
10886 break;
10887 case '|':
10888 if (alternation) return fmt - 1;
10889 break;
10890 case ')':
10891 case '\0':
10892 return fmt - 1;
10893 default: break;
10894 }
10895 }
10896 }
10897
10898 // Recursion limited by compile time patterns
10899 static ufbxi_noinline bool ufbxi_match_imp(const char **p_str, const char *end, const char **p_fmt)
10900 ufbxi_recursive_function(bool, ufbxi_match_imp, (p_str, end, p_fmt), 4,
10901 (const char **p_str, const char *end, const char **p_fmt))
10902 {
10903 const char *str_original_begin = *p_str;
10904 const char *str = str_original_begin;
10905 const char *fmt_begin = *p_fmt;
10906 const char *fmt = fmt_begin;
10907 bool case_insensitive = false;
10908
10909 size_t count = 0;
10910 for (;;) {
10911 char c = *fmt++;
10912 if (!c) {
10913 *p_str = str;
10914 *p_fmt = fmt - 1;
10915 return true;
10916 }
10917
10918 const char *str_begin = str;
10919 char ref = str != end ? *str : '\0';
10920
10921 if (case_insensitive) {
10922 if (ref >= 'A' && ref <= 'Z') {
10923 ref = (char)((int)(ref - 'A') + 'a');
10924 }
10925 }
10926
10927 bool ok = false;
10928 switch (c) {
10929
10930 case '\\': {
10931 const char *macro = NULL;
10932 c = *fmt++;
10933 switch (c) {
10934 case 'd':
10935 macro = "[0-9]";
10936 break;
10937 case 'F':
10938 macro = "[\\-+]?[0-9]+(\\.[0-9]+)?([eE][\\-+]?[0-9]+)?";
10939 break;
10940 case 's':
10941 if (ufbxi_is_space(ref)) {
10942 ok = true;
10943 str++;
10944 }
10945 break;
10946 case 'S':
10947 if (!ufbxi_is_space(ref)) {
10948 ok = true;
10949 str++;
10950 }
10951 break;
10952 case 'c':
10953 case 'C':
10954 case_insensitive = c == 'c';
10955 ok = true;
10956 break;
10957 default:
10958 if (ref == c) {
10959 ok = true;
10960 str++;
10961 }
10962 break;
10963 }
10964 if (macro) {
10965 ok = ufbxi_match_imp(&str, end, &macro);
10966 }
10967 } break;
10968
10969 case '[': {
10970 while (fmt[0] != ']') {
10971 if (fmt[0] == '\\') {
10972 if (ref == fmt[1]) ok = true;
10973 fmt += 2;
10974 } else if (fmt[1] == '-') {
10975 if (ref >= fmt[0] && ref <= fmt[2]) {
10976 ok = true;
10977 }
10978 fmt += 3;
10979 } else {
10980 if (ref == fmt[0]) ok = true;
10981 fmt += 1;
10982 }
10983 }
10984 fmt++;
10985 if (ok) str++;
10986 } break;
10987
10988 case '(':
10989 if (ufbxi_match_imp(&str, end, &fmt)) {
10990 ok = true;
10991 }
10992 break;
10993
10994 case '|':
10995 fmt = ufbxi_match_skip(fmt, false);
10996 ok = true;
10997 break;
10998
10999 case ')':
11000 *p_str = str;
11001 *p_fmt = fmt;
11002 return true;
11003
11004 case '.':
11005 if (ref != '\0') {
11006 ok = true;
11007 str++;
11008 }
11009 break;
11010
11011 default:
11012 if (c == ref) {
11013 str++;
11014 ok = true;
11015 }
11016 break;
11017 }
11018
11019 bool did_fail = false;
11020 c = *fmt;
11021 switch (c) {
11022 case '*':
11023 fmt++;
11024 if (ok) {
11025 fmt = fmt_begin;
11026 count++;
11027 continue;
11028 }
11029 break;
11030 case '+':
11031 fmt++;
11032 if (ok) {
11033 fmt = fmt_begin;
11034 count++;
11035 continue;
11036 } else if (count == 0) {
11037 did_fail = true;
11038 }
11039 break;
11040 case '?':
11041 fmt++;
11042 break;
11043 default:
11044 did_fail = !ok;
11045 break;
11046 }
11047
11048 if (did_fail) {
11049 fmt = ufbxi_match_skip(fmt, true);
11050 if (*fmt == '|') {
11051 fmt++;
11052 str = str_original_begin;
11053 } else {
11054 *p_fmt = ufbxi_match_skip(fmt, false) + 1;
11055 return false;
11056 }
11057 } else {
11058 if (!ok) {
11059 str = str_begin;
11060 }
11061 }
11062
11063 fmt_begin = fmt;
11064 count = 0;
11065 }
11066 }
11067
11068 static ufbxi_noinline bool ufbxi_match(const ufbx_string *str, const char *fmt)
11069 {
11070 const char *ptr = str->data, *end = str->data + str->length;
11071 if (ufbxi_match_imp(&ptr, end, &fmt)) {
11072 return ptr == end;
11073 } else {
11074 return false;
11075 }
11076 }
11077
11078 static ufbxi_noinline bool ufbxi_is_format(const char *data, size_t size, ufbx_file_format format)
11079 {
11080 ufbx_string line, buf = { data, size };
11081
11082 if (format == UFBX_FILE_FORMAT_FBX) {
11083 if (size >= UFBXI_BINARY_MAGIC_SIZE && !memcmp(data, ufbxi_binary_magic, UFBXI_BINARY_MAGIC_SIZE)) {
11084 return true;
11085 }
11086
11087 while (ufbxi_next_line(&line, &buf, true)) {
11088 if (ufbxi_match(&line, ";\\s*FBX\\s*\\d+\\.\\d+\\.\\d+\\s*project\\s+file")) return true;
11089 if (ufbxi_match(&line, "FBXHeaderExtension:.*")) return true;
11090 }
11091 } else if (format == UFBX_FILE_FORMAT_OBJ) {
11092 while (ufbxi_next_line(&line, &buf, true)) {
11093 const char *pattern =
11094 "(vn?\\s+\\F|vt)\\s+\\F\\s+\\F.*" "|"
11095 "f\\s+[\\-/0-9]+\\s+[\\-/0-9]+\\s*[\\-/0-9]+.*" "|"
11096 "(usemtl|mtllib)\\s+\\S.*";
11097 if (ufbxi_match(&line, pattern)) return true;
11098 }
11099 } else if (format == UFBX_FILE_FORMAT_MTL) {
11100 while (ufbxi_next_line(&line, &buf, true)) {
11101 const char *pattern =
11102 "newmtl\\s+\\S.*";
11103 if (ufbxi_match(&line, pattern)) return true;
11104 }
11105 } else {
11106 ufbxi_unreachable("Unhandled format");
11107 }
11108
11109 return false;
11110 }
11111
11112 ufbxi_nodiscard static ufbxi_noinline int ufbxi_determine_format(ufbxi_context *uc)
11113 {
11114 ufbx_file_format format = uc->opts.file_format;
11115
11116 if (format == UFBX_FILE_FORMAT_UNKNOWN && !uc->opts.no_format_from_content) {
11117 ufbxi_pause_progress(uc);
11118
11119 size_t lookahead = UFBXI_MIN_FILE_FORMAT_LOOKAHEAD;
11120 while (format == UFBX_FILE_FORMAT_UNKNOWN && lookahead <= uc->opts.file_format_lookahead) {
11121 if (lookahead > uc->data_size) {
11122 if (uc->eof) break;
11123 ufbxi_check(ufbxi_refill(uc, lookahead, false));
11124 }
11125
11126 size_t data_size = ufbxi_min_sz(lookahead, uc->data_size);
11127 ufbxi_check_msg(data_size > 0, "Empty file");
11128
11129 for (uint32_t fmt = UFBX_FILE_FORMAT_FBX; fmt < UFBX_FILE_FORMAT_COUNT; fmt++) {
11130 if (ufbxi_is_format(uc->data, data_size, (ufbx_file_format)fmt)) {
11131 format = (ufbx_file_format)fmt;
11132 break;
11133 }
11134 }
11135
11136 if (lookahead >= uc->opts.file_format_lookahead) {
11137 break;
11138 } else if (lookahead < SIZE_MAX / 2) {
11139 lookahead = ufbxi_min_sz(lookahead * 2, uc->opts.file_format_lookahead);
11140 } else {
11141 lookahead = SIZE_MAX;
11142 }
11143 }
11144
11145 ufbxi_check(ufbxi_resume_progress(uc));
11146 }
11147
11148 if (format == UFBX_FILE_FORMAT_UNKNOWN && !uc->opts.no_format_from_extension) {
11149 if (uc->opts.filename.length > 0) {
11150 ufbx_string extension = uc->opts.filename;
11151 for (size_t i = extension.length; i > 0; i--) {
11152 if (extension.data[i - 1] == '.') {
11153 extension.data += i - 1;
11154 extension.length -= i - 1;
11155 break;
11156 }
11157 }
11158
11159 if (ufbxi_match(&extension, "\\c\\.fbx")) {
11160 format = UFBX_FILE_FORMAT_FBX;
11161 } else if (ufbxi_match(&extension, "\\c\\.obj")) {
11162 format = UFBX_FILE_FORMAT_OBJ;
11163 } else if (ufbxi_match(&extension, "\\c\\.mtl")) {
11164 format = UFBX_FILE_FORMAT_MTL;
11165 }
11166 }
11167 }
11168
11169 ufbxi_check_msg(format != UFBX_FILE_FORMAT_UNKNOWN, "Unrecognized file format");
11170 uc->scene.metadata.file_format = format;
11171
11172 return 1;
11173 }
11174
11175 ufbxi_nodiscard static ufbxi_noinline int ufbxi_begin_parse(ufbxi_context *uc)
11176 {
11177 const char *header = ufbxi_peek_bytes(uc, UFBXI_BINARY_HEADER_SIZE);
11178 ufbxi_check(header);
11179
11180 // If the file starts with the binary magic parse it as binary, otherwise
11181 // treat it as an ASCII file.
11182 if (!memcmp(header, ufbxi_binary_magic, UFBXI_BINARY_MAGIC_SIZE)) {
11183
11184 // The byte after the magic indicates endianness
11185 char endian = header[UFBXI_BINARY_MAGIC_SIZE + 0];
11186 uc->file_big_endian = endian != 0;
11187
11188 // Read the version directly from the header
11189 const char *version_word = header + UFBXI_BINARY_MAGIC_SIZE + 1;
11190 if (uc->file_big_endian) {
11191 version_word = ufbxi_swap_endian(uc, version_word, 1, 4);
11192 ufbxi_check(version_word);
11193 }
11194 uc->version = ufbxi_read_u32(version_word);
11195
11196 // This is quite probably an FBX file..
11197 uc->sure_fbx = true;
11198 ufbxi_consume_bytes(uc, UFBXI_BINARY_HEADER_SIZE);
11199
11200 } else {
11201 uc->from_ascii = true;
11202
11203 // Use the current read buffer as the initial parse buffer
11204 memset(&uc->ascii, 0, sizeof(uc->ascii));
11205 uc->ascii.src = uc->data;
11206 uc->ascii.src_yield = uc->data + uc->yield_size;
11207 uc->ascii.src_end = uc->data + uc->data_size + uc->yield_size;
11208
11209 // Initialize the first token
11210 ufbxi_check(ufbxi_ascii_next_token(uc, &uc->ascii.token));
11211
11212 // Default to version 7400 if not found in header
11213 if (uc->version > 0) {
11214 uc->sure_fbx = true;
11215 } else {
11216 if (!uc->opts.strict) uc->version = 7400;
11217 ufbxi_check_msg(uc->version > 0, "Not an FBX file");
11218 }
11219 }
11220
11221 return 1;
11222 }
11223
11224 ufbxi_nodiscard static int ufbxi_parse_toplevel_child_imp(ufbxi_context *uc, ufbxi_parse_state state, ufbxi_buf *buf, bool *p_end)
11225 {
11226 if (uc->from_ascii) {
11227 ufbxi_check(ufbxi_ascii_parse_node(uc, 0, state, p_end, buf, true));
11228 } else {
11229 ufbxi_check(ufbxi_binary_parse_node(uc, 0, state, p_end, buf, true));
11230 }
11231
11232 return 1;
11233 }
11234
11235 ufbxi_nodiscard ufbxi_noinline static int ufbxi_parse_toplevel(ufbxi_context *uc, const char *name)
11236 {
11237 ufbxi_for(ufbxi_node, node, uc->top_nodes, uc->top_nodes_len) {
11238 if (node->name == name) {
11239 uc->top_node = node;
11240 uc->top_child_index = 0;
11241 return 1;
11242 }
11243 }
11244
11245 // Reached end and not found in cache
11246 if (uc->parsed_to_end) {
11247 uc->top_node = NULL;
11248 uc->top_child_index = 0;
11249 return 1;
11250 }
11251
11252 for (;;) {
11253 // Parse the next top-level node
11254 bool end = false;
11255 if (uc->from_ascii) {
11256 ufbxi_check(ufbxi_ascii_parse_node(uc, 0, UFBXI_PARSE_ROOT, &end, &uc->tmp, false));
11257 } else {
11258 ufbxi_check(ufbxi_binary_parse_node(uc, 0, UFBXI_PARSE_ROOT, &end, &uc->tmp, false));
11259 }
11260
11261 // Top-level node not found
11262 if (end) {
11263 uc->top_node = NULL;
11264 uc->top_child_index = 0;
11265 uc->parsed_to_end = true;
11266 if (uc->opts.retain_dom) {
11267 ufbxi_check(ufbxi_retain_toplevel(uc, NULL));
11268 }
11269
11270 // Not needed anymore
11271 ufbxi_buf_free(&uc->tmp_parse);
11272
11273 return 1;
11274 }
11275
11276 uc->top_nodes_len++;
11277 ufbxi_check(ufbxi_grow_array(&uc->ator_tmp, &uc->top_nodes, &uc->top_nodes_cap, uc->top_nodes_len));
11278 ufbxi_node *node = &uc->top_nodes[uc->top_nodes_len - 1];
11279 ufbxi_pop(&uc->tmp_stack, ufbxi_node, 1, node);
11280 if (uc->opts.retain_dom) {
11281 ufbxi_check(ufbxi_retain_toplevel(uc, node));
11282 }
11283
11284 // Return if we parsed the right one
11285 if (node->name == name) {
11286 uc->top_node = node;
11287 uc->top_child_index = SIZE_MAX;
11288 return 1;
11289 }
11290
11291 // If not we need to parse all the children of the node for later
11292 uint32_t num_children = 0;
11293 ufbxi_parse_state state = ufbxi_update_parse_state(UFBXI_PARSE_ROOT, node->name);
11294 if (uc->has_next_child) {
11295 for (;;) {
11296 ufbxi_check(ufbxi_parse_toplevel_child_imp(uc, state, &uc->tmp, &end));
11297 if (end) break;
11298 num_children++;
11299 }
11300 }
11301
11302 node->num_children = num_children;
11303 node->children = ufbxi_push_pop(&uc->tmp, &uc->tmp_stack, ufbxi_node, num_children);
11304 ufbxi_check(node->children);
11305
11306 if (uc->opts.retain_dom) {
11307 for (size_t i = 0; i < num_children; i++) {
11308 ufbxi_check(ufbxi_retain_toplevel_child(uc, &node->children[i]));
11309 }
11310 }
11311 }
11312 }
11313
11314 ufbxi_nodiscard ufbxi_noinline static int ufbxi_parse_toplevel_child(ufbxi_context *uc, ufbxi_node **p_node, ufbxi_buf *tmp_buf)
11315 {
11316 // Top-level node not found
11317 if (!uc->top_node) {
11318 *p_node = NULL;
11319 return 1;
11320 }
11321
11322 if (uc->top_child_index == SIZE_MAX) {
11323 // Parse children on demand
11324 if (!tmp_buf) {
11325 ufbxi_buf_clear(&uc->tmp_parse);
11326 }
11327 bool end = false;
11328 ufbxi_parse_state state = ufbxi_update_parse_state(UFBXI_PARSE_ROOT, uc->top_node->name);
11329 ufbxi_check(ufbxi_parse_toplevel_child_imp(uc, state, tmp_buf ? tmp_buf : &uc->tmp_parse, &end));
11330 if (end) {
11331 *p_node = NULL;
11332 } else {
11333 // Parse to either reused `uc->top_child` or push if retaining to `tmp_buf`.
11334 ufbxi_node *dst = &uc->top_child;
11335 if (tmp_buf) {
11336 dst = ufbxi_push_zero(tmp_buf, ufbxi_node, 1);
11337 ufbxi_check(dst);
11338 }
11339
11340 ufbxi_pop(&uc->tmp_stack, ufbxi_node, 1, dst);
11341 *p_node = dst;
11342
11343 if (uc->opts.retain_dom) {
11344 ufbxi_check(ufbxi_retain_toplevel_child(uc, dst));
11345 }
11346 }
11347 } else {
11348 // Iterate already parsed nodes
11349 size_t child_index = uc->top_child_index;
11350 if (child_index == uc->top_node->num_children) {
11351 *p_node = NULL;
11352 } else {
11353 uc->top_child_index++;
11354 *p_node = &uc->top_node->children[child_index];
11355 }
11356 }
11357
11358 return 1;
11359 }
11360
11361 ufbxi_nodiscard ufbxi_noinline static int ufbxi_parse_legacy_toplevel(ufbxi_context *uc)
11362 {
11363 ufbx_assert(uc->top_nodes_len == 0);
11364
11365 bool end = false;
11366 if (uc->from_ascii) {
11367 ufbxi_check(ufbxi_ascii_parse_node(uc, 0, UFBXI_PARSE_ROOT, &end, &uc->tmp, true));
11368 } else {
11369 ufbxi_check(ufbxi_binary_parse_node(uc, 0, UFBXI_PARSE_ROOT, &end, &uc->tmp, true));
11370 }
11371
11372 // Top-level node not found
11373 if (end) {
11374 uc->top_node = NULL;
11375 uc->top_child_index = 0;
11376 uc->parsed_to_end = true;
11377 return 1;
11378 }
11379
11380 ufbxi_pop(&uc->tmp_stack, ufbxi_node, 1, &uc->legacy_node);
11381 uc->top_child_index = 0;
11382 uc->top_node = &uc->legacy_node;
11383
11384 if (uc->opts.retain_dom) {
11385 ufbxi_check(ufbxi_retain_toplevel(uc, &uc->legacy_node));
11386 }
11387
11388 return 1;
11389 }
11390
11391 // -- Setup
11392
11393 ufbxi_nodiscard static ufbxi_noinline int ufbxi_load_strings(ufbxi_context *uc)
11394 {
11395 #if defined(UFBX_REGRESSION)
11396 ufbx_string reg_prev = ufbx_empty_string;
11397 #endif
11398
11399 // Push all the global 'ufbxi_*' strings into the pool without copying them
11400 // This allows us to compare name pointers to the global values
11401 ufbxi_for(const ufbx_string, str, ufbxi_strings, ufbxi_arraycount(ufbxi_strings)) {
11402 #if defined(UFBX_REGRESSION)
11403 ufbx_assert(strlen(str->data) == str->length);
11404 ufbx_assert(ufbxi_str_less(reg_prev, *str));
11405 reg_prev = *str;
11406 #endif
11407 ufbxi_check(ufbxi_push_string_imp(&uc->string_pool, str->data, str->length, NULL, false, true));
11408 }
11409
11410 return 1;
11411 }
11412
11413 typedef struct {
11414 const char *name;
11415 ufbx_prop_type type;
11416 } ufbxi_prop_type_name;
11417
11418 static const ufbxi_prop_type_name ufbxi_prop_type_names[] = {
11419 { "Boolean", UFBX_PROP_BOOLEAN },
11420 { "bool", UFBX_PROP_BOOLEAN },
11421 { "Bool", UFBX_PROP_BOOLEAN },
11422 { "Integer", UFBX_PROP_INTEGER },
11423 { "int", UFBX_PROP_INTEGER },
11424 { "enum", UFBX_PROP_INTEGER },
11425 { "Enum", UFBX_PROP_INTEGER },
11426 { "Visibility", UFBX_PROP_INTEGER },
11427 { "Visibility Inheritance", UFBX_PROP_INTEGER },
11428 { "KTime", UFBX_PROP_INTEGER },
11429 { "Number", UFBX_PROP_NUMBER },
11430 { "double", UFBX_PROP_NUMBER },
11431 { "Real", UFBX_PROP_NUMBER },
11432 { "Float", UFBX_PROP_NUMBER },
11433 { "Intensity", UFBX_PROP_NUMBER },
11434 { "Vector", UFBX_PROP_VECTOR },
11435 { "Vector3D", UFBX_PROP_VECTOR },
11436 { "Color", UFBX_PROP_COLOR },
11437 { "ColorAndAlpha", UFBX_PROP_COLOR_WITH_ALPHA },
11438 { "ColorRGB", UFBX_PROP_COLOR },
11439 { "String", UFBX_PROP_STRING },
11440 { "KString", UFBX_PROP_STRING },
11441 { "object", UFBX_PROP_STRING },
11442 { "DateTime", UFBX_PROP_DATE_TIME },
11443 { "Lcl Translation", UFBX_PROP_TRANSLATION },
11444 { "Lcl Rotation", UFBX_PROP_ROTATION },
11445 { "Lcl Scaling", UFBX_PROP_SCALING },
11446 { "Distance", UFBX_PROP_DISTANCE },
11447 { "Compound", UFBX_PROP_COMPOUND },
11448 { "Blob", UFBX_PROP_BLOB },
11449 { "Reference", UFBX_PROP_REFERENCE },
11450 };
11451
11452 static ufbx_prop_type ufbxi_get_prop_type(ufbxi_context *uc, const char *name)
11453 {
11454 uint32_t hash = ufbxi_hash_ptr(name);
11455 ufbxi_prop_type_name *entry = ufbxi_map_find(&uc->prop_type_map, ufbxi_prop_type_name, hash, &name);
11456 if (entry) {
11457 return entry->type;
11458 }
11459 return UFBX_PROP_UNKNOWN;
11460 }
11461
11462 static ufbxi_noinline ufbx_prop *ufbxi_find_prop_with_key(const ufbx_props *props, const char *name, uint32_t key)
11463 {
11464 do {
11465 ufbx_prop *prop_data = props->props.data;
11466 size_t begin = 0;
11467 size_t end = props->props.count;
11468 while (end - begin >= 16) {
11469 size_t mid = (begin + end) >> 1;
11470 const ufbx_prop *p = &prop_data[mid];
11471 if (p->_internal_key < key) {
11472 begin = mid + 1;
11473 } else {
11474 end = mid;
11475 }
11476 }
11477
11478 end = props->props.count;
11479 for (; begin < end; begin++) {
11480 const ufbx_prop *p = &prop_data[begin];
11481 if (p->_internal_key > key) break;
11482 if (p->name.data == name && (p->flags & UFBX_PROP_FLAG_NO_VALUE) == 0) {
11483 return (ufbx_prop*)p;
11484 }
11485 }
11486
11487 props = props->defaults;
11488 } while (props);
11489
11490 return NULL;
11491 }
11492
11493 typedef struct {
11494 const char *key;
11495 ufbx_texture_file *file;
11496 } ufbxi_texture_file_entry;
11497
11498 #define ufbxi_find_prop(props, name) ufbxi_find_prop_with_key((props), (name), \
11499 ((uint32_t)(uint8_t)name[0] << 24u) | ((uint32_t)(uint8_t)name[1] << 16u) | \
11500 ((uint32_t)(uint8_t)name[2] << 8u) | (uint32_t)(uint8_t)name[3])
11501
11502 static ufbxi_forceinline ufbx_real ufbxi_find_real(const ufbx_props *props, const char *name, ufbx_real def)
11503 {
11504 ufbx_prop *prop = ufbxi_find_prop(props, name);
11505 if (prop) {
11506 return prop->value_real;
11507 } else {
11508 return def;
11509 }
11510 }
11511
11512 static ufbxi_forceinline ufbx_vec3 ufbxi_find_vec3(const ufbx_props *props, const char *name, ufbx_real def_x, ufbx_real def_y, ufbx_real def_z)
11513 {
11514 ufbx_prop *prop = ufbxi_find_prop(props, name);
11515 if (prop) {
11516 return prop->value_vec3;
11517 } else {
11518 ufbx_vec3 def = { def_x, def_y, def_z };
11519 return def;
11520 }
11521 }
11522
11523 static ufbxi_forceinline int64_t ufbxi_find_int(const ufbx_props *props, const char *name, int64_t def)
11524 {
11525 ufbx_prop *prop = ufbxi_find_prop(props, name);
11526 if (prop) {
11527 return prop->value_int;
11528 } else {
11529 return def;
11530 }
11531 }
11532
11533 static ufbxi_forceinline int64_t ufbxi_find_enum(const ufbx_props *props, const char *name, int64_t def, int64_t max_value)
11534 {
11535 ufbx_prop *prop = ufbxi_find_prop(props, name);
11536 if (prop) {
11537 int64_t value = prop->value_int;
11538 if (value >= 0 && value <= max_value) {
11539 return value;
11540 } else {
11541 return def;
11542 }
11543 } else {
11544 return def;
11545 }
11546 }
11547
11548 ufbxi_noinline static bool ufbxi_matrix_all_zero(const ufbx_matrix *matrix)
11549 {
11550 for (size_t i = 0; i < 12; i++) {
11551 if (matrix->v[i] != 0.0f) return false;
11552 }
11553 return true;
11554 }
11555
11556 static ufbxi_forceinline bool ufbxi_is_vec3_zero(ufbx_vec3 v)
11557 {
11558 return (v.x == 0.0) & (v.y == 0.0) & (v.z == 0.0);
11559 }
11560
11561 static ufbxi_forceinline bool ufbxi_is_vec4_zero(ufbx_vec4 v)
11562 {
11563 return (v.x == 0.0) & (v.y == 0.0) & (v.z == 0.0);
11564 }
11565
11566 static ufbxi_forceinline bool ufbxi_is_vec3_one(ufbx_vec3 v)
11567 {
11568 return (v.x == 1.0) & (v.y == 1.0) & (v.z == 1.0);
11569 }
11570
11571 static ufbxi_forceinline bool ufbxi_is_quat_identity(ufbx_quat v)
11572 {
11573 return (v.x == 0.0) & (v.y == 0.0) & (v.z == 0.0) & (v.w == 1.0);
11574 }
11575
11576 static ufbxi_noinline bool ufbxi_is_transform_identity(const ufbx_transform *t)
11577 {
11578 return (bool)((int)ufbxi_is_vec3_zero(t->translation) & (int)ufbxi_is_quat_identity(t->rotation) & (int)ufbxi_is_vec3_one(t->scale));
11579 }
11580
11581 static ufbxi_forceinline uint32_t ufbxi_get_name_key(const char *name, size_t len)
11582 {
11583 uint32_t key = 0;
11584 if (len >= 4) {
11585 key = (uint32_t)(uint8_t)name[0]<<24 | (uint32_t)(uint8_t)name[1]<<16
11586 | (uint32_t)(uint8_t)name[2]<<8 | (uint32_t)(uint8_t)name[3];
11587 } else {
11588 for (size_t i = 0; i < 4; i++) {
11589 key <<= 8;
11590 if (i < len) key |= (uint8_t)name[i];
11591 }
11592 }
11593 return key;
11594 }
11595
11596 static ufbxi_forceinline uint32_t ufbxi_get_name_key_c(const char *name)
11597 {
11598 if (name[0] == '\0') return 0;
11599 if (name[1] == '\0') return (uint32_t)(uint8_t)name[0]<<24;
11600 if (name[2] == '\0') return (uint32_t)(uint8_t)name[0]<<24 | (uint32_t)(uint8_t)name[1]<<16;
11601 return (uint32_t)(uint8_t)name[0]<<24 | (uint32_t)(uint8_t)name[1]<<16
11602 | (uint32_t)(uint8_t)name[2]<<8 | (uint32_t)(uint8_t)name[3];
11603 }
11604
11605 static ufbxi_forceinline bool ufbxi_name_key_less(ufbx_prop *prop, const char *data, size_t name_len, uint32_t key)
11606 {
11607 if (prop->_internal_key < key) return true;
11608 if (prop->_internal_key > key) return false;
11609
11610 size_t prop_len = prop->name.length;
11611 size_t len = ufbxi_min_sz(prop_len, name_len);
11612 int cmp = memcmp(prop->name.data, data, len);
11613 if (cmp != 0) return cmp < 0;
11614 return prop_len < name_len;
11615 }
11616
11617 static const char *const ufbxi_node_prop_names[] = {
11618 "AxisLen",
11619 "DefaultAttributeIndex",
11620 "Freeze",
11621 "GeometricRotation",
11622 "GeometricScaling",
11623 "GeometricTranslation",
11624 "InheritType",
11625 "LODBox",
11626 "Lcl Rotation",
11627 "Lcl Scaling",
11628 "Lcl Translation",
11629 "LookAtProperty",
11630 "MaxDampRangeX",
11631 "MaxDampRangeY",
11632 "MaxDampRangeZ",
11633 "MaxDampStrengthX",
11634 "MaxDampStrengthY",
11635 "MaxDampStrengthZ",
11636 "MinDampRangeX",
11637 "MinDampRangeY",
11638 "MinDampRangeZ",
11639 "MinDampStrengthX",
11640 "MinDampStrengthY",
11641 "MinDampStrengthZ",
11642 "NegativePercentShapeSupport",
11643 "PostRotation",
11644 "PreRotation",
11645 "PreferedAngleX",
11646 "PreferedAngleY",
11647 "PreferedAngleZ",
11648 "QuaternionInterpolate",
11649 "RotationActive",
11650 "RotationMax",
11651 "RotationMaxX",
11652 "RotationMaxY",
11653 "RotationMaxZ",
11654 "RotationMin",
11655 "RotationMinX",
11656 "RotationMinY",
11657 "RotationMinZ",
11658 "RotationOffset",
11659 "RotationOrder",
11660 "RotationPivot",
11661 "RotationSpaceForLimitOnly",
11662 "RotationStiffnessX",
11663 "RotationStiffnessY",
11664 "RotationStiffnessZ",
11665 "ScalingActive",
11666 "ScalingMax",
11667 "ScalingMaxX",
11668 "ScalingMaxY",
11669 "ScalingMaxZ",
11670 "ScalingMin",
11671 "ScalingMinX",
11672 "ScalingMinY",
11673 "ScalingMinZ",
11674 "ScalingOffset",
11675 "ScalingPivot",
11676 "Show",
11677 "TranslationActive",
11678 "TranslationMax",
11679 "TranslationMaxX",
11680 "TranslationMaxY",
11681 "TranslationMaxZ",
11682 "TranslationMin",
11683 "TranslationMinX",
11684 "TranslationMinY",
11685 "TranslationMinZ",
11686 "UpVectorProperty",
11687 "Visibility Inheritance",
11688 "Visibility",
11689 "notes",
11690 };
11691
11692 ufbxi_nodiscard static ufbxi_noinline int ufbxi_init_node_prop_names(ufbxi_context *uc)
11693 {
11694 ufbxi_check(ufbxi_map_grow(&uc->node_prop_set, const char*, ufbxi_arraycount(ufbxi_node_prop_names)));
11695 for (size_t i = 0; i < ufbxi_arraycount(ufbxi_node_prop_names); i++) {
11696 const char *name = ufbxi_node_prop_names[i];
11697 const char *pooled = ufbxi_push_string_imp(&uc->string_pool, name, strlen(name), NULL, false, true);
11698 ufbxi_check(pooled);
11699 uint32_t hash = ufbxi_hash_ptr(pooled);
11700 const char **entry = ufbxi_map_insert(&uc->node_prop_set, const char*, hash, &pooled);
11701 ufbxi_check(entry);
11702 *entry = pooled;
11703 }
11704
11705 return 1;
11706 }
11707
11708 static bool ufbxi_is_node_property_name(ufbxi_context *uc, const char *name)
11709 {
11710 // You need to call `ufbxi_init_node_prop_names()` before calling this
11711 ufbx_assert(uc->node_prop_set.size > 0);
11712
11713 uint32_t hash = ufbxi_hash_ptr(name);
11714 const char **entry = ufbxi_map_find(&uc->node_prop_set, const char*, hash, &name);
11715 return entry != NULL;
11716 }
11717
11718 ufbxi_nodiscard static ufbxi_noinline int ufbxi_load_maps(ufbxi_context *uc)
11719 {
11720 ufbxi_check(ufbxi_map_grow(&uc->prop_type_map, ufbxi_prop_type_name, ufbxi_arraycount(ufbxi_prop_type_names)));
11721 ufbxi_for(const ufbxi_prop_type_name, name, ufbxi_prop_type_names, ufbxi_arraycount(ufbxi_prop_type_names)) {
11722 const char *pooled = ufbxi_push_string_imp(&uc->string_pool, name->name, strlen(name->name), NULL, false, true);
11723 ufbxi_check(pooled);
11724 uint32_t hash = ufbxi_hash_ptr(pooled);
11725 ufbxi_prop_type_name *entry = ufbxi_map_insert(&uc->prop_type_map, ufbxi_prop_type_name, hash, &pooled);
11726 ufbxi_check(entry);
11727 entry->type = name->type;
11728 entry->name = pooled;
11729 }
11730
11731 return 1;
11732 }
11733
11734 // -- Reading the parsed data
11735
11736 ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_embedded_blob(ufbxi_context *uc, ufbx_blob *dst_blob, ufbxi_node *node)
11737 {
11738 if (!node) return 1;
11739
11740 ufbxi_value_array *content_arr = ufbxi_get_array(node, 'C');
11741 if (content_arr && content_arr->size > 0) {
11742 ufbx_string content;
11743 size_t num_parts = content_arr->size;
11744 ufbx_string *parts = (ufbx_string*)content_arr->data;
11745
11746 if (num_parts == 1 && !uc->from_ascii) {
11747 content = parts[0];
11748 } else {
11749 size_t total_size = 0;
11750 ufbxi_for(ufbx_string, part, parts, num_parts) {
11751 total_size += part->length;
11752 }
11753 char *dst = ufbxi_push(&uc->result, char, total_size);
11754 ufbxi_check(dst);
11755 content.data = dst;
11756 content.length = total_size;
11757 ufbxi_for(ufbx_string, part, parts, num_parts) {
11758 memcpy(dst, part->data, part->length);
11759 dst += part->length;
11760 }
11761 }
11762
11763 dst_blob->data = content.data;
11764 dst_blob->size = content.length;
11765 }
11766
11767 return 1;
11768 }
11769
11770 ufbxi_nodiscard static ufbxi_noinline int ufbxi_read_property(ufbxi_context *uc, ufbxi_node *node, ufbx_prop *prop, int version)
11771 {
11772 const char *type_str = NULL, *subtype_str = NULL;
11773 ufbxi_check(ufbxi_get_val2(node, "SC", &prop->name, (char**)&type_str));
11774 uint32_t val_ix = 2;
11775 if (version == 70) {
11776 ufbxi_check(ufbxi_get_val_at(node, val_ix++, 'C', (char**)&subtype_str));
11777 }
11778
11779 uint32_t flags = 0;
11780 prop->_internal_key = ufbxi_get_name_key(prop->name.data, prop->name.length);
11781
11782 ufbx_string flags_str;
11783 if (ufbxi_get_val_at(node, val_ix++, 'S', &flags_str)) {
11784 for (size_t i = 0; i < flags_str.length; i++) {
11785 char next = i + 1 < flags_str.length ? flags_str.data[i + 1] : '0';
11786 switch (flags_str.data[i]) {
11787 case 'A': flags |= UFBX_PROP_FLAG_ANIMATABLE; break;
11788 case 'U': flags |= UFBX_PROP_FLAG_USER_DEFINED; break;
11789 case 'H': flags |= UFBX_PROP_FLAG_HIDDEN; break;
11790 case 'L': flags |= ((uint32_t)(next - '0') & 0xf) << 4; break; // UFBX_PROP_FLAG_LOCK_*
11791 case 'M': flags |= ((uint32_t)(next - '0') & 0xf) << 8; break; // UFBX_PROP_FLAG_MUTE_*
11792 default: break; // Ignore unknown flags
11793 }
11794 }
11795 }
11796
11797 prop->type = ufbxi_get_prop_type(uc, type_str);
11798 if (prop->type == UFBX_PROP_UNKNOWN && subtype_str) {
11799 prop->type = ufbxi_get_prop_type(uc, subtype_str);
11800 }
11801
11802 if (ufbxi_get_val_at(node, val_ix, 'L', &prop->value_int)) {
11803 flags |= (uint32_t)UFBX_PROP_FLAG_VALUE_INT;
11804 }
11805
11806 size_t real_ix;
11807 for (real_ix = 0; real_ix < 4; real_ix++) {
11808 if (!ufbxi_get_val_at(node, val_ix + real_ix, 'R', &prop->value_real_arr[real_ix])) break;
11809 }
11810 if (real_ix > 0) {
11811 flags |= (uint32_t)UFBX_PROP_FLAG_VALUE_REAL << (real_ix - 1);
11812 }
11813
11814 // Skip one value forward in case the current value is not a string, as some properties
11815 // contain mixed numbers and strings. Currenltly known cases:
11816 // Lod Distance: P: "Thresholds|Level0", "Distance", "", "",64, "cm"
11817 // User Enum: P: "User_Enum", "Enum", "", "A+U",1, "ValueA~ValueB~ValueC"
11818 if (ufbxi_get_val_type(node, val_ix) != UFBXI_VALUE_STRING) {
11819 val_ix++;
11820 }
11821
11822 if (ufbxi_get_val_at(node, val_ix, 'S', &prop->value_str)) {
11823 if (prop->value_str.length > 0) {
11824 ufbxi_ignore(ufbxi_get_val_at(node, val_ix, 'b', &prop->value_blob));
11825 }
11826 flags |= (uint32_t)UFBX_PROP_FLAG_VALUE_STR;
11827 } else {
11828 prop->value_str = ufbx_empty_string;
11829 }
11830
11831 // Very unlikely, seems to only exist in some "non standard" FBX files
11832 if (node->num_children > 0) {
11833 ufbxi_node *binary = ufbxi_find_child(node, ufbxi_BinaryData);
11834 ufbxi_check(ufbxi_read_embedded_blob(uc, &prop->value_blob, binary));
11835 flags |= (uint32_t)UFBX_PROP_FLAG_VALUE_BLOB;
11836 }
11837
11838 prop->flags = (ufbx_prop_flags)flags;
11839
11840 return 1;
11841 }
11842
11843 static ufbxi_forceinline bool ufbxi_prop_less(ufbx_prop *a, ufbx_prop *b)
11844 {
11845 if (a->_internal_key < b->_internal_key) return true;
11846 if (a->_internal_key > b->_internal_key) return false;
11847 return strcmp(a->name.data, b->name.data) < 0;
11848 }
11849
11850 ufbxi_nodiscard ufbxi_noinline static int ufbxi_sort_properties(ufbxi_context *uc, ufbx_prop *props, size_t count)
11851 {
11852 ufbxi_check(ufbxi_grow_array(&uc->ator_tmp, &uc->tmp_arr, &uc->tmp_arr_size, count * sizeof(ufbx_prop)));
11853 ufbxi_macro_stable_sort(ufbx_prop, 32, props, uc->tmp_arr, count, ( ufbxi_prop_less(a, b) ));
11854 return 1;
11855 }
11856
11857 ufbxi_noinline static void ufbxi_deduplicate_properties(ufbx_prop_list *list)
11858 {
11859 if (list->count >= 2) {
11860 ufbx_prop *ps = list->data;
11861 size_t dst = 0, src = 0, end = list->count;
11862 while (src < end) {
11863 if (src + 1 < end && ps[src].name.data == ps[src + 1].name.data) {
11864 src++;
11865 } else if (dst != src) {
11866 ps[dst++] = ps[src++];
11867 } else {
11868 dst++; src++;
11869 }
11870 }
11871 list->count = dst;
11872 }
11873 }
11874
11875 ufbxi_nodiscard static ufbxi_noinline int ufbxi_read_properties(ufbxi_context *uc, ufbxi_node *parent, ufbx_props *props)
11876 {
11877 props->defaults = NULL;
11878
11879 int version = 70;
11880 ufbxi_node *node = ufbxi_find_child(parent, ufbxi_Properties70);
11881 if (!node) {
11882 node = ufbxi_find_child(parent, ufbxi_Properties60);
11883 if (!node) {
11884 // No properties found, not an error
11885 props->props.data = NULL;
11886 props->props.count = 0;
11887 return 1;
11888 }
11889 version = 60;
11890 }
11891
11892 props->props.data = ufbxi_push_zero(&uc->result, ufbx_prop, node->num_children);
11893 props->props.count = node->num_children;
11894 ufbxi_check(props->props.data);
11895
11896 for (size_t i = 0; i < props->props.count; i++) {
11897 ufbxi_check(ufbxi_read_property(uc, &node->children[i], &props->props.data[i], version));
11898 }
11899
11900 ufbxi_check(ufbxi_sort_properties(uc, props->props.data, props->props.count));
11901 ufbxi_deduplicate_properties(&props->props);
11902
11903 return 1;
11904 }
11905
11906 ufbxi_nodiscard static ufbxi_noinline int ufbxi_read_thumbnail(ufbxi_context *uc, ufbxi_node *node, ufbx_thumbnail *thumbnail)
11907 {
11908 ufbxi_check(ufbxi_read_properties(uc, node, &thumbnail->props));
11909
11910 int64_t custom_width = ufbx_find_int(&thumbnail->props, "CustomWidth", 0);
11911 int64_t custom_height = ufbx_find_int(&thumbnail->props, "CustomHeight", 0);
11912
11913 int32_t format;
11914 ufbxi_node *format_node = ufbxi_find_child_strcmp(node, "Format");
11915 if (format_node && ufbxi_get_val1(format_node, "I", &format)) {
11916 if (format >= 0 && format + 1 < UFBX_THUMBNAIL_FORMAT_COUNT) {
11917 thumbnail->format = (ufbx_thumbnail_format)(format + 1);
11918 }
11919 }
11920
11921 int32_t size;
11922 if (ufbxi_find_val1(node, ufbxi_Size, "I", &size)) {
11923 if (size > 0) {
11924 thumbnail->width = (uint32_t)size;
11925 thumbnail->height = (uint32_t)size;
11926 } else if (size < 0 && custom_width > 0 && custom_height > 0) {
11927 thumbnail->width = (uint32_t)custom_width;
11928 thumbnail->height = (uint32_t)custom_height;
11929 }
11930 }
11931
11932 ufbxi_value_array *data_arr = ufbxi_find_array(node, ufbxi_ImageData, 'c');
11933 if (data_arr) {
11934 thumbnail->data.data = data_arr->data;
11935 thumbnail->data.size = data_arr->size;
11936 }
11937
11938 return 1;
11939 }
11940
11941 ufbxi_nodiscard static ufbxi_noinline int ufbxi_read_scene_info(ufbxi_context *uc, ufbxi_node *node)
11942 {
11943 ufbxi_check(ufbxi_read_properties(uc, node, &uc->scene.metadata.scene_props));
11944
11945 ufbxi_node *thumbnail = ufbxi_find_child(node, ufbxi_Thumbnail);
11946 if (thumbnail) {
11947 ufbxi_check(ufbxi_read_thumbnail(uc, thumbnail, &uc->scene.metadata.thumbnail));
11948 }
11949
11950 return 1;
11951 }
11952
11953 ufbxi_nodiscard static ufbxi_noinline int ufbxi_read_header_extension(ufbxi_context *uc)
11954 {
11955 bool has_tc_definition = false;
11956 int32_t tc_definition = 0;
11957 int32_t header_version = 0;
11958
11959 for (;;) {
11960 ufbxi_node *child;
11961 ufbxi_check(ufbxi_parse_toplevel_child(uc, &child, NULL));
11962 if (!child) break;
11963
11964 if (child->name == ufbxi_Creator) {
11965 ufbxi_ignore(ufbxi_get_val1(child, "S", &uc->scene.metadata.creator));
11966 }
11967
11968 if (uc->version < 6000 && child->name == ufbxi_FBXVersion) {
11969 int32_t version;
11970 if (ufbxi_get_val1(child, "I", &version)) {
11971 if (version > 0 && version < 6000 && (uint32_t)version > uc->version) {
11972 uc->version = (uint32_t)version;
11973 }
11974 }
11975 }
11976
11977 if (child->name == ufbxi_FBXHeaderVersion) {
11978 ufbxi_ignore(ufbxi_get_val1(child, "I", &header_version));
11979 }
11980
11981 if (child->name == ufbxi_OtherFlags) {
11982 if (ufbxi_find_val1(child, ufbxi_TCDefinition, "I", &tc_definition)) {
11983 has_tc_definition = true;
11984 }
11985 }
11986
11987 if (child->name == ufbxi_SceneInfo) {
11988 ufbxi_check(ufbxi_read_scene_info(uc, child));
11989 }
11990
11991 }
11992
11993 // FBX 8000 will change the KTime units and the new units are opt-in currently via `TCDefinition`.
11994 // `TCDefinition` seems be accounted in all versions, as long as `FBXHeaderVersion >= 1004`.
11995 // The old KTime units are specified as the value `127` and all other values seem to use the new definition.
11996 bool use_v7_ktime = uc->version < 8000;
11997 if (header_version >= 1004 && has_tc_definition) {
11998 use_v7_ktime = tc_definition == 127;
11999 }
12000
12001 uc->ktime_sec = use_v7_ktime ? 46186158000 : 141120000;
12002 uc->ktime_sec_double = (double)uc->ktime_sec;
12003
12004 return 1;
12005 }
12006
12007 static bool ufbxi_match_version_string(const char *fmt, ufbx_string str, uint32_t *p_version)
12008 {
12009 size_t num_ix = 0;
12010 size_t pos = 0;
12011 while (*fmt) {
12012 char c = *fmt++;
12013 if (c >= 'a' && c <= 'z') {
12014 if (pos >= str.length) return false;
12015 char s = str.data[pos];
12016 if (s != c && (int)s + (int)('a' - 'A') != (int)c) return false;
12017 pos++;
12018 } else if (c == ' ') {
12019 while (pos < str.length) {
12020 char s = str.data[pos];
12021 if (s != ' ' && s != '\t') break;
12022 pos++;
12023 }
12024 } else if (c == '-') {
12025 while (pos < str.length) {
12026 char s = str.data[pos];
12027 if (s == '-') break;
12028 pos++;
12029 }
12030 if (pos >= str.length) return false;
12031 pos++;
12032 } else if (c == '/' || c == '.' || c == '(' || c == ')') {
12033 if (pos >= str.length) return false;
12034 if (str.data[pos] != c) return false;
12035 pos++;
12036 } else if (c == '?') {
12037 uint32_t num = 0;
12038 size_t len = 0;
12039 while (pos < str.length) {
12040 char s = str.data[pos];
12041 if (!(s >= '0' && s <= '9')) break;
12042 num = num*10 + (uint32_t)(s - '0');
12043 pos++;
12044 len++;
12045 }
12046 if (len == 0) return false;
12047 p_version[num_ix++] = num;
12048 } else {
12049 ufbxi_unreachable("Unhandled match character");
12050 }
12051 }
12052
12053 return true;
12054 }
12055
12056 ufbxi_nodiscard ufbxi_noinline static int ufbxi_match_exporter(ufbxi_context *uc)
12057 {
12058 ufbx_string creator = uc->scene.metadata.creator;
12059 uint32_t version[3] = { 0 };
12060 if (ufbxi_match_version_string("blender-- ?.?.?", creator, version)) {
12061 uc->exporter = UFBX_EXPORTER_BLENDER_BINARY;
12062 uc->exporter_version = ufbx_pack_version(version[0], version[1], version[2]);
12063 } else if (ufbxi_match_version_string("blender- ?.?", creator, version)) {
12064 uc->exporter = UFBX_EXPORTER_BLENDER_BINARY;
12065 uc->exporter_version = ufbx_pack_version(version[0], version[1], 0);
12066 } else if (ufbxi_match_version_string("blender version ?.?", creator, version)) {
12067 uc->exporter = UFBX_EXPORTER_BLENDER_ASCII;
12068 uc->exporter_version = ufbx_pack_version(version[0], version[1], 0);
12069 } else if (ufbxi_match_version_string("fbx sdk/fbx plugins version ?.?", creator, version)) {
12070 uc->exporter = UFBX_EXPORTER_FBX_SDK;
12071 uc->exporter_version = ufbx_pack_version(version[0], version[1], 0);
12072 } else if (ufbxi_match_version_string("fbx sdk/fbx plugins build ?", creator, version)) {
12073 uc->exporter = UFBX_EXPORTER_FBX_SDK;
12074 uc->exporter_version = ufbx_pack_version(version[0]/10000u, version[0]/100u%100u, version[0]%100u);
12075 } else if (ufbxi_match_version_string("motionbuilder version ?.?", creator, version)) {
12076 uc->exporter = UFBX_EXPORTER_MOTION_BUILDER;
12077 uc->exporter_version = ufbx_pack_version(version[0], version[1], 0);
12078 } else if (ufbxi_match_version_string("motionbuilder/mocap/online version ?.?", creator, version)) {
12079 uc->exporter = UFBX_EXPORTER_MOTION_BUILDER;
12080 uc->exporter_version = ufbx_pack_version(version[0], version[1], 0);
12081 }
12082
12083 uc->scene.metadata.exporter = uc->exporter;
12084 uc->scene.metadata.exporter_version = uc->exporter_version;
12085
12086 // Un-detect the exporter in `ufbxi_context` to disable special cases
12087 if (uc->opts.disable_quirks) {
12088 uc->exporter = UFBX_EXPORTER_UNKNOWN;
12089 uc->exporter_version = 0;
12090 }
12091
12092 if (uc->exporter == UFBX_EXPORTER_BLENDER_BINARY) {
12093 uc->blender_full_weights = true;
12094 }
12095
12096 return 1;
12097 }
12098
12099 ufbxi_nodiscard static ufbxi_noinline int ufbxi_read_document(ufbxi_context *uc)
12100 {
12101 bool found_root_id = 0;
12102
12103 for (;;) {
12104 ufbxi_node *child;
12105 ufbxi_check(ufbxi_parse_toplevel_child(uc, &child, NULL));
12106 if (!child) break;
12107
12108 if (child->name == ufbxi_Document && !found_root_id) {
12109 // Post-7000: Try to find the first document node and root ID.
12110 // TODO: Multiple documents / roots?
12111 if (ufbxi_find_val1(child, ufbxi_RootNode, "L", &uc->root_id)) {
12112 found_root_id = true;
12113 }
12114 }
12115 }
12116
12117 return 1;
12118 }
12119
12120 ufbxi_nodiscard static ufbxi_noinline int ufbxi_read_definitions(ufbxi_context *uc)
12121 {
12122 for (;;) {
12123 ufbxi_node *object;
12124 ufbxi_check(ufbxi_parse_toplevel_child(uc, &object, NULL));
12125 if (!object) break;
12126
12127 if (object->name != ufbxi_ObjectType) continue;
12128
12129 ufbxi_template *tmpl = ufbxi_push_zero(&uc->tmp_stack, ufbxi_template, 1);
12130 uc->num_templates++;
12131 ufbxi_check(tmpl);
12132 ufbxi_check(ufbxi_get_val1(object, "C", (char**)&tmpl->type));
12133
12134 // Pre-7000 FBX versions don't have property templates, they just have
12135 // the object counts by themselves.
12136 ufbxi_node *props = ufbxi_find_child(object, ufbxi_PropertyTemplate);
12137 if (props) {
12138 ufbxi_check(ufbxi_get_val1(props, "S", &tmpl->sub_type));
12139
12140 // Remove the "Fbx" prefix from sub-types, remember to re-intern!
12141 if (tmpl->sub_type.length > 3 && !strncmp(tmpl->sub_type.data, "Fbx", 3)) {
12142 tmpl->sub_type.data += 3;
12143 tmpl->sub_type.length -= 3;
12144
12145 // HACK: LOD groups use LODGroup for Template, LodGroup for Object?
12146 if (tmpl->sub_type.length == 8 && !memcmp(tmpl->sub_type.data, "LODGroup", 8)) {
12147 tmpl->sub_type.data = "LodGroup";
12148 }
12149
12150 ufbxi_check(ufbxi_push_string_place_str(&uc->string_pool, &tmpl->sub_type, false));
12151 }
12152
12153 ufbxi_check(ufbxi_read_properties(uc, props, &tmpl->props));
12154 }
12155 }
12156
12157 // TODO: Preserve only the `props` part of the templates
12158 uc->templates = ufbxi_push_pop(&uc->result, &uc->tmp_stack, ufbxi_template, uc->num_templates);
12159 ufbxi_check(uc->templates);
12160
12161 return 1;
12162 }
12163
12164 ufbxi_nodiscard static ufbx_props *ufbxi_find_template(ufbxi_context *uc, const char *name, const char *sub_type)
12165 {
12166 // TODO: Binary search
12167 ufbxi_for(ufbxi_template, tmpl, uc->templates, uc->num_templates) {
12168 if (tmpl->type == name) {
12169
12170 // Check that sub_type matches unless the type is Material, Model, AnimationStack, AnimationLayer.
12171 // Those match to all sub-types.
12172 if (tmpl->type != ufbxi_Material && tmpl->type != ufbxi_Model
12173 && tmpl->type != ufbxi_AnimationStack && tmpl->type != ufbxi_AnimationLayer) {
12174 if (tmpl->sub_type.data != sub_type) {
12175 return NULL;
12176 }
12177 }
12178
12179 if (tmpl->props.props.count > 0) {
12180 return &tmpl->props;
12181 } else {
12182 return NULL;
12183 }
12184 }
12185 }
12186 return NULL;
12187 }
12188
12189 // Name ID categories
12190 #if defined(UFBX_REGRESSION)
12191 #define UFBXI_MAXIMUM_FAST_POINTER_ID UINT64_C(0x100)
12192 #else
12193 #define UFBXI_MAXIMUM_FAST_POINTER_ID UINT64_C(0x4000000000000000)
12194 #endif
12195 #define UFBXI_POINTER_ID_START UINT64_C(0x8000000000000000)
12196 #define UFBXI_SYNTHETIC_ID_START (UFBXI_POINTER_ID_START + UFBXI_MAXIMUM_FAST_POINTER_ID)
12197
12198 static ufbxi_forceinline uint64_t ufbxi_push_synthetic_id(ufbxi_context *uc)
12199 {
12200 return ++uc->synthetic_id_counter;
12201 }
12202
12203 static ufbxi_noinline uint64_t ufbxi_synthetic_id_from_ptr_id(ufbxi_context *uc, uintptr_t ptr, uint64_t id)
12204 {
12205 ufbxi_ptr_id ptr_id = { ptr, id };
12206 uint32_t hash = ufbxi_hash_ptr_id(ptr_id);
12207 ufbxi_ptr_fbx_id_entry *entry = ufbxi_map_find(&uc->ptr_fbx_id_map, ufbxi_ptr_fbx_id_entry, hash, &ptr_id);
12208
12209 if (!entry) {
12210 entry = ufbxi_map_insert(&uc->ptr_fbx_id_map, ufbxi_ptr_fbx_id_entry, hash, &ptr_id);
12211 ufbxi_check_return(entry, 0);
12212 entry->ptr_id = ptr_id;
12213 entry->fbx_id = ufbxi_push_synthetic_id(uc);
12214 }
12215
12216 return entry->fbx_id;
12217 }
12218
12219 static ufbxi_forceinline uint64_t ufbxi_synthetic_id_from_string(ufbxi_context *uc, const char *str)
12220 {
12221 uintptr_t uptr = (uintptr_t)str;
12222 if (uptr < (UINTPTR_MAX < UFBXI_MAXIMUM_FAST_POINTER_ID ? UINTPTR_MAX : UFBXI_MAXIMUM_FAST_POINTER_ID)) {
12223 return (uint64_t)uptr;
12224 } else {
12225 return ufbxi_synthetic_id_from_ptr_id(uc, uptr, 0);
12226 }
12227 }
12228
12229 ufbxi_nodiscard ufbxi_forceinline static int ufbxi_validate_fbx_id(ufbxi_context *uc, uint64_t *p_fbx_id)
12230 {
12231 uint64_t fbx_id = *p_fbx_id;
12232 if (fbx_id >= UFBXI_POINTER_ID_START) {
12233 fbx_id = ufbxi_synthetic_id_from_ptr_id(uc, 0, fbx_id);
12234 ufbxi_check(fbx_id);
12235 *p_fbx_id = fbx_id;
12236 }
12237 return 1;
12238 }
12239
12240 ufbxi_nodiscard ufbxi_noinline static int ufbxi_split_type_and_name(ufbxi_context *uc, ufbx_string type_and_name, ufbx_string *type, ufbx_string *name)
12241 {
12242 // Name and type are packed in a single property as Type::Name (in ASCII)
12243 // or Name\x00\x01Type (in binary)
12244 const char *sep = uc->from_ascii ? "::" : "\x00\x01";
12245 size_t type_end = 2;
12246 for (; type_end <= type_and_name.length; type_end++) {
12247 const char *ch = type_and_name.data + type_end - 2;
12248 if (ch[0] == sep[0] && ch[1] == sep[1]) break;
12249 }
12250
12251 // ???: ASCII and binary store type and name in different order
12252 if (type_end <= type_and_name.length) {
12253 if (uc->from_ascii) {
12254 name->data = type_and_name.data + type_end;
12255 name->length = type_and_name.length - type_end;
12256 type->data = type_and_name.data;
12257 type->length = type_end - 2;
12258 } else {
12259 name->data = type_and_name.data;
12260 name->length = type_end - 2;
12261 type->data = type_and_name.data + type_end;
12262 type->length = type_and_name.length - type_end;
12263 }
12264 } else {
12265 *name = type_and_name;
12266 type->data = ufbxi_empty_char;
12267 type->length = 0;
12268 }
12269
12270 ufbxi_check(ufbxi_push_string_place_str(&uc->string_pool, type, false));
12271 ufbxi_check(ufbxi_push_string_place_str(&uc->string_pool, name, false));
12272
12273 return 1;
12274 }
12275
12276 ufbxi_nodiscard ufbxi_noinline static int ufbxi_insert_fbx_id(ufbxi_context *uc, uint64_t fbx_id, uint32_t element_id)
12277 {
12278 uint32_t hash = ufbxi_hash64(fbx_id);
12279 ufbxi_fbx_id_entry *entry = ufbxi_map_find(&uc->fbx_id_map, ufbxi_fbx_id_entry, hash, &fbx_id);
12280
12281 if (!entry) {
12282 entry = ufbxi_map_insert(&uc->fbx_id_map, ufbxi_fbx_id_entry, hash, &fbx_id);
12283 ufbxi_check(entry);
12284 entry->fbx_id = fbx_id;
12285 entry->element_id = element_id;
12286 entry->user_id = 0;
12287 } else {
12288 ufbxi_check(ufbxi_warnf(UFBX_WARNING_DUPLICATE_OBJECT_ID, "Duplicate object ID"));
12289 }
12290
12291 return 1;
12292 }
12293
12294 static ufbxi_noinline ufbxi_fbx_id_entry *ufbxi_find_fbx_id(ufbxi_context *uc, uint64_t fbx_id)
12295 {
12296 uint32_t hash = ufbxi_hash64(fbx_id);
12297 return ufbxi_map_find(&uc->fbx_id_map, ufbxi_fbx_id_entry, hash, &fbx_id);
12298 }
12299
12300 static ufbxi_forceinline bool ufbxi_fbx_id_exists(ufbxi_context *uc, uint64_t fbx_id)
12301 {
12302 return ufbxi_find_fbx_id(uc, fbx_id) != NULL;
12303 }
12304
12305 ufbxi_nodiscard ufbxi_noinline static int ufbxi_insert_fbx_attr(ufbxi_context *uc, uint64_t fbx_id, uint64_t attrib_fbx_id)
12306 {
12307 uint32_t hash = ufbxi_hash64(fbx_id);
12308 ufbxi_fbx_attr_entry *entry = ufbxi_map_find(&uc->fbx_attr_map, ufbxi_fbx_attr_entry, hash, &fbx_id);
12309 // TODO: Strict / warn about duplicate objects
12310
12311 if (!entry) {
12312 entry = ufbxi_map_insert(&uc->fbx_attr_map, ufbxi_fbx_attr_entry, hash, &fbx_id);
12313 ufbxi_check(entry);
12314 entry->node_fbx_id = fbx_id;
12315 entry->attr_fbx_id = attrib_fbx_id;
12316 }
12317
12318 return 1;
12319 }
12320
12321 ufbxi_nodiscard ufbxi_noinline static ufbx_element *ufbxi_push_element_size(ufbxi_context *uc, ufbxi_element_info *info, size_t size, ufbx_element_type type)
12322 {
12323 size_t aligned_size = (size + 7u) & ~0x7u;
12324
12325 uint32_t typed_id = (uint32_t)uc->tmp_typed_element_offsets[type].num_items;
12326 uint32_t element_id = uc->num_elements++;
12327
12328 ufbxi_check_return(ufbxi_push_copy_fast(&uc->tmp_typed_element_offsets[type], size_t, 1, &uc->tmp_element_byte_offset), NULL);
12329 ufbxi_check_return(ufbxi_push_copy_fast(&uc->tmp_element_offsets, size_t, 1, &uc->tmp_element_byte_offset), NULL);
12330 ufbxi_check_return(ufbxi_push_copy_fast(&uc->tmp_element_fbx_ids, uint64_t, 1, &info->fbx_id), NULL);
12331 uc->tmp_element_byte_offset += aligned_size;
12332
12333 ufbx_element *elem = (ufbx_element*)ufbxi_push_zero(&uc->tmp_elements, uint64_t, aligned_size/8);
12334 ufbxi_check_return(elem, NULL);
12335 elem->type = type;
12336 elem->element_id = element_id;
12337 elem->typed_id = typed_id;
12338 elem->name = info->name;
12339 elem->props = info->props;
12340 elem->dom_node = info->dom_node;
12341
12342 if (uc->p_element_id) {
12343 *uc->p_element_id = element_id;
12344 }
12345
12346 ufbxi_check_return(ufbxi_push_copy_fast(&uc->tmp_element_ptrs, ufbx_element*, 1, &elem), NULL);
12347
12348 ufbxi_check_return(ufbxi_insert_fbx_id(uc, info->fbx_id, element_id), NULL);
12349
12350 return elem;
12351 }
12352
12353 ufbxi_nodiscard ufbxi_noinline static ufbx_element *ufbxi_push_synthetic_element_size(ufbxi_context *uc, uint64_t *p_fbx_id, ufbxi_node *node, const char *name, size_t size, ufbx_element_type type)
12354 {
12355 size_t aligned_size = (size + 7u) & ~0x7u;
12356
12357 uint32_t typed_id = (uint32_t)uc->tmp_typed_element_offsets[type].num_items;
12358 uint32_t element_id = uc->num_elements++;
12359
12360 ufbxi_check_return(ufbxi_push_copy_fast(&uc->tmp_typed_element_offsets[type], size_t, 1, &uc->tmp_element_byte_offset), NULL);
12361 ufbxi_check_return(ufbxi_push_copy_fast(&uc->tmp_element_offsets, size_t, 1, &uc->tmp_element_byte_offset), NULL);
12362 uc->tmp_element_byte_offset += aligned_size;
12363
12364 ufbx_element *elem = (ufbx_element*)ufbxi_push_zero(&uc->tmp_elements, uint64_t, aligned_size/8);
12365 ufbxi_check_return(elem, NULL);
12366 elem->type = type;
12367 elem->element_id = element_id;
12368 elem->typed_id = typed_id;
12369 elem->dom_node = ufbxi_get_dom_node(uc, node);
12370 if (name) {
12371 elem->name.data = name;
12372 elem->name.length = strlen(name);
12373 }
12374
12375 ufbxi_check_return(ufbxi_push_copy_fast(&uc->tmp_element_ptrs, ufbx_element*, 1, &elem), NULL);
12376
12377 *p_fbx_id = ufbxi_push_synthetic_id(uc);
12378
12379 ufbxi_check_return(ufbxi_push_copy_fast(&uc->tmp_element_fbx_ids, uint64_t, 1, p_fbx_id), NULL);
12380 ufbxi_check_return(ufbxi_insert_fbx_id(uc, *p_fbx_id, element_id), NULL);
12381
12382 return elem;
12383 }
12384
12385 #define ufbxi_push_element(uc, info, type_name, type_enum) ufbxi_maybe_null((type_name*)ufbxi_push_element_size((uc), (info), sizeof(type_name), (type_enum)))
12386 #define ufbxi_push_synthetic_element(uc, p_fbx_id, node, name, type_name, type_enum) ufbxi_maybe_null((type_name*)ufbxi_push_synthetic_element_size((uc), (p_fbx_id), (node), (name), sizeof(type_name), (type_enum)))
12387
12388 ufbxi_nodiscard ufbxi_noinline static int ufbxi_connect_oo(ufbxi_context *uc, uint64_t src, uint64_t dst)
12389 {
12390 ufbxi_tmp_connection *conn = ufbxi_push(&uc->tmp_connections, ufbxi_tmp_connection, 1);
12391 ufbxi_check(conn);
12392 conn->src = src;
12393 conn->dst = dst;
12394 conn->src_prop = conn->dst_prop = ufbx_empty_string;
12395 return 1;
12396 }
12397
12398 ufbxi_nodiscard ufbxi_noinline static int ufbxi_connect_op(ufbxi_context *uc, uint64_t src, uint64_t dst, ufbx_string prop)
12399 {
12400 ufbxi_tmp_connection *conn = ufbxi_push(&uc->tmp_connections, ufbxi_tmp_connection, 1);
12401 ufbxi_check(conn);
12402 conn->src = src;
12403 conn->dst = dst;
12404 conn->src_prop = ufbx_empty_string;
12405 conn->dst_prop = prop;
12406 return 1;
12407 }
12408
12409 ufbxi_nodiscard ufbxi_noinline static int ufbxi_connect_pp(ufbxi_context *uc, uint64_t src, uint64_t dst, ufbx_string src_prop, ufbx_string dst_prop)
12410 {
12411 ufbxi_tmp_connection *conn = ufbxi_push(&uc->tmp_connections, ufbxi_tmp_connection, 1);
12412 ufbxi_check(conn);
12413 conn->src = src;
12414 conn->dst = dst;
12415 conn->src_prop = src_prop;
12416 conn->dst_prop = dst_prop;
12417 return 1;
12418 }
12419
12420 ufbxi_noinline static void ufbxi_init_synthetic_int_prop(ufbx_prop *dst, const char *name, int64_t value, ufbx_prop_type type)
12421 {
12422 dst->type = type;
12423 dst->name.data = name;
12424 dst->name.length = strlen(name);
12425 dst->value_real = (ufbx_real)value;
12426 dst->flags = (ufbx_prop_flags)(UFBX_PROP_FLAG_SYNTHETIC|UFBX_PROP_FLAG_VALUE_REAL|UFBX_PROP_FLAG_VALUE_INT);
12427 dst->value_int = value;
12428 dst->value_str.data = ufbxi_empty_char;
12429
12430 ufbxi_dev_assert(dst->name.length >= 4);
12431 dst->_internal_key = ufbxi_get_name_key(name, 4);
12432 }
12433
12434 ufbxi_noinline static void ufbxi_init_synthetic_real_prop(ufbx_prop *dst, const char *name, ufbx_real value, ufbx_prop_type type)
12435 {
12436 dst->type = type;
12437 dst->name.data = name;
12438 dst->name.length = strlen(name);
12439 dst->value_real = value;
12440 dst->flags = (ufbx_prop_flags)(UFBX_PROP_FLAG_SYNTHETIC|UFBX_PROP_FLAG_VALUE_REAL);
12441 dst->value_int = (int64_t)value;
12442 dst->value_str.data = ufbxi_empty_char;
12443
12444 ufbxi_dev_assert(dst->name.length >= 4);
12445 dst->_internal_key = ufbxi_get_name_key(name, 4);
12446 }
12447
12448 ufbxi_noinline static void ufbxi_init_synthetic_vec3_prop(ufbx_prop *dst, const char *name, const ufbx_vec3 *value, ufbx_prop_type type)
12449 {
12450 dst->type = type;
12451 dst->name.data = name;
12452 dst->name.length = strlen(name);
12453 dst->value_vec3 = *value;
12454 dst->flags = (ufbx_prop_flags)(UFBX_PROP_FLAG_SYNTHETIC|UFBX_PROP_FLAG_VALUE_VEC3);
12455 dst->value_int = ufbxi_f64_to_i64(dst->value_real);
12456 dst->value_str.data = ufbxi_empty_char;
12457
12458 ufbxi_dev_assert(dst->name.length >= 4);
12459 dst->_internal_key = ufbxi_get_name_key(name, 4);
12460 }
12461
12462 ufbxi_noinline static void ufbxi_set_own_prop_vec3_uniform(ufbx_props *props, const char *name, ufbx_real value)
12463 {
12464 ufbx_props local_props = *props;
12465 local_props.defaults = NULL;
12466 ufbx_prop *prop = ufbx_find_prop(&local_props, name);
12467 if (prop) {
12468 prop->value_vec4.x = value;
12469 prop->value_vec4.y = value;
12470 prop->value_vec4.z = value;
12471 prop->value_vec4.w = 0.0f;
12472 prop->value_int = (int64_t)value;
12473 }
12474 }
12475
12476 typedef struct {
12477 uint32_t geometry_helper_id;
12478 uint32_t scale_helper_id;
12479 } ufbxi_node_extra;
12480
12481 ufbxi_nodiscard ufbxi_noinline static int ufbxi_setup_geometry_transform_helper(ufbxi_context *uc, ufbx_node *node, uint64_t node_fbx_id)
12482 {
12483 ufbx_vec3 geo_translation = ufbxi_find_vec3(&node->props, ufbxi_GeometricTranslation, 0.0f, 0.0f, 0.0f);
12484 ufbx_vec3 geo_rotation = ufbxi_find_vec3(&node->props, ufbxi_GeometricRotation, 0.0f, 0.0f, 0.0f);
12485 ufbx_vec3 geo_scaling = ufbxi_find_vec3(&node->props, ufbxi_GeometricScaling, 1.0f, 1.0f, 1.0f);
12486 if (!ufbxi_is_vec3_zero(geo_translation) || !ufbxi_is_vec3_zero(geo_rotation) || !ufbxi_is_vec3_one(geo_scaling)) {
12487
12488 uint64_t geo_fbx_id;
12489 ufbx_node *geo_node = ufbxi_push_synthetic_element(uc, &geo_fbx_id, NULL, uc->opts.geometry_transform_helper_name.data, ufbx_node, UFBX_ELEMENT_NODE);
12490 ufbxi_check(geo_node);
12491 ufbxi_check(ufbxi_push_copy(&uc->tmp_node_ids, uint32_t, 1, &geo_node->element.element_id));
12492 geo_node->element.dom_node = node->element.dom_node;
12493
12494 ufbx_prop *props = ufbxi_push_zero(&uc->result, ufbx_prop, 3);
12495 ufbxi_check(props);
12496 ufbxi_init_synthetic_vec3_prop(&props[0], ufbxi_Lcl_Rotation, &geo_rotation, UFBX_PROP_ROTATION);
12497 ufbxi_init_synthetic_vec3_prop(&props[1], ufbxi_Lcl_Scaling, &geo_scaling, UFBX_PROP_SCALING);
12498 ufbxi_init_synthetic_vec3_prop(&props[2], ufbxi_Lcl_Translation, &geo_translation, UFBX_PROP_TRANSLATION);
12499
12500 geo_node->props.props.data = props;
12501 geo_node->props.props.count = 3;
12502
12503 node->has_geometry_transform = true;
12504 geo_node->is_geometry_transform_helper = true;
12505
12506 ufbxi_check(ufbxi_connect_oo(uc, geo_fbx_id, node_fbx_id));
12507 uc->has_geometry_transform_nodes = true;
12508
12509 ufbxi_node_extra *extra = ufbxi_push_element_extra(uc, node->element_id, ufbxi_node_extra);
12510 ufbxi_check(extra);
12511 extra->geometry_helper_id = geo_node->element_id;
12512 }
12513
12514 return 1;
12515 }
12516
12517 typedef struct {
12518 const char *name;
12519 ufbx_vec3 default_value;
12520 } ufbxi_scale_helper_prop;
12521
12522 static const ufbxi_scale_helper_prop ufbxi_scale_helper_props[] = {
12523 { ufbxi_GeometricRotation, { 0.0f, 0.0f, 0.0f } },
12524 { ufbxi_GeometricScaling, { 1.0f, 1.0f, 1.0f } },
12525 { ufbxi_GeometricTranslation, { 0.0f, 0.0f, 0.0f } },
12526 { ufbxi_Lcl_Scaling, { 1.0f, 1.0f, 1.0f } },
12527 };
12528
12529 ufbxi_nodiscard ufbxi_noinline static int ufbxi_setup_scale_helper(ufbxi_context *uc, ufbx_node *node, uint64_t node_fbx_id)
12530 {
12531 uint64_t scale_fbx_id;
12532 ufbx_node *scale_node = ufbxi_push_synthetic_element(uc, &scale_fbx_id, NULL, uc->opts.scale_helper_name.data, ufbx_node, UFBX_ELEMENT_NODE);
12533 ufbxi_check(scale_node);
12534 ufbxi_check(ufbxi_push_copy(&uc->tmp_node_ids, uint32_t, 1, &scale_node->element.element_id));
12535 scale_node->element.dom_node = node->element.dom_node;
12536
12537 node->scale_helper = scale_node;
12538 scale_node->is_scale_helper = true;
12539
12540 ufbxi_check(ufbxi_connect_oo(uc, scale_fbx_id, node_fbx_id));
12541 uc->has_scale_helper_nodes = true;
12542
12543 ufbxi_node_extra *extra = ufbxi_push_element_extra(uc, node->element.element_id, ufbxi_node_extra);
12544 ufbxi_check(extra);
12545 extra->scale_helper_id = scale_node->element_id;
12546
12547 size_t max_props = ufbxi_arraycount(ufbxi_scale_helper_props);
12548 ufbx_prop *helper_props = ufbxi_push(&uc->result, ufbx_prop, max_props);
12549 ufbxi_check(helper_props);
12550
12551 size_t num_props = 0;
12552 ufbx_props props_copy = node->props;
12553 props_copy.defaults = NULL;
12554 for (size_t i = 0; i < max_props; i++) {
12555 const ufbxi_scale_helper_prop *hp = &ufbxi_scale_helper_props[i];
12556 ufbx_prop *src_prop = ufbxi_find_prop(&props_copy, hp->name);
12557 if (!src_prop) continue;
12558
12559 helper_props[num_props++] = *src_prop;
12560 src_prop->value_vec3 = hp->default_value;
12561 src_prop->value_int = (int64_t)src_prop->value_vec3.x;
12562 }
12563
12564 scale_node->props.props.data = helper_props;
12565 scale_node->props.props.count = num_props;
12566
12567 return 1;
12568 }
12569
12570 ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_model(ufbxi_context *uc, ufbxi_node *node, ufbxi_element_info *info)
12571 {
12572 (void)node;
12573 ufbx_node *elem_node = ufbxi_push_element(uc, info, ufbx_node, UFBX_ELEMENT_NODE);
12574 ufbxi_check(elem_node);
12575 ufbxi_check(ufbxi_push_copy(&uc->tmp_node_ids, uint32_t, 1, &elem_node->element.element_id));
12576
12577 int64_t inherit_type = ufbxi_find_int(&elem_node->props, ufbxi_InheritType, -1);
12578 switch (inherit_type) {
12579 case 0: // RrSs
12580 elem_node->original_inherit_mode = UFBX_INHERIT_MODE_COMPONENTWISE_SCALE;
12581 break;
12582 case 2: // Rrs
12583 elem_node->original_inherit_mode = UFBX_INHERIT_MODE_IGNORE_PARENT_SCALE;
12584 break;
12585 default: break;
12586 }
12587
12588 if (uc->opts.inherit_mode_handling == UFBX_INHERIT_MODE_HANDLING_PRESERVE) {
12589 elem_node->inherit_mode = elem_node->original_inherit_mode;
12590 } else if (uc->opts.inherit_mode_handling == UFBX_INHERIT_MODE_HANDLING_IGNORE) {
12591 elem_node->original_inherit_mode = UFBX_INHERIT_MODE_NORMAL;
12592 elem_node->inherit_mode = UFBX_INHERIT_MODE_NORMAL;
12593 }
12594
12595 return 1;
12596 }
12597
12598 ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_element(ufbxi_context *uc, ufbxi_node *node, ufbxi_element_info *info, size_t size, ufbx_element_type type)
12599 {
12600 (void)node;
12601 ufbx_element *elem = ufbxi_push_element_size(uc, info, size, type);
12602 ufbxi_check(elem);
12603 return 1;
12604 }
12605
12606 ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_unknown(ufbxi_context *uc, ufbxi_node *node, ufbxi_element_info *element, ufbx_string type, ufbx_string sub_type, const char *node_name)
12607 {
12608 (void)node;
12609 ufbx_unknown *unknown = ufbxi_push_element(uc, element, ufbx_unknown, UFBX_ELEMENT_UNKNOWN);
12610 ufbxi_check(unknown);
12611 unknown->type = type;
12612 unknown->sub_type = sub_type;
12613 unknown->super_type.data = node_name;
12614 unknown->super_type.length = strlen(node_name);
12615
12616 // `type`, `sub_type` and `node_name` are raw strings so they may need to be sanitized.
12617 ufbxi_check(ufbxi_push_string_place_str(&uc->string_pool, &unknown->type, false));
12618 ufbxi_check(ufbxi_push_string_place_str(&uc->string_pool, &unknown->sub_type, false));
12619 ufbxi_check(ufbxi_push_string_place_str(&uc->string_pool, &unknown->super_type, false));
12620
12621 return 1;
12622 }
12623
12624 typedef struct {
12625 ufbx_vertex_vec3 elem;
12626 uint32_t index;
12627 } ufbxi_tangent_layer;
12628
12629 static ufbx_real ufbxi_zero_element[8] = { 0 };
12630
12631 // Sentinel pointers used for zero/sequential index buffers
12632 static const uint32_t ufbxi_sentinel_index_zero[1] = { 100000000 };
12633 static const uint32_t ufbxi_sentinel_index_consecutive[1] = { 123456789 };
12634
12635 ufbxi_noinline static int ufbxi_fix_index(ufbxi_context *uc, uint32_t *p_dst, uint32_t index, size_t one_past_max_val)
12636 {
12637 switch (uc->opts.index_error_handling) {
12638 case UFBX_INDEX_ERROR_HANDLING_CLAMP:
12639 ufbxi_check(one_past_max_val > 0);
12640 ufbxi_check(one_past_max_val <= UINT32_MAX);
12641 *p_dst = (uint32_t)one_past_max_val - 1;
12642 ufbxi_check(ufbxi_warnf(UFBX_WARNING_INDEX_CLAMPED, "Clamped index"));
12643 break;
12644 case UFBX_INDEX_ERROR_HANDLING_NO_INDEX:
12645 *p_dst = UFBX_NO_INDEX;
12646 break;
12647 case UFBX_INDEX_ERROR_HANDLING_ABORT_LOADING:
12648 ufbxi_fmt_err_info(&uc->error, "%u (max %u)", index, one_past_max_val ? (one_past_max_val - 1) : 0);
12649 ufbxi_fail_msg("UFBX_INDEX_ERROR_HANDLING_ABORT_LOADING", "Bad index");
12650 case UFBX_INDEX_ERROR_HANDLING_UNSAFE_IGNORE:
12651 *p_dst = index;
12652 break;
12653 default:
12654 ufbxi_unreachable("Unhandled index_error_handling");
12655 return 0;
12656 }
12657
12658 return 1;
12659 }
12660
12661 ufbxi_nodiscard ufbxi_noinline static int ufbxi_check_indices(ufbxi_context *uc, uint32_t **p_dst, uint32_t *indices, bool owns_indices, size_t num_indices, size_t num_indexers, size_t num_elems)
12662 {
12663 // If the indices are truncated extend them with `UFBX_NO_INDEX`, the following normalization pass
12664 // will handle them the same way as other out-of-bounds indices.
12665 if (num_indices < num_indexers) {
12666 uint32_t *new_indices = ufbxi_push(&uc->result, uint32_t, num_indexers);
12667 ufbxi_check(new_indices);
12668
12669 memcpy(new_indices, indices, sizeof(uint32_t) * num_indices);
12670 for (size_t i = num_indices; i < num_indexers; i++) {
12671 new_indices[i] = UFBX_NO_INDEX;
12672 }
12673
12674 indices = new_indices;
12675 num_indices = num_indexers;
12676 owns_indices = true;
12677 }
12678
12679 // Normalize out-of-bounds indices to `invalid_index`
12680 for (size_t i = 0; i < num_indices; i++) {
12681 uint32_t ix = indices[i];
12682 if (ix >= num_elems) {
12683 // If the indices refer to an external buffer we need to
12684 // allocate a separate buffer for them
12685 if (!owns_indices) {
12686 indices = ufbxi_push_copy(&uc->result, uint32_t, num_indices, indices);
12687 ufbxi_check(indices);
12688 owns_indices = true;
12689 }
12690 ufbxi_check(ufbxi_fix_index(uc, &indices[i], ix, num_elems));
12691 }
12692 }
12693
12694 *p_dst = indices;
12695
12696 return 1;
12697 }
12698
12699 ufbx_static_assert(vertex_real_size, sizeof(ufbx_vertex_real) == sizeof(ufbx_vertex_attrib));
12700 ufbx_static_assert(vertex_vec2_size, sizeof(ufbx_vertex_vec2) == sizeof(ufbx_vertex_attrib));
12701 ufbx_static_assert(vertex_vec3_size, sizeof(ufbx_vertex_vec3) == sizeof(ufbx_vertex_attrib));
12702 ufbx_static_assert(vertex_vec4_size, sizeof(ufbx_vertex_vec4) == sizeof(ufbx_vertex_attrib));
12703
12704 ufbxi_nodiscard ufbxi_noinline static int ufbxi_warn_polygon_mapping(ufbxi_context *uc, const char *data_name, const char *mapping)
12705 {
12706 ufbxi_check(ufbxi_warnf(UFBX_WARNING_MISSING_POLYGON_MAPPING, "Ignoring geometry '%s' with bad mapping mode '%s'", data_name, mapping));
12707 return 1;
12708 }
12709
12710 ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_vertex_element(ufbxi_context *uc, ufbx_mesh *mesh, ufbxi_node *node,
12711 ufbx_vertex_attrib *attrib, const char *data_name, const char *index_name, const char *w_name, char data_type, size_t num_components)
12712 {
12713 ufbx_real **p_dst_data = (ufbx_real**)&attrib->values.data;
12714
12715 ufbxi_value_array *data = ufbxi_find_array(node, data_name, data_type);
12716 ufbxi_value_array *indices = ufbxi_find_array(node, index_name, 'i');
12717
12718 if (!uc->opts.strict) {
12719 if (!data) return 1;
12720 }
12721
12722 ufbxi_check(data);
12723 ufbxi_check(data->size % num_components == 0);
12724
12725 size_t num_elems = data->size / num_components;
12726
12727 // HACK: If there's no elements at all keep the attribute as NULL
12728 // TODO: Strict mode for this?
12729 if (num_elems == 0) {
12730 return 1;
12731 }
12732
12733 ufbxi_check(num_elems > 0 && num_elems < INT32_MAX);
12734
12735 attrib->exists = true;
12736 attrib->indices.count = mesh->num_indices;
12737
12738 const char *mapping = "";
12739 ufbxi_ignore(ufbxi_find_val1(node, ufbxi_MappingInformationType, "C", (char**)&mapping));
12740
12741 attrib->values.count = num_elems ? num_elems : 1;
12742
12743 // Data array is always used as-is, if empty set the data to a global
12744 // zero buffer so invalid zero index can point to some valid data.
12745 // The zero data is offset by 4 elements to accommodate for invalid index (-1)
12746 if (num_elems > 0) {
12747 *p_dst_data = (ufbx_real*)data->data;
12748 } else {
12749 *p_dst_data = ufbxi_zero_element + 4;
12750 }
12751
12752 // HACK: Some old exporters seem to use ByPolygon to mean ByPolygonVertex,
12753 // it should be quite safe to remap this
12754 if (mapping == ufbxi_ByPolygon) {
12755 size_t num_indices = indices ? indices->size : num_elems;
12756 if (num_indices == mesh->num_indices) {
12757 mapping = ufbxi_ByPolygonVertex;
12758 }
12759 }
12760
12761 if (indices) {
12762 size_t num_indices = indices->size;
12763 uint32_t *index_data = (uint32_t*)indices->data;
12764
12765 if (mapping == ufbxi_ByPolygonVertex) {
12766
12767 // Indexed by polygon vertex: We can use the provided indices directly.
12768 ufbxi_check(ufbxi_check_indices(uc, &attrib->indices.data, index_data, true, num_indices, mesh->num_indices, num_elems));
12769
12770 } else if (mapping == ufbxi_ByVertex || mapping == ufbxi_ByVertice) {
12771
12772 // Indexed by vertex: Follow through the position index mapping to get the final indices.
12773 uint32_t *new_index_data = ufbxi_push(&uc->result, uint32_t, mesh->num_indices);
12774 ufbxi_check(new_index_data);
12775
12776 uint32_t *vert_ix = mesh->vertex_indices.data;
12777 for (size_t i = 0; i < mesh->num_indices; i++) {
12778 uint32_t ix = vert_ix[i];
12779 if (ix < num_indices) {
12780 new_index_data[i] = index_data[ix];
12781 } else {
12782 ufbxi_check(ufbxi_fix_index(uc, &new_index_data[i], ix, num_elems));
12783 }
12784 }
12785
12786 ufbxi_check(ufbxi_check_indices(uc, &attrib->indices.data, new_index_data, true, mesh->num_indices, mesh->num_indices, num_elems));
12787 attrib->unique_per_vertex = true;
12788
12789 } else if (mapping == ufbxi_ByPolygon) {
12790
12791 // Indexed by polygon: Generate new indices based on polygons
12792 uint32_t *new_index_data = ufbxi_push(&uc->result, uint32_t, mesh->num_indices);
12793 ufbxi_check(new_index_data);
12794
12795 size_t num_faces = mesh->num_faces;
12796 for (size_t face_ix = 0; face_ix < num_faces; face_ix++) {
12797 ufbx_face face = mesh->faces.data[face_ix];
12798 uint32_t index = UFBX_NO_INDEX;
12799 if (face_ix < num_indices) {
12800 index = index_data[face_ix];
12801 }
12802 if (index >= num_elems) {
12803 ufbxi_check(ufbxi_fix_index(uc, &index, index, num_elems));
12804 }
12805 for (size_t i = 0; i < face.num_indices; i++) {
12806 new_index_data[face.index_begin + i] = index;
12807 }
12808 }
12809
12810 attrib->indices.data = new_index_data;
12811
12812 } else if (mapping == ufbxi_AllSame) {
12813
12814 // Indexed by all same: ??? This could be possibly used for making
12815 // holes with invalid indices, but that seems really fringe.
12816 // Just use the shared zero index buffer for this.
12817 uc->max_zero_indices = ufbxi_max_sz(uc->max_zero_indices, mesh->num_indices);
12818 attrib->indices.data = (uint32_t*)ufbxi_sentinel_index_zero;
12819 attrib->unique_per_vertex = true;
12820
12821 } else {
12822 memset(attrib, 0, sizeof(ufbx_vertex_attrib));
12823 ufbxi_check(ufbxi_warn_polygon_mapping(uc, data_name, mapping));
12824 return 1;
12825 }
12826
12827 } else {
12828
12829 if (mapping == ufbxi_ByPolygonVertex) {
12830
12831 // Direct by polygon index: Use shared consecutive array if there's enough
12832 // elements, otherwise use a unique truncated consecutive index array.
12833 if (num_elems >= mesh->num_indices) {
12834 uc->max_consecutive_indices = ufbxi_max_sz(uc->max_consecutive_indices, mesh->num_indices);
12835 attrib->indices.data = (uint32_t*)ufbxi_sentinel_index_consecutive;
12836 } else {
12837 uint32_t *index_data = ufbxi_push(&uc->result, uint32_t, mesh->num_indices);
12838 ufbxi_check(index_data);
12839 for (size_t i = 0; i < mesh->num_indices; i++) {
12840 index_data[i] = (uint32_t)i;
12841 }
12842 ufbxi_check(ufbxi_check_indices(uc, &attrib->indices.data, index_data, true, mesh->num_indices, mesh->num_indices, num_elems));
12843 }
12844
12845 } else if (mapping == ufbxi_ByVertex || mapping == ufbxi_ByVertice) {
12846
12847 // Direct by vertex: We can re-use the position indices..
12848 ufbxi_check(ufbxi_check_indices(uc, &attrib->indices.data, mesh->vertex_position.indices.data, false, mesh->num_indices, mesh->num_indices, num_elems));
12849 attrib->unique_per_vertex = true;
12850
12851 } else if (mapping == ufbxi_ByPolygon) {
12852
12853 // Direct by polygon: Generate new indices based on polygons
12854 uint32_t *new_index_data = ufbxi_push(&uc->result, uint32_t, mesh->num_indices);
12855 ufbxi_check(new_index_data);
12856
12857 uint32_t num_faces = (uint32_t)mesh->num_faces;
12858 for (uint32_t face_ix = 0; face_ix < num_faces; face_ix++) {
12859 ufbx_face face = mesh->faces.data[face_ix];
12860 for (size_t i = 0; i < face.num_indices; i++) {
12861 new_index_data[face.index_begin + i] = face_ix;
12862 }
12863 }
12864
12865 ufbxi_check(ufbxi_check_indices(uc, &attrib->indices.data, new_index_data, true, mesh->num_indices, mesh->num_indices, num_elems));
12866
12867 } else if (mapping == ufbxi_AllSame) {
12868
12869 // Direct by all same: This cannot fail as the index list is just zero.
12870 uc->max_zero_indices = ufbxi_max_sz(uc->max_zero_indices, mesh->num_indices);
12871 attrib->indices.data = (uint32_t*)ufbxi_sentinel_index_zero;
12872 attrib->unique_per_vertex = true;
12873
12874 } else {
12875 memset(attrib, 0, sizeof(ufbx_vertex_attrib));
12876 ufbxi_check(ufbxi_warn_polygon_mapping(uc, data_name, mapping));
12877 return 1;
12878 }
12879 }
12880
12881 if (uc->opts.retain_vertex_attrib_w && w_name) {
12882 ufbxi_value_array *w_data = ufbxi_find_array(node, w_name, 'r');
12883 if (w_data) {
12884 if (w_data->size == num_elems) {
12885 attrib->values_w.count = w_data->size;
12886 attrib->values_w.data = (ufbx_real*)w_data->data;
12887 } else {
12888 ufbxi_check(ufbxi_warnf(UFBX_WARNING_BAD_VERTEX_W_ATTRIBUTE, "Bad W array size %s=%zu, %s=%zu",
12889 w_name, w_data->size, data_name, num_elems));
12890 }
12891 }
12892 }
12893
12894 return 1;
12895 }
12896
12897 ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_truncated_array(ufbxi_context *uc, void *p_data, size_t *p_count, ufbxi_node *node, const char *name, char fmt, size_t size)
12898 {
12899 ufbxi_value_array *arr = ufbxi_find_array(node, name, fmt);
12900 if (!arr) {
12901 ufbxi_check(ufbxi_warnf(UFBX_WARNING_MISSING_GEOMETRY_DATA, "Missing geometry data: %s", name));
12902 return 1;
12903 }
12904
12905 *p_count = size;
12906
12907 void *data = arr->data;
12908 if (arr->size < size) {
12909 ufbxi_check(ufbxi_warnf(UFBX_WARNING_TRUNCATED_ARRAY, "Truncated array: %s", name));
12910
12911 size_t elem_size = ufbxi_array_type_size(fmt);
12912 void *new_data = ufbxi_push_size(&uc->result, elem_size, size);
12913 ufbxi_check(new_data);
12914 memcpy(new_data, data, arr->size * elem_size);
12915 // Extend the array with the last element if possible
12916 if (arr->size > 0) {
12917 char *first_elem = (char*)data + (arr->size - 1) * elem_size;
12918 for (size_t i = arr->size; i < size; i++) {
12919 memcpy((char*)new_data + i * elem_size, first_elem, elem_size);
12920 }
12921 } else {
12922 memset(new_data, 0, size * elem_size);
12923 }
12924 data = new_data;
12925 }
12926
12927 *(void**)p_data = data;
12928 return 1;
12929 }
12930
12931 ufbxi_noinline static bool ufbxi_uv_set_less(void *user, const void *va, const void *vb)
12932 {
12933 (void)user;
12934 const ufbx_uv_set *a = (const ufbx_uv_set *)va, *b = (const ufbx_uv_set *)vb;
12935 return a->index < b->index;
12936 }
12937
12938 ufbxi_noinline static bool ufbxi_color_set_less(void *user, const void *va, const void *vb)
12939 {
12940 (void)user;
12941 const ufbx_color_set *a = (const ufbx_color_set *)va, *b = (const ufbx_color_set *)vb;
12942 return a->index < b->index;
12943 }
12944
12945 ufbxi_nodiscard ufbxi_noinline static int ufbxi_sort_uv_sets(ufbxi_context *uc, ufbx_uv_set *sets, size_t count)
12946 {
12947 ufbxi_check(ufbxi_grow_array(&uc->ator_tmp, &uc->tmp_arr, &uc->tmp_arr_size, count * sizeof(ufbx_uv_set)));
12948 ufbxi_stable_sort(sizeof(ufbx_uv_set), 32, sets, uc->tmp_arr, count, &ufbxi_uv_set_less, NULL);
12949 return 1;
12950 }
12951
12952 ufbxi_nodiscard ufbxi_noinline static int ufbxi_sort_color_sets(ufbxi_context *uc, ufbx_color_set *sets, size_t count)
12953 {
12954 ufbxi_check(ufbxi_grow_array(&uc->ator_tmp, &uc->tmp_arr, &uc->tmp_arr_size, count * sizeof(ufbx_color_set)));
12955 ufbxi_stable_sort(sizeof(ufbx_color_set), 32, sets, uc->tmp_arr, count, &ufbxi_color_set_less, NULL);
12956 return 1;
12957 }
12958
12959 typedef struct ufbxi_blend_offset {
12960 uint32_t vertex;
12961 ufbx_vec3 position_offset;
12962 ufbx_vec3 normal_offset;
12963 } ufbxi_blend_offset;
12964
12965 static ufbxi_noinline bool ufbxi_blend_offset_less(void *user, const void *va, const void *vb)
12966 {
12967 (void)user;
12968 const ufbxi_blend_offset *a = (const ufbxi_blend_offset*)va, *b = (const ufbxi_blend_offset*)vb;
12969 return a->vertex < b->vertex;
12970 }
12971
12972 ufbxi_nodiscard ufbxi_noinline static int ufbxi_sort_blend_offsets(ufbxi_context *uc, ufbxi_blend_offset *offsets, size_t count)
12973 {
12974 ufbxi_check(ufbxi_grow_array(&uc->ator_tmp, &uc->tmp_arr, &uc->tmp_arr_size, count * sizeof(ufbxi_blend_offset)));
12975 ufbxi_stable_sort(sizeof(ufbxi_blend_offset), 16, offsets, uc->tmp_arr, count, &ufbxi_blend_offset_less, NULL);
12976 return 1;
12977 }
12978
12979 ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_shape(ufbxi_context *uc, ufbxi_node *node, ufbxi_element_info *info)
12980 {
12981 ufbxi_node *node_vertices = ufbxi_find_child(node, ufbxi_Vertices);
12982 ufbxi_node *node_indices = ufbxi_find_child(node, ufbxi_Indexes);
12983 ufbxi_node *node_normals = ufbxi_find_child(node, ufbxi_Normals);
12984 if (!node_vertices || !node_indices) return 1;
12985
12986 ufbx_blend_shape *shape = ufbxi_push_element(uc, info, ufbx_blend_shape, UFBX_ELEMENT_BLEND_SHAPE);
12987 ufbxi_check(shape);
12988
12989 if (uc->opts.ignore_geometry) return 1;
12990
12991 ufbxi_value_array *vertices = ufbxi_get_array(node_vertices, 'r');
12992 ufbxi_value_array *indices = ufbxi_get_array(node_indices, 'i');
12993
12994 ufbxi_check(vertices && indices);
12995 ufbxi_check(vertices->size % 3 == 0);
12996 ufbxi_check(indices->size == vertices->size / 3);
12997
12998 size_t num_offsets = indices->size;
12999 uint32_t *vertex_indices = (uint32_t*)indices->data;
13000
13001 shape->num_offsets = num_offsets;
13002 shape->position_offsets.data = (ufbx_vec3*)vertices->data;
13003 shape->offset_vertices.data = vertex_indices;
13004 shape->position_offsets.count = num_offsets;
13005 shape->offset_vertices.count = num_offsets;
13006
13007 if (node_normals) {
13008 ufbxi_value_array *normals = ufbxi_get_array(node_normals, 'r');
13009 ufbxi_check(normals && normals->size == vertices->size);
13010 shape->normal_offsets.data = (ufbx_vec3*)normals->data;
13011 shape->normal_offsets.count = num_offsets;
13012 }
13013
13014 // Sort the blend shape vertices only if absolutely necessary
13015 bool sorted = true;
13016 for (size_t i = 1; i < num_offsets; i++) {
13017 if (vertex_indices[i - 1] > vertex_indices[i]) {
13018 sorted = false;
13019 break;
13020 }
13021 }
13022
13023 if (!sorted) {
13024 ufbxi_blend_offset *offsets = ufbxi_push(&uc->tmp_stack, ufbxi_blend_offset, num_offsets);
13025 ufbxi_check(offsets);
13026
13027 for (size_t i = 0; i < num_offsets; i++) {
13028 offsets[i].vertex = shape->offset_vertices.data[i];
13029 offsets[i].position_offset = shape->position_offsets.data[i];
13030 if (node_normals) offsets[i].normal_offset = shape->normal_offsets.data[i];
13031 }
13032
13033 ufbxi_check(ufbxi_sort_blend_offsets(uc, offsets, num_offsets));
13034
13035 for (size_t i = 0; i < num_offsets; i++) {
13036 shape->offset_vertices.data[i] = offsets[i].vertex;
13037 shape->position_offsets.data[i] = offsets[i].position_offset;
13038 if (node_normals) shape->normal_offsets.data[i] = offsets[i].normal_offset;
13039 }
13040 ufbxi_pop(&uc->tmp_stack, ufbxi_blend_offset, num_offsets, NULL);
13041 }
13042
13043 return 1;
13044 }
13045
13046 ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_synthetic_blend_shapes(ufbxi_context *uc, ufbxi_node *node, ufbxi_element_info *info)
13047 {
13048 ufbx_blend_deformer *deformer = NULL;
13049 uint64_t deformer_fbx_id = 0;
13050
13051 ufbxi_for (ufbxi_node, n, node->children, node->num_children) {
13052 if (n->name != ufbxi_Shape) continue;
13053
13054 ufbx_string name;
13055 ufbxi_check(ufbxi_get_val1(n, "S", &name));
13056
13057 if (deformer == NULL) {
13058 deformer = ufbxi_push_synthetic_element(uc, &deformer_fbx_id, n, name.data, ufbx_blend_deformer, UFBX_ELEMENT_BLEND_DEFORMER);
13059 ufbxi_check(deformer);
13060 ufbxi_check(ufbxi_connect_oo(uc, deformer_fbx_id, info->fbx_id));
13061 }
13062
13063 uint64_t channel_fbx_id = 0;
13064 ufbx_blend_channel *channel = ufbxi_push_synthetic_element(uc, &channel_fbx_id, n, name.data, ufbx_blend_channel, UFBX_ELEMENT_BLEND_CHANNEL);
13065 ufbxi_check(channel);
13066
13067 ufbx_real_list weight_list = { NULL, 0 };
13068 ufbxi_check(ufbxi_push_copy(&uc->tmp_full_weights, ufbx_real_list, 1, &weight_list));
13069
13070 size_t num_shape_props = 1;
13071 ufbx_prop *shape_props = ufbxi_push_zero(&uc->result, ufbx_prop, num_shape_props);
13072 ufbxi_check(shape_props);
13073 shape_props[0].name.data = ufbxi_DeformPercent;
13074 shape_props[0].name.length = sizeof(ufbxi_DeformPercent) - 1;
13075 shape_props[0]._internal_key = ufbxi_get_name_key_c(ufbxi_DeformPercent);
13076 shape_props[0].type = UFBX_PROP_NUMBER;
13077 shape_props[0].value_real = (ufbx_real)0.0;
13078 shape_props[0].value_str = ufbx_empty_string;
13079 shape_props[0].value_blob = ufbx_empty_blob;
13080
13081 ufbx_prop *self_prop = ufbx_find_prop_len(&info->props, name.data, name.length);
13082 if (self_prop && (self_prop->type == UFBX_PROP_NUMBER || self_prop->type == UFBX_PROP_INTEGER)) {
13083 shape_props[0].value_real = self_prop->value_real;
13084 ufbxi_check(ufbxi_connect_pp(uc, info->fbx_id, channel_fbx_id, name, shape_props[0].name));
13085 } else if (uc->version < 6000) {
13086 ufbxi_check(ufbxi_connect_pp(uc, info->fbx_id, channel_fbx_id, name, shape_props[0].name));
13087 }
13088
13089 channel->name = name;
13090 channel->props.props.data = shape_props;
13091 channel->props.props.count = num_shape_props;
13092
13093 ufbxi_element_info shape_info = { 0 };
13094
13095 shape_info.fbx_id = ufbxi_push_synthetic_id(uc);
13096 shape_info.name = name;
13097 shape_info.dom_node = ufbxi_get_dom_node(uc, n);
13098
13099 ufbxi_check(ufbxi_read_shape(uc, n, &shape_info));
13100
13101 ufbxi_check(ufbxi_connect_oo(uc, channel_fbx_id, deformer_fbx_id));
13102 ufbxi_check(ufbxi_connect_oo(uc, shape_info.fbx_id, channel_fbx_id));
13103 }
13104
13105 return 1;
13106 }
13107
13108 ufbxi_nodiscard ufbxi_noinline static int ufbxi_process_indices(ufbxi_context *uc, ufbx_mesh *mesh, uint32_t *index_data)
13109 {
13110 // Count the number of faces and allocate the index list
13111 // Indices less than zero (~actual_index) ends a polygon
13112 size_t num_total_faces = 0;
13113 ufbxi_for (uint32_t, p_ix, index_data, mesh->num_indices) {
13114 num_total_faces += ((int32_t)*p_ix < 0) ? 1u : 0u;
13115 }
13116 mesh->faces.data = ufbxi_push(&uc->result, ufbx_face, num_total_faces);
13117 ufbxi_check(mesh->faces.data);
13118
13119 size_t num_triangles = 0;
13120 size_t max_face_triangles = 0;
13121 size_t num_bad_faces[3] = { 0 };
13122
13123 ufbx_face *dst_face = mesh->faces.data;
13124 uint32_t *p_face_begin = index_data;
13125 ufbxi_for (uint32_t, p_ix, index_data, mesh->num_indices) {
13126 uint32_t ix = *p_ix;
13127 // Un-negate final indices of polygons
13128 if ((int32_t)ix < 0) {
13129 ix = ~ix;
13130 *p_ix = ix;
13131 uint32_t num_indices = (uint32_t)((p_ix - p_face_begin) + 1);
13132 dst_face->index_begin = (uint32_t)(p_face_begin - index_data);
13133 dst_face->num_indices = num_indices;
13134 if (num_indices >= 3) {
13135 num_triangles += num_indices - 2;
13136 max_face_triangles = ufbxi_max_sz(max_face_triangles, num_indices - 2);
13137 } else {
13138 num_bad_faces[num_indices]++;
13139 }
13140 dst_face++;
13141 p_face_begin = p_ix + 1;
13142 }
13143 ufbxi_check((size_t)ix < mesh->num_vertices);
13144 }
13145
13146 mesh->vertex_position.indices.data = index_data;
13147 mesh->num_faces = ufbxi_to_size(dst_face - mesh->faces.data);
13148 mesh->faces.count = mesh->num_faces;
13149 mesh->num_triangles = num_triangles;
13150 mesh->max_face_triangles = max_face_triangles;
13151 mesh->num_empty_faces = num_bad_faces[0];
13152 mesh->num_point_faces = num_bad_faces[1];
13153 mesh->num_line_faces = num_bad_faces[2];
13154
13155 mesh->vertex_first_index.count = mesh->num_vertices;
13156 mesh->vertex_first_index.data = ufbxi_push(&uc->result, uint32_t, mesh->num_vertices);
13157 ufbxi_check(mesh->vertex_first_index.data);
13158
13159 ufbxi_for_list(uint32_t, p_vx_ix, mesh->vertex_first_index) {
13160 *p_vx_ix = UFBX_NO_INDEX;
13161 }
13162
13163 {
13164 size_t num_indices = mesh->num_indices;
13165 size_t num_vertices = mesh->num_vertices;
13166 uint32_t *vertex_indices = mesh->vertex_indices.data;
13167 uint32_t *vertex_first_index = mesh->vertex_first_index.data;
13168 for (size_t ix = 0; ix < num_indices; ix++) {
13169 uint32_t vx = vertex_indices[ix];
13170 if (vx < num_vertices) {
13171 if (vertex_first_index[vx] == UFBX_NO_INDEX) {
13172 vertex_first_index[vx] = (uint32_t)ix;
13173 }
13174 } else {
13175 ufbxi_check(ufbxi_fix_index(uc, &vertex_indices[ix], vx, mesh->num_vertices));
13176 }
13177 }
13178 }
13179
13180 // HACK(consecutive-faces): Prepare for finalize to re-use a consecutive/zero
13181 // index buffer for face materials..
13182 uc->max_zero_indices = ufbxi_max_sz(uc->max_zero_indices, mesh->num_faces);
13183 uc->max_consecutive_indices = ufbxi_max_sz(uc->max_consecutive_indices, mesh->num_faces);
13184
13185 return 1;
13186 }
13187
13188 ufbxi_noinline static void ufbxi_patch_mesh_reals(ufbx_mesh *mesh)
13189 {
13190 mesh->vertex_position.value_reals = 3;
13191 mesh->vertex_normal.value_reals = 3;
13192 mesh->vertex_uv.value_reals = 2;
13193 mesh->vertex_tangent.value_reals = 3;
13194 mesh->vertex_bitangent.value_reals = 3;
13195 mesh->vertex_color.value_reals = 4;
13196 mesh->vertex_crease.value_reals = 1;
13197 mesh->skinned_position.value_reals = 3;
13198 mesh->skinned_normal.value_reals = 3;
13199
13200 ufbxi_nounroll ufbxi_for_list(ufbx_uv_set, set, mesh->uv_sets) {
13201 set->vertex_uv.value_reals = 2;
13202 set->vertex_tangent.value_reals = 3;
13203 set->vertex_bitangent.value_reals = 3;
13204 }
13205
13206 ufbxi_nounroll ufbxi_for_list(ufbx_color_set, set, mesh->color_sets) {
13207 set->vertex_color.value_reals = 4;
13208 }
13209 }
13210
13211 typedef struct {
13212 uint32_t id, index;
13213 } ufbxi_id_group;
13214
13215 static bool ufbxi_less_int32(void *user, const void *va, const void *vb)
13216 {
13217 (void)user;
13218 const int32_t a = *(const int32_t*)va, b = *(const int32_t*)vb;
13219 return a < b;
13220 }
13221
13222 ufbx_static_assert(mesh_mat_point_faces, offsetof(ufbx_mesh_part, num_point_faces) - offsetof(ufbx_mesh_part, num_empty_faces) == 1 * sizeof(size_t));
13223 ufbx_static_assert(mesh_mat_line_faces, offsetof(ufbx_mesh_part, num_line_faces) - offsetof(ufbx_mesh_part, num_empty_faces) == 2 * sizeof(size_t));
13224 static ufbxi_forceinline void ufbxi_mesh_part_add_face(ufbx_mesh_part *part, uint32_t num_indices)
13225 {
13226 part->num_faces++;
13227 if (num_indices >= 3) {
13228 part->num_triangles += num_indices - 2;
13229 } else {
13230 // `num_empty/point/line_faces` are consecutive, see static asserts above.
13231 // cppcheck-suppress objectIndex
13232 (&part->num_empty_faces)[num_indices]++;
13233 }
13234 }
13235
13236 ufbxi_nodiscard static ufbxi_noinline int ufbxi_assign_face_groups(ufbxi_buf *buf, ufbx_error *error, ufbx_mesh *mesh, size_t *p_consecutive_indices, bool retain_parts)
13237 {
13238 size_t num_faces = mesh->num_faces;
13239 ufbxi_check_err(error, num_faces > 0);
13240 ufbxi_check_err(error, num_faces < UINT32_MAX);
13241 ufbxi_check_err(error, mesh->face_group.count == num_faces);
13242
13243 uint32_t *ids = ufbxi_push(buf, uint32_t, num_faces);
13244 ufbxi_check_err(error, ids);
13245
13246 uint32_t num_ids = 0;
13247
13248 ufbxi_id_group seen_ids[1 << UFBXI_FACE_GROUP_HASH_BITS];
13249 memset(seen_ids, 0, sizeof(seen_ids));
13250
13251 uint32_t seed = 2654435769u;
13252 uint32_t rehash_threshold = 256;
13253
13254 // Loosely deduplicate group IDs
13255 ufbxi_for_list(uint32_t, p_id, mesh->face_group) {
13256 uint32_t id = *p_id;
13257 uint32_t id_hash = (id * seed) >> (32u - UFBXI_FACE_GROUP_HASH_BITS);
13258 if (seen_ids[id_hash].id != id || seen_ids[id_hash].index == 0) {
13259 seen_ids[id_hash].id = id;
13260 if (++seen_ids[id_hash].index > rehash_threshold) {
13261 seed *= seed;
13262 rehash_threshold *= 2;
13263 }
13264 ids[num_ids++] = id;
13265 }
13266 }
13267
13268 // Sort and deduplicate remaining IDs
13269 ufbxi_unstable_sort(ids, num_ids, sizeof(uint32_t), &ufbxi_less_int32, NULL);
13270
13271 size_t num_groups = 0;
13272 for (size_t i = 0; i < num_ids; ) {
13273 uint32_t id = ids[i];
13274 ids[num_groups++] = id;
13275 do { i++; } while (i < num_ids && ids[i] == id);
13276 }
13277
13278 // Allocate group info structs
13279 ufbx_face_group *groups = ufbxi_push_zero(buf, ufbx_face_group, num_groups);
13280 ufbxi_check_err(error, groups);
13281 for (size_t i = 0; i < num_groups; i++) {
13282 groups[i].id = (int32_t)ids[i];
13283 groups[i].name.data = ufbxi_empty_char;
13284 }
13285
13286 mesh->face_groups.data = groups;
13287 mesh->face_groups.count = num_groups;
13288
13289 ufbx_mesh_part *parts = NULL;
13290 if (retain_parts) {
13291 parts = ufbxi_push_zero(buf, ufbx_mesh_part, num_groups);
13292 ufbxi_check_err(error, parts);
13293 mesh->face_group_parts.data = parts;
13294 mesh->face_group_parts.count = num_groups;
13295 }
13296
13297 // Optimization: Use `consecutive_indices` for a single group
13298 if (p_consecutive_indices && num_groups == 1) {
13299 memset(mesh->face_group.data, 0, sizeof(uint32_t) * num_faces);
13300
13301 if (parts) {
13302 parts[0].face_indices.data = (uint32_t*)ufbxi_sentinel_index_consecutive;
13303 parts[0].face_indices.count = num_faces;
13304 parts[0].num_empty_faces = mesh->num_empty_faces;
13305 parts[0].num_point_faces = mesh->num_point_faces;
13306 parts[0].num_line_faces = mesh->num_line_faces;
13307 parts[0].num_faces = num_faces;
13308 parts[0].num_triangles = mesh->num_triangles;
13309 }
13310
13311 *p_consecutive_indices = ufbxi_max_sz(*p_consecutive_indices, num_faces);
13312 return 1;
13313 }
13314
13315 memset(seen_ids, 0, sizeof(seen_ids));
13316
13317 // Count faces and triangles per group and reassign IDs
13318 const ufbx_face *p_face = mesh->faces.data;
13319 ufbxi_for_list(uint32_t, p_id, mesh->face_group) {
13320 uint32_t id = *p_id;
13321 uint32_t id_hash = (id * seed) >> (32u - UFBXI_FACE_GROUP_HASH_BITS);
13322
13323 uint32_t num_indices = p_face->num_indices;
13324
13325 size_t index;
13326 if (seen_ids[id_hash].id == id && seen_ids[id_hash].index > 0) {
13327 index = seen_ids[id_hash].index - 1;
13328 *p_id = (uint32_t)index;
13329 } else {
13330 int32_t signed_id = (int32_t)id;
13331 index = SIZE_MAX;
13332 ufbxi_macro_lower_bound_eq(ufbx_face_group, 8, &index, groups, 0, num_groups, ( a->id < signed_id ), ( a->id == signed_id ));
13333 ufbx_assert(index < num_groups);
13334 seen_ids[id_hash].id = id;
13335 seen_ids[id_hash].index = (uint32_t)index + 1;
13336 }
13337
13338 if (parts) {
13339 ufbxi_mesh_part_add_face(&parts[index], num_indices);
13340 }
13341
13342 *p_id = (uint32_t)index;
13343 p_face++;
13344 }
13345
13346 if (!parts) return 1;
13347
13348 // Subdivide `ids` for per-group `face_indices`
13349 uint32_t *face_indices = ids;
13350 uint32_t part_index = 0;
13351 ufbxi_for(ufbx_mesh_part, part, parts, num_groups) {
13352 part->index = part_index++;
13353 part->face_indices.data = face_indices;
13354 face_indices += part->num_faces;
13355 }
13356 ufbx_assert(face_indices == ids + num_faces);
13357
13358 // Collect per-group faces
13359 uint32_t face_index = 0;
13360 ufbxi_for_list(uint32_t, p_id, mesh->face_group) {
13361 ufbx_mesh_part *part = &parts[*p_id];
13362 part->face_indices.data[part->face_indices.count++] = face_index++;
13363 }
13364
13365 return 1;
13366 }
13367
13368 ufbxi_nodiscard static ufbxi_noinline int ufbxi_update_face_groups(ufbxi_buf *buf, ufbx_error *error, ufbx_mesh *mesh, bool need_copy)
13369 {
13370 size_t num_faces = mesh->faces.count;
13371 size_t num_groups = mesh->face_group_parts.count;
13372 if (num_groups == 0) return 1;
13373
13374 if (need_copy) {
13375 mesh->face_group_parts.data = ufbxi_push_zero(buf, ufbx_mesh_part, num_groups);
13376 ufbxi_check_err(error, mesh->face_group_parts.data);
13377 }
13378
13379 uint32_t *face_indices = ufbxi_push(buf, uint32_t, num_faces);
13380 ufbxi_check_err(error, face_indices);
13381
13382 ufbxi_nounroll for (size_t i = 0; i < num_faces; i++) {
13383 ufbx_mesh_part *part = &mesh->face_group_parts.data[mesh->face_group.data[i]];
13384 ufbxi_mesh_part_add_face(part, mesh->faces.data[i].num_indices);
13385 }
13386
13387 uint32_t part_index = 0;
13388 ufbxi_for_list(ufbx_mesh_part, part, mesh->face_group_parts) {
13389 part->index = part_index++;
13390 part->face_indices.data = face_indices;
13391 part->face_indices.count = 0;
13392 face_indices += part->num_faces;
13393 }
13394
13395 ufbxi_nounroll for (uint32_t i = 0; i < num_faces; i++) {
13396 ufbx_mesh_part *part = &mesh->face_group_parts.data[mesh->face_group.data[i]];
13397 part->face_indices.data[part->face_indices.count++] = i;
13398 }
13399
13400 return 1;
13401 }
13402
13403 ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_mesh(ufbxi_context *uc, ufbxi_node *node, ufbxi_element_info *info)
13404 {
13405 ufbx_mesh *ufbxi_restrict mesh = ufbxi_push_element(uc, info, ufbx_mesh, UFBX_ELEMENT_MESH);
13406 ufbxi_check(mesh);
13407
13408 // In up to version 7100 FBX files blend shapes are contained within the same geometry node
13409 if (uc->version <= 7100) {
13410 ufbxi_check(ufbxi_read_synthetic_blend_shapes(uc, node, info));
13411 }
13412
13413 ufbxi_patch_mesh_reals(mesh);
13414
13415 // Sometimes there are empty meshes in FBX files?
13416 // TODO: Should these be included in output? option? strict mode?
13417 ufbxi_node *node_vertices = ufbxi_find_child(node, ufbxi_Vertices);
13418 ufbxi_node *node_indices = ufbxi_find_child(node, ufbxi_PolygonVertexIndex);
13419 if (!node_vertices) return 1;
13420
13421 if (uc->opts.ignore_geometry) return 1;
13422
13423 ufbxi_value_array *vertices = ufbxi_get_array(node_vertices, 'r');
13424 ufbxi_value_array *indices = node_indices ? ufbxi_get_array(node_indices, 'i') : NULL;
13425 ufbxi_value_array *edge_indices = ufbxi_find_array(node, ufbxi_Edges, 'i');
13426 ufbxi_check(vertices);
13427 ufbxi_check(!node_indices || indices); // If node_indices exists, it must be an array
13428 ufbxi_check(vertices->size % 3 == 0);
13429
13430 mesh->num_vertices = vertices->size / 3;
13431 mesh->num_indices = indices ? indices->size : 0;
13432
13433 uint32_t *index_data = indices ? (uint32_t*)indices->data : NULL;
13434
13435 // Duplicate `index_data` for modification if we retain DOM
13436 if (uc->opts.retain_dom) {
13437 index_data = ufbxi_push_copy(&uc->result, uint32_t, mesh->num_indices, index_data);
13438 ufbxi_check(index_data);
13439 }
13440
13441 mesh->vertices.data = (ufbx_vec3*)vertices->data;
13442 mesh->vertices.count = mesh->num_vertices;
13443 mesh->vertex_indices.data = index_data;
13444 mesh->vertex_indices.count = mesh->num_indices;
13445
13446 mesh->vertex_position.exists = true;
13447 mesh->vertex_position.values.data = (ufbx_vec3*)vertices->data;
13448 mesh->vertex_position.values.count = mesh->num_vertices;
13449 mesh->vertex_position.indices.data = index_data;
13450 mesh->vertex_position.indices.count = mesh->num_indices;
13451 mesh->vertex_position.unique_per_vertex = true;
13452
13453 // Check/make sure that the last index is negated (last of polygon)
13454 if (mesh->num_indices > 0) {
13455 if ((int32_t)index_data[mesh->num_indices - 1] >= 0) {
13456 if (uc->opts.strict) ufbxi_fail("Non-negated last index");
13457 index_data[mesh->num_indices - 1] = ~index_data[mesh->num_indices - 1];
13458 }
13459 }
13460
13461 // Read edges before un-negating the indices
13462 if (edge_indices) {
13463 size_t num_edges = edge_indices->size;
13464 ufbx_edge *edges = ufbxi_push(&uc->result, ufbx_edge, num_edges);
13465 ufbxi_check(edges);
13466
13467 size_t dst_ix = 0;
13468
13469 // Edges are represented using a single index into PolygonVertexIndex.
13470 // The edge is between two consecutive vertices in the polygon.
13471 uint32_t *edge_data = (uint32_t*)edge_indices->data;
13472 for (size_t i = 0; i < num_edges; i++) {
13473 uint32_t index_ix = edge_data[i];
13474 if (index_ix >= mesh->num_indices) {
13475 if (uc->opts.strict) ufbxi_fail("Edge index out of bounds");
13476 continue;
13477 }
13478 edges[dst_ix].a = index_ix;
13479 if ((int32_t)index_data[index_ix] < 0) {
13480 // Previous index is the last one of this polygon, rewind to first index.
13481 while (index_ix > 0 && (int32_t)index_data[index_ix - 1] >= 0) {
13482 index_ix--;
13483 }
13484 } else {
13485 // Connect to the next index in the same polygon
13486 index_ix++;
13487 }
13488 ufbxi_check(index_ix < mesh->num_indices);
13489 edges[dst_ix].b = index_ix;
13490 dst_ix++;
13491 }
13492
13493 mesh->edges.data = edges;
13494 mesh->edges.count = dst_ix;
13495 mesh->num_edges = mesh->edges.count;
13496 }
13497
13498 ufbxi_check(ufbxi_process_indices(uc, mesh, index_data));
13499
13500 // Count the number of UV/color sets
13501 size_t num_uv = 0, num_color = 0, num_bitangents = 0, num_tangents = 0;
13502 ufbxi_for (ufbxi_node, n, node->children, node->num_children) {
13503 if (n->name == ufbxi_LayerElementUV) num_uv++;
13504 if (n->name == ufbxi_LayerElementColor) num_color++;
13505 if (n->name == ufbxi_LayerElementBinormal) num_bitangents++;
13506 if (n->name == ufbxi_LayerElementTangent) num_tangents++;
13507 }
13508
13509 size_t num_textures = 0;
13510
13511 ufbxi_tangent_layer *bitangents = ufbxi_push_zero(&uc->tmp_stack, ufbxi_tangent_layer, num_bitangents);
13512 ufbxi_tangent_layer *tangents = ufbxi_push_zero(&uc->tmp_stack, ufbxi_tangent_layer, num_tangents);
13513 ufbxi_check(bitangents);
13514 ufbxi_check(tangents);
13515
13516 mesh->uv_sets.data = ufbxi_push_zero(&uc->result, ufbx_uv_set, num_uv);
13517 mesh->color_sets.data = ufbxi_push_zero(&uc->result, ufbx_color_set, num_color);
13518 ufbxi_check(mesh->uv_sets.data);
13519 ufbxi_check(mesh->color_sets.data);
13520
13521 size_t num_bitangents_read = 0, num_tangents_read = 0;
13522 ufbxi_for (ufbxi_node, n, node->children, node->num_children) {
13523 if (n->name[0] != 'L') continue; // All names start with 'LayerElement*'
13524
13525 if (n->name == ufbxi_LayerElementNormal) {
13526 if (mesh->vertex_normal.exists) continue;
13527 ufbxi_check(ufbxi_read_vertex_element(uc, mesh, n, (ufbx_vertex_attrib*)&mesh->vertex_normal,
13528 ufbxi_Normals, ufbxi_NormalsIndex, ufbxi_NormalsW, 'r', 3));
13529 } else if (n->name == ufbxi_LayerElementBinormal) {
13530 ufbxi_tangent_layer *layer = &bitangents[num_bitangents_read++];
13531
13532 ufbxi_ignore(ufbxi_get_val1(n, "I", &layer->index));
13533 ufbxi_check(ufbxi_read_vertex_element(uc, mesh, n, (ufbx_vertex_attrib*)&layer->elem,
13534 ufbxi_Binormals, ufbxi_BinormalsIndex, ufbxi_BinormalsW, 'r', 3));
13535 if (!layer->elem.exists) num_bitangents_read--;
13536
13537 } else if (n->name == ufbxi_LayerElementTangent) {
13538 ufbxi_tangent_layer *layer = &tangents[num_tangents_read++];
13539
13540 ufbxi_ignore(ufbxi_get_val1(n, "I", &layer->index));
13541 ufbxi_check(ufbxi_read_vertex_element(uc, mesh, n, (ufbx_vertex_attrib*)&layer->elem,
13542 ufbxi_Tangents, ufbxi_TangentsIndex, ufbxi_TangentsW, 'r', 3));
13543 if (!layer->elem.exists) num_tangents_read--;
13544
13545 } else if (n->name == ufbxi_LayerElementUV) {
13546 ufbx_uv_set *set = &mesh->uv_sets.data[mesh->uv_sets.count++];
13547
13548 ufbxi_ignore(ufbxi_get_val1(n, "I", &set->index));
13549 if (!ufbxi_find_val1(n, ufbxi_Name, "S", &set->name)) {
13550 set->name = ufbx_empty_string;
13551 }
13552
13553 ufbxi_check(ufbxi_read_vertex_element(uc, mesh, n, (ufbx_vertex_attrib*)&set->vertex_uv,
13554 ufbxi_UV, ufbxi_UVIndex, NULL, 'r', 2));
13555 if (!set->vertex_uv.exists) mesh->uv_sets.count--;
13556
13557 } else if (n->name == ufbxi_LayerElementColor) {
13558 ufbx_color_set *set = &mesh->color_sets.data[mesh->color_sets.count++];
13559
13560 ufbxi_ignore(ufbxi_get_val1(n, "I", &set->index));
13561 if (!ufbxi_find_val1(n, ufbxi_Name, "S", &set->name)) {
13562 set->name = ufbx_empty_string;
13563 }
13564
13565 ufbxi_check(ufbxi_read_vertex_element(uc, mesh, n, (ufbx_vertex_attrib*)&set->vertex_color,
13566 ufbxi_Colors, ufbxi_ColorIndex, NULL, 'r', 4));
13567 if (!set->vertex_color.exists) mesh->color_sets.count--;
13568
13569 } else if (n->name == ufbxi_LayerElementVertexCrease) {
13570 ufbxi_check(ufbxi_read_vertex_element(uc, mesh, n, (ufbx_vertex_attrib*)&mesh->vertex_crease,
13571 ufbxi_VertexCrease, ufbxi_VertexCreaseIndex, NULL, 'r', 1));
13572 } else if (n->name == ufbxi_LayerElementEdgeCrease) {
13573 const char *mapping = "";
13574 ufbxi_ignore(ufbxi_find_val1(n, ufbxi_MappingInformationType, "c", (char**)&mapping));
13575 if (mapping == ufbxi_ByEdge) {
13576 if (mesh->edge_crease.count) continue;
13577 ufbxi_check(ufbxi_read_truncated_array(uc, &mesh->edge_crease.data, &mesh->edge_crease.count, n, ufbxi_EdgeCrease, 'r', mesh->num_edges));
13578 } else {
13579 ufbxi_check(ufbxi_warn_polygon_mapping(uc, ufbxi_EdgeCrease, mapping));
13580 }
13581 } else if (n->name == ufbxi_LayerElementSmoothing) {
13582 const char *mapping = "";
13583 ufbxi_ignore(ufbxi_find_val1(n, ufbxi_MappingInformationType, "c", (char**)&mapping));
13584 if (mapping == ufbxi_ByEdge) {
13585 if (mesh->edge_smoothing.count) continue;
13586 ufbxi_check(ufbxi_read_truncated_array(uc, &mesh->edge_smoothing.data, &mesh->edge_smoothing.count, n, ufbxi_Smoothing, 'b', mesh->num_edges));
13587 } else if (mapping == ufbxi_ByPolygon) {
13588 if (mesh->face_smoothing.count) continue;
13589 ufbxi_check(ufbxi_read_truncated_array(uc, &mesh->face_smoothing.data, &mesh->face_smoothing.count, n, ufbxi_Smoothing, 'b', mesh->num_faces));
13590 } else {
13591 ufbxi_check(ufbxi_warn_polygon_mapping(uc, ufbxi_Smoothing, mapping));
13592 }
13593 } else if (n->name == ufbxi_LayerElementVisibility) {
13594 const char *mapping = "";
13595 ufbxi_ignore(ufbxi_find_val1(n, ufbxi_MappingInformationType, "c", (char**)&mapping));
13596 if (mapping == ufbxi_ByEdge) {
13597 if (mesh->edge_visibility.count) continue;
13598 ufbxi_check(ufbxi_read_truncated_array(uc, &mesh->edge_visibility.data, &mesh->edge_visibility.count, n, ufbxi_Visibility, 'b', mesh->num_edges));
13599 } else {
13600 ufbxi_check(ufbxi_warn_polygon_mapping(uc, ufbxi_Visibility, mapping));
13601 }
13602 } else if (n->name == ufbxi_LayerElementMaterial) {
13603 if (mesh->face_material.count) continue;
13604 const char *mapping = "";
13605 ufbxi_ignore(ufbxi_find_val1(n, ufbxi_MappingInformationType, "c", (char**)&mapping));
13606 if (mapping == ufbxi_ByPolygon) {
13607 ufbxi_check(ufbxi_read_truncated_array(uc, &mesh->face_material.data, &mesh->face_material.count, n, ufbxi_Materials, 'i', mesh->num_faces));
13608 } else if (mapping == ufbxi_AllSame) {
13609 ufbxi_value_array *arr = ufbxi_find_array(n, ufbxi_Materials, 'i');
13610 ufbxi_check(arr && arr->size >= 1);
13611 uint32_t material = *(uint32_t*)arr->data;
13612 mesh->face_material.count = mesh->num_faces;
13613 if (material == 0) {
13614 mesh->face_material.data = (uint32_t*)ufbxi_sentinel_index_zero;
13615 } else {
13616 mesh->face_material.data = ufbxi_push(&uc->result, uint32_t, mesh->num_faces);
13617 ufbxi_check(mesh->face_material.data);
13618 ufbxi_for_list(uint32_t, p_mat, mesh->face_material) {
13619 *p_mat = material;
13620 }
13621 }
13622 } else {
13623 ufbxi_check(ufbxi_warn_polygon_mapping(uc, ufbxi_Materials, mapping));
13624 }
13625 } else if (n->name == ufbxi_LayerElementPolygonGroup) {
13626 if (mesh->face_group.count) continue;
13627 const char *mapping = NULL;
13628 ufbxi_check(ufbxi_find_val1(n, ufbxi_MappingInformationType, "c", (char**)&mapping));
13629 if (mapping == ufbxi_ByPolygon) {
13630 ufbxi_check(ufbxi_read_truncated_array(uc, &mesh->face_group.data, &mesh->face_group.count, n, ufbxi_PolygonGroup, 'i', mesh->num_faces));
13631 }
13632 } else if (n->name == ufbxi_LayerElementHole) {
13633 if (mesh->face_group.count) continue;
13634 const char *mapping = NULL;
13635 ufbxi_check(ufbxi_find_val1(n, ufbxi_MappingInformationType, "c", (char**)&mapping));
13636 if (mapping == ufbxi_ByPolygon) {
13637 ufbxi_check(ufbxi_read_truncated_array(uc, &mesh->face_hole.data, &mesh->face_hole.count, n, ufbxi_Hole, 'b', mesh->num_faces));
13638 }
13639 } else if (!strncmp(n->name, "LayerElement", 12)) {
13640
13641 // Make sure the name has no internal zero bytes
13642 ufbxi_check(!memchr(n->name, '\0', n->name_len));
13643
13644 // What?! 6x00 stores textures in mesh geometry, eg. "LayerElementTexture",
13645 // "LayerElementDiffuseFactorTextures", "LayerElementEmissive_Textures"...
13646 ufbx_string prop_name = ufbx_empty_string;
13647 if (n->name_len > 20 && !strcmp(n->name + n->name_len - 8, "Textures")) {
13648 prop_name.data = n->name + 12;
13649 prop_name.length = (size_t)n->name_len - 20;
13650 if (prop_name.data[prop_name.length - 1] == '_') {
13651 prop_name.length -= 1;
13652 }
13653 } else if (!strcmp(n->name, "LayerElementTexture")) {
13654 prop_name.data = "Diffuse";
13655 prop_name.length = 7;
13656 }
13657
13658 if (prop_name.length > 0) {
13659 ufbxi_check(ufbxi_push_string_place_str(&uc->string_pool, &prop_name, false));
13660 const char *mapping = NULL;
13661 if (ufbxi_find_val1(n, ufbxi_MappingInformationType, "c", (char**)&mapping)) {
13662 ufbxi_value_array *arr = ufbxi_find_array(n, ufbxi_TextureId, 'i');
13663
13664 ufbxi_tmp_mesh_texture *tex = ufbxi_push_zero(&uc->tmp_mesh_textures, ufbxi_tmp_mesh_texture, 1);
13665 ufbxi_check(tex);
13666 if (arr) {
13667 tex->face_texture = (uint32_t*)arr->data;
13668 tex->num_faces = arr->size;
13669 }
13670 tex->prop_name = prop_name;
13671 tex->all_same = (mapping == ufbxi_AllSame);
13672 num_textures++;
13673 }
13674 }
13675 }
13676 }
13677
13678 // Always use a default zero material, this will be removed if no materials are found
13679 if (!mesh->face_material.count) {
13680 uc->max_zero_indices = ufbxi_max_sz(uc->max_zero_indices, mesh->num_faces);
13681 mesh->face_material.data = (uint32_t*)ufbxi_sentinel_index_zero;
13682 mesh->face_material.count = mesh->num_faces;
13683 }
13684
13685 if (uc->opts.strict) {
13686 ufbxi_check(mesh->uv_sets.count == num_uv);
13687 ufbxi_check(mesh->color_sets.count == num_color);
13688 ufbxi_check(num_bitangents_read == num_bitangents);
13689 ufbxi_check(num_tangents_read == num_tangents);
13690 }
13691
13692 // Connect bitangents/tangents to UV sets
13693 ufbxi_for (ufbxi_node, n, node->children, node->num_children) {
13694 if (n->name != ufbxi_Layer) continue;
13695 ufbx_uv_set *uv_set = NULL;
13696 ufbxi_tangent_layer *bitangent_layer = NULL;
13697 ufbxi_tangent_layer *tangent_layer = NULL;
13698
13699 ufbxi_for (ufbxi_node, c, n->children, n->num_children) {
13700 uint32_t index;
13701 const char *type;
13702 if (c->name != ufbxi_LayerElement) continue;
13703 if (!ufbxi_find_val1(c, ufbxi_TypedIndex, "I", &index)) continue;
13704 if (!ufbxi_find_val1(c, ufbxi_Type, "C", (char**)&type)) continue;
13705
13706 if (type == ufbxi_LayerElementUV) {
13707 ufbxi_for(ufbx_uv_set, set, mesh->uv_sets.data, mesh->uv_sets.count) {
13708 if (set->index == index) {
13709 uv_set = set;
13710 break;
13711 }
13712 }
13713 } else if (type == ufbxi_LayerElementBinormal) {
13714 ufbxi_for(ufbxi_tangent_layer, layer, bitangents, num_bitangents_read) {
13715 if (layer->index == index) {
13716 bitangent_layer = layer;
13717 break;
13718 }
13719 }
13720 } else if (type == ufbxi_LayerElementTangent) {
13721 ufbxi_for(ufbxi_tangent_layer, layer, tangents, num_tangents_read) {
13722 if (layer->index == index) {
13723 tangent_layer = layer;
13724 break;
13725 }
13726 }
13727 }
13728 }
13729
13730 if (uv_set) {
13731 if (bitangent_layer) {
13732 uv_set->vertex_bitangent = bitangent_layer->elem;
13733 }
13734 if (tangent_layer) {
13735 uv_set->vertex_tangent = tangent_layer->elem;
13736 }
13737 }
13738 }
13739
13740 mesh->skinned_is_local = true;
13741 mesh->skinned_position = mesh->vertex_position;
13742 mesh->skinned_normal = mesh->vertex_normal;
13743
13744 ufbxi_patch_mesh_reals(mesh);
13745
13746 if (mesh->face_group.count > 0 && mesh->face_groups.count == 0) {
13747 ufbxi_check(ufbxi_assign_face_groups(&uc->result, &uc->error, mesh, &uc->max_consecutive_indices, uc->retain_mesh_parts));
13748 }
13749
13750 // Sort UV and color sets by set index
13751 ufbxi_check(ufbxi_sort_uv_sets(uc, mesh->uv_sets.data, mesh->uv_sets.count));
13752 ufbxi_check(ufbxi_sort_color_sets(uc, mesh->color_sets.data, mesh->color_sets.count));
13753
13754 if (num_textures > 0) {
13755 ufbxi_mesh_extra *extra = ufbxi_push_element_extra(uc, mesh->element.element_id, ufbxi_mesh_extra);
13756 ufbxi_check(extra);
13757 extra->texture_count = num_textures;
13758 extra->texture_arr = ufbxi_push_pop(&uc->tmp, &uc->tmp_mesh_textures, ufbxi_tmp_mesh_texture, num_textures);
13759 ufbxi_check(extra->texture_arr);
13760 }
13761
13762 // Subdivision
13763
13764 ufbxi_ignore(ufbxi_find_val1(node, ufbxi_PreviewDivisionLevels, "I", &mesh->subdivision_preview_levels));
13765 ufbxi_ignore(ufbxi_find_val1(node, ufbxi_RenderDivisionLevels, "I", &mesh->subdivision_render_levels));
13766
13767 int32_t smoothness, boundary;
13768 if (ufbxi_find_val1(node, ufbxi_Smoothness, "I", &smoothness)) {
13769 if (smoothness >= 0 && smoothness <= UFBX_SUBDIVISION_DISPLAY_SMOOTH) {
13770 mesh->subdivision_display_mode = (ufbx_subdivision_display_mode)smoothness;
13771 }
13772 }
13773 if (ufbxi_find_val1(node, ufbxi_BoundaryRule, "I", &boundary)) {
13774 if (boundary >= 0 && boundary <= UFBX_SUBDIVISION_BOUNDARY_SHARP_CORNERS - 1) {
13775 mesh->subdivision_boundary = (ufbx_subdivision_boundary)(boundary + 1);
13776 }
13777 }
13778
13779 return 1;
13780 }
13781
13782 ufbxi_noinline static ufbx_nurbs_topology ufbxi_read_nurbs_topology(const char *form)
13783 {
13784 if (!strcmp(form, "Open")) {
13785 return UFBX_NURBS_TOPOLOGY_OPEN;
13786 } else if (!strcmp(form, "Closed")) {
13787 return UFBX_NURBS_TOPOLOGY_CLOSED;
13788 } else if (!strcmp(form, "Periodic")) {
13789 return UFBX_NURBS_TOPOLOGY_PERIODIC;
13790 }
13791 return UFBX_NURBS_TOPOLOGY_OPEN;
13792 }
13793
13794 ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_nurbs_curve(ufbxi_context *uc, ufbxi_node *node, ufbxi_element_info *info)
13795 {
13796 ufbx_nurbs_curve *nurbs = ufbxi_push_element(uc, info, ufbx_nurbs_curve, UFBX_ELEMENT_NURBS_CURVE);
13797 ufbxi_check(nurbs);
13798
13799 int32_t dimension = 3;
13800
13801 const char *form = NULL;
13802 ufbxi_check(ufbxi_find_val1(node, ufbxi_Order, "I", &nurbs->basis.order));
13803 ufbxi_ignore(ufbxi_find_val1(node, ufbxi_Dimension, "I", &dimension));
13804 ufbxi_check(ufbxi_find_val1(node, ufbxi_Form, "C", (char**)&form));
13805 nurbs->basis.topology = ufbxi_read_nurbs_topology(form);
13806 nurbs->basis.is_2d = dimension == 2;
13807
13808 if (!uc->opts.ignore_geometry) {
13809 ufbxi_value_array *points = ufbxi_find_array(node, ufbxi_Points, 'r');
13810 ufbxi_value_array *knot = ufbxi_find_array(node, ufbxi_KnotVector, 'r');
13811 ufbxi_check(points);
13812 ufbxi_check(knot);
13813 ufbxi_check(points->size % 4 == 0);
13814
13815 nurbs->control_points.count = points->size / 4;
13816 nurbs->control_points.data = (ufbx_vec4*)points->data;
13817 nurbs->basis.knot_vector.data = (ufbx_real*)knot->data;
13818 nurbs->basis.knot_vector.count = knot->size;
13819 }
13820
13821 return 1;
13822 }
13823
13824 ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_nurbs_surface(ufbxi_context *uc, ufbxi_node *node, ufbxi_element_info *info)
13825 {
13826 ufbx_nurbs_surface *nurbs = ufbxi_push_element(uc, info, ufbx_nurbs_surface, UFBX_ELEMENT_NURBS_SURFACE);
13827 ufbxi_check(nurbs);
13828
13829 const char *form_u = NULL, *form_v = NULL;
13830 size_t dimension_u = 0, dimension_v = 0;
13831 int32_t step_u = 0, step_v = 0;
13832 ufbxi_check(ufbxi_find_val2(node, ufbxi_NurbsSurfaceOrder, "II", &nurbs->basis_u.order, &nurbs->basis_v.order));
13833 ufbxi_check(ufbxi_find_val2(node, ufbxi_Dimensions, "ZZ", &dimension_u, &dimension_v));
13834 ufbxi_check(ufbxi_find_val2(node, ufbxi_Step, "II", &step_u, &step_v));
13835 ufbxi_check(ufbxi_find_val2(node, ufbxi_Form, "CC", (char**)&form_u, (char**)&form_v));
13836 ufbxi_ignore(ufbxi_find_val1(node, ufbxi_FlipNormals, "B", &nurbs->flip_normals));
13837 nurbs->basis_u.topology = ufbxi_read_nurbs_topology(form_u);
13838 nurbs->basis_v.topology = ufbxi_read_nurbs_topology(form_v);
13839 nurbs->num_control_points_u = dimension_u;
13840 nurbs->num_control_points_v = dimension_v;
13841 nurbs->span_subdivision_u = step_u > 0 ? (uint32_t)step_u : 4u;
13842 nurbs->span_subdivision_v = step_v > 0 ? (uint32_t)step_v : 4u;
13843
13844 if (!uc->opts.ignore_geometry) {
13845 ufbxi_value_array *points = ufbxi_find_array(node, ufbxi_Points, 'r');
13846 ufbxi_value_array *knot_u = ufbxi_find_array(node, ufbxi_KnotVectorU, 'r');
13847 ufbxi_value_array *knot_v = ufbxi_find_array(node, ufbxi_KnotVectorV, 'r');
13848 ufbxi_check(points);
13849 ufbxi_check(knot_u);
13850 ufbxi_check(knot_v);
13851 ufbxi_check(points->size % 4 == 0);
13852 ufbxi_check(points->size / 4 == (size_t)dimension_u * (size_t)dimension_v);
13853
13854 nurbs->control_points.count = points->size / 4;
13855 nurbs->control_points.data = (ufbx_vec4*)points->data;
13856 nurbs->basis_u.knot_vector.data = (ufbx_real*)knot_u->data;
13857 nurbs->basis_u.knot_vector.count = knot_u->size;
13858 nurbs->basis_v.knot_vector.data = (ufbx_real*)knot_v->data;
13859 nurbs->basis_v.knot_vector.count = knot_v->size;
13860 }
13861
13862 return 1;
13863 }
13864
13865 ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_line(ufbxi_context *uc, ufbxi_node *node, ufbxi_element_info *info)
13866 {
13867 ufbx_line_curve *line = ufbxi_push_element(uc, info, ufbx_line_curve, UFBX_ELEMENT_LINE_CURVE);
13868 ufbxi_check(line);
13869
13870 if (!uc->opts.ignore_geometry) {
13871 ufbxi_value_array *points = ufbxi_find_array(node, ufbxi_Points, 'r');
13872 ufbxi_value_array *points_index = ufbxi_find_array(node, ufbxi_PointsIndex, 'i');
13873 ufbxi_check(points);
13874 ufbxi_check(points_index);
13875 ufbxi_check(points->size % 3 == 0);
13876
13877 if (points->size > 0) {
13878 line->control_points.count = points->size / 3;
13879 line->control_points.data = (ufbx_vec3*)points->data;
13880 line->point_indices.count = points_index->size;
13881 line->point_indices.data = (uint32_t*)points_index->data;
13882
13883 ufbxi_check(line->control_points.count < INT32_MAX);
13884
13885 // Count end points
13886 size_t num_segments = 1;
13887 if (line->point_indices.count > 0) {
13888 for (size_t i = 0; i < line->point_indices.count - 1; i++) {
13889 uint32_t ix = line->point_indices.data[i];
13890 num_segments += (int32_t)ix < 0 ? 1u : 0u;
13891 }
13892 }
13893
13894 size_t prev_end = 0;
13895 line->segments.data = ufbxi_push(&uc->result, ufbx_line_segment, num_segments);
13896 ufbxi_check(line->segments.data);
13897 for (size_t i = 0; i < line->point_indices.count; i++) {
13898 uint32_t ix = line->point_indices.data[i];
13899 if ((int32_t)ix < 0) {
13900 ix = ~ix;
13901 if (i + 1 < line->point_indices.count) {
13902 ufbx_line_segment *segment = &line->segments.data[line->segments.count++];
13903 segment->index_begin = (uint32_t)prev_end;
13904 segment->num_indices = (uint32_t)(i - prev_end);
13905 prev_end = i;
13906 }
13907 }
13908
13909 if (ix < line->control_points.count) {
13910 line->point_indices.data[i] = ix;
13911 } else {
13912 ufbxi_check(ufbxi_fix_index(uc, &line->point_indices.data[i], ix, line->control_points.count));
13913 }
13914 }
13915
13916 ufbx_line_segment *segment = &line->segments.data[line->segments.count++];
13917 segment->index_begin = (uint32_t)prev_end;
13918 segment->num_indices = (uint32_t)ufbxi_to_size(line->point_indices.count - prev_end);
13919 ufbx_assert(line->segments.count == num_segments);
13920 }
13921 }
13922
13923 return 1;
13924 }
13925
13926 ufbxi_noinline static void ufbxi_read_transform_matrix(ufbx_matrix *m, ufbx_real *data)
13927 {
13928 m->m00 = data[ 0]; m->m10 = data[ 1]; m->m20 = data[ 2];
13929 m->m01 = data[ 4]; m->m11 = data[ 5]; m->m21 = data[ 6];
13930 m->m02 = data[ 8]; m->m12 = data[ 9]; m->m22 = data[10];
13931 m->m03 = data[12]; m->m13 = data[13]; m->m23 = data[14];
13932 }
13933
13934 ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_bone(ufbxi_context *uc, ufbxi_node *node, ufbxi_element_info *info, const char *sub_type)
13935 {
13936 (void)node;
13937
13938 ufbx_bone *bone = ufbxi_push_element(uc, info, ufbx_bone, UFBX_ELEMENT_BONE);
13939 ufbxi_check(bone);
13940
13941 if (sub_type == ufbxi_Root) {
13942 bone->is_root = true;
13943 }
13944
13945 return 1;
13946 }
13947
13948 ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_marker(ufbxi_context *uc, ufbxi_node *node, ufbxi_element_info *info, const char *sub_type, ufbx_marker_type type)
13949 {
13950 (void)node;
13951 (void)sub_type;
13952
13953 ufbx_marker *marker = ufbxi_push_element(uc, info, ufbx_marker, UFBX_ELEMENT_MARKER);
13954 ufbxi_check(marker);
13955
13956 marker->type = type;
13957
13958 return 1;
13959 }
13960
13961 ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_skin(ufbxi_context *uc, ufbxi_node *node, ufbxi_element_info *info)
13962 {
13963 ufbx_skin_deformer *skin = ufbxi_push_element(uc, info, ufbx_skin_deformer, UFBX_ELEMENT_SKIN_DEFORMER);
13964 ufbxi_check(skin);
13965
13966 const char *skinning_type = NULL;
13967 if (ufbxi_find_val1(node, ufbxi_SkinningType, "C", (char**)&skinning_type)) {
13968 if (!strcmp(skinning_type, "Rigid")) {
13969 skin->skinning_method = UFBX_SKINNING_METHOD_RIGID;
13970 } else if (!strcmp(skinning_type, "Linear")) {
13971 skin->skinning_method = UFBX_SKINNING_METHOD_LINEAR;
13972 } else if (!strcmp(skinning_type, "DualQuaternion")) {
13973 skin->skinning_method = UFBX_SKINNING_METHOD_DUAL_QUATERNION;
13974 } else if (!strcmp(skinning_type, "Blend")) {
13975 skin->skinning_method = UFBX_SKINNING_METHOD_BLENDED_DQ_LINEAR;
13976 }
13977 }
13978
13979 ufbxi_value_array *indices = ufbxi_find_array(node, ufbxi_Indexes, 'i');
13980 ufbxi_value_array *weights = ufbxi_find_array(node, ufbxi_BlendWeights, 'r');
13981 if (indices && weights) {
13982 // TODO strict: ufbxi_check(indices->size == weights->size);
13983 skin->num_dq_weights = ufbxi_min_sz(indices->size, weights->size);
13984 skin->dq_vertices.data = (uint32_t*)indices->data;
13985 skin->dq_weights.data = (ufbx_real*)weights->data;
13986 skin->dq_vertices.count = skin->num_dq_weights;
13987 skin->dq_weights.count = skin->num_dq_weights;
13988 }
13989
13990 return 1;
13991 }
13992
13993 ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_skin_cluster(ufbxi_context *uc, ufbxi_node *node, ufbxi_element_info *info)
13994 {
13995 ufbx_skin_cluster *cluster = ufbxi_push_element(uc, info, ufbx_skin_cluster, UFBX_ELEMENT_SKIN_CLUSTER);
13996 ufbxi_check(cluster);
13997
13998 ufbxi_value_array *indices = ufbxi_find_array(node, ufbxi_Indexes, 'i');
13999 ufbxi_value_array *weights = ufbxi_find_array(node, ufbxi_Weights, 'r');
14000
14001 if (indices && weights) {
14002 ufbxi_check(indices->size == weights->size);
14003 cluster->num_weights = indices->size;
14004 cluster->vertices.data = (uint32_t*)indices->data;
14005 cluster->weights.data = (ufbx_real*)weights->data;
14006 cluster->vertices.count = cluster->num_weights;
14007 cluster->weights.count = cluster->num_weights;
14008 }
14009
14010 ufbxi_value_array *transform = ufbxi_find_array(node, ufbxi_Transform, 'r');
14011 ufbxi_value_array *transform_link = ufbxi_find_array(node, ufbxi_TransformLink, 'r');
14012 if (transform && transform_link) {
14013 ufbxi_check(transform->size >= 16);
14014 ufbxi_check(transform_link->size >= 16);
14015
14016 ufbxi_read_transform_matrix(&cluster->mesh_node_to_bone, (ufbx_real*)transform->data);
14017 ufbxi_read_transform_matrix(&cluster->bind_to_world, (ufbx_real*)transform_link->data);
14018 }
14019
14020 return 1;
14021 }
14022
14023 ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_blend_channel(ufbxi_context *uc, ufbxi_node *node, ufbxi_element_info *info)
14024 {
14025 ufbx_blend_channel *channel = ufbxi_push_element(uc, info, ufbx_blend_channel, UFBX_ELEMENT_BLEND_CHANNEL);
14026 ufbxi_check(channel);
14027
14028 ufbx_real_list list = { NULL, 0 };
14029 ufbxi_value_array *full_weights = ufbxi_find_array(node, ufbxi_FullWeights, 'r');
14030 if (full_weights) {
14031 list.data = (ufbx_real*)full_weights->data;
14032 list.count = full_weights->size;
14033 }
14034 ufbxi_check(ufbxi_push_copy(&uc->tmp_full_weights, ufbx_real_list, 1, &list));
14035
14036 // Blender saves blend shapes with DeformPercent as a field, not a property.
14037 // However, the animations are mapped to the DeformPercent property.
14038 ufbxi_node *deform_percent = ufbxi_find_child(node, ufbxi_DeformPercent);
14039 if (channel->props.props.count == 0 && deform_percent) {
14040 size_t num_shape_props = 1;
14041 ufbx_prop *shape_props = ufbxi_push_zero(&uc->result, ufbx_prop, num_shape_props);
14042 ufbxi_check(shape_props);
14043 shape_props[0].name.data = ufbxi_DeformPercent;
14044 shape_props[0].name.length = sizeof(ufbxi_DeformPercent) - 1;
14045 shape_props[0]._internal_key = ufbxi_get_name_key_c(ufbxi_DeformPercent);
14046 shape_props[0].type = UFBX_PROP_NUMBER;
14047 shape_props[0].value_str = ufbx_empty_string;
14048 shape_props[0].value_real = 100.0f;
14049 ufbxi_ignore(ufbxi_get_val1(deform_percent, "R", &shape_props[0].value_real));
14050 channel->props.props.data = shape_props;
14051 channel->props.props.count = num_shape_props;
14052 }
14053
14054 return 1;
14055 }
14056
14057 typedef enum {
14058 UFBXI_KEY_INTERPOLATION_CONSTANT = 0x2,
14059 UFBXI_KEY_INTERPOLATION_LINEAR = 0x4,
14060 UFBXI_KEY_INTERPOLATION_CUBIC = 0x8,
14061 UFBXI_KEY_TANGENT_AUTO = 0x100,
14062 UFBXI_KEY_TANGENT_TCB = 0x200,
14063 UFBXI_KEY_TANGENT_USER = 0x400,
14064 UFBXI_KEY_TANGENT_BROKEN = 0x800,
14065 UFBXI_KEY_CONSTANT_NEXT = 0x100,
14066 UFBXI_KEY_CLAMP = 0x1000,
14067 UFBXI_KEY_TIME_INDEPENDENT = 0x2000,
14068 UFBXI_KEY_CLAMP_PROGRESSIVE = 0x4000,
14069 UFBXI_KEY_WEIGHTED_RIGHT = 0x1000000,
14070 UFBXI_KEY_WEIGHTED_NEXT_LEFT = 0x2000000,
14071 UFBXI_KEY_VELOCITY_RIGHT = 0x10000000,
14072 UFBXI_KEY_VELOCITY_NEXT_LEFT = 0x20000000,
14073 } ufbxi_key_flags;
14074
14075 static ufbxi_noinline float ufbxi_solve_auto_tangent(ufbxi_context *uc, double prev_time, double time, double next_time, ufbx_real prev_value, ufbx_real value, ufbx_real next_value, float weight_left, float weight_right, float auto_bias, uint32_t flags)
14076 {
14077 // Clamp tangent to zero if near either left or right key
14078 if (flags & UFBXI_KEY_CLAMP) {
14079 if (ufbx_fmin(ufbx_fabs(prev_value - value), ufbx_fabs(next_value - value)) <= uc->opts.key_clamp_threshold) {
14080 return 0.0f;
14081 }
14082 }
14083
14084 // Time-independent: Set the initial slope to be the difference between the two keyframes.
14085 double slope = (next_value - prev_value) / (next_time - prev_time);
14086
14087 // Non-time-independent tangents seem to blend between left/right tangent and the total difference.
14088 if ((flags & UFBXI_KEY_TIME_INDEPENDENT) == 0) {
14089 double slope_left = (value - prev_value) / (time - prev_time);
14090 double slope_right = (next_value - value) / (next_time - time);
14091 double delta = (time - prev_time) / (next_time - prev_time);
14092 slope = slope * 0.5 + (slope_left * (1.0 - delta) + slope_right * delta) * 0.5;
14093
14094 double bias_weight = ufbx_fabs(auto_bias) / 100.0;
14095 if (bias_weight > 0.0001) {
14096 double bias_target = auto_bias > 0.0 ? slope_right : slope_left;
14097 double bias_delta = bias_target - slope;
14098 slope = slope * (1.0 - bias_weight) + bias_target * bias_weight;
14099
14100 // Auto bias larger than 500 (positive or negative) adds an absolute
14101 // value to the slope, determined by `((bias-500) / 100)^2 * 40`.
14102 double abs_bias_weight = bias_weight - 5.0;
14103 if (abs_bias_weight > 0.0) {
14104 double bias_sign = ufbx_fabs(bias_delta) > 0.00001 ? bias_delta : auto_bias;
14105 bias_sign = bias_sign > 0.0 ? 1.0 : -1.0;
14106 slope += abs_bias_weight * abs_bias_weight * bias_sign * 40.0;
14107 }
14108 }
14109 }
14110
14111 // Prevent overshooting by clamping the slope in case either
14112 // tangent goes above/below the endpoints.
14113 if (flags & UFBXI_KEY_CLAMP_PROGRESSIVE) {
14114 // Split the slope to sign and a non-negative absolute value
14115 double slope_sign = slope >= 0.0 ? 1.0 : -1.0;
14116 double abs_slope = slope_sign * slope;
14117
14118 // Find limits for the absolute value of the slope
14119 double range_left = weight_left * (time - prev_time);
14120 double range_right = weight_right * (next_time - time);
14121 double max_left = range_left > 0.0 ? slope_sign * (value - prev_value) / range_left : 0.0;
14122 double max_right = range_right > 0.0 ? slope_sign * (next_value - value) / range_right : 0.0;
14123
14124 // Clamp negative values and NaNs to zero
14125 if (!(max_left > 0.0)) max_left = 0.0;
14126 if (!(max_right > 0.0)) max_right = 0.0;
14127
14128 // Clamp the absolute slope from both sides
14129 if (abs_slope > max_left) abs_slope = max_left;
14130 if (abs_slope > max_right) abs_slope = max_right;
14131
14132 slope = (slope_sign * abs_slope);
14133 }
14134
14135 return (float)slope;
14136 }
14137
14138 static float ufbxi_solve_auto_tangent_left(ufbxi_context *uc, double prev_time, double time, ufbx_real prev_value, ufbx_real value, float weight_left, float auto_bias, uint32_t flags)
14139 {
14140 (void)weight_left;
14141 if (flags & UFBXI_KEY_CLAMP_PROGRESSIVE) return 0.0f;
14142 if (flags & UFBXI_KEY_CLAMP) {
14143 if (ufbx_fabs(prev_value - value) <= uc->opts.key_clamp_threshold) {
14144 return 0.0f;
14145 }
14146 }
14147
14148 double slope = (value - prev_value) / (time - prev_time);
14149
14150 if ((flags & UFBXI_KEY_TIME_INDEPENDENT) == 0) {
14151 double abs_bias_weight = ufbx_fabs(auto_bias) / 100.0 - 5.0;
14152 if (abs_bias_weight > 0.0) {
14153 double bias_sign = auto_bias > 0.0 ? 1.0 : -1.0;
14154 slope += abs_bias_weight * abs_bias_weight * bias_sign * 40.0;
14155 }
14156 }
14157
14158 return (float)slope;
14159 }
14160
14161 static float ufbxi_solve_auto_tangent_right(ufbxi_context *uc, double time, double next_time, ufbx_real value, ufbx_real next_value, float weight_right, float auto_bias, uint32_t flags)
14162 {
14163 (void)weight_right;
14164 if (flags & UFBXI_KEY_CLAMP_PROGRESSIVE) return 0.0f;
14165 if (flags & UFBXI_KEY_CLAMP) {
14166 if (ufbx_fabs(next_value - value) <= uc->opts.key_clamp_threshold) {
14167 return 0.0f;
14168 }
14169 }
14170
14171 double slope = (next_value - value) / (next_time - time);
14172
14173 if ((flags & UFBXI_KEY_TIME_INDEPENDENT) == 0) {
14174 double abs_bias_weight = ufbx_fabs(auto_bias) / 100.0 - 5.0;
14175 if (abs_bias_weight > 0.0) {
14176 double bias_sign = auto_bias > 0.0 ? 1.0 : -1.0;
14177 slope += abs_bias_weight * abs_bias_weight * bias_sign * 40.0;
14178 }
14179 }
14180
14181 return (float)slope;
14182 }
14183
14184 static void ufbxi_solve_tcb(float *p_slope_left, float *p_slope_right, double tension, double continuity, double bias, double slope_left, double slope_right, bool edge)
14185 {
14186 double factor = edge ? 1.0 : 0.5;
14187 double d00 = factor * (1.0 - tension) * (1.0 + bias) * (1.0 - continuity);
14188 double d01 = factor * (1.0 - tension) * (1.0 - bias) * (1.0 + continuity);
14189 double d10 = factor * (1.0 - tension) * (1.0 + bias) * (1.0 + continuity);
14190 double d11 = factor * (1.0 - tension) * (1.0 - bias) * (1.0 - continuity);
14191
14192 *p_slope_left = (float)(d00 * slope_left + d01 * slope_right);
14193 *p_slope_right = (float)(d10 * slope_left + d11 * slope_right);
14194 }
14195
14196 ufbxi_noinline static void ufbxi_read_extrapolation(ufbx_extrapolation *p_extrapolation, ufbxi_node *node, const char *name)
14197 {
14198 ufbxi_node *child = ufbxi_find_child(node, name);
14199 ufbx_extrapolation_mode mode = UFBX_EXTRAPOLATION_CONSTANT;
14200 int32_t repeat_count = -1;
14201
14202 if (child) {
14203 int32_t mode_ch;
14204 if (ufbxi_find_val1(child, ufbxi_Type, "I", &mode_ch)) {
14205
14206 switch (mode_ch) {
14207 case 'A': mode = UFBX_EXTRAPOLATION_REPEAT_RELATIVE; break;
14208 case 'C': mode = UFBX_EXTRAPOLATION_CONSTANT; break;
14209 case 'K': mode = UFBX_EXTRAPOLATION_SLOPE; break;
14210 case 'M': mode = UFBX_EXTRAPOLATION_MIRROR; break;
14211 case 'R': mode = UFBX_EXTRAPOLATION_REPEAT; break;
14212 default: /* Unknown */ break;
14213 }
14214 if (ufbxi_find_val1(child, ufbxi_Repetition, "I", &repeat_count)) {
14215 if (repeat_count < 0) {
14216 repeat_count = -1;
14217 }
14218 }
14219 }
14220 }
14221
14222 p_extrapolation->mode = mode;
14223 p_extrapolation->repeat_count = repeat_count;
14224 }
14225
14226 ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_animation_curve(ufbxi_context *uc, ufbxi_node *node, ufbxi_element_info *info)
14227 {
14228 ufbx_anim_curve *curve = ufbxi_push_element(uc, info, ufbx_anim_curve, UFBX_ELEMENT_ANIM_CURVE);
14229 ufbxi_check(curve);
14230
14231 ufbxi_read_extrapolation(&curve->pre_extrapolation, node, ufbxi_Pre_Extrapolation);
14232 ufbxi_read_extrapolation(&curve->post_extrapolation, node, ufbxi_Post_Extrapolation);
14233
14234 if (uc->opts.ignore_animation) return 1;
14235
14236 ufbxi_value_array *times, *values, *attr_flags, *attrs, *refs;
14237 ufbxi_check(times = ufbxi_find_array(node, ufbxi_KeyTime, 'l'));
14238 ufbxi_check(values = ufbxi_find_array(node, ufbxi_KeyValueFloat, 'r'));
14239 ufbxi_check(attr_flags = ufbxi_find_array(node, ufbxi_KeyAttrFlags, 'i'));
14240 ufbxi_check(attrs = ufbxi_find_array(node, ufbxi_KeyAttrDataFloat, '?'));
14241 ufbxi_check(refs = ufbxi_find_array(node, ufbxi_KeyAttrRefCount, 'i'));
14242
14243 // Time and value arrays that define the keyframes should be parallel
14244 ufbxi_check(times->size == values->size);
14245
14246 // Flags and attributes are run-length encoded where KeyAttrRefCount (refs)
14247 // is an array that describes how many times to repeat a given flag/attribute.
14248 // Attributes consist of 4 32-bit floating point values per key.
14249 ufbxi_check(attr_flags->size == refs->size);
14250 ufbxi_check(attrs->size == refs->size * 4u);
14251
14252 size_t num_keys = times->size;
14253 ufbx_keyframe *keys = ufbxi_push(&uc->result, ufbx_keyframe, num_keys);
14254 ufbxi_check(keys);
14255
14256 curve->keyframes.data = keys;
14257 curve->keyframes.count = num_keys;
14258
14259 int64_t *p_time = (int64_t*)times->data;
14260 ufbx_real *p_value = (ufbx_real*)values->data;
14261 int32_t *p_flag = (int32_t*)attr_flags->data;
14262 float *p_attr = (float*)attrs->data;
14263 int32_t *p_ref = (int32_t*)refs->data, *p_ref_end = p_ref + refs->size;
14264
14265 // The previous key defines the weight/slope of the left tangent
14266 float slope_left = 0.0f;
14267 float weight_left = 0.333333f;
14268 // float velocity_left = 0.0f;
14269
14270 double prev_time = 0.0;
14271 double next_time = 0.0;
14272
14273 int32_t refs_left = 0;
14274 if (num_keys > 0) {
14275 next_time = (double)p_time[0] / uc->ktime_sec_double;
14276 if (p_ref < p_ref_end) refs_left = *p_ref;
14277 }
14278
14279 for (size_t i = 0; i < num_keys; i++) {
14280 ufbx_keyframe *key = &keys[i];
14281 ufbxi_check(refs_left > 0);
14282
14283 ufbx_real value = *p_value;
14284 if (i == 0) {
14285 curve->min_value = value;
14286 curve->max_value = value;
14287 } else {
14288 curve->min_value = ufbxi_min_real(curve->min_value, value);
14289 curve->max_value = ufbxi_max_real(curve->max_value, value);
14290 }
14291
14292 key->time = next_time;
14293 key->value = value;
14294
14295 if (i + 1 < num_keys) {
14296 next_time = (double)p_time[1] / uc->ktime_sec_double;
14297 }
14298
14299 uint32_t flags = (uint32_t)*p_flag;
14300
14301 float slope_right = p_attr[0];
14302 float weight_right = 0.333333f;
14303 //float velocity_right = 0.0f;
14304 float next_slope_left = p_attr[1];
14305 float next_weight_left = 0.333333f;
14306 // float next_velocity_left = 0.0f;
14307
14308 if ((flags & (UFBXI_KEY_WEIGHTED_RIGHT|UFBXI_KEY_WEIGHTED_NEXT_LEFT)) != 0) {
14309 // At least one of the tangents is weighted. The weights are encoded as
14310 // two 0.4 _decimal_ fixed point values that are packed into 32 bits and
14311 // interpreted as a 32-bit float.
14312 uint32_t packed_weights;
14313 memcpy(&packed_weights, &p_attr[2], sizeof(uint32_t));
14314
14315 if (flags & UFBXI_KEY_WEIGHTED_RIGHT) {
14316 // Right tangent is weighted
14317 weight_right = (float)(packed_weights & 0xffff) * 0.0001f;
14318 }
14319
14320 if (flags & UFBXI_KEY_WEIGHTED_NEXT_LEFT) {
14321 // Next left tangent is weighted
14322 next_weight_left = (float)(packed_weights >> 16) * 0.0001f;
14323 }
14324 }
14325 #if 0
14326 if ((flags & (UFBXI_KEY_VELOCITY_RIGHT|UFBXI_KEY_VELOCITY_NEXT_LEFT)) != 0) {
14327 // Velocities are encoded in the same way as weights, see above.
14328 uint32_t packed_velocities;
14329 memcpy(&packed_velocities, &p_attr[3], sizeof(uint32_t));
14330
14331 if (flags & UFBXI_KEY_VELOCITY_RIGHT) {
14332 // Right tangent has velocity
14333 velocity_right = (float)(int16_t)(packed_velocities & 0xffff) * 0.0001f;
14334 }
14335
14336 if (flags & UFBXI_KEY_VELOCITY_NEXT_LEFT) {
14337 // Next left tangent has velocity
14338 next_velocity_left = (float)(int16_t)(packed_velocities >> 16) * 0.0001f;
14339 }
14340 }
14341 #endif
14342
14343 if (flags & UFBXI_KEY_INTERPOLATION_CONSTANT) {
14344 // Constant interpolation: Set cubic tangents to flat.
14345
14346 if (flags & UFBXI_KEY_CONSTANT_NEXT) {
14347 // Take constant value from next key
14348 key->interpolation = UFBX_INTERPOLATION_CONSTANT_NEXT;
14349
14350 } else {
14351 // Take constant value from the previous key
14352 key->interpolation = UFBX_INTERPOLATION_CONSTANT_PREV;
14353 }
14354
14355 weight_right = next_weight_left = 0.333333f;
14356 slope_right = next_slope_left = 0.0f;
14357
14358 } else if (flags & UFBXI_KEY_INTERPOLATION_CUBIC) {
14359 // Cubic interpolation
14360 key->interpolation = UFBX_INTERPOLATION_CUBIC;
14361
14362 if (flags & UFBXI_KEY_TANGENT_TCB) {
14363 double tcb_slope_left = 0.0;
14364 double tcb_slope_right = 0.0;
14365 bool tcb_edge = false;
14366 if (i > 0 && key->time > prev_time) {
14367 tcb_slope_left = (key->value - p_value[-1]) / (key->time - prev_time);
14368 } else {
14369 tcb_edge = true;
14370 }
14371 if (i + 1 < num_keys && next_time > key->time) {
14372 tcb_slope_right = (p_value[1] - key->value) / (next_time - key->time);
14373 } else {
14374 tcb_edge = true;
14375 }
14376
14377 ufbxi_solve_tcb(&slope_left, &slope_right, p_attr[0], p_attr[1], p_attr[2], tcb_slope_left, tcb_slope_right, tcb_edge);
14378
14379 // TODO: How to handle these?
14380 next_slope_left = 0.0f;
14381 next_weight_left = 0.333333f;
14382 // next_velocity_left = 0.0f;
14383 } else if (flags & UFBXI_KEY_TANGENT_USER) {
14384 // User tangents
14385
14386 if (flags & UFBXI_KEY_TANGENT_BROKEN) {
14387 // Broken tangents: No need to modify slopes
14388 } else {
14389 // Unified tangents: Use right slope for both sides
14390 // TODO: ??? slope_left = slope_right;
14391 }
14392
14393 } else {
14394 // TODO: Auto break (0x800)
14395
14396 if (i > 0 && i + 1 < num_keys && key->time > prev_time && next_time > key->time) {
14397 if (ufbx_fabs(slope_left + slope_right) <= 0.0001f) {
14398 slope_left = slope_right = ufbxi_solve_auto_tangent(uc,
14399 prev_time, key->time, next_time,
14400 p_value[-1], key->value, p_value[1],
14401 weight_left, weight_right, slope_right, flags);
14402 } else {
14403 slope_left = ufbxi_solve_auto_tangent(uc,
14404 prev_time, key->time, next_time,
14405 p_value[-1], key->value, p_value[1],
14406 weight_left, weight_right, -slope_left, flags);
14407 slope_right = ufbxi_solve_auto_tangent(uc,
14408 prev_time, key->time, next_time,
14409 p_value[-1], key->value, p_value[1],
14410 weight_left, weight_right, slope_right, flags);
14411 }
14412 } else if (i > 0 && key->time > prev_time) {
14413 slope_left = slope_right = ufbxi_solve_auto_tangent_left(uc,
14414 prev_time, key->time,
14415 p_value[-1], key->value,
14416 weight_left, -slope_left, flags);
14417 } else if (i + 1 < num_keys && next_time > key->time) {
14418 slope_left = slope_right = ufbxi_solve_auto_tangent_right(uc,
14419 key->time, next_time,
14420 key->value, p_value[1],
14421 weight_right, slope_right, flags);
14422 } else {
14423 // Only / invalid keyframe: Set both slopes to zero
14424 slope_left = slope_right = 0.0f;
14425 }
14426
14427
14428 // ??? Looks like at least MotionBuilder adjusts weight and auto bias to
14429 // implement velocity and the velocity information in the file is purely
14430 // for UI (?) If auto bias is not accounted for the velocity computation
14431 // below results in the correct tangents, but with auto bias the velocity
14432 // seems to be accounted for twice resulting in incorrect values...
14433 #if 0
14434 if (weight_left >= UFBX_EPSILON) {
14435 slope_left *= (float)(1.0 - ufbx_fmin(velocity_left / weight_left, 1.0));
14436 }
14437 if (weight_right >= UFBX_EPSILON) {
14438 slope_right *= (float)(1.0 - ufbx_fmin(velocity_right / weight_right, 1.0));
14439 }
14440 #endif
14441 }
14442
14443 } else {
14444 // Linear or unknown interpolation: Set cubic tangents to match
14445 // the linear interpolation with weights of 1/3.
14446 key->interpolation = UFBX_INTERPOLATION_LINEAR;
14447
14448 weight_right = 0.333333f;
14449 next_weight_left = 0.333333f;
14450
14451 if (next_time > key->time) {
14452 double delta_time = next_time - key->time;
14453 if (delta_time > 0.0) {
14454 double slope = (p_value[1] - key->value) / delta_time;
14455 slope_right = next_slope_left = (float)slope;
14456 } else {
14457 slope_right = next_slope_left = 0.0f;
14458 }
14459 } else {
14460 slope_right = next_slope_left = 0.0f;
14461 }
14462 }
14463
14464 // Set the tangents based on weights (dx relative to the time difference
14465 // between the previous/next key) and slope (simply d = slope * dx)
14466 if (key->time > prev_time) {
14467 double delta = key->time - prev_time;
14468 key->left.dx = (float)(weight_left * delta);
14469 key->left.dy = key->left.dx * slope_left;
14470 } else {
14471 key->left.dx = 0.0f;
14472 key->left.dy = 0.0f;
14473 }
14474
14475 if (next_time > key->time) {
14476 double delta = next_time - key->time;
14477 key->right.dx = (float)(weight_right * delta);
14478 key->right.dy = key->right.dx * slope_right;
14479 } else {
14480 key->right.dx = 0.0f;
14481 key->right.dy = 0.0f;
14482 }
14483
14484 slope_left = next_slope_left;
14485 weight_left = next_weight_left;
14486 // velocity_left = next_velocity_left;
14487 prev_time = key->time;
14488
14489 // Decrement attribute refcount and potentially move to the next one.
14490 if (--refs_left == 0) {
14491 p_flag++;
14492 p_attr += 4;
14493 p_ref++;
14494 if (p_ref < p_ref_end) refs_left = *p_ref;
14495 }
14496 p_time++;
14497 p_value++;
14498 }
14499
14500 return 1;
14501 }
14502
14503 ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_material(ufbxi_context *uc, ufbxi_node *node, ufbxi_element_info *info)
14504 {
14505 ufbx_material *material = ufbxi_push_element(uc, info, ufbx_material, UFBX_ELEMENT_MATERIAL);
14506 ufbxi_check(material);
14507
14508 if (!ufbxi_find_val1(node, ufbxi_ShadingModel, "S", &material->shading_model_name)) {
14509 material->shading_model_name = ufbx_empty_string;
14510 }
14511
14512 material->shader_prop_prefix = ufbx_empty_string;
14513
14514 return 1;
14515 }
14516
14517 ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_texture(ufbxi_context *uc, ufbxi_node *node, ufbxi_element_info *info)
14518 {
14519 ufbx_texture *texture = ufbxi_push_element(uc, info, ufbx_texture, UFBX_ELEMENT_TEXTURE);
14520 ufbxi_check(texture);
14521
14522 texture->type = UFBX_TEXTURE_FILE;
14523
14524 texture->filename = ufbx_empty_string;
14525 texture->absolute_filename = ufbx_empty_string;
14526 texture->relative_filename = ufbx_empty_string;
14527
14528 ufbxi_ignore(ufbxi_find_val1(node, ufbxi_FileName, "S", &texture->absolute_filename));
14529 ufbxi_ignore(ufbxi_find_val1(node, ufbxi_Filename, "S", &texture->absolute_filename));
14530 ufbxi_ignore(ufbxi_find_val1(node, ufbxi_RelativeFileName, "S", &texture->relative_filename));
14531 ufbxi_ignore(ufbxi_find_val1(node, ufbxi_RelativeFilename, "S", &texture->relative_filename));
14532
14533 ufbxi_ignore(ufbxi_find_val1(node, ufbxi_FileName, "b", &texture->raw_absolute_filename));
14534 ufbxi_ignore(ufbxi_find_val1(node, ufbxi_Filename, "b", &texture->raw_absolute_filename));
14535 ufbxi_ignore(ufbxi_find_val1(node, ufbxi_RelativeFileName, "b", &texture->raw_relative_filename));
14536 ufbxi_ignore(ufbxi_find_val1(node, ufbxi_RelativeFilename, "b", &texture->raw_relative_filename));
14537
14538 return 1;
14539 }
14540
14541 ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_layered_texture(ufbxi_context *uc, ufbxi_node *node, ufbxi_element_info *info)
14542 {
14543 ufbx_texture *texture = ufbxi_push_element(uc, info, ufbx_texture, UFBX_ELEMENT_TEXTURE);
14544 ufbxi_check(texture);
14545
14546 texture->type = UFBX_TEXTURE_LAYERED;
14547
14548 texture->filename = ufbx_empty_string;
14549 texture->absolute_filename = ufbx_empty_string;
14550 texture->relative_filename = ufbx_empty_string;
14551
14552 ufbxi_texture_extra *extra = ufbxi_push_element_extra(uc, texture->element.element_id, ufbxi_texture_extra);
14553 ufbxi_check(extra);
14554
14555 ufbxi_value_array *alphas = ufbxi_find_array(node, ufbxi_Alphas, 'r');
14556 if (alphas) {
14557 extra->alphas = (ufbx_real*)alphas->data;
14558 extra->num_alphas = alphas->size;
14559 }
14560
14561 ufbxi_value_array *blend_modes = ufbxi_find_array(node, ufbxi_BlendModes, 'i');
14562 if (blend_modes) {
14563 extra->blend_modes = (int32_t*)blend_modes->data;
14564 extra->num_blend_modes = blend_modes->size;
14565 }
14566
14567 return 1;
14568 }
14569
14570 ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_video(ufbxi_context *uc, ufbxi_node *node, ufbxi_element_info *info)
14571 {
14572 ufbx_video *video = ufbxi_push_element(uc, info, ufbx_video, UFBX_ELEMENT_VIDEO);
14573 ufbxi_check(video);
14574
14575 video->filename = ufbx_empty_string;
14576 video->absolute_filename = ufbx_empty_string;
14577 video->relative_filename = ufbx_empty_string;
14578
14579 ufbxi_ignore(ufbxi_find_val1(node, ufbxi_FileName, "S", &video->absolute_filename));
14580 ufbxi_ignore(ufbxi_find_val1(node, ufbxi_Filename, "S", &video->absolute_filename));
14581 ufbxi_ignore(ufbxi_find_val1(node, ufbxi_RelativeFileName, "S", &video->relative_filename));
14582 ufbxi_ignore(ufbxi_find_val1(node, ufbxi_RelativeFilename, "S", &video->relative_filename));
14583
14584 ufbxi_ignore(ufbxi_find_val1(node, ufbxi_FileName, "b", &video->raw_absolute_filename));
14585 ufbxi_ignore(ufbxi_find_val1(node, ufbxi_Filename, "b", &video->raw_absolute_filename));
14586 ufbxi_ignore(ufbxi_find_val1(node, ufbxi_RelativeFileName, "b", &video->raw_relative_filename));
14587 ufbxi_ignore(ufbxi_find_val1(node, ufbxi_RelativeFilename, "b", &video->raw_relative_filename));
14588
14589 ufbxi_node *content_node = ufbxi_find_child(node, ufbxi_Content);
14590 ufbxi_check(ufbxi_read_embedded_blob(uc, &video->content, content_node));
14591
14592 return 1;
14593 }
14594
14595 ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_anim_stack(ufbxi_context *uc, ufbxi_node *node, ufbxi_element_info *info)
14596 {
14597 (void)node;
14598
14599 ufbx_anim_stack *stack = ufbxi_push_element(uc, info, ufbx_anim_stack, UFBX_ELEMENT_ANIM_STACK);
14600 ufbxi_check(stack);
14601
14602 uint32_t hash = ufbxi_hash_ptr(info->name.data);
14603 ufbxi_tmp_anim_stack *entry = ufbxi_map_find(&uc->anim_stack_map, ufbxi_tmp_anim_stack, hash, &info->name.data);
14604 if (!entry) {
14605 entry = ufbxi_map_insert(&uc->anim_stack_map, ufbxi_tmp_anim_stack, hash, &info->name.data);
14606 ufbxi_check(entry);
14607 entry->name = info->name.data;
14608 entry->stack = stack;
14609 }
14610
14611 return 1;
14612 }
14613
14614 ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_pose(ufbxi_context *uc, ufbxi_node *node, ufbxi_element_info *info, const char *sub_type)
14615 {
14616 ufbx_pose *pose = ufbxi_push_element(uc, info, ufbx_pose, UFBX_ELEMENT_POSE);
14617 ufbxi_check(pose);
14618
14619 // TODO: What are the actual other types?
14620 pose->is_bind_pose = sub_type == ufbxi_BindPose;
14621
14622 size_t num_bones = 0;
14623 ufbxi_for(ufbxi_node, n, node->children, node->num_children) {
14624 if (n->name != ufbxi_PoseNode) continue;
14625
14626 // Bones are linked with FBX names/IDs bypassing the connection system (!?)
14627 uint64_t fbx_id = 0;
14628 if (uc->version < 7000) {
14629 char *name = NULL;
14630 if (!ufbxi_find_val1(n, ufbxi_Node, "c", &name)) continue;
14631 fbx_id = ufbxi_synthetic_id_from_string(uc, name);
14632 ufbxi_check(fbx_id);
14633 } else {
14634 if (!ufbxi_find_val1(n, ufbxi_Node, "L", &fbx_id)) continue;
14635 ufbxi_check(ufbxi_validate_fbx_id(uc, &fbx_id));
14636 }
14637
14638 ufbxi_value_array *matrix = ufbxi_find_array(n, ufbxi_Matrix, 'r');
14639 if (!matrix) continue;
14640 ufbxi_check(matrix->size >= 16);
14641
14642 ufbxi_tmp_bone_pose *tmp_pose = ufbxi_push(&uc->tmp_stack, ufbxi_tmp_bone_pose, 1);
14643 ufbxi_check(tmp_pose);
14644
14645 num_bones++;
14646 tmp_pose->bone_fbx_id = fbx_id;
14647 ufbxi_read_transform_matrix(&tmp_pose->bone_to_world, (ufbx_real*)matrix->data);
14648 }
14649
14650 // HACK: Transport `ufbxi_tmp_bone_pose` array through the `ufbx_bone_pose` pointer
14651 pose->bone_poses.count = num_bones;
14652 pose->bone_poses.data = (ufbx_bone_pose*)ufbxi_push_pop(&uc->tmp, &uc->tmp_stack, ufbxi_tmp_bone_pose, num_bones);
14653 ufbxi_check(pose->bone_poses.data);
14654
14655 return 1;
14656 }
14657
14658 ufbxi_nodiscard ufbxi_noinline static int ufbxi_sort_shader_prop_bindings(ufbxi_context *uc, ufbx_shader_prop_binding *bindings, size_t count)
14659 {
14660 ufbxi_check(ufbxi_grow_array(&uc->ator_tmp, &uc->tmp_arr, &uc->tmp_arr_size, count * sizeof(ufbx_shader_prop_binding)));
14661 ufbxi_macro_stable_sort(ufbx_shader_prop_binding, 32, bindings, uc->tmp_arr, count,
14662 ( ufbxi_str_less(a->shader_prop, b->shader_prop) ) );
14663 return 1;
14664 }
14665
14666
14667 ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_binding_table(ufbxi_context *uc, ufbxi_node *node, ufbxi_element_info *info)
14668 {
14669 ufbx_shader_binding *bindings = ufbxi_push_element(uc, info, ufbx_shader_binding, UFBX_ELEMENT_SHADER_BINDING);
14670 ufbxi_check(bindings);
14671
14672 size_t num_entries = 0;
14673 ufbxi_for (ufbxi_node, n, node->children, node->num_children) {
14674 if (n->name != ufbxi_Entry) continue;
14675
14676 ufbx_string src, dst;
14677 const char *src_type = NULL, *dst_type = NULL;
14678 if (!ufbxi_get_val4(n, "SCSC", &src, (char**)&src_type, &dst, (char**)&dst_type)) {
14679 continue;
14680 }
14681
14682 if (src_type == ufbxi_FbxPropertyEntry && dst_type == ufbxi_FbxSemanticEntry) {
14683 ufbx_shader_prop_binding *bind = ufbxi_push(&uc->tmp_stack, ufbx_shader_prop_binding, 1);
14684 ufbxi_check(bind);
14685 bind->material_prop = src;
14686 bind->shader_prop = dst;
14687 num_entries++;
14688 } else if (src_type == ufbxi_FbxSemanticEntry && dst_type == ufbxi_FbxPropertyEntry) {
14689 ufbx_shader_prop_binding *bind = ufbxi_push(&uc->tmp_stack, ufbx_shader_prop_binding, 1);
14690 ufbxi_check(bind);
14691 bind->material_prop = dst;
14692 bind->shader_prop = src;
14693 num_entries++;
14694 }
14695 }
14696
14697 bindings->prop_bindings.count = num_entries;
14698 bindings->prop_bindings.data = ufbxi_push_pop(&uc->result, &uc->tmp_stack, ufbx_shader_prop_binding, num_entries);
14699 ufbxi_check(bindings->prop_bindings.data);
14700
14701 ufbxi_check(ufbxi_sort_shader_prop_bindings(uc, bindings->prop_bindings.data, bindings->prop_bindings.count));
14702
14703 return 1;
14704 }
14705
14706 ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_selection_set(ufbxi_context *uc, ufbxi_node *node, ufbxi_element_info *info)
14707 {
14708 (void)node;
14709
14710 ufbx_selection_set *set = ufbxi_push_element(uc, info, ufbx_selection_set, UFBX_ELEMENT_SELECTION_SET);
14711 ufbxi_check(set);
14712
14713 return 1;
14714 }
14715
14716 ufbxi_noinline static void ufbxi_find_uint32_list(ufbx_uint32_list *dst, ufbxi_node *node, const char *name)
14717 {
14718 ufbxi_value_array *arr = ufbxi_find_array(node, name, 'i');
14719 if (arr) {
14720 dst->data = (uint32_t*)arr->data;
14721 dst->count = arr->size;
14722 }
14723 }
14724
14725 ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_selection_node(ufbxi_context *uc, ufbxi_node *node, ufbxi_element_info *info)
14726 {
14727 ufbx_selection_node *sel = ufbxi_push_element(uc, info, ufbx_selection_node, UFBX_ELEMENT_SELECTION_NODE);
14728 ufbxi_check(sel);
14729
14730 int32_t in_set = 0;
14731 if (ufbxi_find_val1(node, ufbxi_IsTheNodeInSet, "I", &in_set) && in_set) {
14732 sel->include_node = true;
14733 }
14734
14735 ufbxi_find_uint32_list(&sel->vertices, node, ufbxi_VertexIndexArray);
14736 ufbxi_find_uint32_list(&sel->edges, node, ufbxi_EdgeIndexArray);
14737 ufbxi_find_uint32_list(&sel->faces, node, ufbxi_PolygonIndexArray);
14738
14739 return 1;
14740 }
14741
14742 ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_character(ufbxi_context *uc, ufbxi_node *node, ufbxi_element_info *info)
14743 {
14744 (void)node;
14745
14746 ufbx_character *character = ufbxi_push_element(uc, info, ufbx_character, UFBX_ELEMENT_CHARACTER);
14747 ufbxi_check(character);
14748
14749 // TODO: There's some extremely cursed all-caps data in characters
14750
14751 return 1;
14752 }
14753
14754 ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_audio_clip(ufbxi_context *uc, ufbxi_node *node, ufbxi_element_info *info)
14755 {
14756 ufbx_audio_clip *audio = ufbxi_push_element(uc, info, ufbx_audio_clip, UFBX_ELEMENT_AUDIO_CLIP);
14757 ufbxi_check(audio);
14758
14759 audio->filename = ufbx_empty_string;
14760 audio->absolute_filename = ufbx_empty_string;
14761 audio->relative_filename = ufbx_empty_string;
14762
14763 ufbxi_node *content_node = ufbxi_find_child(node, ufbxi_Content);
14764 ufbxi_check(ufbxi_read_embedded_blob(uc, &audio->content, content_node));
14765
14766 return 1;
14767 }
14768
14769 typedef struct {
14770 ufbx_constraint_type type;
14771 const char *name;
14772 } ufbxi_constraint_type;
14773
14774 static const ufbxi_constraint_type ufbxi_constraint_types[] = {
14775 { UFBX_CONSTRAINT_AIM, "Aim" },
14776 { UFBX_CONSTRAINT_PARENT, "Parent-Child" },
14777 { UFBX_CONSTRAINT_POSITION, "Position From Positions" },
14778 { UFBX_CONSTRAINT_ROTATION, "Rotation From Rotations" },
14779 { UFBX_CONSTRAINT_SCALE, "Scale From Scales" },
14780 { UFBX_CONSTRAINT_SINGLE_CHAIN_IK, "Single Chain IK" },
14781 };
14782
14783 ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_constraint(ufbxi_context *uc, ufbxi_node *node, ufbxi_element_info *info)
14784 {
14785 (void)node;
14786
14787 ufbx_constraint *constraint = ufbxi_push_element(uc, info, ufbx_constraint, UFBX_ELEMENT_CONSTRAINT);
14788 ufbxi_check(constraint);
14789
14790 if (!ufbxi_find_val1(node, ufbxi_Type, "S", &constraint->type_name)) {
14791 constraint->type_name = ufbx_empty_string;
14792 }
14793
14794 ufbxi_for(const ufbxi_constraint_type, ctype, ufbxi_constraint_types, ufbxi_arraycount(ufbxi_constraint_types)) {
14795 if (!strcmp(constraint->type_name.data, ctype->name)) {
14796 constraint->type = ctype->type;
14797 break;
14798 }
14799 }
14800
14801 // TODO: There's some extremely cursed all-caps data in characters
14802
14803 return 1;
14804 }
14805
14806 ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_synthetic_attribute(ufbxi_context *uc, ufbxi_node *node, ufbxi_element_info *info, ufbx_string type_str, const char *sub_type, const char *super_type)
14807 {
14808 if ((sub_type == ufbxi_empty_char || sub_type == ufbxi_Model) && type_str.data == ufbxi_Model) {
14809 // Plain model
14810 return 1;
14811 }
14812
14813 ufbxi_element_info attrib_info = *info;
14814
14815 attrib_info.fbx_id = ufbxi_push_synthetic_id(uc);
14816
14817 // Use type and name from NodeAttributeName if it exists *uniquely*
14818 ufbx_string type_and_name;
14819 if (ufbxi_find_val1(node, ufbxi_NodeAttributeName, "s", &type_and_name)) {
14820 ufbx_string attrib_type_str, attrib_name_str;
14821 ufbxi_check(ufbxi_split_type_and_name(uc, type_and_name, &attrib_type_str, &attrib_name_str));
14822 if (attrib_name_str.length > 0) {
14823 attrib_info.name = attrib_name_str;
14824 uint64_t attrib_id = ufbxi_synthetic_id_from_string(uc, type_and_name.data);
14825 ufbxi_check(attrib_id);
14826 if (info->fbx_id != attrib_id && !ufbxi_fbx_id_exists(uc, attrib_id)) {
14827 attrib_info.fbx_id = attrib_id;
14828 }
14829 }
14830 }
14831
14832 // 6x00: Link the node to the node attribute so property connections can be
14833 // redirected from connections if necessary.
14834 ufbxi_check(ufbxi_insert_fbx_attr(uc, info->fbx_id, attrib_info.fbx_id));
14835
14836 // Split properties between the node and the attribute.
14837 // Consider all user properties as node properties.
14838 ufbx_prop *ps = info->props.props.data;
14839 size_t dst = 0, src = 0, end = info->props.props.count;
14840 while (src < end) {
14841 if (!ufbxi_is_node_property_name(uc, ps[src].name.data) && (ps[src].flags & UFBX_PROP_FLAG_USER_DEFINED) == 0) {
14842 ufbxi_check(ufbxi_push_copy(&uc->tmp_stack, ufbx_prop, 1, &ps[src]));
14843 src++;
14844 } else if (dst != src) {
14845 ps[dst++] = ps[src++];
14846 } else {
14847 dst++; src++;
14848 }
14849 }
14850 attrib_info.props.props.count = end - dst;
14851 attrib_info.props.props.data = ufbxi_push_pop(&uc->result, &uc->tmp_stack, ufbx_prop, attrib_info.props.props.count);
14852 ufbxi_check(attrib_info.props.props.data);
14853 info->props.props.count = dst;
14854
14855 if (sub_type == ufbxi_Mesh) {
14856 ufbxi_check(ufbxi_read_mesh(uc, node, &attrib_info));
14857 } else if (sub_type == ufbxi_Light) {
14858 ufbxi_check(ufbxi_read_element(uc, node, &attrib_info, sizeof(ufbx_light), UFBX_ELEMENT_LIGHT));
14859 } else if (sub_type == ufbxi_Camera) {
14860 ufbxi_check(ufbxi_read_element(uc, node, &attrib_info, sizeof(ufbx_camera), UFBX_ELEMENT_CAMERA));
14861 } else if (sub_type == ufbxi_LimbNode || sub_type == ufbxi_Limb || sub_type == ufbxi_Root) {
14862 ufbxi_check(ufbxi_read_bone(uc, node, &attrib_info, sub_type));
14863 } else if (sub_type == ufbxi_Null || sub_type == ufbxi_Marker) {
14864 ufbxi_check(ufbxi_read_element(uc, node, &attrib_info, sizeof(ufbx_empty), UFBX_ELEMENT_EMPTY));
14865 } else if (sub_type == ufbxi_NurbsCurve) {
14866 if (!ufbxi_find_child(node, ufbxi_KnotVector)) return 1;
14867 ufbxi_check(ufbxi_read_nurbs_curve(uc, node, &attrib_info));
14868 } else if (sub_type == ufbxi_NurbsSurface) {
14869 if (!ufbxi_find_child(node, ufbxi_KnotVectorU)) return 1;
14870 if (!ufbxi_find_child(node, ufbxi_KnotVectorV)) return 1;
14871 ufbxi_check(ufbxi_read_nurbs_surface(uc, node, &attrib_info));
14872 } else if (sub_type == ufbxi_Line) {
14873 if (!ufbxi_find_child(node, ufbxi_Points)) return 1;
14874 if (!ufbxi_find_child(node, ufbxi_PointsIndex)) return 1;
14875 ufbxi_check(ufbxi_read_line(uc, node, &attrib_info));
14876 } else if (sub_type == ufbxi_TrimNurbsSurface) {
14877 if (!ufbxi_find_child(node, ufbxi_Layer)) return 1;
14878 ufbxi_check(ufbxi_read_element(uc, node, &attrib_info, sizeof(ufbx_nurbs_trim_surface), UFBX_ELEMENT_NURBS_TRIM_SURFACE));
14879 } else if (sub_type == ufbxi_Boundary) {
14880 ufbxi_check(ufbxi_read_element(uc, node, &attrib_info, sizeof(ufbx_nurbs_trim_boundary), UFBX_ELEMENT_NURBS_TRIM_BOUNDARY));
14881 } else if (sub_type == ufbxi_CameraStereo) {
14882 ufbxi_check(ufbxi_read_element(uc, node, &attrib_info, sizeof(ufbx_stereo_camera), UFBX_ELEMENT_STEREO_CAMERA));
14883 } else if (sub_type == ufbxi_CameraSwitcher) {
14884 ufbxi_check(ufbxi_read_element(uc, node, &attrib_info, sizeof(ufbx_camera_switcher), UFBX_ELEMENT_CAMERA_SWITCHER));
14885 } else if (sub_type == ufbxi_FKEffector) {
14886 ufbxi_check(ufbxi_read_marker(uc, node, &attrib_info, sub_type, UFBX_MARKER_FK_EFFECTOR));
14887 } else if (sub_type == ufbxi_IKEffector) {
14888 ufbxi_check(ufbxi_read_marker(uc, node, &attrib_info, sub_type, UFBX_MARKER_IK_EFFECTOR));
14889 } else if (sub_type == ufbxi_LodGroup) {
14890 ufbxi_check(ufbxi_read_element(uc, node, &attrib_info, sizeof(ufbx_lod_group), UFBX_ELEMENT_LOD_GROUP));
14891 } else {
14892 ufbx_string sub_type_str = { sub_type, strlen(sub_type) };
14893 ufbxi_check(ufbxi_read_unknown(uc, node, &attrib_info, type_str, sub_type_str, super_type));
14894 }
14895
14896 ufbxi_check(ufbxi_connect_oo(uc, attrib_info.fbx_id, info->fbx_id));
14897 return 1;
14898 }
14899
14900 ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_global_settings(ufbxi_context *uc, ufbxi_node *node)
14901 {
14902 ufbxi_check(ufbxi_read_properties(uc, node, &uc->scene.settings.props));
14903 return 1;
14904 }
14905
14906 ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_object(ufbxi_context *uc, ufbxi_node *node)
14907 {
14908 ufbxi_element_info info = { 0 };
14909 info.dom_node = ufbxi_get_dom_node(uc, node);
14910
14911 if (node->name == ufbxi_GlobalSettings) {
14912 ufbxi_check(ufbxi_read_global_settings(uc, node));
14913 return 1;
14914 }
14915
14916 ufbx_string type_and_name, sub_type_str;
14917
14918 // Failing to parse the object properties is not an error since
14919 // there's some weird objects mixed in every now and then.
14920 // FBX version 7000 and up uses 64-bit unique IDs per object,
14921 // older FBX versions just use name/type pairs, which we can
14922 // use as IDs since all strings are interned into a string pool.
14923 if (uc->version >= 7000) {
14924 if (!ufbxi_get_val3(node, "Lss", &info.fbx_id, &type_and_name, &sub_type_str)) return 1;
14925 ufbxi_check(ufbxi_validate_fbx_id(uc, &info.fbx_id));
14926 } else {
14927 if (!ufbxi_get_val2(node, "ss", &type_and_name, &sub_type_str)) return 1;
14928 info.fbx_id = ufbxi_synthetic_id_from_string(uc, type_and_name.data);
14929 ufbxi_check(info.fbx_id);
14930 }
14931
14932 // Remove the "Fbx" prefix from sub-types, remember to re-intern!
14933 if (sub_type_str.length > 3 && !memcmp(sub_type_str.data, "Fbx", 3)) {
14934 sub_type_str.data += 3;
14935 sub_type_str.length -= 3;
14936 ufbxi_check(ufbxi_push_string_place_str(&uc->string_pool, &sub_type_str, false));
14937 }
14938
14939 ufbx_string type_str;
14940 ufbxi_check(ufbxi_split_type_and_name(uc, type_and_name, &type_str, &info.name));
14941
14942 const char *name = node->name, *sub_type = sub_type_str.data;
14943 ufbxi_check(ufbxi_read_properties(uc, node, &info.props));
14944 info.props.defaults = ufbxi_find_template(uc, name, sub_type);
14945
14946 if (name == ufbxi_Model) {
14947 if (uc->version < 7000) {
14948 ufbxi_check(ufbxi_read_synthetic_attribute(uc, node, &info, type_str, sub_type, name));
14949 }
14950 ufbxi_check(ufbxi_read_model(uc, node, &info));
14951 } else if (name == ufbxi_NodeAttribute) {
14952 if (sub_type == ufbxi_Light) {
14953 ufbxi_check(ufbxi_read_element(uc, node, &info, sizeof(ufbx_light), UFBX_ELEMENT_LIGHT));
14954 } else if (sub_type == ufbxi_Camera) {
14955 ufbxi_check(ufbxi_read_element(uc, node, &info, sizeof(ufbx_camera), UFBX_ELEMENT_CAMERA));
14956 } else if (sub_type == ufbxi_LimbNode || sub_type == ufbxi_Limb || sub_type == ufbxi_Root) {
14957 ufbxi_check(ufbxi_read_bone(uc, node, &info, sub_type));
14958 } else if (sub_type == ufbxi_Null || sub_type == ufbxi_Marker) {
14959 ufbxi_check(ufbxi_read_element(uc, node, &info, sizeof(ufbx_empty), UFBX_ELEMENT_EMPTY));
14960 } else if (sub_type == ufbxi_CameraStereo) {
14961 ufbxi_check(ufbxi_read_element(uc, node, &info, sizeof(ufbx_stereo_camera), UFBX_ELEMENT_STEREO_CAMERA));
14962 } else if (sub_type == ufbxi_CameraSwitcher) {
14963 ufbxi_check(ufbxi_read_element(uc, node, &info, sizeof(ufbx_camera_switcher), UFBX_ELEMENT_CAMERA_SWITCHER));
14964 } else if (sub_type == ufbxi_FKEffector) {
14965 ufbxi_check(ufbxi_read_marker(uc, node, &info, sub_type, UFBX_MARKER_FK_EFFECTOR));
14966 } else if (sub_type == ufbxi_IKEffector) {
14967 ufbxi_check(ufbxi_read_marker(uc, node, &info, sub_type, UFBX_MARKER_IK_EFFECTOR));
14968 } else if (sub_type == ufbxi_LodGroup) {
14969 ufbxi_check(ufbxi_read_element(uc, node, &info, sizeof(ufbx_lod_group), UFBX_ELEMENT_LOD_GROUP));
14970 } else {
14971 ufbxi_check(ufbxi_read_unknown(uc, node, &info, type_str, sub_type_str, name));
14972 }
14973 } else if (name == ufbxi_Geometry) {
14974 if (sub_type == ufbxi_Mesh) {
14975 ufbxi_check(ufbxi_read_mesh(uc, node, &info));
14976 } else if (sub_type == ufbxi_Shape) {
14977 ufbxi_check(ufbxi_read_shape(uc, node, &info));
14978 } else if (sub_type == ufbxi_NurbsCurve) {
14979 ufbxi_check(ufbxi_read_nurbs_curve(uc, node, &info));
14980 } else if (sub_type == ufbxi_NurbsSurface) {
14981 ufbxi_check(ufbxi_read_nurbs_surface(uc, node, &info));
14982 } else if (sub_type == ufbxi_Line) {
14983 ufbxi_check(ufbxi_read_line(uc, node, &info));
14984 } else if (sub_type == ufbxi_TrimNurbsSurface) {
14985 ufbxi_check(ufbxi_read_element(uc, node, &info, sizeof(ufbx_nurbs_trim_surface), UFBX_ELEMENT_NURBS_TRIM_SURFACE));
14986 } else if (sub_type == ufbxi_Boundary) {
14987 ufbxi_check(ufbxi_read_element(uc, node, &info, sizeof(ufbx_nurbs_trim_boundary), UFBX_ELEMENT_NURBS_TRIM_BOUNDARY));
14988 } else {
14989 ufbxi_check(ufbxi_read_unknown(uc, node, &info, type_str, sub_type_str, name));
14990 }
14991 } else if (name == ufbxi_Deformer) {
14992 if (sub_type == ufbxi_Skin) {
14993 ufbxi_check(ufbxi_read_skin(uc, node, &info));
14994 } else if (sub_type == ufbxi_Cluster) {
14995 ufbxi_check(ufbxi_read_skin_cluster(uc, node, &info));
14996 } else if (sub_type == ufbxi_BlendShape) {
14997 ufbxi_check(ufbxi_read_element(uc, node, &info, sizeof(ufbx_blend_deformer), UFBX_ELEMENT_BLEND_DEFORMER));
14998 } else if (sub_type == ufbxi_BlendShapeChannel) {
14999 ufbxi_check(ufbxi_read_blend_channel(uc, node, &info));
15000 } else if (sub_type == ufbxi_VertexCacheDeformer) {
15001 ufbxi_check(ufbxi_read_element(uc, node, &info, sizeof(ufbx_cache_deformer), UFBX_ELEMENT_CACHE_DEFORMER));
15002 } else {
15003 ufbxi_check(ufbxi_read_unknown(uc, node, &info, type_str, sub_type_str, name));
15004 }
15005 } else if (name == ufbxi_Material) {
15006 ufbxi_check(ufbxi_read_material(uc, node, &info));
15007 } else if (name == ufbxi_Texture) {
15008 ufbxi_check(ufbxi_read_texture(uc, node, &info));
15009 } else if (name == ufbxi_LayeredTexture) {
15010 ufbxi_check(ufbxi_read_layered_texture(uc, node, &info));
15011 } else if (name == ufbxi_Video) {
15012 ufbxi_check(ufbxi_read_video(uc, node, &info));
15013 } else if (name == ufbxi_AnimationStack) {
15014 ufbxi_check(ufbxi_read_anim_stack(uc, node, &info));
15015 } else if (name == ufbxi_AnimationLayer) {
15016 ufbxi_check(ufbxi_read_element(uc, node, &info, sizeof(ufbx_anim_layer), UFBX_ELEMENT_ANIM_LAYER));
15017 } else if (name == ufbxi_AnimationCurveNode) {
15018 ufbxi_check(ufbxi_read_element(uc, node, &info, sizeof(ufbx_anim_value), UFBX_ELEMENT_ANIM_VALUE));
15019 } else if (name == ufbxi_AnimationCurve) {
15020 ufbxi_check(ufbxi_read_animation_curve(uc, node, &info));
15021 } else if (name == ufbxi_Pose) {
15022 ufbxi_check(ufbxi_read_pose(uc, node, &info, sub_type));
15023 } else if (name == ufbxi_Implementation) {
15024 ufbxi_check(ufbxi_read_element(uc, node, &info, sizeof(ufbx_shader), UFBX_ELEMENT_SHADER));
15025 } else if (name == ufbxi_BindingTable) {
15026 ufbxi_check(ufbxi_read_binding_table(uc, node, &info));
15027 } else if (name == ufbxi_Collection) {
15028 if (sub_type == ufbxi_SelectionSet) {
15029 ufbxi_check(ufbxi_read_selection_set(uc, node, &info));
15030 }
15031 } else if (name == ufbxi_CollectionExclusive) {
15032 if (sub_type == ufbxi_DisplayLayer) {
15033 ufbxi_check(ufbxi_read_element(uc, node, &info, sizeof(ufbx_display_layer), UFBX_ELEMENT_DISPLAY_LAYER));
15034 }
15035 } else if (name == ufbxi_SelectionNode) {
15036 ufbxi_check(ufbxi_read_selection_node(uc, node, &info));
15037 } else if (name == ufbxi_Constraint) {
15038 if (sub_type == ufbxi_Character) {
15039 ufbxi_check(ufbxi_read_character(uc, node, &info));
15040 } else {
15041 ufbxi_check(ufbxi_read_constraint(uc, node, &info));
15042 }
15043 } else if (name == ufbxi_SceneInfo) {
15044 ufbxi_check(ufbxi_read_scene_info(uc, node));
15045 } else if (name == ufbxi_Cache) {
15046 ufbxi_check(ufbxi_read_element(uc, node, &info, sizeof(ufbx_cache_file), UFBX_ELEMENT_CACHE_FILE));
15047 } else if (name == ufbxi_ObjectMetaData) {
15048 ufbxi_check(ufbxi_read_element(uc, node, &info, sizeof(ufbx_metadata_object), UFBX_ELEMENT_METADATA_OBJECT));
15049 } else if (name == ufbxi_AudioLayer) {
15050 ufbxi_check(ufbxi_read_element(uc, node, &info, sizeof(ufbx_audio_layer), UFBX_ELEMENT_AUDIO_LAYER));
15051 } else if (name == ufbxi_Audio) {
15052 ufbxi_check(ufbxi_read_audio_clip(uc, node, &info));
15053 } else {
15054 ufbxi_check(ufbxi_read_unknown(uc, node, &info, type_str, sub_type_str, name));
15055 }
15056
15057 return 1;
15058 }
15059
15060 ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_objects(ufbxi_context *uc)
15061 {
15062 for (;;) {
15063 // Push a deferred element ID for tagging warnings
15064 uc->p_element_id = ufbxi_push(&uc->tmp_element_id, uint32_t, 1);
15065 ufbxi_check(uc->p_element_id);
15066 *uc->p_element_id = UFBX_NO_INDEX;
15067 uc->warnings.deferred_element_id_plus_one = (uint32_t)uc->tmp_element_id.num_items;
15068
15069 ufbxi_node *node;
15070 ufbxi_check(ufbxi_parse_toplevel_child(uc, &node, NULL));
15071 if (!node) break;
15072
15073 ufbxi_check(ufbxi_read_object(uc, node));
15074
15075 uc->warnings.deferred_element_id_plus_one = 0;
15076 uc->p_element_id = NULL;
15077 }
15078
15079 return 1;
15080 }
15081
15082 typedef struct {
15083 ufbxi_node **nodes;
15084 size_t num_nodes;
15085 uint32_t task_index;
15086 } ufbxi_object_batch;
15087
15088 ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_objects_threaded(ufbxi_context *uc)
15089 {
15090 uc->parse_threaded = true;
15091
15092 bool parsed_to_end = false;
15093 ufbxi_object_batch batches[UFBX_THREAD_GROUP_COUNT]; // ufbxi_uninit
15094 memset(batches, 0, sizeof(batches));
15095
15096 size_t empty_count = 0;
15097 size_t batch_index = 0;
15098 while (empty_count < UFBX_THREAD_GROUP_COUNT) {
15099 ufbxi_object_batch *batch = &batches[batch_index];
15100
15101 ufbxi_check(ufbxi_thread_pool_wait_group(&uc->thread_pool));
15102
15103 if (batch->num_nodes > 0) {
15104 ufbxi_for_ptr(ufbxi_node, p_node, batch->nodes, batch->num_nodes) {
15105 ufbxi_buf_clear(&uc->tmp_parse);
15106
15107 // Push a deferred element ID for tagging warnings
15108 uc->p_element_id = ufbxi_push(&uc->tmp_element_id, uint32_t, 1);
15109 ufbxi_check(uc->p_element_id);
15110 *uc->p_element_id = UFBX_NO_INDEX;
15111 uc->warnings.deferred_element_id_plus_one = (uint32_t)uc->tmp_element_id.num_items;
15112
15113 ufbxi_check(ufbxi_read_object(uc, *p_node));
15114
15115 uc->warnings.deferred_element_id_plus_one = 0;
15116 uc->p_element_id = NULL;
15117 }
15118 batch->num_nodes = 0;
15119 }
15120
15121 ufbxi_buf *tmp_buf = &uc->tmp_thread_parse[batch_index];
15122
15123 // ASCII data may be in `tmp_buf`, so copy it to safety in case
15124 if (uc->ascii.src_buf == tmp_buf) {
15125 ufbxi_ascii *ua = &uc->ascii;
15126 size_t size = ufbxi_to_size(ua->src_end - ua->src);
15127 if (uc->read_buffer_size < size) {
15128 ufbxi_check(ufbxi_grow_array(&uc->ator_tmp, &uc->read_buffer, &uc->read_buffer_size, size));
15129 }
15130 memcpy(uc->read_buffer, ua->src, size);
15131 uc->data = uc->data_begin = ua->src = uc->read_buffer;
15132 ua->src_end = uc->read_buffer + size;
15133 ua->src_is_retained = false;
15134 ua->src_buf = NULL;
15135 if (ufbxi_to_size(ua->src_end - ua->src) < uc->progress_interval) {
15136 ua->src_yield = ua->src_end;
15137 } else {
15138 ua->src_yield = ua->src + uc->progress_interval;
15139 }
15140 uc->data = ua->src;
15141 }
15142
15143 ufbxi_buf_clear(tmp_buf);
15144
15145 if (!parsed_to_end) {
15146 size_t num_nodes = 0;
15147 uint32_t task_start = uc->thread_pool.start_index;
15148 uint32_t max_tasks = uc->thread_pool.num_tasks / UFBX_THREAD_GROUP_COUNT;
15149 max_tasks = ufbxi_min32(max_tasks, ufbxi_thread_pool_available_tasks(&uc->thread_pool));
15150 size_t max_memory = uc->opts.thread_opts.memory_limit / UFBX_THREAD_GROUP_COUNT;
15151
15152 for (;;) {
15153 ufbxi_node *node = NULL;
15154 ufbxi_check(ufbxi_parse_toplevel_child(uc, &node, tmp_buf));
15155 if (!node) {
15156 parsed_to_end = true;
15157 break;
15158 }
15159 ufbxi_check(ufbxi_push_copy(&uc->tmp_stack, ufbxi_node*, 1, &node));
15160 num_nodes++;
15161
15162 uint32_t num_tasks = uc->thread_pool.start_index - task_start;
15163 if (num_tasks >= max_tasks) break;
15164
15165 size_t memory_used = tmp_buf->pushed_size + tmp_buf->pos;
15166 if (memory_used >= max_memory) break;
15167 }
15168
15169 batch->num_nodes = num_nodes;
15170 batch->nodes = ufbxi_push_pop(tmp_buf, &uc->tmp_stack, ufbxi_node*, num_nodes);
15171 ufbxi_check(batch->nodes);
15172 batch->task_index = uc->thread_pool.start_index;
15173
15174 }
15175
15176 // Not safe to refer to this buffer anymore
15177 uc->ascii.src_is_retained = false;
15178
15179 ufbxi_thread_pool_flush_group(&uc->thread_pool);
15180
15181 if (batch->num_nodes == 0) {
15182 empty_count += 1;
15183 }
15184
15185 batch_index = (batch_index + 1) % UFBX_THREAD_GROUP_COUNT;
15186 }
15187
15188 ufbxi_check(ufbxi_thread_pool_wait_all(&uc->thread_pool));
15189
15190 uc->parse_threaded = false;
15191
15192 return 1;
15193 }
15194
15195 ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_connections(ufbxi_context *uc)
15196 {
15197 // Read the connections to the list first
15198 for (;;) {
15199 ufbxi_node *node;
15200 ufbxi_check(ufbxi_parse_toplevel_child(uc, &node, NULL));
15201 if (!node) break;
15202
15203 char *type;
15204
15205 uint64_t src_id = 0, dst_id = 0;
15206 ufbx_string src_prop = ufbx_empty_string, dst_prop = ufbx_empty_string;
15207
15208 if (uc->version < 7000) {
15209 char *src_name = NULL, *dst_name = NULL;
15210 // Pre-7000 versions use Type::Name pairs as identifiers
15211
15212 if (!ufbxi_get_val1(node, "c", &type)) continue;
15213
15214 if (type == ufbxi_OO) {
15215 if (!ufbxi_get_val3(node, "_cc", NULL, &src_name, &dst_name)) continue;
15216 } else if (type == ufbxi_OP) {
15217 if (!ufbxi_get_val4(node, "_ccs", NULL, &src_name, &dst_name, &dst_prop)) continue;
15218 } else if (type == ufbxi_PO) {
15219 if (!ufbxi_get_val4(node, "_csc", NULL, &src_name, &src_prop, &dst_name)) continue;
15220 } else if (type == ufbxi_PP) {
15221 if (!ufbxi_get_val5(node, "_cscs", NULL, &src_name, &src_prop, &dst_name, &dst_prop)) continue;
15222 } else {
15223 // TODO: Strict mode?
15224 continue;
15225 }
15226
15227 if (src_prop.length > 0) {
15228 ufbxi_check(ufbxi_push_string_place_str(&uc->string_pool, &src_prop, false));
15229 }
15230 if (dst_prop.length > 0) {
15231 ufbxi_check(ufbxi_push_string_place_str(&uc->string_pool, &dst_prop, false));
15232 }
15233
15234 src_id = ufbxi_synthetic_id_from_string(uc, src_name);
15235 dst_id = ufbxi_synthetic_id_from_string(uc, dst_name);
15236 ufbxi_check(src_id && dst_id);
15237
15238 } else {
15239 // Post-7000 versions use proper unique 64-bit IDs
15240
15241 if (!ufbxi_get_val1(node, "C", &type)) continue;
15242
15243 if (type == ufbxi_OO) {
15244 if (!ufbxi_get_val3(node, "_LL", NULL, &src_id, &dst_id)) continue;
15245 } else if (type == ufbxi_OP) {
15246 if (!ufbxi_get_val4(node, "_LLS", NULL, &src_id, &dst_id, &dst_prop)) continue;
15247 } else if (type == ufbxi_PO) {
15248 if (!ufbxi_get_val4(node, "_LSL", NULL, &src_id, &src_prop, &dst_id)) continue;
15249 } else if (type == ufbxi_PP) {
15250 if (!ufbxi_get_val5(node, "_LSLS", NULL, &src_id, &src_prop, &dst_id, &dst_prop)) continue;
15251 } else {
15252 // TODO: Strict mode?
15253 continue;
15254 }
15255
15256 ufbxi_check(ufbxi_validate_fbx_id(uc, &src_id));
15257 ufbxi_check(ufbxi_validate_fbx_id(uc, &dst_id));
15258 }
15259
15260 ufbxi_tmp_connection *conn = ufbxi_push(&uc->tmp_connections, ufbxi_tmp_connection, 1);
15261 ufbxi_check(conn);
15262 conn->src = src_id;
15263 conn->dst = dst_id;
15264 conn->src_prop = src_prop;
15265 conn->dst_prop = dst_prop;
15266 }
15267
15268 return 1;
15269 }
15270
15271 // -- Pre-7000 "Take" based animation
15272
15273 ufbxi_forceinline static char ufbxi_double_to_char(double value)
15274 {
15275 if (value >= 0.0 && value <= 127.0) {
15276 return (char)(int)value;
15277 } else {
15278 return 0;
15279 }
15280 }
15281
15282 ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_take_anim_channel(ufbxi_context *uc, ufbxi_node *node, uint64_t value_fbx_id, const char *name, ufbx_real *p_default)
15283 {
15284 ufbxi_ignore(ufbxi_find_val1(node, ufbxi_Default, "R", p_default));
15285
15286 // Find the key array, early return with success if not found as we may have only a default
15287 ufbxi_value_array *keys = ufbxi_find_array(node, ufbxi_Key, 'd');
15288 if (!keys) return 1;
15289
15290 uint64_t curve_fbx_id = 0;
15291 ufbx_anim_curve *curve = ufbxi_push_synthetic_element(uc, &curve_fbx_id, node, name, ufbx_anim_curve, UFBX_ELEMENT_ANIM_CURVE);
15292 ufbxi_check(curve);
15293
15294 ufbxi_check(ufbxi_connect_op(uc, curve_fbx_id, value_fbx_id, curve->name));
15295
15296 ufbxi_read_extrapolation(&curve->pre_extrapolation, node, ufbxi_Pre_Extrapolation);
15297 ufbxi_read_extrapolation(&curve->post_extrapolation, node, ufbxi_Post_Extrapolation);
15298
15299 if (uc->opts.ignore_animation) return 1;
15300
15301 size_t num_keys = 0;
15302 ufbxi_check(ufbxi_find_val1(node, ufbxi_KeyCount, "Z", &num_keys));
15303 curve->keyframes.data = ufbxi_push(&uc->result, ufbx_keyframe, num_keys);
15304 curve->keyframes.count = num_keys;
15305 ufbxi_check(curve->keyframes.data);
15306
15307 float slope_left = 0.0f;
15308 float weight_left = 0.333333f;
15309
15310 double next_time = 0.0;
15311 double next_value = 0.0;
15312 double prev_time = 0.0;
15313
15314 // The pre-7000 keyframe data is stored as a _heterogenous_ array containing 64-bit integers,
15315 // floating point values, and _bare characters_. We cast all values to double and interpret them.
15316 double *data = (double*)keys->data, *data_end = data + keys->size;
15317
15318 if (num_keys > 0) {
15319 ufbxi_check(data_end - data >= 2);
15320 next_time = data[0] / uc->ktime_sec_double;
15321 next_value = data[1];
15322 }
15323
15324 for (size_t i = 0; i < num_keys; i++) {
15325 ufbx_keyframe *key = &curve->keyframes.data[i];
15326
15327 if (i == 0) {
15328 curve->min_value = (ufbx_real)next_value;
15329 curve->max_value = (ufbx_real)next_value;
15330 } else {
15331 curve->min_value = ufbxi_min_real(curve->min_value, (ufbx_real)next_value);
15332 curve->max_value = ufbxi_max_real(curve->max_value, (ufbx_real)next_value);
15333 }
15334
15335 // First three values: Time, Value, InterpolationMode
15336 ufbxi_check(data_end - data >= 3);
15337 key->time = next_time;
15338 key->value = (ufbx_real)next_value;
15339 char mode = ufbxi_double_to_char(data[2]);
15340 data += 3;
15341
15342 float slope_right = 0.0f;
15343 float weight_right = 0.333333f;
15344 float next_slope_left = 0.0f;
15345 float next_weight_left = 0.333333f;
15346 bool auto_slope = false;
15347
15348 if (mode == 'U') {
15349 // Cubic interpolation
15350 key->interpolation = UFBX_INTERPOLATION_CUBIC;
15351
15352 ufbxi_check(data_end - data >= 1);
15353 char slope_mode = ufbxi_double_to_char(data[0]);
15354 data += 1;
15355
15356 size_t num_weights = 1;
15357 if (slope_mode == 's' || slope_mode == 'b') {
15358 // Slope mode 's'/'b' (standard? broken?) always have two explicit slopes
15359 // TODO: `b` might actually be some kind of TCB curve
15360 ufbxi_check(data_end - data >= 2);
15361 slope_right = (float)data[0];
15362 next_slope_left = (float)data[1];
15363 data += 2;
15364 } else if (slope_mode == 'a') {
15365 // Parameterless slope mode 'a' seems to appear in baked animations. Let's just assume
15366 // automatic tangents for now as they're the least likely to break with
15367 // objectionable artifacts. We need to defer the automatic tangent resolve
15368 // until we have read the next time/value.
15369 // TODO: Solve what this is more throroughly
15370 auto_slope = true;
15371 if (uc->version == 5000) {
15372 num_weights = 0;
15373 }
15374 } else if (slope_mode == 'p') {
15375 // TODO: What is this mode? It seems to have negative values sometimes?
15376 // Also it seems to have _two_ trailing weights values, currently observed:
15377 // `n,n` and `a,X,Y,n`...
15378 // Ignore unknown values for now
15379 ufbxi_check(data_end - data >= 2);
15380 data += 2;
15381 num_weights = 2;
15382 } else if (slope_mode == 't') {
15383 // TODO: What is this mode? It seems that it does not have any weights and the
15384 // third value seems _tiny_ (around 1e-30?)
15385 ufbxi_check(data_end - data >= 3);
15386 data += 3;
15387 num_weights = 0;
15388 } else {
15389 ufbxi_fail("Unknown slope mode");
15390 }
15391
15392 for (; num_weights > 0; num_weights--) {
15393 ufbxi_check(data_end - data >= 1);
15394 char weight_mode = ufbxi_double_to_char(data[0]);
15395 data += 1;
15396
15397 if (weight_mode == 'n') {
15398 // Automatic weights (0.3333...)
15399 } else if (weight_mode == 'a') {
15400 // Manual weights: RightWeight, NextLeftWeight
15401 ufbxi_check(data_end - data >= 2);
15402 weight_right = (float)data[0];
15403 next_weight_left = (float)data[1];
15404 data += 2;
15405 } else if (weight_mode == 'l') {
15406 // Next left tangent is weighted
15407 ufbxi_check(data_end - data >= 1);
15408 next_weight_left = (float)data[0];
15409 data += 1;
15410 } else if (weight_mode == 'r') {
15411 // Right tangent is weighted
15412 ufbxi_check(data_end - data >= 1);
15413 weight_right = (float)data[0];
15414 data += 1;
15415 } else if (weight_mode == 'c') {
15416 // TODO: What is this mode? At least it has no parameters so let's
15417 // just assume automatic weights for the time being (0.3333...)
15418 } else {
15419 ufbxi_fail("Unknown weight mode");
15420 }
15421 }
15422
15423 } else if (mode == 'L') {
15424 // Linear interpolation: No parameters
15425 key->interpolation = UFBX_INTERPOLATION_LINEAR;
15426 } else if (mode == 'C') {
15427 // Constant interpolation: Single parameter (use prev/next)
15428 ufbxi_check(data_end - data >= 1);
15429 key->interpolation = ufbxi_double_to_char(data[0]) == 'n' ? UFBX_INTERPOLATION_CONSTANT_NEXT : UFBX_INTERPOLATION_CONSTANT_PREV;
15430 data += 1;
15431 } else {
15432 ufbxi_fail("Unknown key mode");
15433 }
15434
15435 // Retrieve next key and value
15436 if (i + 1 < num_keys) {
15437 ufbxi_check(data_end - data >= 2);
15438 next_time = data[0] / uc->ktime_sec_double;
15439 next_value = data[1];
15440 }
15441
15442 if (auto_slope) {
15443 if (i > 0) {
15444 slope_left = slope_right = ufbxi_solve_auto_tangent(uc,
15445 prev_time, key->time, next_time,
15446 key[-1].value, key->value, (ufbx_real)next_value,
15447 weight_left, weight_right, 0.0f, UFBXI_KEY_CLAMP_PROGRESSIVE|UFBXI_KEY_TIME_INDEPENDENT);
15448 } else {
15449 slope_left = slope_right = 0.0f;
15450 }
15451 }
15452
15453 // Set up linear cubic tangents if necessary
15454 if (key->interpolation == UFBX_INTERPOLATION_LINEAR) {
15455 if (next_time > key->time) {
15456 double slope = (next_value - key->value) / (next_time - key->time);
15457 slope_right = next_slope_left = (float)slope;
15458 } else {
15459 slope_right = next_slope_left = 0.0f;
15460 }
15461 }
15462
15463 if (key->time > prev_time) {
15464 double delta = key->time - prev_time;
15465 key->left.dx = (float)(weight_left * delta);
15466 key->left.dy = key->left.dx * slope_left;
15467 } else {
15468 key->left.dx = 0.0f;
15469 key->left.dy = 0.0f;
15470 }
15471
15472 if (next_time > key->time) {
15473 double delta = next_time - key->time;
15474 key->right.dx = (float)(weight_right * delta);
15475 key->right.dy = key->right.dx * slope_right;
15476 } else {
15477 key->right.dx = 0.0f;
15478 key->right.dy = 0.0f;
15479 }
15480
15481 slope_left = next_slope_left;
15482 weight_left = next_weight_left;
15483 prev_time = key->time;
15484 }
15485
15486 ufbxi_check(data == data_end);
15487
15488 return 1;
15489 }
15490
15491 // Recursion limited as it is further called only for `name="T"/"R"/"S"` and
15492 // cannot enter the `name=="Transform"` branch.
15493 ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_take_prop_channel(ufbxi_context *uc, ufbxi_node *node, uint64_t target_fbx_id, uint64_t layer_fbx_id, ufbx_string name)
15494 ufbxi_recursive_function(int, ufbxi_read_take_prop_channel, (uc, node, target_fbx_id, layer_fbx_id, name), 2,
15495 (ufbxi_context *uc, ufbxi_node *node, uint64_t target_fbx_id, uint64_t layer_fbx_id, ufbx_string name))
15496 {
15497 if (name.data == ufbxi_Transform) {
15498 // Pre-7000 have transform keyframes in a deeply nested structure,
15499 // flatten it to make it resemble post-7000 structure a bit closer:
15500 // old: Model: { Channel: "Transform" { Channel: "T" { Channel "X": { ... } } } }
15501 // new: Model: { Channel: "Lcl Translation" { Channel "X": { ... } } }
15502
15503 ufbxi_for(ufbxi_node, child, node->children, node->num_children) {
15504 if (child->name != ufbxi_Channel) continue;
15505
15506 const char *old_name = NULL;
15507 ufbxi_check(ufbxi_get_val1(child, "C", (char**)&old_name));
15508
15509 ufbx_string new_name;
15510 if (old_name == ufbxi_T) { new_name.data = ufbxi_Lcl_Translation; new_name.length = sizeof(ufbxi_Lcl_Translation) - 1; }
15511 else if (old_name == ufbxi_R) { new_name.data = ufbxi_Lcl_Rotation; new_name.length = sizeof(ufbxi_Lcl_Rotation) - 1; }
15512 else if (old_name == ufbxi_S) { new_name.data = ufbxi_Lcl_Scaling; new_name.length = sizeof(ufbxi_Lcl_Scaling) - 1; }
15513 else {
15514 continue;
15515 }
15516
15517 // Read child as a top-level property channel
15518 ufbxi_check(ufbxi_read_take_prop_channel(uc, child, target_fbx_id, layer_fbx_id, new_name));
15519 }
15520
15521 } else {
15522
15523 // Pre-6000 FBX files store blend shape keys with a " (Shape)" suffix
15524 if (uc->version < 6000) {
15525 const char *const suffix = " (Shape)";
15526 size_t suffix_len = strlen(suffix);
15527 if (name.length > suffix_len && !memcmp(name.data + name.length - suffix_len, suffix, suffix_len)) {
15528 name.length -= suffix_len;
15529 ufbxi_check(ufbxi_push_string_place_str(&uc->string_pool, &name, false));
15530 }
15531 }
15532
15533 // Find 1-3 channel nodes that contain a `Key:` node
15534 ufbxi_node *channel_nodes[3] = { 0 };
15535 const char *channel_names[3] = { 0 };
15536 size_t num_channel_nodes = 0;
15537
15538 if (ufbxi_find_child(node, ufbxi_Key) || ufbxi_find_child(node, ufbxi_Default)) {
15539 // Channel has only a single curve
15540 channel_nodes[0] = node;
15541 channel_names[0] = name.data;
15542 num_channel_nodes = 1;
15543 } else {
15544 // Channel is a compound of multiple curves
15545 ufbxi_for(ufbxi_node, child, node->children, node->num_children) {
15546 if (child->name != ufbxi_Channel) continue;
15547 if (!ufbxi_find_child(child, ufbxi_Key) && !ufbxi_find_child(child, ufbxi_Default)) continue;
15548 if (!ufbxi_get_val1(child, "C", (char**)&channel_names[num_channel_nodes])) continue;
15549 channel_nodes[num_channel_nodes] = child;
15550 if (++num_channel_nodes == 3) break;
15551 }
15552 }
15553
15554 // Early return: No valid channels found, not an error
15555 if (num_channel_nodes == 0) return 1;
15556
15557 uint64_t value_fbx_id = 0;
15558 ufbx_anim_value *value = ufbxi_push_synthetic_element(uc, &value_fbx_id, node, name.data, ufbx_anim_value, UFBX_ELEMENT_ANIM_VALUE);
15559
15560 // Add a "virtual" connection between the animated property and the layer/target
15561 ufbxi_check(ufbxi_connect_oo(uc, value_fbx_id, layer_fbx_id));
15562 ufbxi_check(ufbxi_connect_op(uc, value_fbx_id, target_fbx_id, name));
15563
15564 for (size_t i = 0; i < num_channel_nodes; i++) {
15565 ufbxi_check(ufbxi_read_take_anim_channel(uc, channel_nodes[i], value_fbx_id, channel_names[i], &value->default_value.v[i]));
15566 }
15567 }
15568
15569 return 1;
15570 }
15571
15572 ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_take_object(ufbxi_context *uc, ufbxi_node *node, uint64_t layer_fbx_id)
15573 {
15574 // Takes are used only in pre-7000 FBX versions so objects are identified
15575 // by their unique Type::Name pair that we use as unique IDs through the
15576 // pooled interned string pointers.
15577 const char *type_and_name = NULL;
15578 ufbxi_check(ufbxi_get_val1(node, "c", (char**)&type_and_name));
15579 uint64_t target_fbx_id = ufbxi_synthetic_id_from_string(uc, type_and_name);
15580 ufbxi_check(target_fbx_id);
15581
15582 // Add all suitable Channels as animated properties
15583 ufbxi_for(ufbxi_node, child, node->children, node->num_children) {
15584 ufbx_string name;
15585 if (child->name != ufbxi_Channel) continue;
15586 if (!ufbxi_get_val1(child, "S", &name)) continue;
15587
15588 ufbxi_check(ufbxi_read_take_prop_channel(uc, child, target_fbx_id, layer_fbx_id, name));
15589 }
15590
15591 return 1;
15592 }
15593
15594 ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_take(ufbxi_context *uc, ufbxi_node *node)
15595 {
15596 ufbx_prop tmp_props[4];
15597 uint32_t num_props = 0;
15598 memset(tmp_props, 0, sizeof(tmp_props));
15599
15600 int64_t start = 0, stop = 0;
15601 if (ufbxi_find_val2(node, ufbxi_LocalTime, "LL", &start, &stop)) {
15602 ufbxi_init_synthetic_int_prop(&tmp_props[num_props++], ufbxi_LocalStart, start, UFBX_PROP_INTEGER);
15603 ufbxi_init_synthetic_int_prop(&tmp_props[num_props++], ufbxi_LocalStop, stop, UFBX_PROP_INTEGER);
15604 }
15605 if (ufbxi_find_val2(node, ufbxi_ReferenceTime, "LL", &start, &stop)) {
15606 ufbxi_init_synthetic_int_prop(&tmp_props[num_props++], ufbxi_ReferenceStart, start, UFBX_PROP_INTEGER);
15607 ufbxi_init_synthetic_int_prop(&tmp_props[num_props++], ufbxi_ReferenceStop, stop, UFBX_PROP_INTEGER);
15608 }
15609
15610 const char *name;
15611 ufbxi_check(ufbxi_get_val1(node, "C", (char**)&name));
15612
15613 // Hack: For post-7000 files we are only interested in the animation times
15614 // for fallback in case the information is missing in the stacks.
15615 if (uc->version >= 7000) {
15616 uint32_t hash = ufbxi_hash_ptr(name);
15617 ufbxi_tmp_anim_stack *entry = ufbxi_map_find(&uc->anim_stack_map, ufbxi_tmp_anim_stack, hash, &name);
15618
15619 if (entry) {
15620 ufbx_anim_stack *stack = entry->stack;
15621 if (stack->props.props.count == 0) {
15622 stack->props.props.count = num_props;
15623 stack->props.props.data = ufbxi_push_copy(&uc->result, ufbx_prop, num_props, tmp_props);
15624 ufbxi_check(stack->props.props.data);
15625 }
15626 }
15627
15628 return 1;
15629 }
15630
15631 uint64_t stack_fbx_id = 0, layer_fbx_id = 0;
15632
15633 // Treat the Take as a post-7000 version animation stack and layer.
15634 ufbx_anim_stack *stack = ufbxi_push_synthetic_element(uc, &stack_fbx_id, node, name, ufbx_anim_stack, UFBX_ELEMENT_ANIM_STACK);
15635 ufbxi_check(stack);
15636
15637 stack->props.props.count = num_props;
15638 stack->props.props.data = ufbxi_push_copy(&uc->result, ufbx_prop, num_props, tmp_props);
15639 ufbxi_check(stack->props.props.data);
15640
15641 ufbx_anim_layer *layer = ufbxi_push_synthetic_element(uc, &layer_fbx_id, node, ufbxi_BaseLayer, ufbx_anim_layer, UFBX_ELEMENT_ANIM_LAYER);
15642 ufbxi_check(layer);
15643
15644 ufbxi_check(ufbxi_connect_oo(uc, layer_fbx_id, stack_fbx_id));
15645
15646 // Read all properties of objects included in the take
15647 ufbxi_for(ufbxi_node, child, node->children, node->num_children) {
15648 // TODO: Do some object types have another name?
15649 if (child->name != ufbxi_Model) continue;
15650
15651 ufbxi_check(ufbxi_read_take_object(uc, child, layer_fbx_id));
15652 }
15653
15654 return 1;
15655 }
15656
15657 ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_takes(ufbxi_context *uc)
15658 {
15659 for (;;) {
15660 ufbxi_node *node;
15661 ufbxi_check(ufbxi_parse_toplevel_child(uc, &node, NULL));
15662 if (!node) break;
15663
15664 if (node->name == ufbxi_Take) {
15665 ufbxi_check(ufbxi_read_take(uc, node));
15666 }
15667 }
15668
15669 return 1;
15670 }
15671
15672 ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_legacy_settings(ufbxi_context *uc, ufbxi_node *node)
15673 {
15674 if (uc->read_legacy_settings) return 1;
15675 uc->read_legacy_settings = true;
15676
15677 ufbx_prop tmp_props[2];
15678 uint32_t num_props = 0;
15679 memset(tmp_props, 0, sizeof(tmp_props));
15680
15681 ufbxi_node *frame_rate = ufbxi_find_child_strcmp(node, "FrameRate");
15682 if (frame_rate) {
15683 double fps = 0.0;
15684 if (!ufbxi_get_val1(frame_rate, "D", &fps)) {
15685 ufbx_string str;
15686 if (ufbxi_get_val1(frame_rate, "S", &str)) {
15687 char *end;
15688 double val = ufbxi_parse_double(str.data, str.length, &end, uc->double_parse_flags);
15689 if (end == str.data + str.length) {
15690 fps = val;
15691 }
15692 }
15693 }
15694 if (fps > 0.0) {
15695 ufbxi_init_synthetic_real_prop(&tmp_props[num_props++], ufbxi_CustomFrameRate, (ufbx_real)fps, UFBX_PROP_NUMBER);
15696 ufbxi_init_synthetic_real_prop(&tmp_props[num_props++], ufbxi_TimeMode, UFBX_TIME_MODE_CUSTOM, UFBX_PROP_INTEGER);
15697 }
15698 }
15699
15700 if (num_props > 0) {
15701 ufbx_props *props = &uc->scene.settings.props;
15702 size_t num_existing = props->props.count;
15703
15704 size_t new_count = num_props + num_existing;
15705 ufbx_prop *new_props = ufbxi_push(&uc->result, ufbx_prop, new_count);
15706 ufbxi_check(new_props);
15707
15708 memcpy(new_props, tmp_props, num_props * sizeof(ufbx_prop));
15709 if (num_existing > 0) {
15710 memcpy(new_props + num_props, props->props.data, num_existing * sizeof(ufbx_prop));
15711 }
15712
15713 ufbxi_check(ufbxi_sort_properties(uc, new_props, new_count));
15714 props->props.data = new_props;
15715 props->props.count = new_count;
15716 ufbxi_deduplicate_properties(&props->props);
15717
15718 ufbxi_check(uc->scene.settings.props.props.data);
15719 }
15720
15721 return 1;
15722 }
15723
15724 ufbxi_noinline static ufbx_matrix ufbxi_unscaled_transform_to_matrix(const ufbx_transform *t)
15725 {
15726 ufbx_transform transform = *t;
15727 transform.scale.x = 1.0f;
15728 transform.scale.y = 1.0f;
15729 transform.scale.z = 1.0f;
15730 return ufbx_transform_to_matrix(&transform);
15731 }
15732
15733 ufbxi_noinline static void ufbxi_setup_root_node(ufbxi_context *uc, ufbx_node *root)
15734 {
15735 if (uc->opts.use_root_transform) {
15736 root->local_transform = uc->opts.root_transform;
15737 root->node_to_parent = ufbx_transform_to_matrix(&uc->opts.root_transform);
15738 } else {
15739 root->local_transform = ufbx_identity_transform;
15740 root->node_to_parent = ufbx_identity_matrix;
15741 }
15742 root->is_root = true;
15743 }
15744
15745 static ufbxi_forceinline bool ufbxi_supports_version(uint32_t version)
15746 {
15747 return version >= 3000 && version <= 7700;
15748 }
15749
15750 ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_root(ufbxi_context *uc)
15751 {
15752 // FBXHeaderExtension: Some metadata (optional)
15753 ufbxi_check(ufbxi_parse_toplevel(uc, ufbxi_FBXHeaderExtension));
15754 ufbxi_check(ufbxi_read_header_extension(uc));
15755
15756 // The ASCII exporter version is stored in top-level
15757 if (uc->exporter == UFBX_EXPORTER_BLENDER_ASCII) {
15758 ufbxi_check(ufbxi_parse_toplevel(uc, ufbxi_Creator));
15759 if (uc->top_node) {
15760 ufbxi_ignore(ufbxi_get_val1(uc->top_node, "S", &uc->scene.metadata.creator));
15761 }
15762 }
15763
15764 // Resolve the exporter before continuing
15765 ufbxi_check(ufbxi_match_exporter(uc));
15766 if (uc->version < 7000) {
15767 ufbxi_check(ufbxi_init_node_prop_names(uc));
15768 }
15769 // Don't allow changing version from this point onwards
15770 uc->ascii.found_version = true;
15771
15772 // Document: Read root ID
15773 if (uc->version >= 7000) {
15774 ufbxi_check(ufbxi_parse_toplevel(uc, ufbxi_Documents));
15775 ufbxi_check(ufbxi_read_document(uc));
15776 } else {
15777 // Pre-7000: Root node has a specific type-name pair "Model::Scene"
15778 // (or reversed in binary). Use the interned name as ID as usual.
15779 const char *root_name = uc->from_ascii ? "Model::Scene" : "Scene\x00\x01Model";
15780 root_name = ufbxi_push_string_imp(&uc->string_pool, root_name, 12, NULL, false, true);
15781 ufbxi_check(root_name);
15782 uc->root_id = ufbxi_synthetic_id_from_string(uc, root_name);
15783 ufbxi_check(uc->root_id);
15784 }
15785
15786 // Add a nameless root node with the root ID
15787 {
15788 ufbxi_element_info root_info = { uc->root_id };
15789 root_info.name = ufbx_empty_string;
15790 ufbx_node *root = ufbxi_push_element(uc, &root_info, ufbx_node, UFBX_ELEMENT_NODE);
15791 ufbxi_check(root);
15792 ufbxi_setup_root_node(uc, root);
15793 ufbxi_check(ufbxi_push_copy(&uc->tmp_node_ids, uint32_t, 1, &root->element.element_id));
15794 }
15795
15796 // Definitions: Object type counts and property templates (optional)
15797 ufbxi_check(ufbxi_parse_toplevel(uc, ufbxi_Definitions));
15798 ufbxi_check(ufbxi_read_definitions(uc));
15799
15800 // Objects: Actual scene data
15801 ufbxi_check(ufbxi_parse_toplevel(uc, ufbxi_Objects));
15802 if (!uc->sure_fbx) {
15803 // If the file is a bit iffy about being a real FBX file reject it if
15804 // even the objects are not found.
15805 ufbxi_check_msg(uc->top_node, "Not an FBX file");
15806 }
15807 if (uc->thread_pool.enabled) {
15808 ufbxi_check(ufbxi_read_objects_threaded(uc));
15809 } else {
15810 ufbxi_check(ufbxi_read_objects(uc));
15811 }
15812
15813 // Connections: Relationships between nodes
15814 ufbxi_check(ufbxi_parse_toplevel(uc, ufbxi_Connections));
15815 ufbxi_check(ufbxi_read_connections(uc));
15816
15817 // Takes: Pre-7000 animation data
15818 ufbxi_check(ufbxi_parse_toplevel(uc, ufbxi_Takes));
15819 ufbxi_check(ufbxi_read_takes(uc));
15820
15821 // Check if there's a top-level GlobalSettings that we skimmed over
15822 ufbxi_check(ufbxi_parse_toplevel(uc, ufbxi_GlobalSettings));
15823 if (uc->top_node) {
15824 ufbxi_check(ufbxi_read_global_settings(uc, uc->top_node));
15825 }
15826
15827 // Version5: Pre-6000 settings
15828 ufbxi_check(ufbxi_parse_toplevel(uc, ufbxi_Version5));
15829 if (uc->top_node) {
15830 ufbxi_node *settings = ufbxi_find_child_strcmp(uc->top_node, "Settings");
15831 if (settings) {
15832 ufbxi_check(ufbxi_read_legacy_settings(uc, settings));
15833 }
15834 }
15835
15836 // Force parsing all the nodes by parsing a toplevel that cannot be found
15837 if (uc->opts.retain_dom) {
15838 ufbxi_check(ufbxi_parse_toplevel(uc, NULL));
15839 }
15840
15841 return 1;
15842 }
15843
15844 typedef struct {
15845 const char *prop_name;
15846 ufbx_prop_type prop_type;
15847 const char *node_name;
15848 const char *node_fmt;
15849 } ufbxi_legacy_prop;
15850
15851 // Must be alphabetically sorted!
15852 static const ufbxi_legacy_prop ufbxi_legacy_light_props[] = {
15853 { ufbxi_CastLight, UFBX_PROP_BOOLEAN, ufbxi_CastLight, "L" },
15854 { ufbxi_CastShadows, UFBX_PROP_BOOLEAN, ufbxi_CastShadows, "L" },
15855 { ufbxi_Color, UFBX_PROP_COLOR, ufbxi_Color, "RRR" },
15856 { ufbxi_ConeAngle, UFBX_PROP_NUMBER, ufbxi_ConeAngle, "R" },
15857 { ufbxi_HotSpot, UFBX_PROP_NUMBER, ufbxi_HotSpot, "R" },
15858 { ufbxi_Intensity, UFBX_PROP_NUMBER, ufbxi_Intensity, "R" },
15859 { ufbxi_LightType, UFBX_PROP_INTEGER, ufbxi_LightType, "L" },
15860 };
15861
15862 // Must be alphabetically sorted!
15863 static const ufbxi_legacy_prop ufbxi_legacy_camera_props[] = {
15864 { ufbxi_ApertureMode, UFBX_PROP_INTEGER, ufbxi_ApertureMode, "L" },
15865 { ufbxi_AspectH, UFBX_PROP_NUMBER, ufbxi_AspectH, "R" },
15866 { ufbxi_AspectRatioMode, UFBX_PROP_INTEGER, "AspectType", "L" },
15867 { ufbxi_AspectW, UFBX_PROP_NUMBER, ufbxi_AspectW, "R" },
15868 { ufbxi_FieldOfView, UFBX_PROP_NUMBER, "Aperture", "R" },
15869 { ufbxi_FieldOfViewX, UFBX_PROP_NUMBER, "FieldOfViewXProperty", "R" },
15870 { ufbxi_FieldOfViewY, UFBX_PROP_NUMBER, "FieldOfViewYProperty", "R" },
15871 { ufbxi_FilmHeight, UFBX_PROP_NUMBER, "CameraAperture", "_R" },
15872 { ufbxi_FilmSqueezeRatio, UFBX_PROP_NUMBER, "SqueezeRatio", "R" },
15873 { ufbxi_FilmWidth, UFBX_PROP_NUMBER, "CameraAperture", "R_" },
15874 { ufbxi_FocalLength, UFBX_PROP_NUMBER, ufbxi_FocalLength, "R" },
15875 };
15876
15877 // Must be alphabetically sorted!
15878 static const ufbxi_legacy_prop ufbxi_legacy_bone_props[] = {
15879 { ufbxi_Size, UFBX_PROP_NUMBER, ufbxi_Size, "R" },
15880 };
15881
15882 // Must be alphabetically sorted!
15883 static const ufbxi_legacy_prop ufbxi_legacy_material_props[] = {
15884 { ufbxi_AmbientColor, UFBX_PROP_COLOR, "Ambient", "RRR" },
15885 { ufbxi_DiffuseColor, UFBX_PROP_COLOR, "Diffuse", "RRR" },
15886 { ufbxi_EmissiveColor, UFBX_PROP_COLOR, "Emissive", "RRR" },
15887 { ufbxi_ShadingModel, UFBX_PROP_COLOR, ufbxi_ShadingModel, "S" },
15888 { ufbxi_Shininess, UFBX_PROP_NUMBER, "Shininess", "R" },
15889 { ufbxi_SpecularColor, UFBX_PROP_COLOR, "Specular", "RRR" },
15890 };
15891
15892 ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_legacy_prop(ufbxi_node *node, ufbx_prop *prop, const ufbxi_legacy_prop *legacy_prop)
15893 {
15894 size_t value_ix = 0;
15895 uint32_t flags = 0;
15896
15897 const char *fmt = legacy_prop->node_fmt;
15898 for (size_t fmt_ix = 0; fmt[fmt_ix]; fmt_ix++) {
15899 char c = fmt[fmt_ix];
15900 switch (c) {
15901 case 'L':
15902 ufbx_assert(value_ix == 0);
15903 if (!ufbxi_get_val_at(node, fmt_ix, 'L', &prop->value_int)) return 0;
15904 prop->value_real = (ufbx_real)prop->value_int;
15905 prop->value_real_arr[1] = 0.0f;
15906 prop->value_real_arr[2] = 0.0f;
15907 prop->value_real_arr[3] = 0.0f;
15908 prop->value_str = ufbx_empty_string;
15909 prop->value_blob = ufbx_empty_blob;
15910 flags |= (uint32_t)UFBX_PROP_FLAG_VALUE_INT;
15911 value_ix++;
15912 break;
15913 case 'R':
15914 ufbx_assert(value_ix < 4);
15915 if (!ufbxi_get_val_at(node, fmt_ix, 'R', &prop->value_real_arr[value_ix])) return 0;
15916 if (value_ix == 0) {
15917 prop->value_int = ufbxi_f64_to_i64(prop->value_real);
15918 prop->value_real_arr[1] = 0.0f;
15919 prop->value_real_arr[2] = 0.0f;
15920 prop->value_real_arr[3] = 0.0f;
15921 prop->value_str = ufbx_empty_string;
15922 prop->value_blob = ufbx_empty_blob;
15923 }
15924 flags &= ~(uint32_t)(UFBX_PROP_FLAG_VALUE_REAL|UFBX_PROP_FLAG_VALUE_VEC2|UFBX_PROP_FLAG_VALUE_VEC3|UFBX_PROP_FLAG_VALUE_VEC4);
15925 flags |= (uint32_t)UFBX_PROP_FLAG_VALUE_REAL << value_ix;
15926 value_ix++;
15927 break;
15928 case 'S':
15929 ufbx_assert(value_ix == 0);
15930 if (!ufbxi_get_val_at(node, fmt_ix, 'S', &prop->value_str)) return 0;
15931 if (prop->value_str.length > 0) {
15932 int found = ufbxi_get_val_at(node, fmt_ix, 'b', &prop->value_blob);
15933 ufbxi_ignore(found);
15934 ufbx_assert(found);
15935 } else {
15936 prop->value_blob = ufbx_empty_blob;
15937 }
15938 prop->value_real = 0.0f;
15939 prop->value_real_arr[1] = 0.0f;
15940 prop->value_real_arr[2] = 0.0f;
15941 prop->value_real_arr[3] = 0.0f;
15942 prop->value_int = 0;
15943 flags |= (uint32_t)UFBX_PROP_FLAG_VALUE_STR;
15944 value_ix++;
15945 break;
15946 case '_':
15947 break;
15948 default:
15949 ufbxi_unreachable("Unhandled legacy fmt");
15950 }
15951 }
15952
15953 prop->flags = (ufbx_prop_flags)flags;
15954
15955 return 1;
15956 }
15957
15958 ufbxi_nodiscard ufbxi_noinline static size_t ufbxi_read_legacy_props(ufbxi_node *node, ufbx_prop *props, const ufbxi_legacy_prop *legacy_props, size_t num_legacy)
15959 {
15960 size_t num_props = 0;
15961 for (size_t legacy_ix = 0; legacy_ix < num_legacy; legacy_ix++) {
15962 const ufbxi_legacy_prop *legacy_prop = &legacy_props[legacy_ix];
15963 ufbx_prop *prop = &props[num_props];
15964
15965 ufbxi_node *n = ufbxi_find_child_strcmp(node, legacy_prop->node_name);
15966 if (!n) continue;
15967 if (!ufbxi_read_legacy_prop(n, prop, legacy_prop)) continue;
15968
15969 prop->name.data = legacy_prop->prop_name;
15970 prop->name.length = strlen(legacy_prop->prop_name);
15971 prop->_internal_key = ufbxi_get_name_key(prop->name.data, prop->name.length);
15972 prop->flags = (ufbx_prop_flags)0;
15973 prop->type = legacy_prop->prop_type;
15974 num_props++;
15975 }
15976
15977 return num_props;
15978 }
15979
15980 ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_legacy_material(ufbxi_context *uc, ufbxi_node *node, uint64_t *p_fbx_id, const char *name)
15981 {
15982 ufbx_material *ufbxi_restrict material = ufbxi_push_synthetic_element(uc, p_fbx_id, node, name, ufbx_material, UFBX_ELEMENT_MATERIAL);
15983 ufbxi_check(material);
15984
15985 ufbx_prop tmp_props[ufbxi_arraycount(ufbxi_legacy_material_props)];
15986 size_t num_props = ufbxi_read_legacy_props(node, tmp_props, ufbxi_legacy_material_props, ufbxi_arraycount(ufbxi_legacy_material_props));
15987
15988 material->shading_model_name = ufbx_empty_string;
15989 material->props.props.count = num_props;
15990 material->props.props.data = ufbxi_push_copy(&uc->result, ufbx_prop, num_props, tmp_props);
15991 ufbxi_check(material->props.props.data);
15992
15993 material->shader_prop_prefix = ufbx_empty_string;
15994
15995 return 1;
15996 }
15997
15998 ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_legacy_link(ufbxi_context *uc, ufbxi_node *node, uint64_t *p_fbx_id, const char *name)
15999 {
16000 ufbx_skin_cluster *ufbxi_restrict cluster = ufbxi_push_synthetic_element(uc, p_fbx_id, node, name, ufbx_skin_cluster, UFBX_ELEMENT_SKIN_CLUSTER);
16001 ufbxi_check(cluster);
16002
16003 // TODO: Merge with ufbxi_read_skin_cluster(), at least partially?
16004 ufbxi_value_array *indices = ufbxi_find_array(node, ufbxi_Indexes, 'i');
16005 ufbxi_value_array *weights = ufbxi_find_array(node, ufbxi_Weights, 'r');
16006
16007 if (indices && weights) {
16008 ufbxi_check(indices->size == weights->size);
16009 cluster->num_weights = indices->size;
16010 cluster->vertices.data = (uint32_t*)indices->data;
16011 cluster->weights.data = (ufbx_real*)weights->data;
16012 cluster->vertices.count = cluster->num_weights;
16013 cluster->weights.count = cluster->num_weights;
16014 }
16015
16016 ufbxi_value_array *transform = ufbxi_find_array(node, ufbxi_Transform, 'r');
16017 ufbxi_value_array *transform_link = ufbxi_find_array(node, ufbxi_TransformLink, 'r');
16018 if (transform && transform_link) {
16019 ufbxi_check(transform->size >= 16);
16020 ufbxi_check(transform_link->size >= 16);
16021
16022 ufbxi_read_transform_matrix(&cluster->mesh_node_to_bone, (ufbx_real*)transform->data);
16023 ufbxi_read_transform_matrix(&cluster->bind_to_world, (ufbx_real*)transform_link->data);
16024 }
16025
16026 return 1;
16027 }
16028
16029 ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_legacy_light(ufbxi_context *uc, ufbxi_node *node, ufbxi_element_info *info)
16030 {
16031 ufbx_light *ufbxi_restrict light = ufbxi_push_element(uc, info, ufbx_light, UFBX_ELEMENT_LIGHT);
16032 ufbxi_check(light);
16033
16034 ufbx_prop tmp_props[ufbxi_arraycount(ufbxi_legacy_light_props)];
16035 size_t num_props = ufbxi_read_legacy_props(node, tmp_props, ufbxi_legacy_light_props, ufbxi_arraycount(ufbxi_legacy_light_props));
16036
16037 light->props.props.count = num_props;
16038 light->props.props.data = ufbxi_push_copy(&uc->result, ufbx_prop, num_props, tmp_props);
16039 ufbxi_check(light->props.props.data);
16040
16041 return 1;
16042 }
16043
16044 ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_legacy_camera(ufbxi_context *uc, ufbxi_node *node, ufbxi_element_info *info)
16045 {
16046 ufbx_camera *ufbxi_restrict camera = ufbxi_push_element(uc, info, ufbx_camera, UFBX_ELEMENT_CAMERA);
16047 ufbxi_check(camera);
16048
16049 ufbx_prop tmp_props[ufbxi_arraycount(ufbxi_legacy_camera_props)];
16050 size_t num_props = ufbxi_read_legacy_props(node, tmp_props, ufbxi_legacy_camera_props, ufbxi_arraycount(ufbxi_legacy_camera_props));
16051
16052 camera->props.props.count = num_props;
16053 camera->props.props.data = ufbxi_push_copy(&uc->result, ufbx_prop, num_props, tmp_props);
16054 ufbxi_check(camera->props.props.data);
16055
16056 return 1;
16057 }
16058
16059 ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_legacy_limb_node(ufbxi_context *uc, ufbxi_node *node, ufbxi_element_info *info)
16060 {
16061 ufbx_bone *ufbxi_restrict bone = ufbxi_push_element(uc, info, ufbx_bone, UFBX_ELEMENT_BONE);
16062 ufbxi_check(bone);
16063
16064 ufbx_prop tmp_props[ufbxi_arraycount(ufbxi_legacy_bone_props)];
16065 size_t num_props = 0;
16066
16067 ufbxi_node *prop_node = ufbxi_find_child_strcmp(node, "Properties");
16068 if (prop_node) {
16069 num_props = ufbxi_read_legacy_props(prop_node, tmp_props, ufbxi_legacy_bone_props, ufbxi_arraycount(ufbxi_legacy_bone_props));
16070 }
16071
16072 bone->props.props.count = num_props;
16073 bone->props.props.data = ufbxi_push_copy(&uc->result, ufbx_prop, num_props, tmp_props);
16074 ufbxi_check(bone->props.props.data);
16075
16076 return 1;
16077 }
16078
16079 ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_legacy_mesh(ufbxi_context *uc, ufbxi_node *node, ufbxi_element_info *info)
16080 {
16081 // Only read polygon meshes, ignore eg. NURBS without error
16082 ufbxi_node *node_vertices = ufbxi_find_child(node, ufbxi_Vertices);
16083 ufbxi_node *node_indices = ufbxi_find_child(node, ufbxi_PolygonVertexIndex);
16084 if (!node_vertices || !node_indices) return 1;
16085
16086 ufbx_mesh *ufbxi_restrict mesh = ufbxi_push_element(uc, info, ufbx_mesh, UFBX_ELEMENT_MESH);
16087 ufbxi_check(mesh);
16088
16089 ufbxi_check(ufbxi_read_synthetic_blend_shapes(uc, node, info));
16090
16091 ufbxi_patch_mesh_reals(mesh);
16092
16093 if (uc->opts.ignore_geometry) return 1;
16094
16095 ufbxi_value_array *vertices = ufbxi_get_array(node_vertices, 'r');
16096 ufbxi_value_array *indices = ufbxi_get_array(node_indices, 'i');
16097 ufbxi_check(vertices && indices);
16098 ufbxi_check(vertices->size % 3 == 0);
16099
16100 mesh->num_vertices = vertices->size / 3;
16101 mesh->num_indices = indices->size;
16102
16103 uint32_t *index_data = (uint32_t*)indices->data;
16104
16105 // Duplicate `index_data` for modification if we retain DOM
16106 if (uc->opts.retain_dom) {
16107 index_data = ufbxi_push_copy(&uc->result, uint32_t, indices->size, index_data);
16108 ufbxi_check(index_data);
16109 }
16110
16111 mesh->vertices.data = (ufbx_vec3*)vertices->data;
16112 mesh->vertex_indices.data = index_data;
16113 mesh->vertices.count = mesh->num_vertices;
16114 mesh->vertex_indices.count = mesh->num_indices;
16115
16116 mesh->vertex_position.exists = true;
16117 mesh->vertex_position.values.data = (ufbx_vec3*)vertices->data;
16118 mesh->vertex_position.values.count = mesh->num_vertices;
16119 mesh->vertex_position.indices.data = index_data;
16120 mesh->vertex_position.indices.count = mesh->num_indices;
16121 mesh->vertex_position.unique_per_vertex = true;
16122
16123 // Check/make sure that the last index is negated (last of polygon)
16124 if (mesh->num_indices > 0) {
16125 if ((int32_t)index_data[mesh->num_indices - 1] >= 0) {
16126 if (uc->opts.strict) ufbxi_fail("Non-negated last index");
16127 index_data[mesh->num_indices - 1] = ~index_data[mesh->num_indices - 1];
16128 }
16129 }
16130
16131 ufbxi_check(ufbxi_process_indices(uc, mesh, index_data));
16132
16133 // Normals are either per-vertex or per-index in legacy FBX files?
16134 // If the version is 5000 prefer per-vertex, otherwise per-index...
16135 ufbxi_value_array *normals = ufbxi_find_array(node, ufbxi_Normals, 'r');
16136 if (normals) {
16137 size_t num_normals = normals->size / 3;
16138 bool per_vertex = num_normals == mesh->num_vertices;
16139 bool per_index = num_normals == mesh->num_indices;
16140 if (per_vertex && (!per_index || uc->version == 5000)) {
16141 mesh->vertex_normal.exists = true;
16142 mesh->vertex_normal.values.count = num_normals;
16143 mesh->vertex_normal.indices.count = mesh->num_indices;
16144 mesh->vertex_normal.unique_per_vertex = true;
16145 mesh->vertex_normal.values.data = (ufbx_vec3*)normals->data;
16146 mesh->vertex_normal.indices.data = mesh->vertex_indices.data;
16147 } else if (per_index) {
16148 uc->max_consecutive_indices = ufbxi_max_sz(uc->max_consecutive_indices, mesh->num_indices);
16149 mesh->vertex_normal.exists = true;
16150 mesh->vertex_normal.values.count = num_normals;
16151 mesh->vertex_normal.indices.count = mesh->num_indices;
16152 mesh->vertex_normal.unique_per_vertex = false;
16153 mesh->vertex_normal.values.data = (ufbx_vec3*)normals->data;
16154 mesh->vertex_normal.indices.data = (uint32_t*)ufbxi_sentinel_index_consecutive;
16155 }
16156 }
16157
16158 // Optional UV values are stored pretty much like a modern vertex element
16159 ufbxi_node *uv_info = ufbxi_find_child(node, ufbxi_GeometryUVInfo);
16160 if (uv_info) {
16161 ufbx_uv_set *set = ufbxi_push_zero(&uc->result, ufbx_uv_set, 1);
16162 ufbxi_check(set);
16163 set->index = 0;
16164 set->name.data = ufbxi_empty_char;
16165 ufbxi_check(ufbxi_read_vertex_element(uc, mesh, uv_info, (ufbx_vertex_attrib*)&set->vertex_uv,
16166 ufbxi_TextureUV, ufbxi_TextureUVVerticeIndex, NULL, 'r', 2));
16167
16168 mesh->uv_sets.data = set;
16169 mesh->uv_sets.count = 1;
16170 mesh->vertex_uv = set->vertex_uv;
16171 }
16172
16173 // Material indices
16174 {
16175 const char *mapping = NULL;
16176 ufbxi_check(ufbxi_find_val1(node, ufbxi_MaterialAssignation, "C", (char**)&mapping));
16177 if (mapping == ufbxi_ByPolygon) {
16178 ufbxi_check(ufbxi_read_truncated_array(uc, &mesh->face_material.data, &mesh->face_material.count, node, ufbxi_Materials, 'i', mesh->num_faces));
16179 } else if (mapping == ufbxi_AllSame) {
16180 ufbxi_value_array *arr = ufbxi_find_array(node, ufbxi_Materials, 'i');
16181 uint32_t material = 0;
16182 if (arr && arr->size >= 1) {
16183 material = ((uint32_t*)arr->data)[0];
16184 }
16185
16186 mesh->face_material.count = mesh->num_faces;
16187 if (material == 0) {
16188 mesh->face_material.data = (uint32_t*)ufbxi_sentinel_index_zero;
16189 } else {
16190 mesh->face_material.data = ufbxi_push(&uc->result, uint32_t, mesh->num_faces);
16191 ufbxi_check(mesh->face_material.data);
16192 ufbxi_for_list(uint32_t, p_mat, mesh->face_material) {
16193 *p_mat = material;
16194 }
16195 }
16196 }
16197 }
16198
16199 uint64_t skin_fbx_id = 0;
16200 ufbx_skin_deformer *skin = NULL;
16201
16202 // Materials, Skin Clusters
16203 ufbxi_for(ufbxi_node, child, node->children, node->num_children) {
16204 if (child->name == ufbxi_Material) {
16205 uint64_t fbx_id = 0;
16206 ufbx_string type_and_name, type, name;
16207 ufbxi_check(ufbxi_get_val1(child, "s", &type_and_name));
16208 ufbxi_check(ufbxi_split_type_and_name(uc, type_and_name, &type, &name));
16209 ufbxi_check(ufbxi_read_legacy_material(uc, child, &fbx_id, name.data));
16210 ufbxi_check(ufbxi_connect_oo(uc, fbx_id, info->fbx_id));
16211 } else if (child->name == ufbxi_Link) {
16212 uint64_t fbx_id = 0;
16213 ufbx_string type_and_name, type, name;
16214 ufbxi_check(ufbxi_get_val1(child, "s", &type_and_name));
16215 ufbxi_check(ufbxi_split_type_and_name(uc, type_and_name, &type, &name));
16216 ufbxi_check(ufbxi_read_legacy_link(uc, child, &fbx_id, name.data));
16217
16218 uint64_t node_fbx_id = ufbxi_synthetic_id_from_string(uc, type_and_name.data);
16219 ufbxi_check(node_fbx_id);
16220 ufbxi_check(ufbxi_connect_oo(uc, node_fbx_id, fbx_id));
16221 if (!skin) {
16222 skin = ufbxi_push_synthetic_element(uc, &skin_fbx_id, NULL, info->name.data, ufbx_skin_deformer, UFBX_ELEMENT_SKIN_DEFORMER);
16223 ufbxi_check(skin);
16224 ufbxi_check(ufbxi_connect_oo(uc, skin_fbx_id, info->fbx_id));
16225 }
16226 ufbxi_check(ufbxi_connect_oo(uc, fbx_id, skin_fbx_id));
16227 }
16228 }
16229
16230 mesh->skinned_is_local = true;
16231 mesh->skinned_position = mesh->vertex_position;
16232 mesh->skinned_normal = mesh->vertex_normal;
16233
16234 ufbxi_patch_mesh_reals(mesh);
16235
16236 return 1;
16237 }
16238
16239 ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_legacy_media(ufbxi_context *uc, ufbxi_node *node)
16240 {
16241 ufbxi_node *videos = ufbxi_find_child(node, ufbxi_Video);
16242 if (videos) {
16243 ufbxi_for(ufbxi_node, child, videos->children, videos->num_children) {
16244 ufbxi_element_info video_info = { 0 };
16245 ufbxi_check(ufbxi_get_val1(child, "S", &video_info.name));
16246 video_info.fbx_id = ufbxi_push_synthetic_id(uc);
16247 video_info.dom_node = ufbxi_get_dom_node(uc, node);
16248
16249 ufbxi_check(ufbxi_read_video(uc, child, &video_info));
16250 }
16251 }
16252
16253 return 1;
16254 }
16255
16256 ufbxi_nodiscard ufbxi_noinline static int ufbxi_read_legacy_model(ufbxi_context *uc, ufbxi_node *node)
16257 {
16258 ufbx_string type_and_name, type, name;
16259 ufbxi_check(ufbxi_get_val1(node, "s", &type_and_name));
16260 ufbxi_check(ufbxi_split_type_and_name(uc, type_and_name, &type, &name));
16261
16262 ufbxi_element_info info = { 0 };
16263 info.fbx_id = ufbxi_synthetic_id_from_string(uc, type_and_name.data);
16264 ufbxi_check(info.fbx_id);
16265 info.name = name;
16266 info.dom_node = ufbxi_get_dom_node(uc, node);
16267
16268 ufbx_node *elem_node = ufbxi_push_element(uc, &info, ufbx_node, UFBX_ELEMENT_NODE);
16269 ufbxi_check(elem_node);
16270 ufbxi_check(ufbxi_push_copy(&uc->tmp_node_ids, uint32_t, 1, &elem_node->element.element_id));
16271
16272 ufbxi_element_info attrib_info = { 0 };
16273 attrib_info.fbx_id = ufbxi_push_synthetic_id(uc);
16274 attrib_info.name = name;
16275 attrib_info.dom_node = info.dom_node;
16276
16277 // If we make unused connections it doesn't matter..
16278 ufbxi_check(ufbxi_connect_oo(uc, attrib_info.fbx_id, info.fbx_id));
16279
16280 const char *attrib_type = ufbxi_empty_char;
16281 ufbxi_ignore(ufbxi_find_val1(node, ufbxi_Type, "C", (char**)&attrib_type));
16282
16283 bool has_attrib = true;
16284 if (attrib_type == ufbxi_Light) {
16285 ufbxi_check(ufbxi_read_legacy_light(uc, node, &attrib_info));
16286 } else if (attrib_type == ufbxi_Camera) {
16287 ufbxi_check(ufbxi_read_legacy_camera(uc, node, &attrib_info));
16288 } else if (attrib_type == ufbxi_LimbNode) {
16289 ufbxi_check(ufbxi_read_legacy_limb_node(uc, node, &attrib_info));
16290 } else if (ufbxi_find_child(node, ufbxi_Vertices)) {
16291 ufbxi_check(ufbxi_read_legacy_mesh(uc, node, &attrib_info));
16292 } else {
16293 has_attrib = false;
16294 }
16295
16296 // Mark the node as having an attribute so property connections can be forwarded
16297 if (has_attrib) {
16298 ufbxi_check(ufbxi_insert_fbx_attr(uc, info.fbx_id, attrib_info.fbx_id));
16299 }
16300
16301 // Children are represented as an array of strings
16302 ufbxi_value_array *children = ufbxi_find_array(node, ufbxi_Children, 's');
16303 if (children) {
16304 ufbx_string *names = (ufbx_string*)children->data;
16305 for (size_t i = 0; i < children->size; i++) {
16306 uint64_t child_fbx_id = ufbxi_synthetic_id_from_string(uc, names[i].data);
16307 ufbxi_check(child_fbx_id);
16308 ufbxi_check(ufbxi_connect_oo(uc, child_fbx_id, info.fbx_id));
16309 }
16310 }
16311
16312 // Non-take animation channels
16313 ufbxi_for(ufbxi_node, child, node->children, node->num_children) {
16314 if (child->name == ufbxi_Channel) {
16315 ufbx_string channel_name;
16316 if (ufbxi_get_val1(child, "S", &channel_name)) {
16317 if (uc->legacy_implicit_anim_layer_id == 0) {
16318 // Defer creation so we won't be the first animation stack..
16319 uc->legacy_implicit_anim_layer_id = ufbxi_push_synthetic_id(uc);
16320 }
16321 ufbxi_check(ufbxi_read_take_prop_channel(uc, child, info.fbx_id, uc->legacy_implicit_anim_layer_id, channel_name));
16322 }
16323 }
16324 }
16325
16326 return 1;
16327 }
16328
16329 // Read a pre-6000 FBX file where everything is stored at the root level
16330 ufbxi_nodiscard static ufbxi_noinline int ufbxi_read_legacy_root(ufbxi_context *uc)
16331 {
16332 ufbxi_check(ufbxi_init_node_prop_names(uc));
16333
16334 // Some legacy FBX files have an `Fbx_Root` node that could be used as the
16335 // root node. However no other formats have root node with transforms so it
16336 // might be better to leave it as-is and create an empty one.
16337 {
16338 ufbx_node *root = ufbxi_push_synthetic_element(uc, &uc->root_id, NULL, ufbxi_empty_char, ufbx_node, UFBX_ELEMENT_NODE);
16339 ufbxi_check(root);
16340 ufbxi_setup_root_node(uc, root);
16341 ufbxi_check(ufbxi_push_copy(&uc->tmp_node_ids, uint32_t, 1, &root->element.element_id));
16342 }
16343
16344 // NOTE: `ufbxi_read_header_extension()` is optional so use default KTime definition
16345 uc->ktime_sec = 46186158000;
16346 uc->ktime_sec_double = (double)uc->ktime_sec;
16347
16348 for (;;) {
16349 ufbxi_check(ufbxi_parse_legacy_toplevel(uc));
16350 if (!uc->top_node) break;
16351
16352 ufbxi_node *node = uc->top_node;
16353 if (node->name == ufbxi_FBXHeaderExtension) {
16354 ufbxi_check(ufbxi_read_header_extension(uc));
16355 } else if (node->name == ufbxi_Media) {
16356 ufbxi_check(ufbxi_read_legacy_media(uc, node));
16357 } else if (node->name == ufbxi_Takes) {
16358 ufbxi_check(ufbxi_read_takes(uc));
16359 } else if (node->name == ufbxi_Model) {
16360 ufbxi_check(ufbxi_read_legacy_model(uc, node));
16361 } else if (!strcmp(node->name, "Settings")) {
16362 ufbxi_check(ufbxi_read_legacy_settings(uc, node));
16363 }
16364 }
16365
16366 if (uc->opts.retain_dom) {
16367 ufbxi_check(ufbxi_retain_toplevel(uc, NULL));
16368 }
16369
16370 // Create the implicit animation stack if necessary
16371 if (uc->legacy_implicit_anim_layer_id) {
16372 ufbxi_element_info layer_info = { 0 };
16373 layer_info.fbx_id = uc->legacy_implicit_anim_layer_id;
16374 layer_info.name.data = "(internal)";
16375 layer_info.name.length = strlen(layer_info.name.data);
16376 ufbxi_check(ufbxi_push_string_place_str(&uc->string_pool, &layer_info.name, true));
16377 ufbx_anim_layer *layer = ufbxi_push_element(uc, &layer_info, ufbx_anim_layer, UFBX_ELEMENT_ANIM_LAYER);
16378 ufbxi_check(layer);
16379
16380 ufbxi_element_info stack_info = layer_info;
16381 stack_info.fbx_id = ufbxi_push_synthetic_id(uc);
16382 ufbx_anim_stack *stack = ufbxi_push_element(uc, &stack_info, ufbx_anim_stack, UFBX_ELEMENT_ANIM_STACK);
16383 ufbxi_check(stack);
16384
16385 ufbxi_check(ufbxi_connect_oo(uc, layer_info.fbx_id, stack_info.fbx_id));
16386 }
16387
16388 return 1;
16389 }
16390
16391 // Filename manipulation
16392
16393 ufbxi_nodiscard ufbxi_noinline static size_t ufbxi_trim_delimiters(ufbxi_context *uc, const char *data, size_t length)
16394 {
16395 for (; length > 0; length--) {
16396 char c = data[length - 1];
16397 bool is_separator = c == '/' || c == uc->opts.path_separator;
16398 if (is_separator) {
16399 length--;
16400 break;
16401 }
16402 }
16403 return length;
16404 }
16405
16406 ufbxi_nodiscard ufbxi_noinline static int ufbxi_init_file_paths(ufbxi_context *uc)
16407 {
16408 if (uc->opts.filename.length > 0) {
16409 uc->scene.metadata.filename = uc->opts.filename;
16410 } else if (uc->opts.raw_filename.size > 0) {
16411 uc->scene.metadata.filename.data = (const char*)uc->opts.raw_filename.data;
16412 uc->scene.metadata.filename.length = uc->opts.raw_filename.size;
16413 }
16414
16415 if (uc->opts.raw_filename.size > 0) {
16416 uc->scene.metadata.raw_filename = uc->opts.raw_filename;
16417 } else if (uc->opts.filename.length > 0) {
16418 uc->scene.metadata.raw_filename.data = uc->opts.filename.data;
16419 uc->scene.metadata.raw_filename.size = uc->opts.filename.length;
16420 }
16421
16422 ufbxi_check(ufbxi_push_string_place_str(&uc->string_pool, &uc->scene.metadata.filename, false));
16423 ufbxi_check(ufbxi_push_string_place_blob(&uc->string_pool, &uc->scene.metadata.raw_filename, true));
16424
16425 uc->scene.metadata.relative_root.data = uc->scene.metadata.filename.data;
16426 uc->scene.metadata.relative_root.length = ufbxi_trim_delimiters(uc, uc->scene.metadata.filename.data, uc->scene.metadata.filename.length);
16427
16428 uc->scene.metadata.raw_relative_root.data = uc->scene.metadata.raw_filename.data;
16429 uc->scene.metadata.raw_relative_root.size = ufbxi_trim_delimiters(uc, (const char*)uc->scene.metadata.raw_filename.data, uc->scene.metadata.raw_filename.size);
16430
16431 ufbxi_check(ufbxi_push_string_place_str(&uc->string_pool, &uc->scene.metadata.relative_root, false));
16432 ufbxi_check(ufbxi_push_string_place_blob(&uc->string_pool, &uc->scene.metadata.raw_relative_root, true));
16433
16434 return 1;
16435 }
16436
16437 typedef union {
16438 ufbx_string str;
16439 ufbx_blob blob;
16440 } ufbxi_strblob;
16441
16442 static ufbxi_noinline void ufbxi_strblob_set(ufbxi_strblob *dst, const char *data, size_t length, bool raw)
16443 {
16444 if (raw) {
16445 dst->blob.data = data;
16446 dst->blob.size = length;
16447 } else {
16448 dst->str.data = length == 0 ? ufbxi_empty_char : data;
16449 dst->str.length = length;
16450 }
16451 }
16452
16453 static ufbxi_forceinline const char *ufbxi_strblob_data(const ufbxi_strblob *strblob, bool raw)
16454 {
16455 return raw ? (const char*)strblob->blob.data : strblob->str.data;
16456 }
16457
16458 static ufbxi_forceinline size_t ufbxi_strblob_length(const ufbxi_strblob *strblob, bool raw)
16459 {
16460 return raw ? strblob->blob.size : strblob->str.length;
16461 }
16462
16463 ufbxi_nodiscard ufbxi_noinline static bool ufbxi_is_absolute_path(const char *path, size_t length)
16464 {
16465 if (length > 0 && (path[0] == '/' || path[0] == '\\')) {
16466 return true;
16467 } else if (length > 2 && path[1] == ':' && (path[2] == '\\' || path[2] == '/')) {
16468 return true;
16469 }
16470 return false;
16471 }
16472
16473 ufbxi_nodiscard ufbxi_noinline static int ufbxi_resolve_relative_filename(ufbxi_context *uc, ufbxi_strblob *p_dst, const ufbxi_strblob *p_src, bool raw)
16474 {
16475 const char *src = ufbxi_strblob_data(p_src, raw);
16476 size_t src_length = ufbxi_strblob_length(p_src, raw);
16477
16478 // Skip leading directory separators and early return if the relative path is empty
16479 while (src_length > 0 && (src[0] == '/' || src[0] == '\\')) {
16480 src++;
16481 src_length--;
16482 }
16483 if (src_length == 0) {
16484 ufbxi_strblob_set(p_dst, NULL, 0, raw);
16485 return 1;
16486 }
16487
16488 const char *prefix_data;
16489 size_t prefix_length;
16490 if (raw) {
16491 prefix_data = (const char*)uc->scene.metadata.raw_relative_root.data;
16492 prefix_length = uc->scene.metadata.raw_relative_root.size;
16493 } else {
16494 prefix_data = (const char*)uc->scene.metadata.relative_root.data;
16495 prefix_length = uc->scene.metadata.relative_root.length;
16496 }
16497
16498 // Retain absolute paths
16499 if (ufbxi_is_absolute_path(src, src_length)) {
16500 prefix_length = 0;
16501 }
16502
16503 // Undo directories from `prefix` for every `..`
16504 while (prefix_length > 0 && src_length >= 3 && src[0] == '.' && src[1] == '.' && (src[2] == '/' || src[2] == '\\')) {
16505 size_t part_start = prefix_length;
16506 while (part_start > 0 && !(prefix_data[part_start - 1] == '/' || prefix_data[part_start - 1] == '\\')) {
16507 part_start--;
16508 }
16509 size_t part_len = prefix_length - part_start;
16510
16511 if (part_len == 2 && prefix_data[part_start] == '.' && prefix_data[part_start + 1] == '.') {
16512 // Prefix itself ends in `..`, cannot cancel out a leading `../`
16513 break;
16514 }
16515
16516 // Eat the leading '/' before the part segment
16517 prefix_length = part_start > 0 ? part_start - 1 : 0;
16518
16519 if (part_len == 1 && prefix_data[part_start] == '.') {
16520 // Single '.' -> remove and continue without cancelling out a leading `../`
16521 continue;
16522 }
16523
16524 src += 3;
16525 src_length -= 3;
16526 }
16527
16528 size_t result_cap = prefix_length + src_length + 1;
16529 char *result = ufbxi_push(&uc->tmp_stack, char, result_cap);
16530 ufbxi_check(result);
16531 char *ptr = result;
16532
16533 // Copy prefix and suffix converting separators in the process
16534 if (prefix_length > 0) {
16535 memcpy(ptr, prefix_data, prefix_length);
16536 ptr[prefix_length] = uc->opts.path_separator;
16537 ptr += prefix_length + 1;
16538 }
16539 for (size_t i = 0; i < src_length; i++) {
16540 char c = src[i];
16541 if (c == '/' || c == '\\') {
16542 c = uc->opts.path_separator;
16543 }
16544 *ptr++ = c;
16545 }
16546
16547 // Intern the string and pop the temporary buffer
16548 ufbx_string dst = { result, ufbxi_to_size(ptr - result) };
16549 ufbx_assert(dst.length <= result_cap);
16550 ufbxi_check(ufbxi_push_string_place_str(&uc->string_pool, &dst, raw));
16551 ufbxi_pop(&uc->tmp_stack, char, result_cap, NULL);
16552
16553 ufbxi_strblob_set(p_dst, dst.data, dst.length, raw);
16554
16555 return 1;
16556 }
16557
16558 // Open file utility
16559
16560 static ufbxi_noinline bool ufbxi_open_file(const ufbx_open_file_cb *cb, ufbx_stream *stream, const char *path, size_t path_len, const ufbx_blob *original_filename, ufbxi_allocator *ator, ufbx_open_file_type type)
16561 {
16562 if (!cb || !cb->fn) return false;
16563
16564 ufbx_open_file_info info; // ufbxi_uninit
16565 info.context = (uintptr_t)ator;
16566 if (original_filename) {
16567 info.original_filename = *original_filename;
16568 } else {
16569 info.original_filename.data = path;
16570 info.original_filename.size = path_len;
16571 }
16572 info.type = type;
16573
16574 return cb->fn(cb->user, stream, path, path_len, &info);
16575 }
16576
16577 #define ufbxi_patch_zero(dst, src) do { \
16578 ufbx_assert((dst) == 0 || (dst) == (src)); \
16579 (dst) = (src); \
16580 } while (0)
16581
16582 static void ufbxi_update_vertex_first_index(ufbx_mesh *mesh)
16583 {
16584 ufbxi_for_list(uint32_t, p_vx_ix, mesh->vertex_first_index) {
16585 *p_vx_ix = UFBX_NO_INDEX;
16586 }
16587
16588 uint32_t num_vertices = (uint32_t)mesh->num_vertices;
16589 for (size_t ix = 0; ix < mesh->num_indices; ix++) {
16590 uint32_t vx = mesh->vertex_indices.data[ix];
16591 if (vx < num_vertices && mesh->vertex_first_index.data[vx] == UFBX_NO_INDEX) {
16592 mesh->vertex_first_index.data[vx] = (uint32_t)ix;
16593 }
16594 }
16595 }
16596
16597 ufbxi_nodiscard static ufbxi_noinline int ufbxi_finalize_mesh(ufbxi_buf *buf, ufbx_error *error, ufbx_mesh *mesh)
16598 {
16599 if (mesh->vertices.count == 0) {
16600 mesh->vertices = mesh->vertex_position.values;
16601 }
16602 if (mesh->vertex_indices.count == 0) {
16603 mesh->vertex_indices = mesh->vertex_position.indices;
16604 }
16605
16606 ufbxi_patch_zero(mesh->num_vertices, mesh->vertices.count);
16607 ufbxi_patch_zero(mesh->num_indices, mesh->vertex_indices.count);
16608 ufbxi_patch_zero(mesh->num_faces, mesh->faces.count);
16609
16610 if (mesh->num_triangles == 0 || mesh->max_face_triangles == 0) {
16611 size_t num_triangles = 0;
16612 size_t max_face_triangles = 0;
16613 size_t num_bad_faces[3] = { 0 };
16614 ufbxi_nounroll ufbxi_for_list(ufbx_face, face, mesh->faces) {
16615 if (face->num_indices >= 3) {
16616 size_t tris = face->num_indices - 2;
16617 num_triangles += tris;
16618 max_face_triangles = ufbxi_max_sz(max_face_triangles, tris);
16619 } else {
16620 num_bad_faces[face->num_indices]++;
16621 }
16622 }
16623
16624 ufbxi_patch_zero(mesh->num_triangles, num_triangles);
16625 ufbxi_patch_zero(mesh->max_face_triangles, max_face_triangles);
16626 ufbxi_patch_zero(mesh->num_empty_faces, num_bad_faces[0]);
16627 ufbxi_patch_zero(mesh->num_point_faces, num_bad_faces[1]);
16628 ufbxi_patch_zero(mesh->num_line_faces, num_bad_faces[2]);
16629 }
16630
16631 if (!mesh->skinned_position.exists) {
16632 mesh->skinned_is_local = true;
16633 mesh->skinned_position = mesh->vertex_position;
16634 mesh->skinned_normal = mesh->vertex_normal;
16635 }
16636
16637 if (mesh->vertex_first_index.count == 0) {
16638 mesh->vertex_first_index.count = mesh->num_vertices;
16639 mesh->vertex_first_index.data = ufbxi_push(buf, uint32_t, mesh->num_vertices);
16640 ufbxi_check_err(error, mesh->vertex_first_index.data);
16641 ufbxi_update_vertex_first_index(mesh);
16642 }
16643
16644 if (mesh->uv_sets.count == 0 && mesh->vertex_uv.exists) {
16645 ufbx_uv_set *uv_set = ufbxi_push_zero(buf, ufbx_uv_set, 1);
16646 ufbxi_check_err(error, uv_set);
16647
16648 uv_set->name.data = ufbxi_empty_char;
16649 uv_set->vertex_uv = mesh->vertex_uv;
16650 uv_set->vertex_tangent = mesh->vertex_tangent;
16651 uv_set->vertex_bitangent = mesh->vertex_bitangent;
16652
16653 mesh->uv_sets.data = uv_set;
16654 mesh->uv_sets.count = 1;
16655 }
16656
16657 if (mesh->color_sets.count == 0 && mesh->vertex_color.exists) {
16658 ufbx_color_set *color_set = ufbxi_push_zero(buf, ufbx_color_set, 1);
16659 ufbxi_check_err(error, color_set);
16660
16661 color_set->name.data = ufbxi_empty_char;
16662 color_set->vertex_color = mesh->vertex_color;
16663
16664 mesh->color_sets.data = color_set;
16665 mesh->color_sets.count = 1;
16666 }
16667
16668 ufbxi_patch_mesh_reals(mesh);
16669
16670 return 1;
16671 }
16672
16673 // -- .obj file
16674
16675 #if UFBXI_FEATURE_FORMAT_OBJ
16676
16677 static const uint8_t ufbxi_obj_attrib_stride[] = {
16678 3, 2, 3, 4,
16679 };
16680
16681 ufbx_static_assert(obj_attrib_strides, ufbxi_arraycount(ufbxi_obj_attrib_stride) == UFBXI_OBJ_NUM_ATTRIBS_EXT);
16682
16683 ufbxi_nodiscard static ufbxi_noinline int ufbxi_obj_pop_props(ufbxi_context *uc, ufbx_prop_list *dst, size_t count)
16684 {
16685 ufbx_prop_list props; // ufbxi_uninit
16686 props.count = count;
16687 props.data = ufbxi_push_pop(&uc->result, &uc->obj.tmp_props, ufbx_prop, count);
16688 ufbxi_check(props.data);
16689
16690 ufbxi_for_list(ufbx_prop, prop, props) {
16691 prop->_internal_key = ufbxi_get_name_key(prop->name.data, prop->name.length);
16692 if (prop->value_str.length == 0) {
16693 prop->value_str.data = ufbxi_empty_char;
16694 }
16695 if (!prop->value_int) {
16696 prop->value_int = ufbxi_f64_to_i64(prop->value_real);
16697 }
16698 if (prop->value_blob.size == 0 && prop->value_str.length > 0) {
16699 prop->value_blob.data = prop->value_str.data;
16700 prop->value_blob.size = prop->value_str.length;
16701 }
16702 }
16703
16704 if (props.count > 1) {
16705 ufbxi_check(ufbxi_sort_properties(uc, props.data, props.count));
16706 ufbxi_deduplicate_properties(&props);
16707 }
16708
16709 *dst = props;
16710 return 1;
16711 }
16712
16713 ufbxi_nodiscard static ufbxi_noinline int ufbxi_obj_push_mesh(ufbxi_context *uc)
16714 {
16715 ufbxi_obj_mesh *mesh = ufbxi_push_zero(&uc->obj.tmp_meshes, ufbxi_obj_mesh, 1);
16716 ufbxi_check(mesh);
16717 uc->obj.mesh = mesh;
16718
16719 ufbxi_nounroll for (size_t i = 0; i < UFBXI_OBJ_NUM_ATTRIBS; i++) {
16720 mesh->vertex_range[i].min_ix = UINT64_MAX;
16721 }
16722
16723 const char *name = "";
16724 if (uc->opts.obj_split_groups && uc->obj.group.length > 0) {
16725 name = uc->obj.group.data;
16726 } else if (!uc->opts.obj_merge_objects && uc->obj.object.length > 0) {
16727 name = uc->obj.object.data;
16728 } else if (!uc->opts.obj_merge_groups && uc->obj.group.length > 0) {
16729 name = uc->obj.group.data;
16730 }
16731
16732 mesh->fbx_node = ufbxi_push_synthetic_element(uc, &mesh->fbx_node_id, NULL, name, ufbx_node, UFBX_ELEMENT_NODE);
16733 mesh->fbx_mesh = ufbxi_push_synthetic_element(uc, &mesh->fbx_mesh_id, NULL, name, ufbx_mesh, UFBX_ELEMENT_MESH);
16734 ufbxi_check(mesh->fbx_node && mesh->fbx_mesh);
16735
16736 mesh->fbx_mesh->vertex_position.unique_per_vertex = true;
16737
16738 ufbxi_check(ufbxi_push_copy(&uc->tmp_node_ids, uint32_t, 1, &mesh->fbx_node->element_id));
16739
16740 uc->obj.face_material = UFBX_NO_INDEX;
16741 uc->obj.face_group = 0;
16742 uc->obj.face_group_dirty = true;
16743 uc->obj.material_dirty = true;
16744
16745 ufbxi_check(ufbxi_connect_oo(uc, mesh->fbx_mesh_id, mesh->fbx_node_id));
16746 ufbxi_check(ufbxi_connect_oo(uc, mesh->fbx_node_id, 0));
16747
16748 return 1;
16749 }
16750
16751 ufbxi_nodiscard static ufbxi_noinline int ufbxi_obj_flush_mesh(ufbxi_context *uc)
16752 {
16753 if (!uc->obj.mesh) return 1;
16754
16755 size_t num_props = uc->obj.tmp_props.num_items;
16756 ufbxi_check(ufbxi_obj_pop_props(uc, &uc->obj.mesh->fbx_mesh->props.props, num_props));
16757
16758 size_t num_groups = uc->obj.tmp_face_group_infos.num_items;
16759 ufbx_face_group *groups = ufbxi_push_pop(&uc->result, &uc->obj.tmp_face_group_infos, ufbx_face_group, num_groups);
16760 ufbxi_check(groups);
16761
16762 uc->obj.mesh->fbx_mesh->face_groups.data = groups;
16763 uc->obj.mesh->fbx_mesh->face_groups.count = num_groups;
16764
16765 return 1;
16766 }
16767
16768 ufbxi_nodiscard static ufbxi_noinline int ufbxi_obj_init(ufbxi_context *uc)
16769 {
16770 uc->from_ascii = true;
16771 uc->obj.initialized = true;
16772
16773
16774 ufbxi_nounroll for (size_t i = 0; i < UFBXI_OBJ_NUM_ATTRIBS_EXT; i++) {
16775 uc->obj.tmp_vertices[i].ator = &uc->ator_tmp;
16776 uc->obj.tmp_indices[i].ator = &uc->ator_tmp;
16777 }
16778 uc->obj.tmp_color_valid.ator = &uc->ator_tmp;
16779 uc->obj.tmp_faces.ator = &uc->ator_tmp;
16780 uc->obj.tmp_face_material.ator = &uc->ator_tmp;
16781 uc->obj.tmp_face_smoothing.ator = &uc->ator_tmp;
16782 uc->obj.tmp_face_group.ator = &uc->ator_tmp;
16783 uc->obj.tmp_face_group_infos.ator = &uc->ator_tmp;
16784 uc->obj.tmp_meshes.ator = &uc->ator_tmp;
16785 uc->obj.tmp_props.ator = &uc->ator_tmp;
16786
16787 // .obj parsing does its own yield logic
16788 uc->data_size += uc->yield_size;
16789
16790 uc->obj.object.data = ufbxi_empty_char;
16791 uc->obj.group.data = ufbxi_empty_char;
16792
16793 ufbxi_map_init(&uc->obj.group_map, &uc->ator_tmp, ufbxi_map_cmp_const_char_ptr, NULL);
16794
16795 // Add a nameless root node with the root ID
16796 {
16797 ufbxi_element_info root_info = { uc->root_id };
16798 root_info.name = ufbx_empty_string;
16799 ufbx_node *root = ufbxi_push_element(uc, &root_info, ufbx_node, UFBX_ELEMENT_NODE);
16800 ufbxi_check(root);
16801 ufbxi_setup_root_node(uc, root);
16802 ufbxi_check(ufbxi_push_copy(&uc->tmp_node_ids, uint32_t, 1, &root->element.element_id));
16803 }
16804
16805 return 1;
16806 }
16807
16808 static ufbxi_noinline void ufbxi_obj_free(ufbxi_context *uc)
16809 {
16810 if (!uc->obj.initialized) return;
16811
16812 ufbxi_nounroll for (size_t i = 0; i < UFBXI_OBJ_NUM_ATTRIBS_EXT; i++) {
16813 ufbxi_buf_free(&uc->obj.tmp_vertices[i]);
16814 ufbxi_buf_free(&uc->obj.tmp_indices[i]);
16815 }
16816 ufbxi_buf_free(&uc->obj.tmp_color_valid);
16817 ufbxi_buf_free(&uc->obj.tmp_faces);
16818 ufbxi_buf_free(&uc->obj.tmp_face_material);
16819 ufbxi_buf_free(&uc->obj.tmp_face_smoothing);
16820 ufbxi_buf_free(&uc->obj.tmp_face_group);
16821 ufbxi_buf_free(&uc->obj.tmp_face_group_infos);
16822 ufbxi_buf_free(&uc->obj.tmp_meshes);
16823 ufbxi_buf_free(&uc->obj.tmp_props);
16824
16825 ufbxi_map_free(&uc->obj.group_map);
16826
16827 ufbxi_free(&uc->ator_tmp, ufbx_string, uc->obj.tokens, uc->obj.tokens_cap);
16828 ufbxi_free(&uc->ator_tmp, ufbx_material*, uc->obj.tmp_materials, uc->obj.tmp_materials_cap);
16829 }
16830
16831 ufbxi_nodiscard static ufbxi_noinline int ufbxi_obj_read_line(ufbxi_context *uc)
16832 {
16833 ufbxi_dev_assert(!uc->obj.eof);
16834
16835 size_t offset = 0;
16836
16837 for (;;) {
16838 const char *begin = ufbxi_add_ptr(uc->data, offset);
16839 const char *end = begin ? (const char*)memchr(begin, '\n', uc->data_size - offset) : NULL;
16840 if (!end) {
16841 if (uc->eof) {
16842 offset = uc->data_size;
16843 uc->obj.eof = true;
16844 break;
16845 } else {
16846 size_t new_cap = ufbxi_max_sz(1, uc->data_size * 2);
16847 ufbxi_check(ufbxi_refill(uc, new_cap, false));
16848 continue;
16849 }
16850 }
16851
16852 offset += ufbxi_to_size(end - begin) + 1;
16853
16854 // Handle line continuations
16855 const char *esc = end;
16856 if (esc > begin && esc[-1] == '\r') esc--;
16857 if (esc > begin && esc[-1] == '\\') {
16858 continue;
16859 }
16860
16861 break;
16862 }
16863
16864 size_t line_len = offset;
16865
16866 uc->obj.line.data = uc->data;
16867 uc->obj.line.length = line_len;
16868 uc->data += line_len;
16869 uc->data_size -= line_len;
16870
16871 uc->obj.read_progress += line_len;
16872 if (uc->obj.read_progress >= uc->progress_interval) {
16873 ufbxi_check(ufbxi_report_progress(uc));
16874 uc->obj.read_progress %= uc->progress_interval;
16875 }
16876
16877 if (uc->obj.eof) {
16878 char *new_data = ufbxi_push(&uc->tmp, char, line_len + 1);
16879 ufbxi_check(new_data);
16880 memcpy(new_data, uc->obj.line.data, line_len);
16881 new_data[line_len] = '\n';
16882 uc->obj.line.data = new_data;
16883 uc->obj.line.length++;
16884 }
16885
16886 return 1;
16887 }
16888
16889 static ufbxi_noinline ufbx_string ufbxi_obj_span_token(ufbxi_context *uc, size_t start_token, size_t end_token)
16890 {
16891 ufbx_assert(start_token < uc->obj.num_tokens);
16892 end_token = ufbxi_min_sz(end_token, uc->obj.num_tokens - 1);
16893
16894 ufbx_assert(start_token <= end_token);
16895 ufbx_string start = uc->obj.tokens[start_token];
16896 ufbx_string end = uc->obj.tokens[end_token];
16897 size_t num_between = ufbxi_to_size(end.data - start.data);
16898
16899 ufbx_string result;
16900 result.data = start.data;
16901 result.length = num_between + end.length;
16902 return result;
16903 }
16904
16905 ufbxi_nodiscard static ufbxi_noinline int ufbxi_obj_tokenize(ufbxi_context *uc)
16906 {
16907 const char *ptr = uc->obj.line.data, *end = ptr + uc->obj.line.length;
16908 uc->obj.num_tokens = 0;
16909
16910 for (;;) {
16911 char c;
16912
16913 // Skip whitespace
16914 for (;;) {
16915 c = *ptr;
16916 if (c == ' ' || c == '\t' || c == '\r') {
16917 ptr++;
16918 continue;
16919 }
16920
16921 // Treat line continuations as whitespace
16922 if (c == '\\') {
16923 const char *p = ptr + 1;
16924 if (*p == '\r') p++;
16925 if (*p == '\n' && p < end - 1) {
16926 ptr = p + 1;
16927 continue;
16928 }
16929 }
16930
16931 break;
16932 }
16933
16934 c = *ptr;
16935 if (c == '\n') break;
16936 if (c == '#' && uc->obj.num_tokens > 0) break;
16937
16938 size_t index = uc->obj.num_tokens++;
16939 ufbxi_check(ufbxi_grow_array(&uc->ator_tmp, &uc->obj.tokens, &uc->obj.tokens_cap, index + 1));
16940
16941 ufbx_string *tok = &uc->obj.tokens[index];
16942 tok->data = ptr;
16943
16944 // Treat comment start as a single token
16945 if (c == '#') {
16946 ptr++;
16947 tok->length = 1;
16948 continue;
16949 }
16950
16951 for (;;) {
16952 c = *++ptr;
16953
16954 if (ufbxi_is_space(c)) {
16955 break;
16956 }
16957
16958 if (c == '\\') {
16959 const char *p = ptr + 1;
16960 if (*p == '\r') p++;
16961 if (*p == '\n' && p < end - 1) {
16962 break;
16963 }
16964 }
16965 }
16966
16967 tok->length = ufbxi_to_size(ptr - tok->data);
16968 }
16969
16970 return 1;
16971 }
16972
16973 ufbxi_nodiscard static ufbxi_noinline int ufbxi_obj_tokenize_line(ufbxi_context *uc)
16974 {
16975 ufbxi_check(ufbxi_obj_read_line(uc));
16976 ufbxi_check(ufbxi_obj_tokenize(uc));
16977 return 1;
16978 }
16979
16980 static ufbxi_noinline int ufbxi_obj_parse_vertex(ufbxi_context *uc, ufbxi_obj_attrib attrib, size_t offset)
16981 {
16982 if (uc->opts.ignore_geometry) return 1;
16983
16984 ufbxi_buf *dst = &uc->obj.tmp_vertices[attrib];
16985 size_t num_values = ufbxi_obj_attrib_stride[attrib];
16986 uc->obj.vertex_count[attrib]++;
16987
16988 size_t read_values = num_values;
16989 if (attrib == UFBXI_OBJ_ATTRIB_COLOR) {
16990 if (offset + read_values > uc->obj.num_tokens) {
16991 read_values = 3;
16992 }
16993 }
16994 ufbxi_check(offset + read_values <= uc->obj.num_tokens);
16995
16996 uint32_t parse_flags = uc->double_parse_flags;
16997 ufbx_real *vals = ufbxi_push_fast(dst, ufbx_real, num_values);
16998 ufbxi_check(vals);
16999 for (size_t i = 0; i < read_values; i++) {
17000 ufbx_string str = uc->obj.tokens[offset + i];
17001 char *end; // ufbxi_uninit
17002 double val = ufbxi_parse_double(str.data, str.length, &end, parse_flags);
17003 ufbxi_check(end == str.data + str.length);
17004 vals[i] = (ufbx_real)val;
17005 }
17006
17007 if (read_values < num_values) {
17008 ufbx_assert(read_values + 1 == num_values);
17009 ufbx_assert(attrib == UFBXI_OBJ_ATTRIB_COLOR);
17010 vals[read_values] = 1.0f;
17011 }
17012
17013 return 1;
17014 }
17015
17016 ufbxi_nodiscard static ufbxi_noinline int ufbxi_obj_parse_index(ufbxi_context *uc, ufbx_string *s, uint32_t attrib)
17017 {
17018 const char *ptr = s->data, *end = ptr + s->length;
17019
17020 bool negative = false;
17021 if (*ptr == '-') {
17022 negative = true;
17023 ptr++;
17024 }
17025
17026 // As .obj indices are never zero we can detect missing indices
17027 // by simply not writing to it.
17028 uint64_t index = 0;
17029 for (; ptr != end; ptr++) {
17030 char c = *ptr;
17031 if (c >= '0' && c <= '9') {
17032 ufbxi_check(index < UINT64_MAX / 10 - 10);
17033 index = index * 10 + (uint64_t)(c - '0');
17034 } else if (c == '/') {
17035 ptr++;
17036 break;
17037 }
17038 }
17039
17040 if (negative) {
17041 size_t count = uc->obj.vertex_count[attrib];
17042 index = index <= count ? count - index : UINT64_MAX;
17043 } else {
17044 // Corrects to zero based indices and wraps 0 to UINT64_MAX (missing)
17045 index -= 1;
17046 }
17047
17048 ufbxi_obj_fast_indices *fast_indices = &uc->obj.fast_indices[attrib];
17049 if (fast_indices->num_left == 0) {
17050 size_t num_push = 128;
17051 uint64_t *dst = ufbxi_push(&uc->obj.tmp_indices[attrib], uint64_t, num_push);
17052 ufbxi_check(dst);
17053 uc->obj.fast_indices[attrib].indices = dst;
17054 uc->obj.fast_indices[attrib].num_left = num_push;
17055 }
17056
17057 *fast_indices->indices++ = index;
17058 fast_indices->num_left--;
17059
17060 ufbxi_obj_mesh *mesh = uc->obj.mesh;
17061
17062 if (index != UINT64_MAX) {
17063 ufbxi_obj_index_range *range = &mesh->vertex_range[attrib];
17064 range->min_ix = ufbxi_min64(range->min_ix, index);
17065 range->max_ix = ufbxi_max64(range->max_ix, index);
17066 }
17067
17068 s->data = ptr;
17069 s->length = ufbxi_to_size(end - ptr);
17070
17071 return 1;
17072 }
17073
17074 ufbxi_nodiscard static ufbxi_noinline int ufbxi_obj_parse_indices(ufbxi_context *uc, size_t token_begin, size_t num_tokens)
17075 {
17076 bool flush_mesh = false;
17077 if (uc->obj.object_dirty) {
17078 if (!uc->opts.obj_merge_objects) {
17079 flush_mesh = true;
17080 }
17081 uc->obj.object_dirty = false;
17082 }
17083
17084 if (uc->obj.group_dirty) {
17085 if (((uc->obj.object.length == 0 || uc->opts.obj_merge_objects) && !uc->opts.obj_merge_groups) || uc->opts.obj_split_groups) {
17086 flush_mesh = true;
17087 }
17088 uc->obj.group_dirty = false;
17089 uc->obj.face_group_dirty = true;
17090 }
17091
17092 if (!uc->obj.mesh || flush_mesh) {
17093 ufbxi_check(ufbxi_obj_flush_mesh(uc));
17094 ufbxi_check(ufbxi_obj_push_mesh(uc));
17095 }
17096 ufbxi_obj_mesh *mesh = uc->obj.mesh;
17097
17098 if (uc->obj.material_dirty) {
17099 if (uc->obj.usemtl_fbx_id != 0) {
17100 ufbxi_fbx_id_entry *entry = ufbxi_find_fbx_id(uc, uc->obj.usemtl_fbx_id);
17101 ufbx_assert(entry);
17102 if (mesh->usemtl_base == 0 || entry->user_id < mesh->usemtl_base) {
17103 ufbxi_check(ufbxi_connect_oo(uc, uc->obj.usemtl_fbx_id, mesh->fbx_node_id));
17104
17105 uint32_t index = ++uc->obj.usemtl_index;
17106 ufbxi_check(index < UINT32_MAX);
17107 entry->user_id = index;
17108
17109 if (mesh->usemtl_base == 0) {
17110 mesh->usemtl_base = index;
17111 }
17112 uc->obj.face_material = index - mesh->usemtl_base;
17113 }
17114 uc->obj.face_material = entry->user_id - mesh->usemtl_base;
17115 } else {
17116 uc->obj.face_material = UFBX_NO_INDEX;
17117 }
17118 }
17119
17120 // EARLY RETURN: Rest of the function should only be related to geometry!
17121 if (uc->opts.ignore_geometry) return 1;
17122
17123 if (num_tokens == 0 && !uc->opts.allow_empty_faces) {
17124 ufbxi_check(ufbxi_warnf(UFBX_WARNING_EMPTY_FACE_REMOVED, "Empty face has been removed"));
17125 return 1;
17126 }
17127
17128 if (uc->obj.face_group_dirty) {
17129 ufbx_string name = ufbx_empty_string;
17130 if (uc->obj.group.length > 0 && (uc->obj.object.length > 0 || uc->opts.obj_merge_groups) && !uc->opts.obj_split_groups) {
17131 name = uc->obj.group;
17132 }
17133
17134 uint32_t hash = ufbxi_hash_ptr(name.data);
17135 ufbxi_obj_group_entry *entry = ufbxi_map_find(&uc->obj.group_map, ufbxi_obj_group_entry, hash, &name.data);
17136 if (!entry) {
17137 entry = ufbxi_map_insert(&uc->obj.group_map, ufbxi_obj_group_entry, hash, &name.data);
17138 ufbxi_check(entry);
17139 entry->name = name.data;
17140 entry->mesh_id = 0;
17141 entry->local_id = 0;
17142 }
17143
17144 uint32_t mesh_id = mesh->fbx_mesh->element_id;
17145 if (entry->mesh_id != mesh_id) {
17146 uint32_t id = mesh->num_groups++;
17147 entry->mesh_id = mesh_id;
17148 entry->local_id = id;
17149
17150 ufbx_face_group *group = ufbxi_push_zero(&uc->obj.tmp_face_group_infos, ufbx_face_group, 1);
17151 ufbxi_check(group);
17152 group->id = 0;
17153 group->name = name;
17154 }
17155
17156 uc->obj.face_group = entry->local_id;
17157
17158 if (!uc->obj.has_face_group) {
17159 uc->obj.has_face_group = true;
17160 ufbxi_check(ufbxi_push_zero(&uc->obj.tmp_face_group, uint32_t, uc->obj.tmp_faces.num_items));
17161 }
17162
17163 uc->obj.face_group_dirty = false;
17164 }
17165
17166 size_t num_indices = num_tokens;
17167 ufbxi_check(UINT32_MAX - mesh->num_indices >= num_indices);
17168
17169 ufbx_face *face = ufbxi_push_fast(&uc->obj.tmp_faces, ufbx_face, 1);
17170 ufbxi_check(face);
17171
17172 face->index_begin = (uint32_t)mesh->num_indices;
17173 face->num_indices = (uint32_t)num_indices;
17174
17175 mesh->num_faces++;
17176 mesh->num_indices += num_indices;
17177
17178 uint32_t *p_face_mat = ufbxi_push_fast(&uc->obj.tmp_face_material, uint32_t, 1);
17179 ufbxi_check(p_face_mat);
17180 *p_face_mat = uc->obj.face_material;
17181
17182 if (uc->obj.has_face_smoothing) {
17183 bool *p_face_smooth = ufbxi_push_fast(&uc->obj.tmp_face_smoothing, bool, 1);
17184 ufbxi_check(p_face_smooth);
17185 *p_face_smooth = uc->obj.face_smoothing;
17186 }
17187
17188 if (uc->obj.has_face_group) {
17189 uint32_t *p_face_group = ufbxi_push_fast(&uc->obj.tmp_face_group, uint32_t, 1);
17190 ufbxi_check(p_face_group);
17191 *p_face_group = uc->obj.face_group;
17192 }
17193
17194 for (size_t ix = 0; ix < num_indices; ix++) {
17195 ufbx_string tok = uc->obj.tokens[token_begin + ix];
17196 for (uint32_t attrib = 0; attrib < UFBXI_OBJ_NUM_ATTRIBS; attrib++) {
17197 ufbxi_check(ufbxi_obj_parse_index(uc, &tok, attrib));
17198 }
17199 }
17200
17201 return 1;
17202 }
17203
17204 ufbxi_nodiscard static ufbxi_noinline int ufbxi_obj_parse_multi_indices(ufbxi_context *uc, size_t window)
17205 {
17206 for (size_t begin = 1; begin + window <= uc->obj.num_tokens; begin++) {
17207 ufbxi_check(ufbxi_obj_parse_indices(uc, begin, window));
17208 }
17209 return 1;
17210 }
17211
17212 static ufbxi_noinline uint32_t ufbxi_parse_hex(const char *digits, size_t length)
17213 {
17214 uint32_t value = 0;
17215
17216 for (size_t i = 0; i < length; i++) {
17217 char c = digits[i];
17218 uint32_t v = 0;
17219 if (c >= '0' && c <= '9') {
17220 v = (uint32_t)(c - '0');
17221 } else if (c >= 'A' && c <= 'F') {
17222 v = (uint32_t)(c - 'A') + 10;
17223 } else if (c >= 'a' && c <= 'f') {
17224 v = (uint32_t)(c - 'a') + 10;
17225 }
17226 value = (value << 4) | v;
17227 }
17228
17229 return value;
17230 }
17231
17232 ufbxi_nodiscard static ufbxi_noinline int ufbxi_obj_parse_comment(ufbxi_context *uc)
17233 {
17234 if (uc->obj.num_tokens >= 3 && ufbxi_str_equal(uc->obj.tokens[1], ufbxi_str_c("MRGB"))) {
17235 size_t num_color = uc->obj.vertex_count[UFBXI_OBJ_ATTRIB_COLOR];
17236
17237 // Pop standard vertex colors and replace them with MRGB colors
17238 if (num_color > uc->obj.mrgb_vertex_count) {
17239 size_t num_pop = num_color - uc->obj.mrgb_vertex_count;
17240 ufbxi_pop(&uc->obj.tmp_color_valid, bool, num_pop, NULL);
17241 ufbxi_pop(&uc->obj.tmp_vertices[UFBXI_OBJ_ATTRIB_COLOR], ufbx_real, num_pop * 4, NULL);
17242 uc->obj.vertex_count[UFBXI_OBJ_ATTRIB_COLOR] -= num_pop;
17243 }
17244
17245 ufbx_string mrgb = uc->obj.tokens[2];
17246 for (size_t i = 0; i + 8 <= mrgb.length; i += 8) {
17247 ufbx_real *p_rgba = ufbxi_push(&uc->obj.tmp_vertices[UFBXI_OBJ_ATTRIB_COLOR], ufbx_real, 4);
17248 bool *p_valid = ufbxi_push(&uc->obj.tmp_color_valid, bool, 1);
17249 ufbxi_check(p_rgba && p_valid);
17250 *p_valid = true;
17251
17252 uint32_t hex = ufbxi_parse_hex(mrgb.data + i, 8);
17253 p_rgba[0] = (ufbx_real)((hex >> 16u) & 0xff) / 255.0f;
17254 p_rgba[1] = (ufbx_real)((hex >> 8u) & 0xff) / 255.0f;
17255 p_rgba[2] = (ufbx_real)((hex >> 0u) & 0xff) / 255.0f;
17256 p_rgba[3] = (ufbx_real)((hex >> 24u) & 0xff) / 255.0f;
17257 }
17258
17259 uc->obj.has_vertex_color = true;
17260 }
17261
17262 if (!uc->opts.disable_quirks) {
17263 if (ufbxi_match(&uc->obj.line, "\\s*#\\s*File exported by ZBrush.*")) {
17264 if (!uc->obj.mesh) {
17265 uc->opts.obj_merge_groups = true;
17266 }
17267 }
17268 }
17269
17270 return 1;
17271 }
17272
17273 ufbxi_nodiscard static ufbxi_noinline int ufbxi_obj_parse_material(ufbxi_context *uc)
17274 {
17275 uc->obj.material_dirty = true;
17276
17277 // Allow empty `usemtl` lines to specify "no material".
17278 if (uc->obj.num_tokens < 2) {
17279 uc->obj.usemtl_fbx_id = 0;
17280 return 1;
17281 }
17282
17283 ufbx_string name = ufbxi_obj_span_token(uc, 1, SIZE_MAX);
17284
17285 ufbxi_check(ufbxi_push_string_place_str(&uc->string_pool, &name, false));
17286
17287 uint64_t fbx_id = ufbxi_synthetic_id_from_string(uc, name.data);
17288 ufbxi_check(fbx_id);
17289
17290 ufbxi_fbx_id_entry *entry = ufbxi_find_fbx_id(uc, fbx_id);
17291
17292 uc->obj.usemtl_fbx_id = fbx_id;
17293
17294 if (!entry) {
17295 ufbxi_element_info info = { 0 };
17296 info.fbx_id = fbx_id;
17297 info.name = name;
17298
17299 ufbx_material *material = ufbxi_push_element(uc, &info, ufbx_material, UFBX_ELEMENT_MATERIAL);
17300 ufbxi_check(material);
17301
17302 material->shader_type = UFBX_SHADER_WAVEFRONT_MTL;
17303 material->shading_model_name.data = ufbxi_empty_char;
17304 material->shader_prop_prefix.data = ufbxi_empty_char;
17305
17306 size_t id = material->element_id;
17307 ufbxi_check(ufbxi_grow_array(&uc->ator_tmp, &uc->obj.tmp_materials, &uc->obj.tmp_materials_cap, id + 1));
17308 uc->obj.tmp_materials[id] = material;
17309 }
17310
17311 return 1;
17312 }
17313
17314 #define ufbxi_obj_cmd1(a) ((uint32_t)(a)<<24u)
17315 #define ufbxi_obj_cmd2(a,b) ((uint32_t)(a)<<24u | (uint32_t)(b)<<16)
17316 #define ufbxi_obj_cmd3(a,b,c) ((uint32_t)(a)<<24u | (uint32_t)(b)<<16 | (uint32_t)(c)<<8u)
17317
17318 ufbxi_nodiscard static ufbxi_noinline int ufbxi_obj_pop_vertices(ufbxi_context *uc, ufbx_real_list *dst, uint32_t attrib, uint64_t min_index)
17319 {
17320 size_t stride = ufbxi_obj_attrib_stride[attrib];
17321 ufbxi_check(min_index < uc->obj.tmp_vertices[attrib].num_items / stride);
17322
17323 size_t count = uc->obj.tmp_vertices[attrib].num_items - (size_t)min_index * stride;
17324 ufbx_real *data = ufbxi_push(&uc->result, ufbx_real, count + 4);
17325 ufbxi_check(data);
17326
17327 data[0] = 0.0f;
17328 data[1] = 0.0f;
17329 data[2] = 0.0f;
17330 data[3] = 0.0f;
17331 data += 4;
17332
17333 ufbxi_pop(&uc->obj.tmp_vertices[attrib], ufbx_real, count, data);
17334
17335 dst->data = data;
17336 dst->count = count;
17337 return 1;
17338 }
17339
17340 ufbxi_nodiscard static ufbxi_noinline int ufbxi_obj_setup_attrib(ufbxi_context *uc, ufbxi_obj_mesh *mesh, uint64_t *tmp_indices,
17341 ufbx_vertex_attrib *dst, const ufbx_real_list *p_data, uint32_t attrib, bool non_disjoint, bool required)
17342 {
17343 ufbx_real_list data = *p_data;
17344
17345 size_t num_indices = mesh->num_indices;
17346 size_t stride = ufbxi_obj_attrib_stride[attrib];
17347 size_t num_values = data.count / stride;
17348
17349 uint64_t mesh_min_ix = mesh->vertex_range[attrib].min_ix;
17350 if (num_indices == 0 || num_values == 0 || mesh_min_ix == UINT64_MAX) {
17351 ufbxi_check(num_indices == 0 || !required);
17352
17353 // Pop indices without copying if the attribute is not used
17354 ufbxi_pop(&uc->obj.tmp_indices[attrib], uint64_t, num_indices, NULL);
17355 return 1;
17356 }
17357
17358 uint64_t min_index = non_disjoint ? 0 : mesh_min_ix;
17359
17360 ufbxi_pop(&uc->obj.tmp_indices[attrib], uint64_t, num_indices, tmp_indices);
17361
17362 uint32_t *dst_indices = ufbxi_push(&uc->result, uint32_t, num_indices);
17363 ufbxi_check(dst_indices);
17364
17365 dst->exists = true;
17366
17367 dst->values.data = data.data;
17368 dst->values.count = num_values;
17369
17370 dst->indices.data = dst_indices;
17371 dst->indices.count = num_indices;
17372
17373 ufbxi_nounroll for (size_t i = 0; i < num_indices; i++) {
17374 uint64_t ix = tmp_indices[i];
17375 if (ix != UINT64_MAX) {
17376 ix -= min_index;
17377 ufbxi_check(ix < UINT32_MAX);
17378 }
17379 if (ix < num_values) {
17380 dst_indices[i] = (uint32_t)ix;
17381 } else {
17382 ufbxi_check(ufbxi_fix_index(uc, &dst_indices[i], (uint32_t)ix, num_values));
17383 }
17384 }
17385
17386 return 1;
17387 }
17388
17389 ufbxi_nodiscard static ufbxi_noinline int ufbxi_obj_pad_colors(ufbxi_context *uc, size_t num_vertices)
17390 {
17391 if (uc->opts.ignore_geometry) return 1;
17392
17393 size_t num_colors = uc->obj.vertex_count[UFBXI_OBJ_ATTRIB_COLOR];
17394 if (num_vertices > num_colors) {
17395 size_t num_pad = num_vertices - num_colors;
17396 ufbxi_check(ufbxi_push_zero(&uc->obj.tmp_vertices[UFBXI_OBJ_ATTRIB_COLOR], ufbx_real, num_pad * 4));
17397 ufbxi_check(ufbxi_push_zero(&uc->obj.tmp_color_valid, bool, num_pad));
17398 uc->obj.vertex_count[UFBXI_OBJ_ATTRIB_COLOR] += num_pad;
17399 }
17400
17401 return 1;
17402 }
17403
17404 ufbxi_nodiscard static ufbxi_noinline int ufbxi_obj_pop_meshes(ufbxi_context *uc)
17405 {
17406 size_t num_meshes = uc->obj.tmp_meshes.num_items;
17407 ufbxi_obj_mesh *meshes = ufbxi_push_pop(&uc->tmp, &uc->obj.tmp_meshes, ufbxi_obj_mesh, num_meshes);
17408 ufbxi_check(meshes);
17409
17410 if (uc->obj.has_vertex_color) {
17411 ufbxi_check(ufbxi_obj_pad_colors(uc, uc->obj.vertex_count[UFBXI_OBJ_ATTRIB_POSITION]));
17412 }
17413
17414 // Pop unused fast indices
17415 for (size_t i = 0; i < UFBXI_OBJ_NUM_ATTRIBS; i++) {
17416 ufbxi_pop(&uc->obj.tmp_indices[i], uint64_t, uc->obj.fast_indices[i].num_left, NULL);
17417 }
17418
17419 // Check if the file has disjoint vertices
17420 bool non_disjoint[UFBXI_OBJ_NUM_ATTRIBS] = { 0 };
17421 uint64_t next_min[UFBXI_OBJ_NUM_ATTRIBS] = { 0 };
17422 ufbx_real_list vertices[UFBXI_OBJ_NUM_ATTRIBS_EXT] = { 0 };
17423 bool *color_valid = NULL;
17424
17425 size_t max_indices = 0;
17426
17427 for (size_t i = 0; i < num_meshes; i++) {
17428 ufbxi_obj_mesh *mesh = &meshes[i];
17429 max_indices = ufbxi_max_sz(max_indices, mesh->num_indices);
17430 ufbxi_nounroll for (uint32_t attrib = 0; attrib < UFBXI_OBJ_NUM_ATTRIBS; attrib++) {
17431 ufbxi_obj_index_range range = mesh->vertex_range[attrib];
17432 if (range.min_ix > range.max_ix) continue;
17433 if (range.min_ix < next_min[attrib]) {
17434 non_disjoint[attrib] = true;
17435 }
17436 next_min[attrib] = range.max_ix + 1;
17437 }
17438 }
17439
17440 uint64_t *tmp_indices = ufbxi_push(&uc->tmp, uint64_t, max_indices);
17441 ufbxi_check(tmp_indices);
17442
17443 ufbxi_nounroll for (uint32_t attrib = 0; attrib < UFBXI_OBJ_NUM_ATTRIBS; attrib++) {
17444 if (!non_disjoint[attrib]) continue;
17445 ufbxi_check(ufbxi_obj_pop_vertices(uc, &vertices[attrib], attrib, 0));
17446 }
17447 if (uc->obj.has_vertex_color && non_disjoint[UFBXI_OBJ_ATTRIB_POSITION]) {
17448 ufbxi_check(ufbxi_obj_pop_vertices(uc, &vertices[UFBXI_OBJ_ATTRIB_COLOR], UFBXI_OBJ_ATTRIB_COLOR, 0));
17449 color_valid = ufbxi_push_pop(&uc->tmp, &uc->obj.tmp_color_valid, bool, vertices[UFBXI_OBJ_ATTRIB_COLOR].count / 4);
17450 ufbxi_check(color_valid);
17451 }
17452
17453 for (size_t i = num_meshes; i > 0; i--) {
17454 ufbxi_obj_mesh *mesh = &meshes[i - 1];
17455
17456 ufbx_mesh *fbx_mesh = mesh->fbx_mesh;
17457
17458 size_t num_faces = mesh->num_faces;
17459
17460 if (!uc->opts.ignore_geometry) {
17461 ufbxi_nounroll for (uint32_t attrib = 0; attrib < UFBXI_OBJ_NUM_ATTRIBS; attrib++) {
17462 if (non_disjoint[attrib]) continue;
17463 uint64_t min_ix = mesh->vertex_range[attrib].min_ix;
17464 if (min_ix < UINT64_MAX) {
17465 ufbxi_check(ufbxi_obj_pop_vertices(uc, &vertices[attrib], attrib, min_ix));
17466 }
17467 }
17468 if (uc->obj.has_vertex_color && !non_disjoint[UFBXI_OBJ_ATTRIB_POSITION]) {
17469 uint64_t min_ix = mesh->vertex_range[UFBXI_OBJ_ATTRIB_POSITION].min_ix;
17470 ufbxi_check(min_ix < UINT64_MAX);
17471 ufbxi_check(ufbxi_obj_pop_vertices(uc, &vertices[UFBXI_OBJ_ATTRIB_COLOR], UFBXI_OBJ_ATTRIB_COLOR, min_ix));
17472 color_valid = ufbxi_push_pop(&uc->tmp, &uc->obj.tmp_color_valid, bool, vertices[UFBXI_OBJ_ATTRIB_COLOR].count / 4);
17473 ufbxi_check(color_valid);
17474 }
17475
17476 fbx_mesh->faces.count = num_faces;
17477 fbx_mesh->face_material.count = num_faces;
17478
17479 fbx_mesh->faces.data = ufbxi_push_pop(&uc->result, &uc->obj.tmp_faces, ufbx_face, num_faces);
17480 fbx_mesh->face_material.data = ufbxi_push_pop(&uc->result, &uc->obj.tmp_face_material, uint32_t, num_faces);
17481
17482 ufbxi_check(fbx_mesh->faces.data);
17483 ufbxi_check(fbx_mesh->face_material.data);
17484
17485 if (uc->obj.has_face_smoothing) {
17486 fbx_mesh->face_smoothing.count = num_faces;
17487 fbx_mesh->face_smoothing.data = ufbxi_push_pop(&uc->result, &uc->obj.tmp_face_smoothing, bool, num_faces);
17488 ufbxi_check(fbx_mesh->face_smoothing.data);
17489 }
17490
17491 if (uc->obj.has_face_group) {
17492 if (mesh->num_groups > 1) {
17493 fbx_mesh->face_group.count = num_faces;
17494 fbx_mesh->face_group.data = ufbxi_push_pop(&uc->result, &uc->obj.tmp_face_group, uint32_t, num_faces);
17495 ufbxi_check(fbx_mesh->face_group.data);
17496 } else {
17497 ufbxi_pop(&uc->obj.tmp_face_group, uint32_t, num_faces, NULL);
17498 }
17499 }
17500
17501 ufbxi_check(ufbxi_obj_setup_attrib(uc, mesh, tmp_indices, (ufbx_vertex_attrib*)&fbx_mesh->vertex_position,
17502 &vertices[UFBXI_OBJ_ATTRIB_POSITION], UFBXI_OBJ_ATTRIB_POSITION, non_disjoint[UFBXI_OBJ_ATTRIB_POSITION], true));
17503
17504 ufbxi_check(ufbxi_obj_setup_attrib(uc, mesh, tmp_indices, (ufbx_vertex_attrib*)&fbx_mesh->vertex_uv,
17505 &vertices[UFBXI_OBJ_ATTRIB_UV], UFBXI_OBJ_ATTRIB_UV, non_disjoint[UFBXI_OBJ_ATTRIB_UV], false));
17506
17507 ufbxi_check(ufbxi_obj_setup_attrib(uc, mesh, tmp_indices, (ufbx_vertex_attrib*)&fbx_mesh->vertex_normal,
17508 &vertices[UFBXI_OBJ_ATTRIB_NORMAL], UFBXI_OBJ_ATTRIB_NORMAL, non_disjoint[UFBXI_OBJ_ATTRIB_NORMAL], false));
17509
17510 if (uc->obj.has_vertex_color) {
17511 ufbx_assert(color_valid);
17512 bool has_color = false;
17513 bool all_valid = true;
17514 size_t max_index = fbx_mesh->vertex_position.values.count;
17515 ufbxi_for_list(uint32_t, p_ix, fbx_mesh->vertex_position.indices) {
17516 if (*p_ix < max_index) {
17517 if (color_valid[*p_ix]) {
17518 has_color = true;
17519 } else {
17520 all_valid = false;
17521 }
17522 }
17523 }
17524
17525 if (has_color) {
17526 fbx_mesh->vertex_color.exists = true;
17527 fbx_mesh->vertex_color.values.data = (ufbx_vec4*)vertices[UFBXI_OBJ_ATTRIB_COLOR].data;
17528 fbx_mesh->vertex_color.values.count = vertices[UFBXI_OBJ_ATTRIB_COLOR].count / 4;
17529 fbx_mesh->vertex_color.indices = fbx_mesh->vertex_position.indices;
17530 fbx_mesh->vertex_color.unique_per_vertex = true;
17531
17532 if (!all_valid) {
17533 uint32_t *indices = fbx_mesh->vertex_color.indices.data;
17534 indices = ufbxi_push_copy(&uc->result, uint32_t, mesh->num_indices, indices);
17535 ufbxi_check(indices);
17536
17537 size_t num_values = fbx_mesh->vertex_color.values.count;
17538 ufbxi_for(uint32_t, p_ix, indices, mesh->num_indices) {
17539 if (*p_ix >= num_values || !color_valid[*p_ix]) {
17540 ufbxi_check(ufbxi_fix_index(uc, p_ix, *p_ix, num_values));
17541 }
17542 }
17543
17544 fbx_mesh->vertex_color.indices.data = indices;
17545 }
17546 }
17547 }
17548 }
17549
17550 ufbxi_check(ufbxi_finalize_mesh(&uc->result, &uc->error, fbx_mesh));
17551
17552 if (uc->retain_mesh_parts) {
17553 fbx_mesh->face_group_parts.count = mesh->num_groups;
17554 fbx_mesh->face_group_parts.data = ufbxi_push_zero(&uc->result, ufbx_mesh_part, mesh->num_groups);
17555 ufbxi_check(fbx_mesh->face_group_parts.data);
17556 }
17557
17558 if (mesh->num_groups > 1) {
17559 ufbxi_check(ufbxi_update_face_groups(&uc->result, &uc->error, fbx_mesh, false));
17560 } else if (mesh->num_groups == 1) {
17561 fbx_mesh->face_group.data = (uint32_t*)ufbxi_sentinel_index_zero;
17562 fbx_mesh->face_group.count = num_faces;
17563 // NOTE: Consecutive and zero indices are always allocated so we can skip doing it here,
17564 // see HACK(consecutiv-faces)..
17565 if (fbx_mesh->face_group_parts.count > 0) {
17566 ufbx_mesh_part *part = &fbx_mesh->face_group_parts.data[0];
17567 part->num_faces = fbx_mesh->num_faces;
17568 part->num_faces = num_faces;
17569 part->num_empty_faces = fbx_mesh->num_empty_faces;
17570 part->num_point_faces = fbx_mesh->num_point_faces;
17571 part->num_line_faces = fbx_mesh->num_line_faces;
17572 part->num_triangles = fbx_mesh->num_triangles;
17573 part->face_indices.data = (uint32_t*)ufbxi_sentinel_index_consecutive;
17574 part->face_indices.count = num_faces;
17575 }
17576 }
17577
17578 // HACK(consecutive-faces): Prepare for finalize to re-use a consecutive/zero
17579 // index buffer for face materials..
17580 uc->max_zero_indices = ufbxi_max_sz(uc->max_zero_indices, num_faces);
17581 uc->max_consecutive_indices = ufbxi_max_sz(uc->max_consecutive_indices, num_faces);
17582 }
17583
17584 return 1;
17585 }
17586
17587 ufbxi_nodiscard static ufbxi_noinline int ufbxi_obj_parse_file(ufbxi_context *uc)
17588 {
17589 while (!uc->obj.eof) {
17590 ufbxi_check(ufbxi_obj_tokenize_line(uc));
17591 size_t num_tokens = uc->obj.num_tokens;
17592 if (num_tokens == 0) continue;
17593
17594 ufbx_string cmd = uc->obj.tokens[0];
17595 uint32_t key = ufbxi_get_name_key(cmd.data, cmd.length);
17596 if (key == ufbxi_obj_cmd1('v')) {
17597 ufbxi_check(ufbxi_obj_parse_vertex(uc, UFBXI_OBJ_ATTRIB_POSITION, 1));
17598 if (num_tokens >= 7) {
17599 size_t num_vertices = uc->obj.vertex_count[UFBXI_OBJ_ATTRIB_POSITION];
17600 uc->obj.has_vertex_color = true;
17601 ufbxi_check(ufbxi_obj_pad_colors(uc, num_vertices - 1));
17602 if (uc->obj.vertex_count[UFBXI_OBJ_ATTRIB_COLOR] < num_vertices) {
17603 ufbx_assert(uc->obj.vertex_count[UFBXI_OBJ_ATTRIB_COLOR] == num_vertices - 1);
17604 ufbxi_check(ufbxi_obj_parse_vertex(uc, UFBXI_OBJ_ATTRIB_COLOR, 4));
17605 bool *valid = ufbxi_push(&uc->obj.tmp_color_valid, bool, 1);
17606 ufbxi_check(valid);
17607 *valid = true;
17608 }
17609 }
17610 } else if (key == ufbxi_obj_cmd2('v','t')) {
17611 ufbxi_check(ufbxi_obj_parse_vertex(uc, UFBXI_OBJ_ATTRIB_UV, 1));
17612 } else if (key == ufbxi_obj_cmd2('v','n')) {
17613 ufbxi_check(ufbxi_obj_parse_vertex(uc, UFBXI_OBJ_ATTRIB_NORMAL, 1));
17614 } else if (key == ufbxi_obj_cmd1('f')) {
17615 ufbxi_check(ufbxi_obj_parse_indices(uc, 1, uc->obj.num_tokens - 1));
17616 } else if (key == ufbxi_obj_cmd1('p')) {
17617 ufbxi_check(ufbxi_obj_parse_multi_indices(uc, 1));
17618 } else if (key == ufbxi_obj_cmd1('l')) {
17619 ufbxi_check(ufbxi_obj_parse_multi_indices(uc, 2));
17620 } else if (key == ufbxi_obj_cmd1('s')) {
17621 if (num_tokens >= 2) {
17622 uc->obj.has_face_smoothing = true;
17623 uc->obj.face_smoothing = !ufbxi_str_equal(uc->obj.tokens[1], ufbxi_str_c("off"));
17624
17625 // Fill in previously missed face smoothing data
17626 if (uc->obj.tmp_face_smoothing.num_items == 0 && uc->obj.tmp_faces.num_items > 0) {
17627 ufbxi_check(ufbxi_push_zero(&uc->obj.tmp_face_smoothing, bool, uc->obj.tmp_faces.num_items));
17628 }
17629 }
17630 } else if (key == ufbxi_obj_cmd1('o')) {
17631 if (num_tokens >= 2) {
17632 uc->obj.object = ufbxi_obj_span_token(uc, 1, SIZE_MAX);
17633 ufbxi_check(ufbxi_push_string_place_str(&uc->string_pool, &uc->obj.object, false));
17634 uc->obj.object_dirty = true;
17635 }
17636 } else if (key == ufbxi_obj_cmd1('g')) {
17637 if (num_tokens >= 2) {
17638 uc->obj.group = ufbxi_obj_span_token(uc, 1, SIZE_MAX);
17639 ufbxi_check(ufbxi_push_string_place_str(&uc->string_pool, &uc->obj.group, false));
17640 uc->obj.group_dirty = true;
17641 } else {
17642 uc->obj.group = ufbx_empty_string;
17643 uc->obj.group_dirty = true;
17644 }
17645 } else if (key == ufbxi_obj_cmd1('#')) {
17646 ufbxi_check(ufbxi_obj_parse_comment(uc));
17647 } else if (ufbxi_str_equal(cmd, ufbxi_str_c("mtllib"))) {
17648 ufbxi_check(uc->obj.num_tokens >= 2);
17649 ufbx_string lib = ufbxi_obj_span_token(uc, 1, SIZE_MAX);
17650 lib.data = ufbxi_push_copy(&uc->tmp, char, lib.length + 1, lib.data);
17651 ufbxi_check(lib.data);
17652 uc->obj.mtllib_relative_path.data = lib.data;
17653 uc->obj.mtllib_relative_path.size = lib.length;
17654 } else if (ufbxi_str_equal(cmd, ufbxi_str_c("usemtl"))) {
17655 ufbxi_check(ufbxi_obj_parse_material(uc));
17656 } else if (!uc->opts.disable_quirks && key == 0) {
17657 // ZBrush exporter seems to end the files with '\0', sometimes..
17658 } else {
17659 ufbxi_check(ufbxi_warnf(UFBX_WARNING_UNKNOWN_OBJ_DIRECTIVE, "Unknown .obj directive, skipped line"));
17660 }
17661 }
17662
17663 ufbxi_check(ufbxi_obj_flush_mesh(uc));
17664 ufbxi_check(ufbxi_obj_pop_meshes(uc));
17665
17666 return 1;
17667 }
17668
17669 ufbxi_nodiscard static ufbxi_noinline int ufbxi_obj_flush_material(ufbxi_context *uc)
17670 {
17671 if (uc->obj.usemtl_fbx_id == 0) return 1;
17672
17673 ufbxi_fbx_id_entry *entry = ufbxi_find_fbx_id(uc, uc->obj.usemtl_fbx_id);
17674 ufbx_assert(entry);
17675 ufbx_material *material = uc->obj.tmp_materials[entry->element_id];
17676
17677 size_t num_props = uc->obj.tmp_props.num_items;
17678 ufbxi_check(ufbxi_obj_pop_props(uc, &material->props.props, num_props));
17679
17680 return 1;
17681 }
17682
17683 ufbxi_nodiscard static ufbxi_noinline int ufbxi_obj_parse_prop(ufbxi_context *uc, ufbx_string name, size_t start, bool include_rest, size_t *p_next)
17684 {
17685 if (start >= uc->obj.num_tokens) {
17686 if (p_next) {
17687 *p_next = start;
17688 }
17689 return 1;
17690 }
17691
17692 ufbx_prop *prop = ufbxi_push_zero(&uc->obj.tmp_props, ufbx_prop, 1);
17693 ufbxi_check(prop);
17694 prop->name = name;
17695
17696 ufbxi_check(ufbxi_push_string_place_str(&uc->string_pool, &prop->name, false));
17697
17698 uint32_t flags = UFBX_PROP_FLAG_VALUE_STR;
17699
17700 size_t num_reals = 0;
17701 for (; num_reals < 4; num_reals++) {
17702 if (start + num_reals >= uc->obj.num_tokens) break;
17703 ufbx_string tok = uc->obj.tokens[start + num_reals];
17704
17705 char *end; // ufbxi_uninit
17706 double val = ufbxi_parse_double(tok.data, tok.length, &end, uc->double_parse_flags);
17707 if (end != tok.data + tok.length) break;
17708
17709 prop->value_real_arr[num_reals] = (ufbx_real)val;
17710 if (num_reals == 0) {
17711 prop->value_int = ufbxi_f64_to_i64(val);
17712 flags |= UFBX_PROP_FLAG_VALUE_INT;
17713 }
17714 }
17715
17716 size_t num_args = 0;
17717 if (!include_rest) {
17718 for (; start + num_args < uc->obj.num_tokens - 1; num_args++) {
17719 if (ufbxi_match(&uc->obj.tokens[start + num_args], "-[A-Za-z][\\-A-Za-z0-9_]*")) break;
17720 }
17721 }
17722
17723 if (num_args > 0 || include_rest) {
17724 ufbx_string span = ufbxi_obj_span_token(uc, start, include_rest ? SIZE_MAX : start + num_args - 1);
17725 prop->value_str = span;
17726 prop->value_blob.data = span.data;
17727 prop->value_blob.size = span.length;
17728
17729 ufbxi_check(ufbxi_push_string_place_str(&uc->string_pool, &prop->value_str, false));
17730 ufbxi_check(ufbxi_push_string_place_blob(&uc->string_pool, &prop->value_blob, true));
17731 } else {
17732 prop->value_str.data = ufbxi_empty_char;
17733 }
17734
17735 if (num_reals > 0) {
17736 flags = (uint32_t)UFBX_PROP_FLAG_VALUE_REAL << (num_reals - 1);
17737 } else {
17738 if (!strcmp(prop->value_str.data, "on")) {
17739 prop->value_int = 1;
17740 prop->value_real = 1.0f;
17741 flags |= UFBX_PROP_FLAG_VALUE_INT;
17742 } else if (!strcmp(prop->value_str.data, "off")) {
17743 prop->value_int = 0;
17744 prop->value_real = 0.0f;
17745 flags |= UFBX_PROP_FLAG_VALUE_INT;
17746 }
17747 }
17748
17749 prop->flags = (ufbx_prop_flags)flags;
17750
17751 if (p_next) {
17752 *p_next = start + num_args;
17753 }
17754
17755 return 1;
17756 }
17757
17758 ufbxi_nodiscard static ufbxi_noinline int ufbxi_obj_parse_mtl_map(ufbxi_context *uc, size_t prefix_len)
17759 {
17760 if (uc->obj.num_tokens < 2) return 1;
17761
17762 size_t num_props = 1;
17763 ufbxi_check(ufbxi_obj_parse_prop(uc, ufbxi_str_c("obj|args"), 1, true, NULL));
17764
17765 size_t start = 1;
17766 for (; start + 1 < uc->obj.num_tokens; ) {
17767 ufbx_string tok = uc->obj.tokens[start];
17768 if (ufbxi_match(&tok, "-[A-Za-z][\\-A-Za-z0-9_]*")) {
17769 tok.data += 1;
17770 tok.length -= 1;
17771 ufbxi_check(ufbxi_obj_parse_prop(uc, tok, start + 1, false, &start));
17772 num_props++;
17773 } else {
17774 break;
17775 }
17776 }
17777
17778 ufbx_string tex_str = ufbxi_obj_span_token(uc, start, SIZE_MAX);
17779 ufbx_blob tex_raw = { tex_str.data, tex_str.length };
17780
17781 ufbxi_check(ufbxi_push_string_place_str(&uc->string_pool, &tex_str, false));
17782 ufbxi_check(ufbxi_push_string_place_blob(&uc->string_pool, &tex_raw, true));
17783
17784 uint64_t fbx_id = 0;
17785 ufbx_texture *texture = ufbxi_push_synthetic_element(uc, &fbx_id, NULL, "", ufbx_texture, UFBX_ELEMENT_TEXTURE);
17786 ufbxi_check(texture);
17787
17788 texture->filename.data = ufbxi_empty_char;
17789 texture->absolute_filename.data = ufbxi_empty_char;
17790 texture->uv_set.data = ufbxi_empty_char;
17791
17792 texture->relative_filename = tex_str;
17793 texture->raw_relative_filename = tex_raw;
17794
17795 ufbxi_check(ufbxi_obj_pop_props(uc, &texture->props.props, num_props));
17796
17797 ufbx_string prop = uc->obj.tokens[0];
17798 ufbx_assert(prop.length >= prefix_len);
17799 prop.data += prefix_len;
17800 prop.length -= prefix_len;
17801 ufbxi_check(ufbxi_push_string_place_str(&uc->string_pool, &prop, false));
17802
17803 if (uc->obj.usemtl_fbx_id != 0) {
17804 ufbxi_check(ufbxi_connect_op(uc, fbx_id, uc->obj.usemtl_fbx_id, prop));
17805 }
17806
17807 return 1;
17808 }
17809
17810 ufbxi_nodiscard static ufbxi_noinline int ufbxi_obj_parse_mtl(ufbxi_context *uc)
17811 {
17812 uc->obj.mesh = NULL;
17813 uc->obj.usemtl_fbx_id = 0;
17814
17815 while (!uc->obj.eof) {
17816 ufbxi_check(ufbxi_obj_tokenize_line(uc));
17817 size_t num_tokens = uc->obj.num_tokens;
17818 if (num_tokens == 0) continue;
17819
17820 ufbx_string cmd = uc->obj.tokens[0];
17821 if (ufbxi_str_equal(cmd, ufbxi_str_c("newmtl"))) {
17822 // HACK: Reuse mesh material parsing, but don't allow for empty material name
17823 ufbxi_check(uc->obj.num_tokens >= 2);
17824 ufbxi_check(ufbxi_obj_flush_material(uc));
17825 ufbxi_check(ufbxi_obj_parse_material(uc));
17826 } else if (cmd.length > 4 && !memcmp(cmd.data, "map_", 4)) {
17827 ufbxi_check(ufbxi_obj_parse_mtl_map(uc, 4));
17828 } else if (cmd.length == 4 && (!memcmp(cmd.data, "bump", 4) || !memcmp(cmd.data, "disp", 4) || !memcmp(cmd.data, "norm", 4))) {
17829 ufbxi_check(ufbxi_obj_parse_mtl_map(uc, 0));
17830 } else if (cmd.length == 1 && cmd.data[0] == '#') {
17831 // Implement .mtl magic comment handling here if necessary
17832 } else {
17833 ufbxi_check(ufbxi_obj_parse_prop(uc, uc->obj.tokens[0], 1, true, NULL));
17834 }
17835 }
17836
17837 ufbxi_check(ufbxi_obj_flush_material(uc));
17838
17839 return 1;
17840 }
17841
17842 ufbxi_nodiscard static ufbxi_noinline int ufbxi_obj_load_mtl(ufbxi_context *uc)
17843 {
17844 // HACK: Reset everything and switch to loading the .mtl file globally
17845 if (uc->close_fn) {
17846 uc->close_fn(uc->read_user);
17847 }
17848
17849 uc->read_fn = NULL;
17850 uc->close_fn = NULL;
17851 uc->read_user = NULL;
17852 uc->data_begin = NULL;
17853 uc->data = NULL;
17854 uc->data_size = 0;
17855 uc->yield_size = 0;
17856 uc->eof = false;
17857 uc->obj.eof = false;
17858
17859 if (uc->opts.obj_mtl_data.size > 0) {
17860 uc->data_begin = uc->data = (const char*)uc->opts.obj_mtl_data.data;
17861 uc->data_size = uc->opts.obj_mtl_data.size;
17862 ufbxi_check(ufbxi_obj_parse_mtl(uc));
17863 return 1;
17864 }
17865
17866 ufbx_stream stream = { 0 };
17867 bool has_stream = false;
17868 bool needs_stream = false;
17869 ufbx_blob stream_path = { 0 };
17870
17871 if (uc->opts.open_file_cb.fn) {
17872 if (uc->opts.obj_mtl_path.length > 0) {
17873 has_stream = ufbxi_open_file(&uc->opts.open_file_cb, &stream, uc->opts.obj_mtl_path.data, uc->opts.obj_mtl_path.length, NULL, &uc->ator_tmp, UFBX_OPEN_FILE_OBJ_MTL);
17874 stream_path.data = uc->opts.obj_mtl_path.data;
17875 stream_path.size = uc->opts.obj_mtl_path.length;
17876 needs_stream = true;
17877 if (!has_stream) {
17878 ufbxi_check(ufbxi_warnf(UFBX_WARNING_MISSING_EXTERNAL_FILE, "Could not open .mtl file: %s", uc->opts.obj_mtl_path.data));
17879 }
17880 }
17881
17882 if (!has_stream && uc->opts.load_external_files && uc->obj.mtllib_relative_path.size > 0) {
17883 ufbx_blob dst; // ufbxi_uninit
17884 ufbxi_check(ufbxi_resolve_relative_filename(uc, (ufbxi_strblob*)&dst, (const ufbxi_strblob*)&uc->obj.mtllib_relative_path, true));
17885 has_stream = ufbxi_open_file(&uc->opts.open_file_cb, &stream, (const char*)dst.data, dst.size, &uc->obj.mtllib_relative_path, &uc->ator_tmp, UFBX_OPEN_FILE_OBJ_MTL);
17886 stream_path = uc->obj.mtllib_relative_path;
17887 needs_stream = true;
17888 if (!has_stream) {
17889 ufbxi_check(ufbxi_warnf(UFBX_WARNING_MISSING_EXTERNAL_FILE, "Could not open .mtl file: %s", dst.data));
17890 }
17891 }
17892
17893 ufbx_string path = uc->scene.metadata.filename;
17894 if (!has_stream && uc->opts.load_external_files && uc->opts.obj_search_mtl_by_filename && path.length > 4) {
17895 ufbx_string ext = { path.data + path.length - 4, 4 };
17896 if (ufbxi_match(&ext, "\\c.obj")) {
17897 ufbxi_analysis_assert(path.length < SIZE_MAX - 1);
17898 char *copy = ufbxi_push_copy(&uc->tmp, char, path.length + 1, path.data);
17899 ufbxi_check(copy);
17900 copy[path.length - 3] = copy[path.length - 3] == 'O' ? 'M' : 'm';
17901 copy[path.length - 2] = copy[path.length - 2] == 'B' ? 'T' : 't';
17902 copy[path.length - 1] = copy[path.length - 1] == 'J' ? 'L' : 'l';
17903 has_stream = ufbxi_open_file(&uc->opts.open_file_cb, &stream, copy, path.length, NULL, &uc->ator_tmp, UFBX_OPEN_FILE_OBJ_MTL);
17904 if (has_stream) {
17905 ufbxi_check(ufbxi_warnf(UFBX_WARNING_IMPLICIT_MTL, "Opened .mtl file derived from .obj filename: %s", copy));
17906 }
17907 }
17908 }
17909 }
17910
17911 if (has_stream) {
17912 // Adopt `stream` to ufbx read callbacks
17913 uc->read_fn = stream.read_fn;
17914 uc->close_fn = stream.close_fn;
17915 uc->read_user = stream.user;
17916
17917 int ok = ufbxi_obj_parse_mtl(uc);
17918
17919 if (uc->close_fn) {
17920 uc->close_fn(uc->read_user);
17921 }
17922 uc->read_fn = NULL;
17923 uc->close_fn = NULL;
17924 uc->read_user = NULL;
17925
17926 ufbxi_check(ok);
17927 } else if (needs_stream && !uc->opts.ignore_missing_external_files) {
17928 ufbxi_set_err_info(&uc->error, (const char*)stream_path.data, stream_path.size);
17929 ufbxi_fail_msg("ufbxi_obj_load_mtl()", "External file not found");
17930 }
17931
17932 return 1;
17933 }
17934
17935 ufbxi_nodiscard static ufbxi_noinline int ufbxi_obj_load(ufbxi_context *uc)
17936 {
17937 ufbxi_check(ufbxi_obj_init(uc));
17938 ufbxi_check(ufbxi_obj_parse_file(uc));
17939 ufbxi_check(ufbxi_init_file_paths(uc));
17940 ufbxi_check(ufbxi_obj_load_mtl(uc));
17941
17942 return 1;
17943 }
17944
17945 ufbxi_nodiscard static ufbxi_noinline int ufbxi_mtl_load(ufbxi_context *uc)
17946 {
17947 ufbxi_check(ufbxi_obj_init(uc));
17948 ufbxi_check(ufbxi_init_file_paths(uc));
17949 ufbxi_check(ufbxi_obj_parse_mtl(uc));
17950
17951 return 1;
17952 }
17953
17954 #else
17955 ufbxi_nodiscard static ufbxi_forceinline int ufbxi_obj_load(ufbxi_context *uc)
17956 {
17957 ufbxi_fmt_err_info(&uc->error, "UFBX_ENABLE_FORMAT_OBJ");
17958 ufbxi_fail_msg("UFBXI_FEATURE_FORMAT_OBJ", "Feature disabled");
17959 }
17960
17961 ufbxi_nodiscard static ufbxi_forceinline int ufbxi_mtl_load(ufbxi_context *uc)
17962 {
17963 ufbxi_fmt_err_info(&uc->error, "UFBX_ENABLE_FORMAT_OBJ");
17964 ufbxi_fail_msg("UFBXI_FEATURE_FORMAT_OBJ", "Feature disabled");
17965 }
17966
17967 static ufbxi_forceinline void ufbxi_obj_free(ufbxi_context *uc)
17968 {
17969 }
17970 #endif
17971
17972 // -- Scene pre-processing
17973
17974 typedef struct {
17975 ufbx_element *src, *dst;
17976 } ufbxi_pre_connection;
17977
17978 typedef struct {
17979 bool has_constant_scale;
17980 bool has_recursive_scale_helper;
17981 bool has_skin_deformer;
17982 ufbx_vec3 constant_scale;
17983 uint32_t element_id;
17984 uint32_t first_child;
17985 uint32_t next_child;
17986 uint32_t parent;
17987 } ufbxi_pre_node;
17988
17989 typedef struct {
17990 bool has_skin_deformer;
17991 } ufbxi_pre_mesh;
17992
17993 typedef struct {
17994 bool has_constant_value;
17995 ufbx_vec3 constant_value;
17996 } ufbxi_pre_anim_value;
17997
17998 static bool ufbxi_pivot_nonzero(ufbx_vec3 offset)
17999 {
18000 // TODO: Expose this as a setting?
18001 const double epsilon = 0.0009765625;
18002 return ufbx_fabs(offset.x) >= epsilon || ufbx_fabs(offset.y) >= epsilon || ufbx_fabs(offset.z) >= epsilon;
18003 }
18004
18005 static ufbx_real ufbxi_pivot_div(ufbx_real offset, ufbx_real initial_scale)
18006 {
18007 const double epsilon = 0.0078125;
18008 if (ufbx_fabs(initial_scale) >= epsilon) {
18009 return offset / initial_scale;
18010 } else {
18011 return offset;
18012 }
18013 }
18014
18015 // Called between parsing and `ufbxi_finalize_scene()`.
18016 // This is a very messy function reminiscent of the _old_ ufbx, where we do
18017 // multiple passes over connections without having a proper scene graph.
18018 // This, however gives us the advantage of allowing us to modify elements
18019 // and connections. We can, for example, add new helper nodes and redirect
18020 // animated properties from source nodes to the helpers. The rest of ufbx
18021 // will treat these as if they were a part of the source file.
18022 ufbxi_nodiscard ufbxi_noinline static int ufbxi_pre_finalize_scene(ufbxi_context *uc)
18023 {
18024 bool required = false;
18025 if (uc->opts.geometry_transform_handling == UFBX_GEOMETRY_TRANSFORM_HANDLING_HELPER_NODES || uc->opts.geometry_transform_handling == UFBX_GEOMETRY_TRANSFORM_HANDLING_MODIFY_GEOMETRY) required = true;
18026 if (uc->opts.inherit_mode_handling == UFBX_INHERIT_MODE_HANDLING_HELPER_NODES || uc->opts.inherit_mode_handling == UFBX_INHERIT_MODE_HANDLING_COMPENSATE || uc->opts.inherit_mode_handling == UFBX_INHERIT_MODE_HANDLING_COMPENSATE_NO_FALLBACK) required = true;
18027 if (uc->opts.pivot_handling == UFBX_PIVOT_HANDLING_ADJUST_TO_PIVOT || uc->opts.pivot_handling == UFBX_PIVOT_HANDLING_ADJUST_TO_ROTATION_PIVOT) required = true;
18028 #if defined(UFBX_REGRESSION)
18029 required = true;
18030 #endif
18031
18032 if (!required) return 1;
18033
18034 uint32_t num_elements = uc->num_elements;
18035 size_t num_nodes = uc->tmp_node_ids.num_items;
18036 ufbx_element **elements = ufbxi_push_pop(&uc->tmp_parse, &uc->tmp_element_ptrs, ufbx_element*, num_elements);
18037 ufbxi_check(elements);
18038
18039 size_t num_connections = uc->tmp_connections.num_items;
18040 ufbxi_tmp_connection *tmp_connections = ufbxi_push_peek(&uc->tmp_parse, &uc->tmp_connections, ufbxi_tmp_connection, num_connections);
18041 ufbxi_check(tmp_connections);
18042
18043 ufbxi_pre_connection *pre_connections = ufbxi_push(&uc->tmp_parse, ufbxi_pre_connection, num_connections);
18044 ufbxi_check(pre_connections);
18045
18046 uint32_t *instance_counts = ufbxi_push_zero(&uc->tmp_parse, uint32_t, num_elements);
18047 ufbxi_check(instance_counts);
18048
18049 bool *modify_not_supported = ufbxi_push_zero(&uc->tmp_parse, bool, num_elements);
18050 ufbxi_check(modify_not_supported);
18051
18052 ufbx_element_type *node_attrib_type = ufbxi_push_zero(&uc->tmp_parse, ufbx_element_type, num_nodes);
18053 ufbxi_check(node_attrib_type);
18054
18055 bool *has_unscaled_children = ufbxi_push_zero(&uc->tmp_parse, bool, num_nodes);
18056 ufbxi_check(has_unscaled_children);
18057
18058 bool *has_scale_animation = ufbxi_push_zero(&uc->tmp_parse, bool, num_nodes);
18059 ufbxi_check(has_scale_animation);
18060
18061 ufbxi_pre_node *pre_nodes = ufbxi_push_zero(&uc->tmp_parse, ufbxi_pre_node, num_nodes);
18062 ufbxi_check(pre_nodes);
18063
18064 size_t num_meshes = uc->tmp_typed_element_offsets[UFBX_ELEMENT_MESH].num_items;
18065 ufbxi_pre_mesh *pre_meshes = ufbxi_push_zero(&uc->tmp_parse, ufbxi_pre_mesh, num_meshes);
18066 ufbxi_check(pre_meshes);
18067
18068 size_t num_anim_values = uc->tmp_typed_element_offsets[UFBX_ELEMENT_ANIM_VALUE].num_items;
18069 ufbxi_pre_anim_value *pre_anim_values = ufbxi_push_zero(&uc->tmp_parse, ufbxi_pre_anim_value, num_anim_values);
18070 ufbxi_check(pre_anim_values);
18071
18072 uint64_t *fbx_ids = ufbxi_push_pop(&uc->tmp_parse, &uc->tmp_element_fbx_ids, uint64_t, num_elements);
18073 ufbxi_check(fbx_ids);
18074
18075 // TODO
18076 const ufbx_real scale_epsilon = 0.001f;
18077 const ufbx_real pivot_epsilon = 0.001f;
18078 const ufbx_real compensate_epsilon = 0.01f;
18079
18080 for (size_t i = 0; i < num_elements; i++) {
18081 ufbx_element *element = elements[i];
18082 uint32_t id = element->typed_id;
18083
18084 if (element->type == UFBX_ELEMENT_NODE) {
18085 ufbxi_pre_node *pre_node = &pre_nodes[id];
18086 pre_node->has_constant_scale = true;
18087 pre_node->constant_scale = ufbxi_find_vec3(&element->props, ufbxi_Lcl_Scaling, 1.0f, 1.0f, 1.0f);
18088 pre_node->element_id = element->element_id;
18089 pre_node->first_child = ~0u;
18090 pre_node->next_child = ~0u;
18091 pre_node->parent = ~0u;
18092 } if (element->type == UFBX_ELEMENT_ANIM_VALUE) {
18093 ufbxi_pre_anim_value *pre_value = &pre_anim_values[id];
18094 pre_value->has_constant_value = true;
18095 pre_value->constant_value.x = ufbxi_find_real(&element->props, ufbxi_X, UFBX_NAN);
18096 pre_value->constant_value.x = ufbxi_find_real(&element->props, ufbxi_d_X, pre_value->constant_value.x);
18097 pre_value->constant_value.y = ufbxi_find_real(&element->props, ufbxi_Y, UFBX_NAN);
18098 pre_value->constant_value.y = ufbxi_find_real(&element->props, ufbxi_d_Y, pre_value->constant_value.y);
18099 pre_value->constant_value.z = ufbxi_find_real(&element->props, ufbxi_Z, UFBX_NAN);
18100 pre_value->constant_value.z = ufbxi_find_real(&element->props, ufbxi_d_Z, pre_value->constant_value.z);
18101 }
18102 }
18103
18104 for (size_t i = 0; i < num_connections; i++) {
18105 ufbxi_tmp_connection *tmp = &tmp_connections[i];
18106 ufbxi_pre_connection *pre = &pre_connections[i];
18107
18108 ufbxi_fbx_id_entry *src_entry = ufbxi_find_fbx_id(uc, tmp->src);
18109 ufbxi_fbx_id_entry *dst_entry = ufbxi_find_fbx_id(uc, tmp->dst);
18110
18111 ufbx_element *src = src_entry ? elements[src_entry->element_id] : NULL;
18112 ufbx_element *dst = dst_entry ? elements[dst_entry->element_id] : NULL;
18113 pre->src = src;
18114 pre->dst = dst;
18115 if (!src || !dst) continue;
18116
18117 if (tmp->src_prop.length == 0 && tmp->dst_prop.length == 0) {
18118 // Count number of instances of each attribute
18119 if (dst->type == UFBX_ELEMENT_NODE) {
18120 ufbx_node *dst_node = (ufbx_node*)dst;
18121
18122 if (src->type >= UFBX_ELEMENT_TYPE_FIRST_ATTRIB && src->type <= UFBX_ELEMENT_TYPE_LAST_ATTRIB) {
18123 uint32_t count = ++instance_counts[src->element_id];
18124 node_attrib_type[dst->typed_id] = count == 1 ? src->type : UFBX_ELEMENT_UNKNOWN;
18125
18126 // These must match what can be trasnsformed in `ufbxi_modify_geometry()`
18127 switch (src->type) {
18128 case UFBX_ELEMENT_MESH:
18129 case UFBX_ELEMENT_LINE_CURVE:
18130 case UFBX_ELEMENT_NURBS_CURVE:
18131 case UFBX_ELEMENT_NURBS_SURFACE:
18132 break; // Nop, supported
18133 default:
18134 modify_not_supported[dst->element_id] = true;
18135 break;
18136 }
18137 }
18138
18139 if (src->type == UFBX_ELEMENT_NODE) {
18140 ufbx_node *src_node = (ufbx_node*)src;
18141 ufbxi_pre_node *pre_dst = &pre_nodes[dst_node->typed_id];
18142 ufbxi_pre_node *pre_src = &pre_nodes[src_node->typed_id];
18143
18144 // Remember parent and add children into a linked list
18145 if (pre_src->parent == ~0u) {
18146 pre_src->parent = dst_node->typed_id;
18147 pre_src->next_child = pre_dst->first_child;
18148 pre_dst->first_child = src_node->typed_id;
18149 }
18150
18151 if (uc->opts.inherit_mode_handling != UFBX_INHERIT_MODE_HANDLING_PRESERVE) {
18152 if (!dst_node->is_root && src_node->original_inherit_mode != UFBX_INHERIT_MODE_NORMAL) {
18153 has_unscaled_children[dst->typed_id] = true;
18154 }
18155 }
18156 }
18157 } else if (dst->type == UFBX_ELEMENT_MESH) {
18158 if (src->type == UFBX_ELEMENT_SKIN_DEFORMER) {
18159 ufbxi_pre_mesh *pre_mesh = &pre_meshes[dst->typed_id];
18160 pre_mesh->has_skin_deformer = true;
18161 }
18162 }
18163 } else if (tmp->src_prop.length == 0 && tmp->dst_prop.length != 0) {
18164 const char *dst_prop = tmp->dst_prop.data;
18165 if (dst->type == UFBX_ELEMENT_ANIM_VALUE && src->type == UFBX_ELEMENT_ANIM_CURVE) {
18166 ufbx_anim_curve *src_curve = (ufbx_anim_curve*)src;
18167 uint32_t index = 0;
18168 if (dst_prop == ufbxi_Y || dst_prop == ufbxi_d_Y) {
18169 index = 1;
18170 } else if (dst_prop == ufbxi_Z || dst_prop == ufbxi_d_Z) {
18171 index = 2;
18172 }
18173
18174 ufbxi_pre_anim_value *pre_value = &pre_anim_values[dst->typed_id];
18175 if (src_curve->max_value - src_curve->min_value >= scale_epsilon) {
18176 pre_value->has_constant_value = false;
18177 } else {
18178 ufbx_real constant_value = (src_curve->min_value + src_curve->max_value) * 0.5f;
18179 if (ufbx_isnan(pre_value->constant_value.v[index])) {
18180 pre_value->constant_value.v[index] = constant_value;
18181 }
18182 if ((ufbx_real)ufbx_fabs(pre_value->constant_value.v[index] - constant_value) > scale_epsilon) {
18183 pre_value->has_constant_value = false;
18184 }
18185 }
18186 }
18187 }
18188 }
18189
18190 for (size_t i = 0; i < num_connections; i++) {
18191 ufbxi_tmp_connection *tmp = &tmp_connections[i];
18192 ufbxi_pre_connection *pre = &pre_connections[i];
18193 ufbx_element *src = pre->src, *dst = pre->dst;
18194 if (!src || !dst) continue;
18195
18196 if (tmp->src_prop.length == 0 && tmp->dst_prop.length == 0) {
18197 // Count maximum number of instanced attributes in a node
18198 if (dst->type == UFBX_ELEMENT_NODE) {
18199 if (src->type >= UFBX_ELEMENT_TYPE_FIRST_ATTRIB && src->type <= UFBX_ELEMENT_TYPE_LAST_ATTRIB) {
18200 instance_counts[dst->element_id] = ufbxi_max32(instance_counts[dst->element_id], instance_counts[src->element_id]);
18201 if (src->type == UFBX_ELEMENT_MESH) {
18202 ufbxi_pre_mesh *pre_mesh = &pre_meshes[src->typed_id];
18203 if (pre_mesh->has_skin_deformer) {
18204 pre_nodes[dst->typed_id].has_skin_deformer = true;
18205 }
18206 }
18207 } else if (src->type == UFBX_ELEMENT_SKIN_DEFORMER) {
18208 pre_nodes[dst->typed_id].has_skin_deformer = true;
18209 }
18210 }
18211 } else if (tmp->src_prop.length == 0 && tmp->dst_prop.length != 0) {
18212 if (dst->type == UFBX_ELEMENT_NODE) {
18213 if (src->type == UFBX_ELEMENT_ANIM_VALUE) {
18214 if (tmp->dst_prop.data == ufbxi_Lcl_Scaling) {
18215 ufbxi_pre_node *pre_node = &pre_nodes[dst->typed_id];
18216 if (pre_node->has_constant_scale) {
18217 ufbxi_pre_anim_value *pre_value = &pre_anim_values[src->typed_id];
18218 if (!pre_value->has_constant_value) {
18219 pre_node->has_constant_scale = false;
18220 } else {
18221 ufbx_real error = 0.0f;
18222 error += (ufbx_real)ufbx_fabs(pre_value->constant_value.x - pre_node->constant_scale.x);
18223 error += (ufbx_real)ufbx_fabs(pre_value->constant_value.y - pre_node->constant_scale.y);
18224 error += (ufbx_real)ufbx_fabs(pre_value->constant_value.z - pre_node->constant_scale.z);
18225 if (error >= scale_epsilon) {
18226 pre_node->has_constant_scale = false;
18227 }
18228 }
18229 }
18230 }
18231 }
18232 }
18233 }
18234 }
18235
18236 if (uc->opts.pivot_handling == UFBX_PIVOT_HANDLING_ADJUST_TO_PIVOT || uc->opts.pivot_handling == UFBX_PIVOT_HANDLING_ADJUST_TO_ROTATION_PIVOT) {
18237 for (size_t i = 0; i < num_nodes; i++) {
18238 ufbxi_pre_node *pre_node = &pre_nodes[i];
18239 ufbx_node *node = (ufbx_node*)elements[pre_node->element_id];
18240
18241 ufbx_vec3 rotation_pivot = ufbxi_find_vec3(&node->props, ufbxi_RotationPivot, 0.0f, 0.0f, 0.0f);
18242 ufbx_vec3 scaling_pivot = ufbxi_find_vec3(&node->props, ufbxi_ScalingPivot, 0.0f, 0.0f, 0.0f);
18243 ufbx_vec3 scaling_offset = ufbxi_find_vec3(&node->props, ufbxi_ScalingOffset, 0.0f, 0.0f, 0.0f);
18244
18245 bool should_modify_pivot = false;
18246 if (uc->opts.pivot_handling == UFBX_PIVOT_HANDLING_ADJUST_TO_PIVOT) {
18247 should_modify_pivot = !ufbxi_is_vec3_zero(rotation_pivot);
18248 } else if (uc->opts.pivot_handling == UFBX_PIVOT_HANDLING_ADJUST_TO_ROTATION_PIVOT) {
18249 should_modify_pivot = ufbxi_pivot_nonzero(rotation_pivot) || ufbxi_pivot_nonzero(scaling_pivot) || ufbxi_pivot_nonzero(scaling_offset);
18250 }
18251
18252 if (should_modify_pivot) {
18253 bool skip_geometry_transform = false;
18254 bool can_modify_geometry_transform = true;
18255 if (uc->opts.pivot_handling == UFBX_PIVOT_HANDLING_ADJUST_TO_ROTATION_PIVOT) {
18256 if (node_attrib_type[node->typed_id] == UFBX_ELEMENT_EMPTY) {
18257 if (!uc->opts.pivot_handling_retain_empties) {
18258 skip_geometry_transform = true;
18259 } else {
18260 can_modify_geometry_transform = false;
18261 }
18262 }
18263 }
18264
18265 if (uc->opts.geometry_transform_handling == UFBX_GEOMETRY_TRANSFORM_HANDLING_MODIFY_GEOMETRY_NO_FALLBACK) {
18266 if (instance_counts[node->element_id] > 1 || modify_not_supported[node->element_id]) {
18267 can_modify_geometry_transform = false;
18268 }
18269 }
18270 // Currently, geometry transform messes up skinning
18271 if (pre_node->has_skin_deformer) {
18272 can_modify_geometry_transform = false;
18273 }
18274
18275 bool can_modify_pivot = true;
18276 if (uc->opts.pivot_handling == UFBX_PIVOT_HANDLING_ADJUST_TO_PIVOT) {
18277 ufbx_real err = 0.0f;
18278 err += (ufbx_real)ufbx_fabs(rotation_pivot.x - scaling_pivot.x);
18279 err += (ufbx_real)ufbx_fabs(rotation_pivot.y - scaling_pivot.y);
18280 err += (ufbx_real)ufbx_fabs(rotation_pivot.z - scaling_pivot.z);
18281 if (err > pivot_epsilon) {
18282 can_modify_pivot = false;
18283 }
18284 }
18285
18286 if (can_modify_pivot && (can_modify_geometry_transform || skip_geometry_transform)) {
18287 ufbx_vec3 geometric_translation = ufbxi_find_vec3(&node->props, ufbxi_GeometricTranslation, 0.0f, 0.0f, 0.0f);
18288
18289 ufbx_vec3 child_offset = { 0.0f };
18290 ufbx_prop *new_props = NULL;
18291 size_t num_props = node->props.props.count;
18292 size_t new_prop_count = num_props;
18293 if (uc->opts.pivot_handling == UFBX_PIVOT_HANDLING_ADJUST_TO_PIVOT) {
18294 ufbx_assert(!skip_geometry_transform); // not supporeted in legacy mode
18295 child_offset = ufbxi_neg3(rotation_pivot);
18296 geometric_translation = ufbxi_add3(geometric_translation, child_offset);
18297
18298 new_props = ufbxi_push_zero(&uc->result, ufbx_prop, num_props + 3);
18299 ufbxi_check(new_props);
18300 memcpy(new_props, node->props.props.data, num_props * sizeof(ufbx_prop));
18301
18302 ufbxi_init_synthetic_vec3_prop(&new_props[new_prop_count++], ufbxi_RotationPivot, &ufbx_zero_vec3, UFBX_PROP_VECTOR);
18303 ufbxi_init_synthetic_vec3_prop(&new_props[new_prop_count++], ufbxi_ScalingPivot, &ufbx_zero_vec3, UFBX_PROP_VECTOR);
18304 ufbxi_init_synthetic_vec3_prop(&new_props[new_prop_count++], ufbxi_GeometricTranslation, &geometric_translation, UFBX_PROP_VECTOR);
18305 } else if (uc->opts.pivot_handling == UFBX_PIVOT_HANDLING_ADJUST_TO_ROTATION_PIVOT) {
18306 // We can eliminate the post-rotation translation and move it to the geometry/children as follows.
18307 // Let Z be the initial value of S in the transform (aka `initial_scale`):
18308 //
18309 // (Rp-1+Soff+Sp) + S * (Sp-1)
18310 // S * (Sp-1 + (Rp-1+Soff+Sp)/S)
18311 // S * (Sp-1 + (Rp-1+Soff+Sp)/S - (Rp-1+Soff+Sp)/Z + (Rp-1+Soff+Sp)/Z)
18312 //
18313 // (Rp-1 + Soff + Sp) + S * (-(Rp-1 + Soff + Sp)/Z + (Sp-1 + (Rp-1 + Soff + Sp)/Z))
18314 // ^-scaled_offset--^ ^-unscaled_offset--^ ^-unscaled_offset--^
18315 // ^---------------- 0, when S=Z ----------------^ ^------- child_offset ------^
18316 //
18317 // We need to be careful when doing this in case any component of Z is 0. Fortunately,
18318 // the above holds for all `Z != 0`, it will just result in non-zero translation in the parent.
18319 ufbx_vec3 initial_scale = ufbxi_find_vec3(&node->props, ufbxi_Lcl_Scaling, 1.0f, 1.0f, 1.0f);
18320 ufbx_vec3 scaled_offset = ufbxi_sub3(ufbxi_add3(scaling_offset, scaling_pivot), rotation_pivot);
18321 ufbx_vec3 unscaled_offset;
18322 unscaled_offset.x = ufbxi_pivot_div(scaled_offset.x, initial_scale.x);
18323 unscaled_offset.y = ufbxi_pivot_div(scaled_offset.y, initial_scale.y);
18324 unscaled_offset.z = ufbxi_pivot_div(scaled_offset.z, initial_scale.z);
18325
18326 // Convert `scaled_offset + S*unscaled_offset` to FBX scaling pivot and offset.
18327 ufbx_vec3 new_scaling_pivot = unscaled_offset;
18328 ufbx_vec3 new_scaling_offset = ufbxi_sub3(scaled_offset, new_scaling_pivot);
18329 child_offset = ufbxi_sub3(unscaled_offset, scaling_pivot);
18330
18331 new_props = ufbxi_push_zero(&uc->result, ufbx_prop, num_props + 4);
18332 ufbxi_check(new_props);
18333 memcpy(new_props, node->props.props.data, num_props * sizeof(ufbx_prop));
18334
18335 ufbxi_init_synthetic_vec3_prop(&new_props[new_prop_count++], ufbxi_RotationPivot, &ufbx_zero_vec3, UFBX_PROP_VECTOR);
18336 ufbxi_init_synthetic_vec3_prop(&new_props[new_prop_count++], ufbxi_ScalingPivot, &new_scaling_pivot, UFBX_PROP_VECTOR);
18337 ufbxi_init_synthetic_vec3_prop(&new_props[new_prop_count++], ufbxi_ScalingOffset, &new_scaling_offset, UFBX_PROP_VECTOR);
18338 if (!skip_geometry_transform) {
18339 geometric_translation = ufbxi_add3(geometric_translation, child_offset);
18340 ufbxi_init_synthetic_vec3_prop(&new_props[new_prop_count++], ufbxi_GeometricTranslation, &geometric_translation, UFBX_PROP_VECTOR);
18341 }
18342 }
18343
18344 node->props.props.data = new_props;
18345 node->props.props.count = new_prop_count;
18346 ufbxi_check(ufbxi_sort_properties(uc, node->props.props.data, node->props.props.count));
18347 ufbxi_deduplicate_properties(&node->props.props);
18348
18349 node->adjust_pre_translation = ufbxi_add3(node->adjust_pre_translation, rotation_pivot);
18350 node->has_adjust_transform = true;
18351 uint32_t ix = pre_node->first_child;
18352 while (ix != ~0u) {
18353 ufbxi_pre_node *pre_child = &pre_nodes[ix];
18354 ufbx_node *child = (ufbx_node*)elements[pre_child->element_id];
18355
18356 child->adjust_pre_translation = ufbxi_add3(child->adjust_pre_translation, child_offset);
18357 child->has_adjust_transform = true;
18358
18359 ix = pre_child->next_child;
18360 }
18361 }
18362 }
18363 }
18364 }
18365
18366 for (size_t i = 0; i < num_elements; i++) {
18367 ufbx_element *element = elements[i];
18368 uint64_t fbx_id = fbx_ids[i];
18369
18370 if (element->type == UFBX_ELEMENT_NODE) {
18371 ufbx_node *node = (ufbx_node*)element;
18372 bool requires_helper_node = false;
18373 if (uc->opts.geometry_transform_handling == UFBX_GEOMETRY_TRANSFORM_HANDLING_HELPER_NODES) {
18374 requires_helper_node = true;
18375 } else if (uc->opts.geometry_transform_handling == UFBX_GEOMETRY_TRANSFORM_HANDLING_MODIFY_GEOMETRY) {
18376 // Setup a geometry transform helper for nodes that have instanced attributes
18377 requires_helper_node = instance_counts[i] > 1 || modify_not_supported[i];
18378 }
18379 if (requires_helper_node) {
18380 ufbxi_check(ufbxi_setup_geometry_transform_helper(uc, node, fbx_id));
18381 }
18382 }
18383 }
18384
18385 for (size_t i = 0; i < num_elements; i++) {
18386 ufbx_element *element = elements[i];
18387 uint64_t fbx_id = fbx_ids[i];
18388
18389 if (element->type == UFBX_ELEMENT_NODE) {
18390 ufbx_node *node = (ufbx_node*)element;
18391 if (has_unscaled_children[node->typed_id] && !node->scale_helper) {
18392 ufbxi_pre_node *pre_node = &pre_nodes[node->typed_id];
18393 ufbx_real ref = uc->opts.inherit_mode_handling == UFBX_INHERIT_MODE_HANDLING_COMPENSATE
18394 ? pre_node->constant_scale.x : (ufbx_real)1.0f;
18395 ufbx_vec3 scale = pre_node->constant_scale;
18396 ufbx_real dx = (ufbx_real)ufbx_fabs(scale.x - ref);
18397 ufbx_real dy = (ufbx_real)ufbx_fabs(scale.y - ref);
18398 ufbx_real dz = (ufbx_real)ufbx_fabs(scale.z - ref);
18399 if ((dx + dy + dz >= scale_epsilon || !pre_node->has_constant_scale || (ufbx_real)ufbx_fabs(scale.x) <= compensate_epsilon)
18400 && uc->opts.inherit_mode_handling != UFBX_INHERIT_MODE_HANDLING_COMPENSATE_NO_FALLBACK) {
18401 ufbxi_check(ufbxi_setup_scale_helper(uc, node, fbx_id));
18402
18403 // If we added a geometry transform helper that may scale further helpers
18404 // recursively for all child nodes using `UFBX_INHERIT_MODE_COMPONENTWISE_SCALE`
18405 // This is guaranteed to terminate as `ufbxi_pre_node` may only have one parent,
18406 // meaning any cycles must contain `node` itself.
18407 uint32_t ix = pre_node->first_child;
18408 while (ix != ~0u && ix != node->typed_id) {
18409 ufbxi_pre_node *pre_child = &pre_nodes[ix];
18410 ufbx_node *child = (ufbx_node*)elements[pre_child->element_id];
18411
18412 if (pre_child->parent != node->typed_id || child->original_inherit_mode == UFBX_INHERIT_MODE_COMPONENTWISE_SCALE) {
18413 if (!pre_child->has_recursive_scale_helper && child->original_inherit_mode != UFBX_INHERIT_MODE_NORMAL) {
18414 pre_child->has_recursive_scale_helper = true;
18415
18416 uint64_t child_fbx_id = fbx_ids[pre_child->element_id];
18417 ufbxi_check(ufbxi_setup_scale_helper(uc, child, child_fbx_id));
18418 child->is_scale_compensate_parent = false;
18419
18420 // Traverse to children if any
18421 if (pre_child->first_child != ~0u) {
18422 ix = pre_child->first_child;
18423 continue;
18424 }
18425 }
18426 }
18427
18428 // Move to next child, popping parents until we find one
18429 while (pre_child->next_child == ~0u) {
18430 ix = pre_child->parent;
18431 if (ix == node->typed_id) break;
18432 pre_child = &pre_nodes[ix];
18433 }
18434 if (ix != node->typed_id) {
18435 ix = pre_child->next_child;
18436 }
18437 }
18438
18439 } else if (uc->opts.inherit_mode_handling == UFBX_INHERIT_MODE_HANDLING_COMPENSATE || uc->opts.inherit_mode_handling == UFBX_INHERIT_MODE_HANDLING_COMPENSATE_NO_FALLBACK) {
18440 if ((ufbx_real)ufbx_fabs(scale.x - 1.0f) >= scale_epsilon) {
18441 node->is_scale_compensate_parent = true;
18442 }
18443 }
18444 }
18445 }
18446 }
18447
18448 return 1;
18449 }
18450
18451 // -- Scene processing
18452
18453 static ufbxi_noinline ufbx_element *ufbxi_find_element_by_fbx_id(ufbxi_context *uc, uint64_t fbx_id)
18454 {
18455 ufbxi_fbx_id_entry *entry = ufbxi_find_fbx_id(uc, fbx_id);
18456 if (entry) {
18457 return uc->scene.elements.data[entry->element_id];
18458 }
18459 return NULL;
18460 }
18461
18462 ufbxi_forceinline static bool ufbxi_cmp_name_element_less(const ufbx_name_element *a, const ufbx_name_element *b)
18463 {
18464 if (a->_internal_key != b->_internal_key) return a->_internal_key < b->_internal_key;
18465 int cmp = strcmp(a->name.data, b->name.data);
18466 if (cmp != 0) return cmp < 0;
18467 return a->type < b->type;
18468 }
18469
18470 ufbxi_forceinline static bool ufbxi_cmp_name_element_less_ref(const ufbx_name_element *a, ufbx_string name, ufbx_element_type type, uint32_t key)
18471 {
18472 if (a->_internal_key != key) return a->_internal_key < key;
18473 int cmp = ufbxi_str_cmp(a->name, name);
18474 if (cmp != 0) return cmp < 0;
18475 return a->type < type;
18476 }
18477
18478 ufbxi_forceinline static bool ufbxi_cmp_prop_less_ref(const ufbx_prop *a, ufbx_string name, uint32_t key)
18479 {
18480 if (a->_internal_key != key) return a->_internal_key < key;
18481 return ufbxi_str_less(a->name, name);
18482 }
18483
18484 ufbxi_forceinline static bool ufbxi_cmp_prop_less_concat(const ufbx_prop *a, const ufbx_string *parts, size_t num_parts, uint32_t key)
18485 {
18486 if (a->_internal_key != key) return a->_internal_key < key;
18487 return ufbxi_concat_str_cmp(&a->name, parts, num_parts) < 0;
18488 }
18489
18490 ufbxi_nodiscard ufbxi_noinline static int ufbxi_sort_name_elements(ufbxi_context *uc, ufbx_name_element *name_elems, size_t count)
18491 {
18492 ufbxi_check(ufbxi_grow_array(&uc->ator_tmp, &uc->tmp_arr, &uc->tmp_arr_size, count * sizeof(ufbx_name_element)));
18493 ufbxi_macro_stable_sort(ufbx_name_element, 32, name_elems, uc->tmp_arr, count,
18494 ( ufbxi_cmp_name_element_less(a, b) ) );
18495 return 1;
18496 }
18497
18498 ufbxi_noinline static bool ufbxi_cmp_node_less(ufbx_node *a, ufbx_node *b)
18499 {
18500 if (a->node_depth != b->node_depth) return a->node_depth < b->node_depth;
18501 if (a->parent && b->parent) {
18502 uint32_t a_pid = a->parent->element.element_id, b_pid = b->parent->element.element_id;
18503 if (a_pid != b_pid) return a_pid < b_pid;
18504 } else {
18505 ufbx_assert(a->parent == NULL && b->parent == NULL);
18506 }
18507 if (a->is_geometry_transform_helper != b->is_geometry_transform_helper) {
18508 // Sort geometry transform helpers always before rest of the children.
18509 return (unsigned)a->is_geometry_transform_helper > (unsigned)b->is_geometry_transform_helper;
18510 }
18511 if (a->is_scale_helper != b->is_scale_helper) {
18512 // Sort scale helpers after geometry transform helpers.
18513 return (unsigned)a->is_scale_helper > (unsigned)b->is_scale_helper;
18514 }
18515 return a->element.element_id < b->element.element_id;
18516 }
18517
18518 ufbxi_nodiscard ufbxi_noinline static int ufbxi_sort_node_ptrs(ufbxi_context *uc, ufbx_node **nodes, size_t count)
18519 {
18520 ufbxi_check(ufbxi_grow_array(&uc->ator_tmp, &uc->tmp_arr, &uc->tmp_arr_size, count * sizeof(ufbx_node*)));
18521 ufbxi_macro_stable_sort(ufbx_node*, 32, nodes, uc->tmp_arr, count,
18522 ( ufbxi_cmp_node_less(*a, *b) ) );
18523 return 1;
18524 }
18525
18526 ufbxi_nodiscard ufbxi_noinline static int ufbxi_cmp_tmp_material_texture_less(const ufbxi_tmp_material_texture *a, const ufbxi_tmp_material_texture *b)
18527 {
18528 if (a->material_id != b->material_id) return a->material_id < b->material_id;
18529 if (a->texture_id != b->texture_id) return a->texture_id < b->texture_id;
18530 return ufbxi_str_less(a->prop_name, b->prop_name);
18531 }
18532
18533 ufbxi_nodiscard ufbxi_noinline static int ufbxi_sort_tmp_material_textures(ufbxi_context *uc, ufbxi_tmp_material_texture *mat_texs, size_t count)
18534 {
18535 ufbxi_check(ufbxi_grow_array(&uc->ator_tmp, &uc->tmp_arr, &uc->tmp_arr_size, count * sizeof(ufbxi_tmp_material_texture)));
18536 ufbxi_macro_stable_sort(ufbxi_tmp_material_texture, 32, mat_texs, uc->tmp_arr, count,
18537 ( ufbxi_cmp_tmp_material_texture_less(a, b) ));
18538 return 1;
18539 }
18540
18541 // We need to be able to assume no padding!
18542 ufbx_static_assert(connection_size, sizeof(ufbx_connection) == sizeof(ufbx_element*)*2 + sizeof(ufbx_string)*2);
18543
18544 ufbxi_forceinline static bool ufbxi_cmp_connection_less(ufbx_connection *a, ufbx_connection *b, size_t index)
18545 {
18546 ufbx_element *a_elem = (&a->src)[index], *b_elem = (&b->src)[index];
18547 if (a_elem != b_elem) return a_elem < b_elem;
18548 int cmp = strcmp((&a->src_prop)[index].data, (&b->src_prop)[index].data);
18549 if (cmp != 0) return cmp < 0;
18550 cmp = strcmp((&a->src_prop)[index ^ 1].data, (&b->src_prop)[index ^ 1].data);
18551 return cmp < 0;
18552 }
18553
18554 ufbxi_nodiscard ufbxi_noinline static int ufbxi_sort_connections(ufbxi_context *uc, ufbx_connection *connections, size_t count, size_t index)
18555 {
18556 ufbxi_check(ufbxi_grow_array(&uc->ator_tmp, &uc->tmp_arr, &uc->tmp_arr_size, count * sizeof(ufbx_connection)));
18557 ufbxi_macro_stable_sort(ufbx_connection, 32, connections, uc->tmp_arr, count, ( ufbxi_cmp_connection_less(a, b, index) ));
18558 return 1;
18559 }
18560
18561 static uint64_t ufbxi_find_attribute_fbx_id(ufbxi_context *uc, uint64_t node_fbx_id)
18562 {
18563 uint32_t hash = ufbxi_hash64(node_fbx_id);
18564 ufbxi_fbx_attr_entry *entry = ufbxi_map_find(&uc->fbx_attr_map, ufbxi_fbx_attr_entry, hash, &node_fbx_id);
18565 if (entry) {
18566 return entry->attr_fbx_id;
18567 }
18568 return node_fbx_id;
18569 }
18570
18571 ufbxi_nodiscard ufbxi_noinline static int ufbxi_resolve_connections(ufbxi_context *uc)
18572 {
18573 size_t num_connections = uc->tmp_connections.num_items;
18574 ufbxi_tmp_connection *tmp_connections = ufbxi_push_pop(&uc->tmp, &uc->tmp_connections, ufbxi_tmp_connection, num_connections);
18575 ufbxi_buf_free(&uc->tmp_connections);
18576 ufbxi_check(tmp_connections);
18577
18578 // NOTE: We truncate this array in case not all connections are resolved
18579 uc->scene.connections_src.data = ufbxi_push(&uc->result, ufbx_connection, num_connections);
18580 ufbxi_check(uc->scene.connections_src.data);
18581
18582 // HACK: Translate property connections from node to attribute if the property name is not included
18583 // in the known node properties and is not a property of the node.
18584 if (uc->version > 0 && uc->version < 7000) {
18585 ufbxi_for(ufbxi_tmp_connection, tmp_conn, tmp_connections, num_connections) {
18586 if (tmp_conn->src_prop.length > 0 && !ufbxi_is_node_property_name(uc, tmp_conn->src_prop.data)) {
18587 ufbx_element *src = ufbxi_find_element_by_fbx_id(uc, tmp_conn->src);
18588 if (!src || !ufbx_find_prop_len(&src->props, tmp_conn->src_prop.data, tmp_conn->src_prop.length)) {
18589 tmp_conn->src = ufbxi_find_attribute_fbx_id(uc, tmp_conn->src);
18590 }
18591 }
18592 if (tmp_conn->dst_prop.length > 0 && !ufbxi_is_node_property_name(uc, tmp_conn->dst_prop.data)) {
18593 ufbx_element *dst = ufbxi_find_element_by_fbx_id(uc, tmp_conn->dst);
18594 if (!dst || !ufbx_find_prop_len(&dst->props, tmp_conn->dst_prop.data, tmp_conn->dst_prop.length)) {
18595 tmp_conn->dst = ufbxi_find_attribute_fbx_id(uc, tmp_conn->dst);
18596 }
18597 }
18598 }
18599 }
18600
18601 ufbxi_for(ufbxi_tmp_connection, tmp_conn, tmp_connections, num_connections) {
18602 ufbx_element *src = ufbxi_find_element_by_fbx_id(uc, tmp_conn->src);
18603 ufbx_element *dst = ufbxi_find_element_by_fbx_id(uc, tmp_conn->dst);
18604 if (!src || !dst) continue;
18605
18606 if (!uc->opts.disable_quirks) {
18607 // Some exporters connect arbitrary non-nodes to root breaking further code, ignore those connections here!
18608 if (dst->type == UFBX_ELEMENT_NODE && src->type != UFBX_ELEMENT_NODE && ((ufbx_node*)dst)->is_root) {
18609 ufbxi_check(ufbxi_warnf_tag(UFBX_WARNING_BAD_ELEMENT_CONNECTED_TO_ROOT, src->element_id, "Non-node element connected to root"));
18610 continue;
18611 }
18612 }
18613
18614 // Remap connections to geometry transform helpers if necessary, see `ufbxi_setup_geometry_transform_helper()` for how these are setup.
18615 if (uc->has_geometry_transform_nodes) {
18616 if (dst->type == UFBX_ELEMENT_NODE && src->type >= UFBX_ELEMENT_TYPE_FIRST_ATTRIB && src->type <= UFBX_ELEMENT_TYPE_LAST_ATTRIB) {
18617 ufbx_node *node = (ufbx_node*)dst;
18618 if (node->has_geometry_transform) {
18619 ufbxi_node_extra *extra = (ufbxi_node_extra*)ufbxi_get_element_extra(uc, node->element_id);
18620 ufbx_assert(extra);
18621 dst = uc->scene.elements.data[extra->geometry_helper_id];
18622 ufbx_assert(dst->type == UFBX_ELEMENT_NODE && ((ufbx_node*)dst)->is_geometry_transform_helper);
18623 }
18624 }
18625 }
18626
18627 // Remap connections to scale helpers if necessary, see `ufbxi_setup_scale_helper()` for how these are setup.
18628 if (uc->has_scale_helper_nodes) {
18629 if (dst->type == UFBX_ELEMENT_NODE) {
18630 ufbx_node *dst_node = (ufbx_node*)dst;
18631 if (dst_node->scale_helper) {
18632 if (src->type == UFBX_ELEMENT_NODE) {
18633 ufbx_node *src_node = (ufbx_node*)src;
18634 if (!src_node->is_scale_helper && src_node->original_inherit_mode == UFBX_INHERIT_MODE_NORMAL) {
18635 dst = &dst_node->scale_helper->element;
18636 }
18637 } else if (src->type == UFBX_ELEMENT_ANIM_VALUE) {
18638 if (tmp_conn->dst_prop.data == ufbxi_Lcl_Scaling) {
18639 dst = &dst_node->scale_helper->element;
18640 }
18641 } else {
18642 dst = &dst_node->scale_helper->element;
18643 }
18644 }
18645 } else if (src->type == UFBX_ELEMENT_NODE) {
18646 ufbx_node *src_node = (ufbx_node*)src;
18647 if (src_node->scale_helper) {
18648 if (dst->type == UFBX_ELEMENT_SKIN_CLUSTER) {
18649 src = &src_node->scale_helper->element;
18650 }
18651 }
18652 }
18653 }
18654
18655 // Translate deformers to point to the geometry in 6100, we don't need to worry about
18656 // blend shapes here as they're always connected synthetically in older files.
18657 if (uc->version > 0 && uc->version < 7000 && dst->type == UFBX_ELEMENT_NODE) {
18658 if (src->type == UFBX_ELEMENT_SKIN_DEFORMER || src->type == UFBX_ELEMENT_CACHE_DEFORMER) {
18659 uint64_t dst_id = ufbxi_find_attribute_fbx_id(uc, tmp_conn->dst);
18660 ufbx_element *dst_elem = ufbxi_find_element_by_fbx_id(uc, dst_id);
18661 if (dst_elem) {
18662 dst = dst_elem;
18663 }
18664 }
18665 }
18666
18667 ufbx_connection *conn = &uc->scene.connections_src.data[uc->scene.connections_src.count++];
18668 conn->src = src;
18669 conn->dst = dst;
18670 conn->src_prop = tmp_conn->src_prop;
18671 conn->dst_prop = tmp_conn->dst_prop;
18672 }
18673
18674 uc->scene.connections_dst.count = uc->scene.connections_src.count;
18675 uc->scene.connections_dst.data = ufbxi_push_copy(&uc->result, ufbx_connection,
18676 uc->scene.connections_src.count, uc->scene.connections_src.data);
18677 ufbxi_check(uc->scene.connections_dst.data);
18678
18679 ufbxi_check(ufbxi_sort_connections(uc, uc->scene.connections_src.data, uc->scene.connections_src.count, 0));
18680 ufbxi_check(ufbxi_sort_connections(uc, uc->scene.connections_dst.data, uc->scene.connections_dst.count, 1));
18681
18682 // We don't need the temporary connections at this point anymore
18683 ufbxi_buf_free(&uc->tmp_connections);
18684
18685 return 1;
18686 }
18687
18688 ufbxi_nodiscard ufbxi_noinline static int ufbxi_add_connections_to_elements(ufbxi_context *uc)
18689 {
18690 ufbx_connection *conn_src = uc->scene.connections_src.data;
18691 ufbx_connection *conn_src_end = ufbxi_add_ptr(conn_src, uc->scene.connections_src.count);
18692 ufbx_connection *conn_dst = uc->scene.connections_dst.data;
18693 ufbx_connection *conn_dst_end = ufbxi_add_ptr(conn_dst, uc->scene.connections_dst.count);
18694
18695 ufbxi_for_ptr(ufbx_element, p_elem, uc->scene.elements.data, uc->scene.elements.count) {
18696 ufbx_element *elem = *p_elem;
18697 uint32_t id = elem->element_id;
18698
18699 while (conn_src < conn_src_end && conn_src->src->element_id < id) conn_src++;
18700 while (conn_dst < conn_dst_end && conn_dst->dst->element_id < id) conn_dst++;
18701 ufbx_connection *src_end = conn_src, *dst_end = conn_dst;
18702
18703 while (src_end < conn_src_end && src_end->src->element_id == id) src_end++;
18704 while (dst_end < conn_dst_end && dst_end->dst->element_id == id) dst_end++;
18705
18706 elem->connections_src.data = conn_src;
18707 elem->connections_src.count = ufbxi_to_size(src_end - conn_src);
18708 elem->connections_dst.data = conn_dst;
18709 elem->connections_dst.count = ufbxi_to_size(dst_end - conn_dst);
18710
18711 // Setup animated properties
18712 // TODO: It seems we're invalidating a lot of properties here actually, maybe they
18713 // should be initially pushed to `tmp` instead of result if this happens so much..
18714 {
18715 ufbx_prop *prop = elem->props.props.data, *prop_end = ufbxi_add_ptr(prop, elem->props.props.count);
18716 ufbx_prop *copy_start = prop;
18717 bool needs_copy = false;
18718 size_t num_animated = 0, num_synthetic = 0;
18719
18720 for (;;) {
18721 // Scan to the next animation connection
18722 for (; conn_dst < dst_end; conn_dst++) {
18723 if (conn_dst->dst_prop.length == 0) continue;
18724 if (conn_dst->src_prop.length > 0) break;
18725 if (conn_dst->src->type == UFBX_ELEMENT_ANIM_VALUE) break;
18726 }
18727
18728 ufbx_string name = ufbx_empty_string;
18729 if (conn_dst < dst_end) {
18730 name = conn_dst->dst_prop;
18731 }
18732 if (name.length == 0) break;
18733
18734 // NOTE: "Animated" properties also include connected ones as we need
18735 // to resolve them during evaluation
18736 num_animated++;
18737
18738 ufbx_anim_value *anim_value = NULL;
18739 uint32_t flags = 0;
18740 for (; conn_dst < dst_end && conn_dst->dst_prop.data == name.data; conn_dst++) {
18741 if (conn_dst->src_prop.length > 0) {
18742 flags |= UFBX_PROP_FLAG_CONNECTED;
18743 } else if (conn_dst->src->type == UFBX_ELEMENT_ANIM_VALUE) {
18744 anim_value = (ufbx_anim_value*)conn_dst->src;
18745 flags |= UFBX_PROP_FLAG_ANIMATED;
18746 }
18747 }
18748
18749 uint32_t key = ufbxi_get_name_key(name.data, name.length);
18750 while (prop != prop_end && ufbxi_name_key_less(prop, name.data, name.length, key)) prop++;
18751
18752 if (prop != prop_end && prop->name.data == name.data) {
18753 prop->flags = (ufbx_prop_flags)((uint32_t)prop->flags | flags);
18754 } else {
18755 // Animated property that is not in the element property list
18756 // Copy the preceding properties to the stack, then push a
18757 // synthetic property for the animated property.
18758 ufbxi_check(ufbxi_push_copy(&uc->tmp_stack, ufbx_prop, ufbxi_to_size(prop - copy_start), copy_start));
18759 copy_start = prop;
18760 needs_copy = true;
18761
18762 // Let's hope we can find the property in the defaults at least
18763 ufbx_prop anim_def_prop;
18764 ufbx_prop *def_prop = NULL;
18765 if (elem->props.defaults) {
18766 def_prop = ufbxi_find_prop_with_key(elem->props.defaults, name.data, key);
18767 } else if (anim_value) {
18768 memset(&anim_def_prop, 0, sizeof(anim_def_prop));
18769 // Hack a couple of common types
18770 ufbx_prop_type type = UFBX_PROP_UNKNOWN;
18771 if (name.data == ufbxi_Lcl_Translation) type = UFBX_PROP_TRANSLATION;
18772 else if (name.data == ufbxi_Lcl_Rotation) type = UFBX_PROP_ROTATION;
18773 else if (name.data == ufbxi_Lcl_Scaling) {
18774 type = UFBX_PROP_SCALING;
18775 anim_def_prop.value_vec3.x = 1.0f;
18776 anim_def_prop.value_vec3.y = 1.0f;
18777 anim_def_prop.value_vec3.z = 1.0f;
18778 }
18779 // Property values are only defined in anim_props on legacy files
18780 if (uc->version < 6000) {
18781 anim_def_prop.value_vec3 = anim_value->default_value;
18782 }
18783 anim_def_prop.type = type;
18784 def_prop = &anim_def_prop;
18785 } else {
18786 flags |= UFBX_PROP_FLAG_NO_VALUE;
18787 }
18788
18789 ufbx_prop *new_prop = ufbxi_push_zero(&uc->tmp_stack, ufbx_prop, 1);
18790 ufbxi_check(new_prop);
18791 if (def_prop) *new_prop = *def_prop;
18792 flags |= (uint32_t)new_prop->flags;
18793 new_prop->flags = (ufbx_prop_flags)(UFBX_PROP_FLAG_ANIMATABLE | UFBX_PROP_FLAG_SYNTHETIC | flags);
18794 new_prop->name = name;
18795 new_prop->_internal_key = key;
18796 new_prop->value_str = ufbx_empty_string;
18797 new_prop->value_blob = ufbx_empty_blob;
18798 num_synthetic++;
18799 }
18800 }
18801
18802 // Copy the properties if necessary
18803 if (needs_copy) {
18804 size_t num_new_props = elem->props.props.count + num_synthetic;
18805 ufbxi_check(ufbxi_push_copy(&uc->tmp_stack, ufbx_prop, ufbxi_to_size(prop_end - copy_start), copy_start));
18806 elem->props.props.data = ufbxi_push_pop(&uc->result, &uc->tmp_stack, ufbx_prop, num_new_props);
18807 ufbxi_check(elem->props.props.data);
18808 elem->props.props.count = num_new_props;
18809 }
18810 elem->props.num_animated = num_animated;
18811 }
18812
18813 conn_src = src_end;
18814 conn_dst = dst_end;
18815 }
18816
18817 return 1;
18818 }
18819
18820 ufbxi_nodiscard ufbxi_noinline static int ufbxi_linearize_nodes(ufbxi_context *uc)
18821 {
18822 size_t num_nodes = uc->tmp_node_ids.num_items;
18823 uint32_t *node_ids = ufbxi_push_pop(&uc->tmp, &uc->tmp_node_ids, uint32_t, num_nodes);
18824 ufbxi_buf_free(&uc->tmp_node_ids);
18825 ufbxi_check(node_ids);
18826
18827 ufbx_node **node_ptrs = ufbxi_push(&uc->tmp_stack, ufbx_node*, num_nodes);
18828 ufbxi_check(node_ptrs);
18829
18830 // Fetch the node pointers
18831 for (size_t i = 0; i < num_nodes; i++) {
18832 node_ptrs[i] = (ufbx_node*)uc->scene.elements.data[node_ids[i]];
18833 ufbx_assert(node_ptrs[i]->element.type == UFBX_ELEMENT_NODE);
18834 }
18835
18836 uc->scene.root_node = node_ptrs[0];
18837
18838 size_t *node_offsets = ufbxi_push_pop(&uc->tmp_stack, &uc->tmp_typed_element_offsets[UFBX_ELEMENT_NODE], size_t, num_nodes);
18839 ufbxi_check(node_offsets);
18840
18841 // Hook up the parent nodes, we'll assume that there's no cycles at this point
18842 ufbxi_for_ptr(ufbx_node, p_node, node_ptrs, num_nodes) {
18843 ufbx_node *node = *p_node;
18844
18845 // Pre-6000 files don't have any explicit root connections so they must always
18846 // be connected to the root..
18847 if (node->parent == NULL && !(uc->opts.allow_nodes_out_of_root && uc->version >= 6000)) {
18848 if (node != uc->scene.root_node) {
18849 node->parent = uc->scene.root_node;
18850 }
18851 }
18852
18853 ufbxi_for_list(ufbx_connection, conn, node->element.connections_dst) {
18854 if (conn->src_prop.length > 0 || conn->dst_prop.length > 0) continue;
18855 if (conn->src->type != UFBX_ELEMENT_NODE) continue;
18856 ((ufbx_node*)conn->src)->parent = node;
18857 }
18858 }
18859
18860 // Count the parent depths and child amounts
18861 ufbxi_for_ptr(ufbx_node, p_node, node_ptrs, num_nodes) {
18862 ufbx_node *node = *p_node;
18863 uint32_t depth = 0;
18864
18865 for (ufbx_node *p = node->parent; p; p = p->parent) {
18866 depth += p->node_depth + 1;
18867 if (p->node_depth > 0) break;
18868 ufbxi_check_msg(depth <= num_nodes, "Cyclic node hierarchy");
18869 }
18870
18871 if (uc->opts.node_depth_limit > 0) {
18872 ufbxi_check_msg(depth <= uc->opts.node_depth_limit, "Node depth limit exceeded");
18873 }
18874 node->node_depth = depth;
18875
18876 // Second pass to cache the depths to avoid O(n^2)
18877 for (ufbx_node *p = node->parent; p; p = p->parent) {
18878 if (--depth <= p->node_depth) break;
18879 p->node_depth = depth;
18880 }
18881 }
18882
18883 ufbxi_check(ufbxi_sort_node_ptrs(uc, node_ptrs, num_nodes));
18884
18885 for (uint32_t i = 0; i < num_nodes; i++) {
18886 size_t *p_offset = ufbxi_push(&uc->tmp_typed_element_offsets[UFBX_ELEMENT_NODE], size_t, 1);
18887 ufbxi_check(p_offset);
18888 ufbx_node *node = node_ptrs[i];
18889
18890 uint32_t original_id = node->element.typed_id;
18891 node->element.typed_id = i;
18892 *p_offset = node_offsets[original_id];
18893 }
18894
18895 // Pop the temporary arrays
18896 ufbxi_pop(&uc->tmp_stack, size_t, num_nodes, NULL);
18897 ufbxi_pop(&uc->tmp_stack, ufbx_node*, num_nodes, NULL);
18898
18899 return 1;
18900 }
18901
18902
18903 ufbxi_nodiscard ufbxi_noinline static ufbx_connection_list ufbxi_find_dst_connections(ufbx_element *element, const char *prop)
18904 {
18905 if (!prop) prop = ufbxi_empty_char;
18906
18907 size_t begin = element->connections_dst.count, end = begin;
18908
18909 ufbxi_macro_lower_bound_eq(ufbx_connection, 32, &begin,
18910 element->connections_dst.data, 0, element->connections_dst.count,
18911 (strcmp(a->dst_prop.data, prop) < 0),
18912 (a->dst_prop.data == prop && a->src_prop.length == 0));
18913
18914 ufbxi_macro_upper_bound_eq(ufbx_connection, 32, &end,
18915 element->connections_dst.data, begin, element->connections_dst.count,
18916 (a->dst_prop.data == prop && a->src_prop.length == 0));
18917
18918 ufbx_connection_list result = { element->connections_dst.data + begin, end - begin };
18919 return result;
18920 }
18921
18922 ufbxi_nodiscard ufbxi_noinline static ufbx_connection_list ufbxi_find_src_connections(ufbx_element *element, const char *prop)
18923 {
18924 if (!prop) prop = ufbxi_empty_char;
18925
18926 size_t begin = element->connections_src.count, end = begin;
18927
18928 ufbxi_macro_lower_bound_eq(ufbx_connection, 32, &begin,
18929 element->connections_src.data, 0, element->connections_src.count,
18930 (strcmp(a->src_prop.data, prop) < 0),
18931 (a->src_prop.data == prop && a->dst_prop.length == 0));
18932
18933 ufbxi_macro_upper_bound_eq(ufbx_connection, 32, &end,
18934 element->connections_src.data, begin, element->connections_src.count,
18935 (a->src_prop.data == prop && a->dst_prop.length == 0));
18936
18937 ufbx_connection_list result = { element->connections_src.data + begin, end - begin };
18938 return result;
18939 }
18940
18941 ufbxi_nodiscard static ufbx_element *ufbxi_get_element_node(ufbx_element *element)
18942 {
18943 if (!element) return NULL;
18944 if (element->type == UFBX_ELEMENT_NODE) {
18945 ufbx_node *node = (ufbx_node*)element;
18946 if (node->is_geometry_transform_helper) return (ufbx_element*)node->parent;
18947 return NULL;
18948 } else {
18949 return element->instances.count > 0 ? &element->instances.data[0]->element : NULL;
18950 }
18951 }
18952
18953 ufbxi_nodiscard ufbxi_noinline static int ufbxi_fetch_dst_elements(ufbxi_context *uc, void *p_dst_list, ufbx_element *element, bool search_node, bool ignore_duplicates, const char *prop, ufbx_element_type src_type)
18954 {
18955 size_t num_elements = 0;
18956
18957 do {
18958 ufbx_connection_list conns = ufbxi_find_dst_connections(element, prop);
18959 ufbxi_for_list(ufbx_connection, conn, conns) {
18960 if (conn->src->type == src_type) {
18961 if (ignore_duplicates) {
18962 uint32_t element_id = conn->src->element_id;
18963 if (uc->tmp_element_flag[element_id]) {
18964 ufbxi_check(ufbxi_warnf_tag(UFBX_WARNING_DUPLICATE_CONNECTION, element_id, "Duplicate connection to %u", element->element_id));
18965 continue;
18966 }
18967 uc->tmp_element_flag[element_id] = 1;
18968 }
18969 ufbx_element **p_elem = ufbxi_push(&uc->tmp_stack, ufbx_element*, 1);
18970 ufbxi_check(p_elem);
18971 *p_elem = conn->src;
18972 num_elements++;
18973 }
18974 }
18975 } while (search_node && (element = ufbxi_get_element_node(element)) != NULL);
18976
18977 ufbx_element_list *list = (ufbx_element_list*)p_dst_list;
18978 list->data = ufbxi_push_pop(&uc->result, &uc->tmp_stack, ufbx_element*, num_elements);
18979 list->count = num_elements;
18980 ufbxi_check(list->data);
18981
18982 if (ignore_duplicates) {
18983 ufbxi_for_ptr_list(ufbx_element, p_elem, *list) {
18984 uc->tmp_element_flag[(*p_elem)->element_id] = 0;
18985 }
18986 }
18987
18988 return 1;
18989 }
18990
18991 ufbxi_nodiscard ufbxi_noinline static int ufbxi_fetch_src_elements(ufbxi_context *uc, void *p_dst_list, ufbx_element *element, bool search_node, bool ignore_duplicates, const char *prop, ufbx_element_type dst_type)
18992 {
18993 size_t num_elements = 0;
18994
18995 do {
18996 ufbx_connection_list conns = ufbxi_find_src_connections(element, prop);
18997 ufbxi_for_list(ufbx_connection, conn, conns) {
18998 if (conn->dst->type == dst_type) {
18999 if (ignore_duplicates) {
19000 uint32_t element_id = conn->dst->element_id;
19001 if (uc->tmp_element_flag[element_id]) {
19002 ufbxi_check(ufbxi_warnf_tag(UFBX_WARNING_DUPLICATE_CONNECTION, element_id, "Duplicate connection to %u", element->element_id));
19003 continue;
19004 }
19005 uc->tmp_element_flag[element_id] = 1;
19006 }
19007 ufbx_element **p_elem = ufbxi_push(&uc->tmp_stack, ufbx_element*, 1);
19008 ufbxi_check(p_elem);
19009 *p_elem = conn->dst;
19010 num_elements++;
19011 }
19012 }
19013 } while (search_node && (element = ufbxi_get_element_node(element)) != NULL);
19014
19015 ufbx_element_list *list = (ufbx_element_list*)p_dst_list;
19016 list->data = ufbxi_push_pop(&uc->result, &uc->tmp_stack, ufbx_element*, num_elements);
19017 list->count = num_elements;
19018 ufbxi_check(list->data);
19019
19020 if (ignore_duplicates) {
19021 ufbxi_for_ptr_list(ufbx_element, p_elem, *list) {
19022 uc->tmp_element_flag[(*p_elem)->element_id] = 0;
19023 }
19024 }
19025
19026 return 1;
19027 }
19028
19029 ufbxi_nodiscard ufbxi_noinline static ufbx_element *ufbxi_fetch_dst_element(ufbx_element *element, bool search_node, const char *prop, ufbx_element_type src_type)
19030 {
19031 do {
19032 ufbx_connection_list conns = ufbxi_find_dst_connections(element, prop);
19033 ufbxi_for_list(ufbx_connection, conn, conns) {
19034 if (conn->src->type == src_type) {
19035 return conn->src;
19036 }
19037 }
19038 } while (search_node && (element = ufbxi_get_element_node(element)) != NULL);
19039
19040 return NULL;
19041 }
19042
19043 ufbxi_nodiscard ufbxi_noinline static ufbx_element *ufbxi_fetch_src_element(ufbx_element *element, bool search_node, const char *prop, ufbx_element_type dst_type)
19044 {
19045 do {
19046 ufbx_connection_list conns = ufbxi_find_src_connections(element, prop);
19047 ufbxi_for_list(ufbx_connection, conn, conns) {
19048 if (conn->dst->type == dst_type) {
19049 return conn->dst;
19050 }
19051 }
19052 } while (search_node && (element = ufbxi_get_element_node(element)) != NULL);
19053
19054 return NULL;
19055 }
19056
19057 ufbxi_nodiscard ufbxi_noinline static int ufbxi_fetch_textures(ufbxi_context *uc, ufbx_material_texture_list *list, ufbx_element *element, bool search_node)
19058 {
19059 size_t num_textures = 0;
19060
19061 do {
19062 ufbxi_for_list(ufbx_connection, conn, element->connections_dst) {
19063 if (conn->src_prop.length > 0) continue;
19064 if (conn->src->type == UFBX_ELEMENT_TEXTURE) {
19065 ufbx_material_texture *tex = ufbxi_push(&uc->tmp_stack, ufbx_material_texture, 1);
19066 ufbxi_check(tex);
19067 tex->shader_prop = tex->material_prop = conn->dst_prop;
19068 tex->texture = (ufbx_texture*)conn->src;
19069 num_textures++;
19070 }
19071 }
19072 } while (search_node && (element = ufbxi_get_element_node(element)) != NULL);
19073
19074 list->data = ufbxi_push_pop(&uc->result, &uc->tmp_stack, ufbx_material_texture, num_textures);
19075 list->count = num_textures;
19076 ufbxi_check(list->data);
19077
19078 return 1;
19079 }
19080
19081 ufbxi_nodiscard ufbxi_noinline static int ufbxi_fetch_mesh_materials(ufbxi_context *uc, ufbx_material_list *list, ufbx_element *element, bool search_node)
19082 {
19083 size_t num_materials = 0;
19084
19085 do {
19086 ufbx_connection_list conns = ufbxi_find_dst_connections(element, NULL);
19087 ufbxi_for_list(ufbx_connection, conn, conns) {
19088 if (conn->src->type == UFBX_ELEMENT_MATERIAL) {
19089 ufbx_material *mat = (ufbx_material*)conn->src;
19090 ufbxi_check(ufbxi_push_copy(&uc->tmp_stack, ufbx_material*, 1, &mat));
19091 num_materials++;
19092 }
19093 }
19094
19095 if (num_materials > 0) break;
19096 } while (search_node && (element = ufbxi_get_element_node(element)) != NULL);
19097
19098 list->data = ufbxi_push_pop(&uc->result, &uc->tmp_stack, ufbx_material*, num_materials);
19099 list->count = num_materials;
19100 ufbxi_check(list->data);
19101
19102 return 1;
19103 }
19104
19105 ufbxi_nodiscard ufbxi_noinline static int ufbxi_fetch_deformers(ufbxi_context *uc, ufbx_element_list *list, ufbx_element *element, bool search_node)
19106 {
19107 size_t num_deformers = 0;
19108
19109 do {
19110 ufbxi_for_list(ufbx_connection, conn, element->connections_dst) {
19111 if (conn->src_prop.length > 0) continue;
19112 ufbx_element_type type = conn->src->type;
19113 if (type == UFBX_ELEMENT_SKIN_DEFORMER || type == UFBX_ELEMENT_BLEND_DEFORMER || type == UFBX_ELEMENT_CACHE_DEFORMER) {
19114 ufbxi_check(ufbxi_push_copy(&uc->tmp_stack, ufbx_element*, 1, &conn->src));
19115 num_deformers++;
19116 }
19117 }
19118 } while (search_node && (element = ufbxi_get_element_node(element)) != NULL);
19119
19120 list->data = ufbxi_push_pop(&uc->result, &uc->tmp_stack, ufbx_element*, num_deformers);
19121 list->count = num_deformers;
19122 ufbxi_check(list->data);
19123
19124 return 1;
19125 }
19126
19127 ufbxi_nodiscard ufbxi_noinline static int ufbxi_fetch_blend_keyframes(ufbxi_context *uc, ufbx_blend_keyframe_list *list, ufbx_element *element)
19128 {
19129 size_t num_keyframes = 0;
19130
19131 ufbx_connection_list conns = ufbxi_find_dst_connections(element, NULL);
19132 ufbxi_for_list(ufbx_connection, conn, conns) {
19133 if (conn->src->type == UFBX_ELEMENT_BLEND_SHAPE) {
19134 ufbx_blend_keyframe key = { (ufbx_blend_shape*)conn->src };
19135 ufbxi_check(ufbxi_push_copy(&uc->tmp_stack, ufbx_blend_keyframe, 1, &key));
19136 num_keyframes++;
19137 }
19138 }
19139
19140 list->data = ufbxi_push_pop(&uc->result, &uc->tmp_stack, ufbx_blend_keyframe, num_keyframes);
19141 list->count = num_keyframes;
19142 ufbxi_check(list->data);
19143
19144 return 1;
19145 }
19146
19147 ufbxi_nodiscard ufbxi_noinline static int ufbxi_fetch_texture_layers(ufbxi_context *uc, ufbx_texture_layer_list *list, ufbx_element *element)
19148 {
19149 size_t num_layers = 0;
19150
19151 ufbx_connection_list conns = ufbxi_find_dst_connections(element, NULL);
19152 ufbxi_for_list(ufbx_connection, conn, conns) {
19153 if (conn->src->type == UFBX_ELEMENT_TEXTURE) {
19154 ufbx_texture *texture = (ufbx_texture*)conn->src;
19155 ufbx_texture_layer layer = { texture };
19156 layer.alpha = ufbxi_find_real(&texture->props, ufbxi_Texture_alpha, 1.0f);
19157 layer.blend_mode = (ufbx_blend_mode)ufbxi_find_enum(&texture->props, ufbxi_BlendMode, UFBX_BLEND_REPLACE, UFBX_BLEND_OVERLAY);
19158 ufbxi_check(ufbxi_push_copy(&uc->tmp_stack, ufbx_texture_layer, 1, &layer));
19159 num_layers++;
19160 }
19161 }
19162
19163 list->data = ufbxi_push_pop(&uc->result, &uc->tmp_stack, ufbx_texture_layer, num_layers);
19164 list->count = num_layers;
19165 ufbxi_check(list->data);
19166
19167 return 1;
19168 }
19169
19170 static ufbxi_forceinline bool ufbxi_prop_connection_less(const ufbx_connection *a, const char *prop)
19171 {
19172 int cmp = strcmp(a->dst_prop.data, prop);
19173 if (cmp != 0) return cmp < 0;
19174 return a->src_prop.length == 0;
19175 }
19176
19177 ufbxi_nodiscard ufbxi_noinline static ufbx_connection *ufbxi_find_prop_connection(const ufbx_element *element, const char *prop)
19178 {
19179 if (!prop) prop = ufbxi_empty_char;
19180
19181 size_t index = SIZE_MAX;
19182
19183 ufbxi_macro_lower_bound_eq(ufbx_connection, 32, &index,
19184 element->connections_dst.data, 0, element->connections_dst.count,
19185 (ufbxi_prop_connection_less(a, prop)),
19186 (a->dst_prop.data == prop && a->src_prop.length > 0));
19187
19188 return index < SIZE_MAX ? &element->connections_dst.data[index] : NULL;
19189 }
19190
19191 ufbxi_forceinline static void ufbxi_patch_index_pointer(ufbxi_context *uc, uint32_t **p_index)
19192 {
19193 if (*p_index == ufbxi_sentinel_index_zero) {
19194 *p_index = uc->zero_indices;
19195 } else if (*p_index == ufbxi_sentinel_index_consecutive) {
19196 *p_index = uc->consecutive_indices;
19197 }
19198 }
19199
19200 ufbxi_nodiscard static bool ufbxi_cmp_anim_prop_less(const ufbx_anim_prop *a, const ufbx_anim_prop *b)
19201 {
19202 if (a->element != b->element) return a->element < b->element;
19203 if (a->_internal_key != b->_internal_key) return a->_internal_key < b->_internal_key;
19204 return ufbxi_str_less(a->prop_name, b->prop_name);
19205 }
19206
19207 ufbxi_nodiscard ufbxi_noinline static int ufbxi_sort_anim_props(ufbxi_context *uc, ufbx_anim_prop *aprops, size_t count)
19208 {
19209 ufbxi_check(ufbxi_grow_array(&uc->ator_tmp, &uc->tmp_arr, &uc->tmp_arr_size, count * sizeof(ufbx_anim_prop)));
19210 ufbxi_macro_stable_sort(ufbx_anim_prop, 32, aprops, uc->tmp_arr, count, ( ufbxi_cmp_anim_prop_less(a, b) ));
19211 return 1;
19212 }
19213
19214 ufbxi_noinline static bool ufbxi_material_texture_less(void *user, const void *va, const void *vb)
19215 {
19216 (void)user;
19217 const ufbx_material_texture *a = (const ufbx_material_texture*)va, *b = (const ufbx_material_texture*)vb;
19218 return ufbxi_str_less(a->material_prop, b->material_prop);
19219 }
19220
19221 ufbxi_nodiscard ufbxi_noinline static int ufbxi_sort_material_textures(ufbxi_context *uc, ufbx_material_texture *textures, size_t count)
19222 {
19223 ufbxi_check(ufbxi_grow_array(&uc->ator_tmp, &uc->tmp_arr, &uc->tmp_arr_size, count * sizeof(ufbx_material_texture)));
19224 ufbxi_stable_sort(sizeof(ufbx_material_texture), 32, textures, uc->tmp_arr, count, &ufbxi_material_texture_less, NULL);
19225 return 1;
19226 }
19227
19228 static ufbxi_noinline bool ufbxi_bone_pose_less(void *user, const void *va, const void *vb)
19229 {
19230 (void)user;
19231 const ufbx_bone_pose *a = (const ufbx_bone_pose *)va, *b = (const ufbx_bone_pose *)vb;
19232 return a->bone_node->typed_id < b->bone_node->typed_id;
19233 }
19234
19235 ufbxi_nodiscard ufbxi_noinline static ufbx_anim_prop *ufbxi_find_anim_prop_start(ufbx_anim_layer *layer, const ufbx_element *element)
19236 {
19237 size_t index = SIZE_MAX;
19238 ufbxi_macro_lower_bound_eq(ufbx_anim_prop, 16, &index, layer->anim_props.data, 0, layer->anim_props.count,
19239 (a->element < element), (a->element == element));
19240 return index != SIZE_MAX ? &layer->anim_props.data[index] : NULL;
19241 }
19242
19243 ufbxi_nodiscard ufbxi_noinline static int ufbxi_sort_bone_poses(ufbxi_context *uc, ufbx_pose *pose)
19244 {
19245 size_t count = pose->bone_poses.count;
19246 ufbxi_check(ufbxi_grow_array(&uc->ator_tmp, &uc->tmp_arr, &uc->tmp_arr_size, pose->bone_poses.count * sizeof(ufbx_bone_pose)));
19247 ufbxi_stable_sort(sizeof(ufbx_bone_pose), 16, pose->bone_poses.data, uc->tmp_arr, count, &ufbxi_bone_pose_less, NULL);
19248 return 1;
19249 }
19250
19251 ufbxi_nodiscard ufbxi_noinline static int ufbxi_sort_skin_weights(ufbxi_context *uc, ufbx_skin_deformer *skin)
19252 {
19253 ufbxi_check(ufbxi_grow_array(&uc->ator_tmp, &uc->tmp_arr, &uc->tmp_arr_size, skin->max_weights_per_vertex * sizeof(ufbx_skin_weight)));
19254
19255 for (size_t i = 0; i < skin->vertices.count; i++) {
19256 ufbx_skin_vertex v = skin->vertices.data[i];
19257 ufbxi_macro_stable_sort(ufbx_skin_weight, 32, skin->weights.data + v.weight_begin, uc->tmp_arr, v.num_weights,
19258 ( a->weight > b->weight ));
19259 }
19260
19261 return 1;
19262 }
19263
19264 ufbxi_noinline static bool ufbxi_blend_keyframe_less(void *user, const void *va, const void *vb)
19265 {
19266 (void)user;
19267 const ufbx_blend_keyframe *a = (const ufbx_blend_keyframe*)va, *b = (const ufbx_blend_keyframe*)vb;
19268 return a->target_weight < b->target_weight;
19269 }
19270
19271 ufbxi_nodiscard ufbxi_noinline static int ufbxi_sort_blend_keyframes(ufbxi_context *uc, ufbx_blend_keyframe *keyframes, size_t count)
19272 {
19273 ufbxi_check(ufbxi_grow_array(&uc->ator_tmp, &uc->tmp_arr, &uc->tmp_arr_size, count * sizeof(ufbx_blend_keyframe)));
19274 ufbxi_stable_sort(sizeof(ufbx_blend_keyframe), 32, keyframes, uc->tmp_arr, count, &ufbxi_blend_keyframe_less, NULL);
19275 return 1;
19276 }
19277
19278 // Material tables
19279
19280 typedef void (*ufbxi_mat_transform_fn)(ufbx_vec4 *a);
19281
19282 static void ufbxi_mat_transform_invert_x(ufbx_vec4 *v) { v->x = 1.0f - v->x; }
19283 static void ufbxi_mat_transform_unknown_shininess(ufbx_vec4 *v) { if (v->x >= 0.0f) v->x = (ufbx_real)(1.0f - ufbx_sqrt(v->x) * (ufbx_real)0.1); if (!(v->x >= 0.0f)) v->x = 0.0f; }
19284 static void ufbxi_mat_transform_blender_opacity(ufbx_vec4 *v) { v->x = 1.0f - v->x; }
19285 static void ufbxi_mat_transform_blender_shininess(ufbx_vec4 *v) { if (v->x >= 0.0f) v->x = (ufbx_real)(1.0f - ufbx_sqrt(v->x) * (ufbx_real)0.1); if (!(v->x >= 0.0f)) v->x = 0.0f; }
19286
19287 typedef enum {
19288 UFBXI_MAT_TRANSFORM_IDENTITY,
19289 UFBXI_MAT_TRANSFORM_INVERT_X,
19290 UFBXI_MAT_TRANSFORM_UNKNOWN_SHININESS,
19291 UFBXI_MAT_TRANSFORM_BLENDER_OPACITY,
19292 UFBXI_MAT_TRANSFORM_BLENDER_SHININESS,
19293
19294 UFBXI_MAT_TRANSFORM_COUNT,
19295 } ufbxi_mat_transform;
19296
19297 typedef enum {
19298 // Set `value_vec4.w` (usually alpha) to 1.0 if not defined by the property
19299 UFBXI_SHADER_MAPPING_DEFAULT_W_1 = 0x1,
19300 // Widen values to RGB if only a single value is present.
19301 UFBXI_SHADER_MAPPING_WIDEN_TO_RGB = 0x2,
19302 // Multiply the existing value.
19303 UFBXI_SHADER_MAPPING_MULTIPLY_VALUE = 0x4,
19304 } ufbxi_shader_mapping_flag;
19305
19306 typedef enum {
19307 // Invert the feature flag
19308 UFBXI_SHADER_FEATURE_INVERTED = 0x1,
19309 // Enable the feature if the given property exists
19310 UFBXI_SHADER_FEATURE_IF_EXISTS = 0x2,
19311 // Enable the feature if the given property has a texture
19312 UFBXI_SHADER_FEATURE_IF_TEXTURE = 0x4,
19313 // Enable if the feature is in [0.5, 1.5], (ie. 2 won't enable this feature)
19314 UFBXI_SHADER_FEATURE_IF_AROUND_1 = 0x8,
19315
19316 UFBXI_SHADER_FEATURE_IF_EXISTS_OR_TEXTURE = UFBXI_SHADER_FEATURE_IF_EXISTS|UFBXI_SHADER_FEATURE_IF_TEXTURE,
19317 } ufbxi_shader_feature_flag;
19318
19319 static const ufbxi_mat_transform_fn ufbxi_mat_transform_fns[] = {
19320 NULL,
19321 &ufbxi_mat_transform_invert_x,
19322 &ufbxi_mat_transform_unknown_shininess,
19323 &ufbxi_mat_transform_blender_opacity,
19324 &ufbxi_mat_transform_blender_shininess,
19325 };
19326
19327 ufbx_static_assert(transform_count, ufbxi_arraycount(ufbxi_mat_transform_fns) == UFBXI_MAT_TRANSFORM_COUNT);
19328
19329 typedef struct {
19330 uint8_t index; // < `ufbx_material_(fbx|pbr)_map`
19331 uint8_t flags; // < Combination of `ufbxi_shader_mapping_flag`
19332 uint8_t transform; // < `ufbxi_mat_transform`
19333 uint8_t prop_len; // < Length of `prop` not including NULL terminator
19334 const char *prop; // < Name of FBX material property or shader mapping
19335 } ufbxi_shader_mapping;
19336
19337 typedef struct {
19338 const ufbxi_shader_mapping *data;
19339 size_t count;
19340 const ufbxi_shader_mapping *features;
19341 size_t feature_count;
19342 uint32_t default_features;
19343 ufbx_string texture_prefix;
19344 ufbx_string texture_suffix;
19345 ufbx_string texture_enabled_prefix;
19346 ufbx_string texture_enabled_suffix;
19347 } ufbxi_shader_mapping_list;
19348
19349 #define ufbxi_mat_string(str) sizeof(str) - 1, str
19350
19351 static const ufbxi_shader_mapping ufbxi_base_fbx_mapping[] = {
19352 { UFBX_MATERIAL_FBX_DIFFUSE_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("Diffuse") },
19353 { UFBX_MATERIAL_FBX_DIFFUSE_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("DiffuseColor") },
19354 { UFBX_MATERIAL_FBX_DIFFUSE_FACTOR, 0, 0, ufbxi_mat_string("DiffuseFactor") },
19355 { UFBX_MATERIAL_FBX_SPECULAR_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("Specular") },
19356 { UFBX_MATERIAL_FBX_SPECULAR_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("SpecularColor") },
19357 { UFBX_MATERIAL_FBX_SPECULAR_FACTOR, 0, 0, ufbxi_mat_string("SpecularFactor") },
19358 { UFBX_MATERIAL_FBX_SPECULAR_EXPONENT, 0, 0, ufbxi_mat_string("Shininess") },
19359 { UFBX_MATERIAL_FBX_SPECULAR_EXPONENT, 0, 0, ufbxi_mat_string("ShininessExponent") },
19360 { UFBX_MATERIAL_FBX_REFLECTION_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("Reflection") },
19361 { UFBX_MATERIAL_FBX_REFLECTION_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("ReflectionColor") },
19362 { UFBX_MATERIAL_FBX_REFLECTION_FACTOR, 0, 0, ufbxi_mat_string("ReflectionFactor") },
19363 { UFBX_MATERIAL_FBX_TRANSPARENCY_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("Transparent") },
19364 { UFBX_MATERIAL_FBX_TRANSPARENCY_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("TransparentColor") },
19365 { UFBX_MATERIAL_FBX_TRANSPARENCY_FACTOR, 0, 0, ufbxi_mat_string("TransparentFactor") },
19366 { UFBX_MATERIAL_FBX_TRANSPARENCY_FACTOR, 0, 0, ufbxi_mat_string("TransparencyFactor") },
19367 { UFBX_MATERIAL_FBX_EMISSION_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("Emissive") },
19368 { UFBX_MATERIAL_FBX_EMISSION_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("EmissiveColor") },
19369 { UFBX_MATERIAL_FBX_EMISSION_FACTOR, 0, 0, ufbxi_mat_string("EmissiveFactor") },
19370 { UFBX_MATERIAL_FBX_AMBIENT_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("Ambient") },
19371 { UFBX_MATERIAL_FBX_AMBIENT_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("AmbientColor") },
19372 { UFBX_MATERIAL_FBX_AMBIENT_FACTOR, 0, 0, ufbxi_mat_string("AmbientFactor") },
19373 { UFBX_MATERIAL_FBX_NORMAL_MAP, 0, 0, ufbxi_mat_string("NormalMap") },
19374 { UFBX_MATERIAL_FBX_BUMP, 0, 0, ufbxi_mat_string("Bump") },
19375 { UFBX_MATERIAL_FBX_BUMP_FACTOR, 0, 0, ufbxi_mat_string("BumpFactor") },
19376 { UFBX_MATERIAL_FBX_DISPLACEMENT, 0, 0, ufbxi_mat_string("Displacement") },
19377 { UFBX_MATERIAL_FBX_DISPLACEMENT_FACTOR, 0, 0, ufbxi_mat_string("DisplacementFactor") },
19378 { UFBX_MATERIAL_FBX_VECTOR_DISPLACEMENT, 0, 0, ufbxi_mat_string("VectorDisplacement") },
19379 { UFBX_MATERIAL_FBX_VECTOR_DISPLACEMENT_FACTOR, 0, 0, ufbxi_mat_string("VectorDisplacementFactor") },
19380 };
19381
19382 static const ufbxi_shader_mapping ufbxi_obj_fbx_mapping[] = {
19383 { UFBX_MATERIAL_FBX_AMBIENT_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1|UFBXI_SHADER_MAPPING_WIDEN_TO_RGB, 0, ufbxi_mat_string("Ka") },
19384 { UFBX_MATERIAL_FBX_DIFFUSE_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1|UFBXI_SHADER_MAPPING_WIDEN_TO_RGB, 0, ufbxi_mat_string("Kd") },
19385 { UFBX_MATERIAL_FBX_SPECULAR_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1|UFBXI_SHADER_MAPPING_WIDEN_TO_RGB, 0, ufbxi_mat_string("Ks") },
19386 { UFBX_MATERIAL_FBX_EMISSION_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1|UFBXI_SHADER_MAPPING_WIDEN_TO_RGB, 0, ufbxi_mat_string("Ke") },
19387 { UFBX_MATERIAL_FBX_SPECULAR_EXPONENT, 0, 0, ufbxi_mat_string("Ns") },
19388 { UFBX_MATERIAL_FBX_TRANSPARENCY_FACTOR, 0, UFBXI_MAT_TRANSFORM_INVERT_X, ufbxi_mat_string("d") },
19389 { UFBX_MATERIAL_FBX_NORMAL_MAP, 0, 0, ufbxi_mat_string("norm") },
19390 { UFBX_MATERIAL_FBX_DISPLACEMENT, 0, 0, ufbxi_mat_string("disp") },
19391 { UFBX_MATERIAL_FBX_BUMP, 0, 0, ufbxi_mat_string("bump") },
19392 };
19393
19394 static const ufbxi_shader_mapping ufbxi_fbx_lambert_shader_pbr_mapping[] = {
19395 { UFBX_MATERIAL_PBR_BASE_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("Diffuse") },
19396 { UFBX_MATERIAL_PBR_BASE_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("DiffuseColor") },
19397 { UFBX_MATERIAL_PBR_BASE_FACTOR, 0, 0, ufbxi_mat_string("DiffuseFactor") },
19398 { UFBX_MATERIAL_PBR_TRANSMISSION_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("Transparent") },
19399 { UFBX_MATERIAL_PBR_TRANSMISSION_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("TransparentColor") },
19400 { UFBX_MATERIAL_PBR_TRANSMISSION_FACTOR, 0, 0, ufbxi_mat_string("TransparentFactor") },
19401 { UFBX_MATERIAL_PBR_TRANSMISSION_FACTOR, 0, 0, ufbxi_mat_string("TransparencyFactor") },
19402 { UFBX_MATERIAL_PBR_EMISSION_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("Emissive") },
19403 { UFBX_MATERIAL_PBR_EMISSION_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("EmissiveColor") },
19404 { UFBX_MATERIAL_PBR_EMISSION_FACTOR, 0, 0, ufbxi_mat_string("EmissiveFactor") },
19405 { UFBX_MATERIAL_PBR_NORMAL_MAP, 0, 0, ufbxi_mat_string("NormalMap") },
19406 };
19407
19408 static const ufbxi_shader_mapping ufbxi_fbx_phong_shader_pbr_mapping[] = {
19409 { UFBX_MATERIAL_PBR_BASE_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("Diffuse") },
19410 { UFBX_MATERIAL_PBR_BASE_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("DiffuseColor") },
19411 { UFBX_MATERIAL_PBR_BASE_FACTOR, 0, 0, ufbxi_mat_string("DiffuseFactor") },
19412 { UFBX_MATERIAL_PBR_SPECULAR_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("Specular") },
19413 { UFBX_MATERIAL_PBR_SPECULAR_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("SpecularColor") },
19414 { UFBX_MATERIAL_PBR_SPECULAR_FACTOR, 0, 0, ufbxi_mat_string("SpecularFactor") },
19415 { UFBX_MATERIAL_PBR_ROUGHNESS, 0, UFBXI_MAT_TRANSFORM_UNKNOWN_SHININESS, ufbxi_mat_string("Shininess") },
19416 { UFBX_MATERIAL_PBR_ROUGHNESS, 0, UFBXI_MAT_TRANSFORM_UNKNOWN_SHININESS, ufbxi_mat_string("ShininessExponent") },
19417 { UFBX_MATERIAL_PBR_TRANSMISSION_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("Transparent") },
19418 { UFBX_MATERIAL_PBR_TRANSMISSION_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("TransparentColor") },
19419 { UFBX_MATERIAL_PBR_TRANSMISSION_FACTOR, 0, 0, ufbxi_mat_string("TransparentFactor") },
19420 { UFBX_MATERIAL_PBR_TRANSMISSION_FACTOR, 0, 0, ufbxi_mat_string("TransparencyFactor") },
19421 { UFBX_MATERIAL_PBR_EMISSION_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("Emissive") },
19422 { UFBX_MATERIAL_PBR_EMISSION_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("EmissiveColor") },
19423 { UFBX_MATERIAL_PBR_EMISSION_FACTOR, 0, 0, ufbxi_mat_string("EmissiveFactor") },
19424 { UFBX_MATERIAL_PBR_NORMAL_MAP, 0, 0, ufbxi_mat_string("NormalMap") },
19425 };
19426
19427 static const ufbxi_shader_mapping ufbxi_osl_standard_shader_pbr_mapping[] = {
19428 { UFBX_MATERIAL_PBR_BASE_FACTOR, 0, 0, ufbxi_mat_string("base") },
19429 { UFBX_MATERIAL_PBR_BASE_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("base_color") },
19430 { UFBX_MATERIAL_PBR_ROUGHNESS, 0, 0, ufbxi_mat_string("specular_roughness") },
19431 { UFBX_MATERIAL_PBR_DIFFUSE_ROUGHNESS, 0, 0, ufbxi_mat_string("diffuse_roughness") },
19432 { UFBX_MATERIAL_PBR_METALNESS, 0, 0, ufbxi_mat_string("metalness") },
19433 { UFBX_MATERIAL_PBR_SPECULAR_FACTOR, 0, 0, ufbxi_mat_string("specular") },
19434 { UFBX_MATERIAL_PBR_SPECULAR_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("specular_color") },
19435 { UFBX_MATERIAL_PBR_SPECULAR_IOR, 0, 0, ufbxi_mat_string("specular_IOR") },
19436 { UFBX_MATERIAL_PBR_SPECULAR_ANISOTROPY, 0, 0, ufbxi_mat_string("specular_anisotropy") },
19437 { UFBX_MATERIAL_PBR_SPECULAR_ROTATION, 0, 0, ufbxi_mat_string("specular_rotation") },
19438 { UFBX_MATERIAL_PBR_TRANSMISSION_FACTOR, 0, 0, ufbxi_mat_string("transmission") },
19439 { UFBX_MATERIAL_PBR_TRANSMISSION_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("transmission_color") },
19440 { UFBX_MATERIAL_PBR_TRANSMISSION_DEPTH, 0, 0, ufbxi_mat_string("transmission_depth") },
19441 { UFBX_MATERIAL_PBR_TRANSMISSION_SCATTER, UFBXI_SHADER_MAPPING_WIDEN_TO_RGB, 0, ufbxi_mat_string("transmission_scatter") },
19442 { UFBX_MATERIAL_PBR_TRANSMISSION_SCATTER_ANISOTROPY, 0, 0, ufbxi_mat_string("transmission_scatter_anisotropy") },
19443 { UFBX_MATERIAL_PBR_TRANSMISSION_DISPERSION, 0, 0, ufbxi_mat_string("transmission_dispersion") },
19444 { UFBX_MATERIAL_PBR_TRANSMISSION_EXTRA_ROUGHNESS, 0, 0, ufbxi_mat_string("transmission_extra_roughness") },
19445 { UFBX_MATERIAL_PBR_SUBSURFACE_FACTOR, 0, 0, ufbxi_mat_string("subsurface") },
19446 { UFBX_MATERIAL_PBR_SUBSURFACE_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("subsurface_color") },
19447 { UFBX_MATERIAL_PBR_SUBSURFACE_RADIUS, UFBXI_SHADER_MAPPING_WIDEN_TO_RGB, 0, ufbxi_mat_string("subsurface_radius") },
19448 { UFBX_MATERIAL_PBR_SUBSURFACE_SCALE, 0, 0, ufbxi_mat_string("subsurface_scale") },
19449 { UFBX_MATERIAL_PBR_SUBSURFACE_ANISOTROPY, 0, 0, ufbxi_mat_string("subsurface_anisotropy") },
19450 { UFBX_MATERIAL_PBR_SHEEN_FACTOR, 0, 0, ufbxi_mat_string("sheen") },
19451 { UFBX_MATERIAL_PBR_SHEEN_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("sheen_color") },
19452 { UFBX_MATERIAL_PBR_SHEEN_ROUGHNESS, 0, 0, ufbxi_mat_string("sheen_roughness") },
19453 { UFBX_MATERIAL_PBR_COAT_FACTOR, 0, 0, ufbxi_mat_string("coat") },
19454 { UFBX_MATERIAL_PBR_COAT_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("coat_color") },
19455 { UFBX_MATERIAL_PBR_COAT_ROUGHNESS, 0, 0, ufbxi_mat_string("coat_roughness") },
19456 { UFBX_MATERIAL_PBR_COAT_IOR, 0, 0, ufbxi_mat_string("coat_IOR") },
19457 { UFBX_MATERIAL_PBR_COAT_ANISOTROPY, 0, 0, ufbxi_mat_string("coat_anisotropy") },
19458 { UFBX_MATERIAL_PBR_COAT_ROTATION, 0, 0, ufbxi_mat_string("coat_rotation") },
19459 { UFBX_MATERIAL_PBR_COAT_NORMAL, 0, 0, ufbxi_mat_string("coat_normal") },
19460 { UFBX_MATERIAL_PBR_COAT_AFFECT_BASE_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("coat_affect_color") },
19461 { UFBX_MATERIAL_PBR_COAT_AFFECT_BASE_ROUGHNESS, 0, 0, ufbxi_mat_string("coat_affect_roughness") },
19462 { UFBX_MATERIAL_PBR_THIN_FILM_THICKNESS, 0, 0, ufbxi_mat_string("thin_film_thickness") },
19463 { UFBX_MATERIAL_PBR_THIN_FILM_IOR, 0, 0, ufbxi_mat_string("thin_film_IOR") },
19464 { UFBX_MATERIAL_PBR_EMISSION_FACTOR, 0, 0, ufbxi_mat_string("emission") },
19465 { UFBX_MATERIAL_PBR_EMISSION_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("emission_color") },
19466 { UFBX_MATERIAL_PBR_OPACITY, UFBXI_SHADER_MAPPING_WIDEN_TO_RGB, 0, ufbxi_mat_string("opacity") },
19467 { UFBX_MATERIAL_PBR_NORMAL_MAP, 0, 0, ufbxi_mat_string("NormalMap") },
19468 { UFBX_MATERIAL_PBR_NORMAL_MAP, 0, 0, ufbxi_mat_string("normalCamera") },
19469 { UFBX_MATERIAL_PBR_TANGENT_MAP, 0, 0, ufbxi_mat_string("tangent") },
19470 };
19471
19472 static const ufbxi_shader_mapping ufbxi_osl_standard_shader_features[] = {
19473 { UFBX_MATERIAL_FEATURE_THIN_WALLED, 0, 0, ufbxi_mat_string("thin_walled") },
19474 };
19475
19476 static const ufbxi_shader_mapping ufbxi_arnold_shader_pbr_mapping[] = {
19477 { UFBX_MATERIAL_PBR_BASE_FACTOR, 0, 0, ufbxi_mat_string("base") },
19478 { UFBX_MATERIAL_PBR_BASE_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("baseColor") },
19479 { UFBX_MATERIAL_PBR_ROUGHNESS, 0, 0, ufbxi_mat_string("specularRoughness") },
19480 { UFBX_MATERIAL_PBR_DIFFUSE_ROUGHNESS, 0, 0, ufbxi_mat_string("diffuseRoughness") },
19481 { UFBX_MATERIAL_PBR_METALNESS, 0, 0, ufbxi_mat_string("metalness") },
19482 { UFBX_MATERIAL_PBR_SPECULAR_FACTOR, 0, 0, ufbxi_mat_string("specular") },
19483 { UFBX_MATERIAL_PBR_SPECULAR_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("specularColor") },
19484 { UFBX_MATERIAL_PBR_SPECULAR_IOR, 0, 0, ufbxi_mat_string("specularIOR") },
19485 { UFBX_MATERIAL_PBR_SPECULAR_ANISOTROPY, 0, 0, ufbxi_mat_string("specularAnisotropy") },
19486 { UFBX_MATERIAL_PBR_SPECULAR_ROTATION, 0, 0, ufbxi_mat_string("specularRotation") },
19487 { UFBX_MATERIAL_PBR_TRANSMISSION_FACTOR, 0, 0, ufbxi_mat_string("transmission") },
19488 { UFBX_MATERIAL_PBR_TRANSMISSION_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("transmissionColor") },
19489 { UFBX_MATERIAL_PBR_TRANSMISSION_DEPTH, 0, 0, ufbxi_mat_string("transmissionDepth") },
19490 { UFBX_MATERIAL_PBR_TRANSMISSION_SCATTER, UFBXI_SHADER_MAPPING_WIDEN_TO_RGB, 0, ufbxi_mat_string("transmissionScatter") },
19491 { UFBX_MATERIAL_PBR_TRANSMISSION_SCATTER_ANISOTROPY, 0, 0, ufbxi_mat_string("transmissionScatterAnisotropy") },
19492 { UFBX_MATERIAL_PBR_TRANSMISSION_DISPERSION, 0, 0, ufbxi_mat_string("transmissionDispersion") },
19493 { UFBX_MATERIAL_PBR_TRANSMISSION_EXTRA_ROUGHNESS, 0, 0, ufbxi_mat_string("transmissionExtraRoughness") },
19494 { UFBX_MATERIAL_PBR_SUBSURFACE_FACTOR, 0, 0, ufbxi_mat_string("subsurface") },
19495 { UFBX_MATERIAL_PBR_SUBSURFACE_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("subsurfaceColor") },
19496 { UFBX_MATERIAL_PBR_SUBSURFACE_RADIUS, UFBXI_SHADER_MAPPING_WIDEN_TO_RGB, 0, ufbxi_mat_string("subsurfaceRadius") },
19497 { UFBX_MATERIAL_PBR_SUBSURFACE_SCALE, 0, 0, ufbxi_mat_string("subsurfaceScale") },
19498 { UFBX_MATERIAL_PBR_SUBSURFACE_ANISOTROPY, 0, 0, ufbxi_mat_string("subsurfaceAnisotropy") },
19499 { UFBX_MATERIAL_PBR_SHEEN_FACTOR, 0, 0, ufbxi_mat_string("sheen") },
19500 { UFBX_MATERIAL_PBR_SHEEN_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("sheenColor") },
19501 { UFBX_MATERIAL_PBR_SHEEN_ROUGHNESS, 0, 0, ufbxi_mat_string("sheenRoughness") },
19502 { UFBX_MATERIAL_PBR_COAT_FACTOR, 0, 0, ufbxi_mat_string("coat") },
19503 { UFBX_MATERIAL_PBR_COAT_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("coatColor") },
19504 { UFBX_MATERIAL_PBR_COAT_ROUGHNESS, 0, 0, ufbxi_mat_string("coatRoughness") },
19505 { UFBX_MATERIAL_PBR_COAT_IOR, 0, 0, ufbxi_mat_string("coatIOR") },
19506 { UFBX_MATERIAL_PBR_COAT_ANISOTROPY, 0, 0, ufbxi_mat_string("coatAnisotropy") },
19507 { UFBX_MATERIAL_PBR_COAT_ROTATION, 0, 0, ufbxi_mat_string("coatRotation") },
19508 { UFBX_MATERIAL_PBR_COAT_NORMAL, 0, 0, ufbxi_mat_string("coatNormal") },
19509 { UFBX_MATERIAL_PBR_THIN_FILM_THICKNESS, 0, 0, ufbxi_mat_string("thinFilmThickness") },
19510 { UFBX_MATERIAL_PBR_THIN_FILM_IOR, 0, 0, ufbxi_mat_string("thinFilmIOR") },
19511 { UFBX_MATERIAL_PBR_EMISSION_FACTOR, 0, 0, ufbxi_mat_string("emission") },
19512 { UFBX_MATERIAL_PBR_EMISSION_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("emissionColor") },
19513 { UFBX_MATERIAL_PBR_OPACITY, UFBXI_SHADER_MAPPING_WIDEN_TO_RGB, 0, ufbxi_mat_string("opacity") },
19514 { UFBX_MATERIAL_PBR_INDIRECT_DIFFUSE, 0, 0, ufbxi_mat_string("indirectDiffuse") },
19515 { UFBX_MATERIAL_PBR_INDIRECT_SPECULAR, 0, 0, ufbxi_mat_string("indirectSpecular") },
19516 { UFBX_MATERIAL_PBR_NORMAL_MAP, 0, 0, ufbxi_mat_string("NormalMap") },
19517 { UFBX_MATERIAL_PBR_NORMAL_MAP, 0, 0, ufbxi_mat_string("normalCamera") },
19518 { UFBX_MATERIAL_PBR_TANGENT_MAP, 0, 0, ufbxi_mat_string("tangent") },
19519 { UFBX_MATERIAL_PBR_MATTE_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("aiMatteColor") },
19520 { UFBX_MATERIAL_PBR_MATTE_FACTOR, 0, 0, ufbxi_mat_string("aiMatteColorA") },
19521 { UFBX_MATERIAL_PBR_SUBSURFACE_TYPE, 0, 0, ufbxi_mat_string("subsurfaceType") },
19522 { UFBX_MATERIAL_PBR_TRANSMISSION_PRIORITY, 0, 0, ufbxi_mat_string("dielectricPriority") },
19523 { UFBX_MATERIAL_PBR_TRANSMISSION_ENABLE_IN_AOV, 0, 0, ufbxi_mat_string("transmitAovs") },
19524 };
19525
19526 static const ufbxi_shader_mapping ufbxi_arnold_shader_features[] = {
19527 { UFBX_MATERIAL_FEATURE_MATTE, 0, 0, ufbxi_mat_string("aiEnableMatte") },
19528 { UFBX_MATERIAL_FEATURE_THIN_WALLED, 0, 0, ufbxi_mat_string("thinWalled") },
19529 { UFBX_MATERIAL_FEATURE_CAUSTICS, 0, 0, ufbxi_mat_string("caustics") },
19530 { UFBX_MATERIAL_FEATURE_INTERNAL_REFLECTIONS, 0, 0, ufbxi_mat_string("internalReflections") },
19531 { UFBX_MATERIAL_FEATURE_EXIT_TO_BACKGROUND, 0, 0, ufbxi_mat_string("exitToBackground") },
19532 };
19533
19534 static const ufbxi_shader_mapping ufbxi_3ds_max_physical_material_pbr_mapping[] = {
19535 { UFBX_MATERIAL_PBR_BASE_FACTOR, 0, 0, ufbxi_mat_string("base_weight") },
19536 { UFBX_MATERIAL_PBR_BASE_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("base_color") },
19537 { UFBX_MATERIAL_PBR_ROUGHNESS, 0, 0, ufbxi_mat_string("roughness") },
19538 { UFBX_MATERIAL_PBR_DIFFUSE_ROUGHNESS, 0, 0, ufbxi_mat_string("diff_rough") },
19539 { UFBX_MATERIAL_PBR_DIFFUSE_ROUGHNESS, 0, 0, ufbxi_mat_string("diff_roughness") },
19540 { UFBX_MATERIAL_PBR_METALNESS, 0, 0, ufbxi_mat_string("metalness") },
19541 { UFBX_MATERIAL_PBR_SPECULAR_FACTOR, 0, 0, ufbxi_mat_string("reflectivity") },
19542 { UFBX_MATERIAL_PBR_SPECULAR_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("refl_color") },
19543 { UFBX_MATERIAL_PBR_SPECULAR_ANISOTROPY, 0, 0, ufbxi_mat_string("anisotropy") },
19544 { UFBX_MATERIAL_PBR_SPECULAR_ROTATION, 0, 0, ufbxi_mat_string("aniso_angle") },
19545 { UFBX_MATERIAL_PBR_SPECULAR_ROTATION, 0, 0, ufbxi_mat_string("anisoangle") },
19546 { UFBX_MATERIAL_PBR_SPECULAR_IOR, 0, 0, ufbxi_mat_string("trans_ior") }, // NOTE: Not a typo, IOR is same for transparency/specular
19547 { UFBX_MATERIAL_PBR_TRANSMISSION_FACTOR, 0, 0, ufbxi_mat_string("transparency") },
19548 { UFBX_MATERIAL_PBR_TRANSMISSION_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("trans_color") },
19549 { UFBX_MATERIAL_PBR_TRANSMISSION_DEPTH, 0, 0, ufbxi_mat_string("trans_depth") },
19550 { UFBX_MATERIAL_PBR_TRANSMISSION_ROUGHNESS, 0, 0, ufbxi_mat_string("trans_rough") },
19551 { UFBX_MATERIAL_PBR_TRANSMISSION_ROUGHNESS, 0, 0, ufbxi_mat_string("trans_roughness") },
19552 { UFBX_MATERIAL_PBR_SUBSURFACE_FACTOR, 0, 0, ufbxi_mat_string("scattering") },
19553 { UFBX_MATERIAL_PBR_SUBSURFACE_TINT_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("sss_color") },
19554 { UFBX_MATERIAL_PBR_SUBSURFACE_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("sss_scatter_color") },
19555 { UFBX_MATERIAL_PBR_SUBSURFACE_RADIUS, UFBXI_SHADER_MAPPING_WIDEN_TO_RGB, 0, ufbxi_mat_string("sss_depth") },
19556 { UFBX_MATERIAL_PBR_SUBSURFACE_SCALE, 0, 0, ufbxi_mat_string("sss_scale") },
19557 { UFBX_MATERIAL_PBR_COAT_FACTOR, 0, 0, ufbxi_mat_string("coat") },
19558 { UFBX_MATERIAL_PBR_COAT_FACTOR, 0, 0, ufbxi_mat_string("coating") },
19559 { UFBX_MATERIAL_PBR_COAT_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("coat_color") },
19560 { UFBX_MATERIAL_PBR_COAT_ROUGHNESS, 0, 0, ufbxi_mat_string("coat_rough") },
19561 { UFBX_MATERIAL_PBR_COAT_ROUGHNESS, 0, 0, ufbxi_mat_string("coat_roughness") },
19562 { UFBX_MATERIAL_PBR_COAT_IOR, 0, 0, ufbxi_mat_string("coat_ior") },
19563 { UFBX_MATERIAL_PBR_COAT_NORMAL, 0, 0, ufbxi_mat_string("coat_bump") },
19564 { UFBX_MATERIAL_PBR_COAT_NORMAL, 0, 0, ufbxi_mat_string("clearcoat_bump_map_amt") },
19565 { UFBX_MATERIAL_PBR_COAT_AFFECT_BASE_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("coat_affect_color") },
19566 { UFBX_MATERIAL_PBR_COAT_AFFECT_BASE_ROUGHNESS, 0, 0, ufbxi_mat_string("coat_affect_roughness") },
19567 { UFBX_MATERIAL_PBR_EMISSION_FACTOR, 0, 0, ufbxi_mat_string("emission") },
19568 { UFBX_MATERIAL_PBR_EMISSION_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("emit_color") },
19569 { UFBX_MATERIAL_PBR_OPACITY, UFBXI_SHADER_MAPPING_WIDEN_TO_RGB, 0, ufbxi_mat_string("cutout") },
19570 { UFBX_MATERIAL_PBR_NORMAL_MAP, 0, 0, ufbxi_mat_string("bump") },
19571 { UFBX_MATERIAL_PBR_NORMAL_MAP, 0, 0, ufbxi_mat_string("bump_map_amt") },
19572 { UFBX_MATERIAL_PBR_DISPLACEMENT_MAP, 0, 0, ufbxi_mat_string("displacement") },
19573 { UFBX_MATERIAL_PBR_DISPLACEMENT_MAP, 0, 0, ufbxi_mat_string("displacement_map_amt") },
19574 { UFBX_MATERIAL_PBR_SUBSURFACE_TYPE, 0, 0, ufbxi_mat_string("subsurfaceType") },
19575 };
19576
19577 static const ufbxi_shader_mapping ufbxi_3ds_max_physical_material_features[] = {
19578 { UFBX_MATERIAL_FEATURE_THIN_WALLED, 0, 0, ufbxi_mat_string("thin_walled") },
19579 { UFBX_MATERIAL_FEATURE_SPECULAR, 0, 0, ufbxi_mat_string("material_mode") },
19580 { UFBX_MATERIAL_FEATURE_DIFFUSE_ROUGHNESS, 0, 0, ufbxi_mat_string("material_mode") },
19581 { UFBX_MATERIAL_FEATURE_TRANSMISSION_ROUGHNESS, UFBXI_SHADER_FEATURE_INVERTED, 0, ufbxi_mat_string("trans_roughness_lock") },
19582 { UFBX_MATERIAL_FEATURE_ROUGHNESS_AS_GLOSSINESS, 0, 0, ufbxi_mat_string("roughness_inv") },
19583 { UFBX_MATERIAL_FEATURE_TRANSMISSION_ROUGHNESS_AS_GLOSSINESS, 0, 0, ufbxi_mat_string("trans_roughness_inv") },
19584 { UFBX_MATERIAL_FEATURE_COAT_ROUGHNESS_AS_GLOSSINESS, 0, 0, ufbxi_mat_string("coat_roughness_inv") },
19585 };
19586
19587 static const ufbxi_shader_mapping ufbxi_gltf_material_pbr_mapping[] = {
19588 { UFBX_MATERIAL_PBR_BASE_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("main|baseColor") },
19589 { UFBX_MATERIAL_PBR_ROUGHNESS, 0, 0, ufbxi_mat_string("main|roughness") },
19590 { UFBX_MATERIAL_PBR_METALNESS, 0, 0, ufbxi_mat_string("main|metalness") },
19591 { UFBX_MATERIAL_PBR_NORMAL_MAP, 0, 0, ufbxi_mat_string("main|normal") },
19592 { UFBX_MATERIAL_PBR_AMBIENT_OCCLUSION, 0, 0, ufbxi_mat_string("main|ambientOcclusion") },
19593 { UFBX_MATERIAL_PBR_EMISSION_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("main|emission") },
19594 { UFBX_MATERIAL_PBR_EMISSION_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("main|emissionColor") },
19595 { UFBX_MATERIAL_PBR_OPACITY, UFBXI_SHADER_MAPPING_WIDEN_TO_RGB, 0, ufbxi_mat_string("main|Alpha") },
19596 { UFBX_MATERIAL_PBR_COAT_FACTOR, 0, 0, ufbxi_mat_string("extension|clearcoat") },
19597 { UFBX_MATERIAL_PBR_COAT_ROUGHNESS, 0, 0, ufbxi_mat_string("extension|clearcoatRoughness") },
19598 { UFBX_MATERIAL_PBR_COAT_NORMAL, 0, 0, ufbxi_mat_string("extension|clearcoatNormal") },
19599 { UFBX_MATERIAL_PBR_SHEEN_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("extension|sheenColor") },
19600 { UFBX_MATERIAL_PBR_SHEEN_ROUGHNESS, 0, 0, ufbxi_mat_string("extension|sheenRoughness") },
19601 { UFBX_MATERIAL_PBR_SPECULAR_FACTOR, 0, 0, ufbxi_mat_string("extension|specular") },
19602 { UFBX_MATERIAL_PBR_SPECULAR_FACTOR, 0, 0, ufbxi_mat_string("extension|Specular") },
19603 { UFBX_MATERIAL_PBR_SPECULAR_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("extension|specularcolor") },
19604 { UFBX_MATERIAL_PBR_SPECULAR_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("extension|specularColor") },
19605 { UFBX_MATERIAL_PBR_TRANSMISSION_FACTOR, 0, 0, ufbxi_mat_string("extension|transmission") },
19606 { UFBX_MATERIAL_PBR_SPECULAR_IOR, 0, 0, ufbxi_mat_string("extension|indexOfRefraction") },
19607 };
19608
19609 static const ufbxi_shader_mapping ufbxi_openpbr_material_pbr_mapping[] = {
19610 { UFBX_MATERIAL_PBR_BASE_FACTOR, 0, 0, ufbxi_mat_string("base_weight") },
19611 { UFBX_MATERIAL_PBR_BASE_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("base_color") },
19612 { UFBX_MATERIAL_PBR_ROUGHNESS, 0, 0, ufbxi_mat_string("specular_roughness") },
19613 { UFBX_MATERIAL_PBR_DIFFUSE_ROUGHNESS, 0, 0, ufbxi_mat_string("base_diffuse_roughness") },
19614 { UFBX_MATERIAL_PBR_METALNESS, 0, 0, ufbxi_mat_string("base_metalness") },
19615 { UFBX_MATERIAL_PBR_SPECULAR_FACTOR, 0, 0, ufbxi_mat_string("specular_weight") },
19616 { UFBX_MATERIAL_PBR_SPECULAR_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("specular_color") },
19617 { UFBX_MATERIAL_PBR_SPECULAR_ANISOTROPY, 0, 0, ufbxi_mat_string("specular_roughness_anisotropy") },
19618 { UFBX_MATERIAL_PBR_SPECULAR_IOR, 0, 0, ufbxi_mat_string("specular_ior") },
19619 { UFBX_MATERIAL_PBR_TRANSMISSION_FACTOR, 0, 0, ufbxi_mat_string("transmission_weight") },
19620 { UFBX_MATERIAL_PBR_TRANSMISSION_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("transmission_color") },
19621 { UFBX_MATERIAL_PBR_TRANSMISSION_DEPTH, 0, 0, ufbxi_mat_string("transmission_depth") },
19622 { UFBX_MATERIAL_PBR_TRANSMISSION_SCATTER, UFBXI_SHADER_MAPPING_WIDEN_TO_RGB, 0, ufbxi_mat_string("transmission_scatter") },
19623 { UFBX_MATERIAL_PBR_TRANSMISSION_SCATTER_ANISOTROPY, 0, 0, ufbxi_mat_string("transmission_scatter_anisotropy") },
19624 { UFBX_MATERIAL_PBR_TRANSMISSION_DISPERSION, 0, 0, ufbxi_mat_string("transmission_dispersion_scale") },
19625 { UFBX_MATERIAL_PBR_SUBSURFACE_FACTOR, 0, 0, ufbxi_mat_string("subsurface_weight") },
19626 { UFBX_MATERIAL_PBR_SUBSURFACE_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("subsurface_color") },
19627 { UFBX_MATERIAL_PBR_SUBSURFACE_RADIUS, UFBXI_SHADER_MAPPING_WIDEN_TO_RGB, 0, ufbxi_mat_string("subsurface_radius_scale") },
19628 { UFBX_MATERIAL_PBR_SUBSURFACE_SCALE, 0, 0, ufbxi_mat_string("subsurface_radius") },
19629 { UFBX_MATERIAL_PBR_SUBSURFACE_ANISOTROPY, 0, 0, ufbxi_mat_string("subsurface_scatter_anisotropy") },
19630 { UFBX_MATERIAL_PBR_COAT_FACTOR, 0, 0, ufbxi_mat_string("coat_weight") },
19631 { UFBX_MATERIAL_PBR_COAT_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("coat_color") },
19632 { UFBX_MATERIAL_PBR_COAT_ROUGHNESS, 0, 0, ufbxi_mat_string("coat_roughness") },
19633 { UFBX_MATERIAL_PBR_COAT_ANISOTROPY, 0, 0, ufbxi_mat_string("coat_roughness_anisotropy") },
19634 { UFBX_MATERIAL_PBR_COAT_IOR, 0, 0, ufbxi_mat_string("coat_ior") },
19635 { UFBX_MATERIAL_PBR_COAT_NORMAL, 0, 0, ufbxi_mat_string("coat_normal_map") },
19636 { UFBX_MATERIAL_PBR_SHEEN_FACTOR, 0, 0, ufbxi_mat_string("fuzz_weight") },
19637 { UFBX_MATERIAL_PBR_SHEEN_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("fuzz_color") },
19638 { UFBX_MATERIAL_PBR_SHEEN_ROUGHNESS, 0, 0, ufbxi_mat_string("fuzz_roughness") },
19639 { UFBX_MATERIAL_PBR_EMISSION_FACTOR, 0, 0, ufbxi_mat_string("emission_weight") },
19640 { UFBX_MATERIAL_PBR_EMISSION_FACTOR, UFBXI_SHADER_MAPPING_MULTIPLY_VALUE, 0, ufbxi_mat_string("emission_luminance") },
19641 { UFBX_MATERIAL_PBR_EMISSION_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("emission_color") },
19642 { UFBX_MATERIAL_PBR_THIN_FILM_FACTOR, 0, 0, ufbxi_mat_string("thin_film_weight") },
19643 { UFBX_MATERIAL_PBR_THIN_FILM_THICKNESS, 0, 0, ufbxi_mat_string("thin_film_thickness") },
19644 { UFBX_MATERIAL_PBR_THIN_FILM_IOR, 0, 0, ufbxi_mat_string("thin_film_ior") },
19645 { UFBX_MATERIAL_PBR_NORMAL_MAP, 0, 0, ufbxi_mat_string("bump") },
19646 { UFBX_MATERIAL_PBR_NORMAL_MAP, 0, 0, ufbxi_mat_string("bump_map_amt") },
19647 { UFBX_MATERIAL_PBR_DISPLACEMENT_MAP, 0, 0, ufbxi_mat_string("displacement") },
19648 { UFBX_MATERIAL_PBR_DISPLACEMENT_MAP, 0, 0, ufbxi_mat_string("displacement_map_amt") },
19649 { UFBX_MATERIAL_PBR_COAT_NORMAL, 0, 0, ufbxi_mat_string("coat_bump") },
19650 { UFBX_MATERIAL_PBR_COAT_NORMAL, 0, 0, ufbxi_mat_string("coat_bump_map_amt") },
19651 { UFBX_MATERIAL_PBR_TANGENT_MAP, 0, 0, ufbxi_mat_string("geometry_tangent_map") },
19652 { UFBX_MATERIAL_PBR_OPACITY, UFBXI_SHADER_MAPPING_WIDEN_TO_RGB, 0, ufbxi_mat_string("geometry_opacity") },
19653 };
19654
19655 static const ufbxi_shader_mapping ufbxi_openpbr_material_features[] = {
19656 { UFBX_MATERIAL_FEATURE_THIN_WALLED, 0, 0, ufbxi_mat_string("geometry_thin_walled") },
19657 };
19658
19659 static const ufbxi_shader_mapping ufbxi_3ds_max_pbr_metal_rough_pbr_mapping[] = {
19660 { UFBX_MATERIAL_PBR_BASE_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("base_color") },
19661 { UFBX_MATERIAL_PBR_BASE_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("baseColor") },
19662 { UFBX_MATERIAL_PBR_ROUGHNESS, 0, 0, ufbxi_mat_string("roughness") },
19663 { UFBX_MATERIAL_PBR_ROUGHNESS, 0, 0, ufbxi_mat_string("Roughness_Map") },
19664 { UFBX_MATERIAL_PBR_METALNESS, 0, 0, ufbxi_mat_string("metalness") },
19665 { UFBX_MATERIAL_PBR_AMBIENT_OCCLUSION, 0, 0, ufbxi_mat_string("ao") },
19666 { UFBX_MATERIAL_PBR_NORMAL_MAP, 0, 0, ufbxi_mat_string("norm") },
19667 { UFBX_MATERIAL_PBR_EMISSION_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("emit_color") },
19668 { UFBX_MATERIAL_PBR_DISPLACEMENT_MAP, 0, 0, ufbxi_mat_string("displacement") },
19669 { UFBX_MATERIAL_PBR_DISPLACEMENT_MAP, 0, 0, ufbxi_mat_string("displacement_amt") },
19670 { UFBX_MATERIAL_PBR_OPACITY, UFBXI_SHADER_MAPPING_WIDEN_TO_RGB, 0, ufbxi_mat_string("opacity") },
19671 };
19672
19673 static const ufbxi_shader_mapping ufbxi_3ds_max_pbr_spec_gloss_pbr_mapping[] = {
19674 { UFBX_MATERIAL_PBR_BASE_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("base_color") },
19675 { UFBX_MATERIAL_PBR_BASE_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("baseColor") },
19676 { UFBX_MATERIAL_PBR_SPECULAR_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("Specular") },
19677 { UFBX_MATERIAL_PBR_SPECULAR_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("specular") },
19678 { UFBX_MATERIAL_PBR_ROUGHNESS, 0, 0, ufbxi_mat_string("glossiness") },
19679 { UFBX_MATERIAL_PBR_AMBIENT_OCCLUSION, 0, 0, ufbxi_mat_string("ao") },
19680 { UFBX_MATERIAL_PBR_NORMAL_MAP, 0, 0, ufbxi_mat_string("norm") },
19681 { UFBX_MATERIAL_PBR_EMISSION_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("emit_color") },
19682 { UFBX_MATERIAL_PBR_DISPLACEMENT_MAP, 0, 0, ufbxi_mat_string("displacement") },
19683 { UFBX_MATERIAL_PBR_DISPLACEMENT_MAP, 0, 0, ufbxi_mat_string("displacement_amt") },
19684 { UFBX_MATERIAL_PBR_OPACITY, UFBXI_SHADER_MAPPING_WIDEN_TO_RGB, 0, ufbxi_mat_string("opacity") },
19685 };
19686
19687 static const ufbxi_shader_mapping ufbxi_3ds_max_pbr_features[] = {
19688 { UFBX_MATERIAL_FEATURE_ROUGHNESS_AS_GLOSSINESS, UFBXI_SHADER_FEATURE_IF_AROUND_1, 0, ufbxi_mat_string("useGlossiness") },
19689 };
19690
19691 static const ufbxi_shader_mapping ufbxi_gltf_material_features[] = {
19692 { UFBX_MATERIAL_FEATURE_DOUBLE_SIDED, 0, 0, ufbxi_mat_string("main|DoubleSided") },
19693 { UFBX_MATERIAL_FEATURE_SHEEN, 0, 0, ufbxi_mat_string("extension|enableSheen") },
19694 { UFBX_MATERIAL_FEATURE_COAT, 0, 0, ufbxi_mat_string("extension|enableClearCoat") },
19695 { UFBX_MATERIAL_FEATURE_TRANSMISSION, 0, 0, ufbxi_mat_string("extension|enableTransmission") },
19696 { UFBX_MATERIAL_FEATURE_IOR, 0, 0, ufbxi_mat_string("extension|enableIndexOfRefraction") },
19697 { UFBX_MATERIAL_FEATURE_SPECULAR, 0, 0, ufbxi_mat_string("extension|enableSpecular") },
19698 { UFBX_MATERIAL_FEATURE_UNLIT, 0, 0, ufbxi_mat_string("extension|unlit") },
19699 };
19700
19701 // NOTE: These are just the names used by the standard PBS "preset".
19702 // In _theory_ we could walk ShaderGraph but that's a bit out of scope for ufbx.
19703 static const ufbxi_shader_mapping ufbxi_shaderfx_graph_pbr_mapping[] = {
19704 { UFBX_MATERIAL_PBR_BASE_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("color") },
19705 { UFBX_MATERIAL_PBR_BASE_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("base_color") },
19706 { UFBX_MATERIAL_PBR_ROUGHNESS, 0, 0, ufbxi_mat_string("roughness") },
19707 { UFBX_MATERIAL_PBR_METALNESS, 0, 0, ufbxi_mat_string("metallic") },
19708 { UFBX_MATERIAL_PBR_NORMAL_MAP, 0, 0, ufbxi_mat_string("normal") },
19709 { UFBX_MATERIAL_PBR_EMISSION_FACTOR, 0, 0, ufbxi_mat_string("emissive_intensity") },
19710 { UFBX_MATERIAL_PBR_EMISSION_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("emissive") },
19711 { UFBX_MATERIAL_PBR_AMBIENT_OCCLUSION, 0, 0, ufbxi_mat_string("ao") },
19712 };
19713
19714 static const ufbxi_shader_mapping ufbxi_blender_phong_shader_pbr_mapping[] = {
19715 { UFBX_MATERIAL_PBR_BASE_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("DiffuseColor") },
19716 { UFBX_MATERIAL_PBR_OPACITY, UFBXI_SHADER_MAPPING_WIDEN_TO_RGB, UFBXI_MAT_TRANSFORM_BLENDER_OPACITY, ufbxi_mat_string("TransparencyFactor") },
19717 { UFBX_MATERIAL_PBR_EMISSION_FACTOR, 0, 0, ufbxi_mat_string("EmissiveFactor") },
19718 { UFBX_MATERIAL_PBR_EMISSION_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1, 0, ufbxi_mat_string("EmissiveColor") },
19719 { UFBX_MATERIAL_PBR_ROUGHNESS, 0, UFBXI_MAT_TRANSFORM_BLENDER_SHININESS, ufbxi_mat_string("Shininess") },
19720 { UFBX_MATERIAL_PBR_ROUGHNESS, 0, UFBXI_MAT_TRANSFORM_BLENDER_SHININESS, ufbxi_mat_string("ShininessExponent") },
19721 { UFBX_MATERIAL_PBR_METALNESS, 0, 0, ufbxi_mat_string("ReflectionFactor") },
19722 { UFBX_MATERIAL_PBR_NORMAL_MAP, 0, 0, ufbxi_mat_string("NormalMap") },
19723 };
19724
19725 static const ufbxi_shader_mapping ufbxi_obj_pbr_mapping[] = {
19726 { UFBX_MATERIAL_PBR_BASE_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1|UFBXI_SHADER_MAPPING_WIDEN_TO_RGB, 0, ufbxi_mat_string("Kd") },
19727 { UFBX_MATERIAL_PBR_SPECULAR_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1|UFBXI_SHADER_MAPPING_WIDEN_TO_RGB, 0, ufbxi_mat_string("Ks") },
19728 { UFBX_MATERIAL_PBR_EMISSION_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1|UFBXI_SHADER_MAPPING_WIDEN_TO_RGB, 0, ufbxi_mat_string("Ke") },
19729 { UFBX_MATERIAL_PBR_ROUGHNESS, 0, UFBXI_MAT_TRANSFORM_UNKNOWN_SHININESS, ufbxi_mat_string("Ns") },
19730 { UFBX_MATERIAL_PBR_ROUGHNESS, 0, 0, ufbxi_mat_string("Pr") },
19731 { UFBX_MATERIAL_PBR_SPECULAR_IOR, 0, 0, ufbxi_mat_string("Ni") },
19732 { UFBX_MATERIAL_PBR_METALNESS, 0, 0, ufbxi_mat_string("Pm") },
19733 { UFBX_MATERIAL_PBR_OPACITY, UFBXI_SHADER_MAPPING_WIDEN_TO_RGB, 0, ufbxi_mat_string("d") },
19734 { UFBX_MATERIAL_PBR_TRANSMISSION_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1|UFBXI_SHADER_MAPPING_WIDEN_TO_RGB, 0, ufbxi_mat_string("Tf") },
19735 { UFBX_MATERIAL_PBR_DISPLACEMENT_MAP, 0, 0, ufbxi_mat_string("disp") },
19736 { UFBX_MATERIAL_PBR_NORMAL_MAP, 0, 0, ufbxi_mat_string("bump") },
19737 { UFBX_MATERIAL_PBR_NORMAL_MAP, 0, 0, ufbxi_mat_string("norm") },
19738 { UFBX_MATERIAL_PBR_SHEEN_COLOR, UFBXI_SHADER_MAPPING_DEFAULT_W_1|UFBXI_SHADER_MAPPING_WIDEN_TO_RGB, 0, ufbxi_mat_string("Ps") },
19739 { UFBX_MATERIAL_PBR_COAT_FACTOR, 0, 0, ufbxi_mat_string("Pc") },
19740 { UFBX_MATERIAL_PBR_COAT_ROUGHNESS, 0, 0, ufbxi_mat_string("Pcr") },
19741 { UFBX_MATERIAL_PBR_SPECULAR_ANISOTROPY, 0, 0, ufbxi_mat_string("aniso") },
19742 { UFBX_MATERIAL_PBR_SPECULAR_ROTATION, 0, 0, ufbxi_mat_string("anisor") },
19743 };
19744
19745 static const ufbxi_shader_mapping ufbxi_obj_features[] = {
19746 { UFBX_MATERIAL_FEATURE_PBR, UFBXI_SHADER_FEATURE_IF_EXISTS_OR_TEXTURE, 0, ufbxi_mat_string("Pr") },
19747 { UFBX_MATERIAL_FEATURE_PBR, UFBXI_SHADER_FEATURE_IF_EXISTS_OR_TEXTURE, 0, ufbxi_mat_string("Pm") },
19748 { UFBX_MATERIAL_FEATURE_SHEEN, UFBXI_SHADER_FEATURE_IF_EXISTS_OR_TEXTURE, 0, ufbxi_mat_string("Ps") },
19749 { UFBX_MATERIAL_FEATURE_COAT, UFBXI_SHADER_FEATURE_IF_EXISTS_OR_TEXTURE, 0, ufbxi_mat_string("Pc") },
19750 { UFBX_MATERIAL_FEATURE_METALNESS, UFBXI_SHADER_FEATURE_IF_EXISTS_OR_TEXTURE, 0, ufbxi_mat_string("Pm") },
19751 { UFBX_MATERIAL_FEATURE_IOR, UFBXI_SHADER_FEATURE_IF_EXISTS_OR_TEXTURE, 0, ufbxi_mat_string("Ni") },
19752 { UFBX_MATERIAL_FEATURE_OPACITY, UFBXI_SHADER_FEATURE_IF_EXISTS_OR_TEXTURE, 0, ufbxi_mat_string("d") },
19753 { UFBX_MATERIAL_FEATURE_TRANSMISSION, UFBXI_SHADER_FEATURE_IF_EXISTS_OR_TEXTURE, 0, ufbxi_mat_string("Tf") },
19754 { UFBX_MATERIAL_FEATURE_EMISSION, UFBXI_SHADER_FEATURE_IF_EXISTS_OR_TEXTURE, 0, ufbxi_mat_string("Ke") },
19755 };
19756
19757 enum {
19758 UFBXI_MAT_PBR = 1 << UFBX_MATERIAL_FEATURE_PBR,
19759 UFBXI_MAT_METALNESS = 1 << UFBX_MATERIAL_FEATURE_METALNESS,
19760 UFBXI_MAT_DIFFUSE = 1 << UFBX_MATERIAL_FEATURE_DIFFUSE,
19761 UFBXI_MAT_SPECULAR = 1 << UFBX_MATERIAL_FEATURE_SPECULAR,
19762 UFBXI_MAT_EMISSION = 1 << UFBX_MATERIAL_FEATURE_EMISSION,
19763 UFBXI_MAT_COAT = 1 << UFBX_MATERIAL_FEATURE_COAT,
19764 UFBXI_MAT_SHEEN = 1 << UFBX_MATERIAL_FEATURE_SHEEN,
19765 UFBXI_MAT_TRANSMISSION = 1 << UFBX_MATERIAL_FEATURE_TRANSMISSION,
19766 UFBXI_MAT_OPACITY = 1 << UFBX_MATERIAL_FEATURE_OPACITY,
19767 UFBXI_MAT_AMBIENT_OCCLUSION = 1 << UFBX_MATERIAL_FEATURE_AMBIENT_OCCLUSION,
19768 UFBXI_MAT_MATTE = 1 << UFBX_MATERIAL_FEATURE_MATTE,
19769 UFBXI_MAT_UNLIT = 1 << UFBX_MATERIAL_FEATURE_UNLIT,
19770 UFBXI_MAT_IOR = 1 << UFBX_MATERIAL_FEATURE_IOR,
19771 UFBXI_MAT_DIFFUSE_ROUGHNESS = 1 << UFBX_MATERIAL_FEATURE_DIFFUSE_ROUGHNESS,
19772 UFBXI_MAT_TRANSMISSION_ROUGHNESS = 1 << UFBX_MATERIAL_FEATURE_TRANSMISSION_ROUGHNESS,
19773 UFBXI_MAT_THIN_WALLED = 1 << UFBX_MATERIAL_FEATURE_THIN_WALLED,
19774 UFBXI_MAT_CAUSTICS = 1 << UFBX_MATERIAL_FEATURE_CAUSTICS,
19775 UFBXI_MAT_EXIT_TO_BACKGROUND = 1 << UFBX_MATERIAL_FEATURE_EXIT_TO_BACKGROUND,
19776 UFBXI_MAT_INTERNAL_REFLECTIONS = 1 << UFBX_MATERIAL_FEATURE_INTERNAL_REFLECTIONS,
19777 UFBXI_MAT_DOUBLE_SIDED = 1 << UFBX_MATERIAL_FEATURE_DOUBLE_SIDED,
19778 };
19779
19780 static const ufbxi_shader_mapping_list ufbxi_shader_pbr_mappings[] = {
19781 { // UFBX_SHADER_UNKNOWN
19782 ufbxi_fbx_phong_shader_pbr_mapping, ufbxi_arraycount(ufbxi_fbx_phong_shader_pbr_mapping),
19783 NULL, 0,
19784 (uint32_t)(UFBXI_MAT_DIFFUSE | UFBXI_MAT_SPECULAR | UFBXI_MAT_EMISSION | UFBXI_MAT_TRANSMISSION),
19785 },
19786 { // UFBX_SHADER_FBX_LAMBERT
19787 ufbxi_fbx_lambert_shader_pbr_mapping, ufbxi_arraycount(ufbxi_fbx_lambert_shader_pbr_mapping),
19788 NULL, 0,
19789 (uint32_t)(UFBXI_MAT_DIFFUSE | UFBXI_MAT_EMISSION | UFBXI_MAT_TRANSMISSION),
19790 },
19791 { // UFBX_SHADER_FBX_PHONG
19792 ufbxi_fbx_phong_shader_pbr_mapping, ufbxi_arraycount(ufbxi_fbx_phong_shader_pbr_mapping),
19793 NULL, 0,
19794 (uint32_t)(UFBXI_MAT_DIFFUSE | UFBXI_MAT_SPECULAR | UFBXI_MAT_EMISSION | UFBXI_MAT_TRANSMISSION),
19795 },
19796 { // UFBX_SHADER_OSL_STANDARD_SURFACE
19797 ufbxi_osl_standard_shader_pbr_mapping, ufbxi_arraycount(ufbxi_osl_standard_shader_pbr_mapping),
19798 ufbxi_osl_standard_shader_features, ufbxi_arraycount(ufbxi_osl_standard_shader_features),
19799 (uint32_t)(UFBXI_MAT_PBR | UFBXI_MAT_METALNESS | UFBXI_MAT_DIFFUSE | UFBXI_MAT_SPECULAR | UFBXI_MAT_COAT
19800 | UFBXI_MAT_SHEEN | UFBXI_MAT_TRANSMISSION | UFBXI_MAT_OPACITY | UFBXI_MAT_IOR | UFBXI_MAT_DIFFUSE_ROUGHNESS),
19801 },
19802 { // UFBX_SHADER_ARNOLD_STANDARD_SURFACE
19803 ufbxi_arnold_shader_pbr_mapping, ufbxi_arraycount(ufbxi_arnold_shader_pbr_mapping),
19804 ufbxi_arnold_shader_features, ufbxi_arraycount(ufbxi_arnold_shader_features),
19805 (uint32_t)(UFBXI_MAT_PBR | UFBXI_MAT_METALNESS | UFBXI_MAT_DIFFUSE | UFBXI_MAT_SPECULAR | UFBXI_MAT_COAT
19806 | UFBXI_MAT_SHEEN | UFBXI_MAT_TRANSMISSION | UFBXI_MAT_OPACITY | UFBXI_MAT_IOR | UFBXI_MAT_DIFFUSE_ROUGHNESS),
19807 },
19808 { // UFBX_SHADER_3DS_MAX_PHYSICAL_MATERIAL
19809 ufbxi_3ds_max_physical_material_pbr_mapping, ufbxi_arraycount(ufbxi_3ds_max_physical_material_pbr_mapping),
19810 ufbxi_3ds_max_physical_material_features, ufbxi_arraycount(ufbxi_3ds_max_physical_material_features),
19811 (uint32_t)(UFBXI_MAT_PBR | UFBXI_MAT_METALNESS | UFBXI_MAT_DIFFUSE | UFBXI_MAT_COAT
19812 | UFBXI_MAT_SHEEN | UFBXI_MAT_TRANSMISSION | UFBXI_MAT_OPACITY | UFBXI_MAT_IOR),
19813 { NULL, 0 }, ufbxi_string_literal("_map"), // texture_prefix/suffix
19814 { NULL, 0 }, ufbxi_string_literal("_map_on"), // texture_enabled_prefix/suffix
19815 },
19816 { // UFBX_SHADER_3DS_MAX_PBR_METAL_ROUGH
19817 ufbxi_3ds_max_pbr_metal_rough_pbr_mapping, ufbxi_arraycount(ufbxi_3ds_max_pbr_metal_rough_pbr_mapping),
19818 ufbxi_3ds_max_pbr_features, ufbxi_arraycount(ufbxi_3ds_max_pbr_features),
19819 (uint32_t)(UFBXI_MAT_PBR | UFBXI_MAT_METALNESS | UFBXI_MAT_DIFFUSE | UFBXI_MAT_OPACITY),
19820 { NULL, 0 }, ufbxi_string_literal("_map"), // texture_prefix/suffix
19821 { NULL, 0 }, { NULL, 0 }, // texture_enabled_prefix/suffix
19822 },
19823 { // UFBX_SHADER_3DS_MAX_PBR_SPEC_GLOSS
19824 ufbxi_3ds_max_pbr_spec_gloss_pbr_mapping, ufbxi_arraycount(ufbxi_3ds_max_pbr_spec_gloss_pbr_mapping),
19825 ufbxi_3ds_max_pbr_features, ufbxi_arraycount(ufbxi_3ds_max_pbr_features),
19826 (uint32_t)(UFBXI_MAT_PBR | UFBXI_MAT_SPECULAR | UFBXI_MAT_DIFFUSE | UFBXI_MAT_OPACITY),
19827 { NULL, 0 }, ufbxi_string_literal("_map"), // texture_prefix/suffix
19828 { NULL, 0 }, { NULL, 0 }, // texture_enabled_prefix/suffix
19829 },
19830 { // UFBX_SHADER_GLTF_MATERIAL
19831 ufbxi_gltf_material_pbr_mapping, ufbxi_arraycount(ufbxi_gltf_material_pbr_mapping),
19832 ufbxi_gltf_material_features, ufbxi_arraycount(ufbxi_gltf_material_features),
19833 (uint32_t)(UFBXI_MAT_PBR | UFBXI_MAT_METALNESS | UFBXI_MAT_DIFFUSE | UFBXI_MAT_EMISSION | UFBXI_MAT_OPACITY | UFBXI_MAT_AMBIENT_OCCLUSION),
19834 { NULL, 0 }, ufbxi_string_literal("Map"), // texture_prefix/suffix
19835 { NULL, 0 }, { NULL, 0 }, // texture_enabled_prefix/suffix
19836 },
19837 { // UFBX_SHADER_OPENPBR_MATERIAL
19838 ufbxi_openpbr_material_pbr_mapping, ufbxi_arraycount(ufbxi_openpbr_material_pbr_mapping),
19839 ufbxi_openpbr_material_features, ufbxi_arraycount(ufbxi_openpbr_material_features),
19840 (uint32_t)(UFBXI_MAT_PBR | UFBXI_MAT_METALNESS | UFBXI_MAT_DIFFUSE | UFBXI_MAT_SPECULAR | UFBXI_MAT_COAT
19841 | UFBXI_MAT_SHEEN | UFBXI_MAT_TRANSMISSION | UFBXI_MAT_OPACITY | UFBXI_MAT_IOR | UFBXI_MAT_DIFFUSE_ROUGHNESS),
19842 { NULL, 0 }, ufbxi_string_literal("_map"), // texture_prefix/suffix
19843 { NULL, 0 }, ufbxi_string_literal("_map_on"), // texture_enabled_prefix/suffix
19844 },
19845 { // UFBX_SHADER_SHADERFX_GRAPH
19846 ufbxi_shaderfx_graph_pbr_mapping, ufbxi_arraycount(ufbxi_shaderfx_graph_pbr_mapping),
19847 NULL, 0,
19848 (uint32_t)(UFBXI_MAT_PBR | UFBXI_MAT_METALNESS | UFBXI_MAT_DIFFUSE | UFBXI_MAT_EMISSION | UFBXI_MAT_AMBIENT_OCCLUSION),
19849 ufbxi_string_literal("TEX_"), ufbxi_string_literal("_map"), // texture_prefix/suffix
19850 ufbxi_string_literal("use_"), ufbxi_string_literal("_map"), // texture_enabled_prefix/suffix
19851 },
19852 { // UFBX_SHADER_BLENDER_PHONG
19853 ufbxi_blender_phong_shader_pbr_mapping, ufbxi_arraycount(ufbxi_blender_phong_shader_pbr_mapping),
19854 NULL, 0,
19855 (uint32_t)(UFBXI_MAT_PBR | UFBXI_MAT_METALNESS | UFBXI_MAT_DIFFUSE | UFBXI_MAT_EMISSION),
19856 },
19857 { // UFBX_SHADER_WAVEFRONT_MTL
19858 ufbxi_obj_pbr_mapping, ufbxi_arraycount(ufbxi_obj_pbr_mapping),
19859 ufbxi_obj_features, ufbxi_arraycount(ufbxi_obj_features),
19860 (uint32_t)(UFBXI_MAT_DIFFUSE | UFBXI_MAT_SPECULAR),
19861 },
19862 };
19863
19864 ufbx_static_assert(shader_pbr_mapping_list, ufbxi_arraycount(ufbxi_shader_pbr_mappings) == UFBX_SHADER_TYPE_COUNT);
19865
19866 enum {
19867 UFBXI_MAPPING_FETCH_VALUE = 0x1,
19868 UFBXI_MAPPING_FETCH_TEXTURE = 0x2,
19869 UFBXI_MAPPING_FETCH_TEXTURE_ENABLED = 0x4,
19870 UFBXI_MAPPING_FETCH_FEATURE = 0x8,
19871 };
19872
19873 ufbxi_noinline static void ufbxi_fetch_mapping_maps(ufbx_material *material, ufbx_material_map *maps, ufbx_material_feature_info *features,
19874 ufbx_shader *shader, const ufbxi_shader_mapping *mappings, size_t count, ufbx_string prefix, ufbx_string prefix2, ufbx_string suffix, uint32_t flags)
19875 {
19876 char combined_name[512];
19877 ufbx_shader_prop_binding identity_binding;
19878
19879 ufbxi_for(const ufbxi_shader_mapping, mapping, mappings, count) {
19880 ufbx_string prop_name = { mapping->prop, mapping->prop_len };
19881 if (prefix.length > 0 || prefix2.length > 0 || suffix.length > 0) {
19882 if (prop_name.length + prefix.length + prefix2.length + suffix.length <= sizeof(combined_name)) {
19883 char *dst = combined_name;
19884
19885 if (prefix.length > 0) {
19886 memcpy(dst, prefix.data, prefix.length);
19887 dst += prefix.length;
19888 }
19889 if (prefix2.length > 0) {
19890 memcpy(dst, prefix2.data, prefix2.length);
19891 dst += prefix2.length;
19892 }
19893 if (prop_name.length > 0) {
19894 memcpy(dst, prop_name.data, prop_name.length);
19895 dst += prop_name.length;
19896 }
19897 if (suffix.length > 0) {
19898 memcpy(dst, suffix.data, suffix.length);
19899 dst += suffix.length;
19900 }
19901
19902 prop_name.data = combined_name;
19903 prop_name.length = ufbxi_to_size(dst - combined_name);
19904 }
19905 }
19906
19907 ufbx_shader_prop_binding_list bindings = ufbx_find_shader_prop_bindings_len(shader, prop_name.data, prop_name.length);
19908 if (bindings.count == 0) {
19909 identity_binding.material_prop = prop_name;
19910 identity_binding.shader_prop = ufbx_empty_string;
19911 bindings.data = &identity_binding;
19912 bindings.count = 1;
19913 }
19914
19915 uint32_t mapping_flags = mapping->flags;
19916 ufbxi_for_list(ufbx_shader_prop_binding, binding, bindings) {
19917 ufbx_string name = binding->material_prop;
19918
19919 ufbx_prop *prop = ufbx_find_prop_len(&material->props, name.data, name.length);
19920 if (flags & UFBXI_MAPPING_FETCH_FEATURE) {
19921 ufbx_material_feature_info *feature = &features[mapping->index];
19922 if (prop && prop->type != UFBX_PROP_REFERENCE) {
19923 feature->enabled = prop->value_int != 0;
19924 feature->is_explicit = true;
19925 if (mapping_flags & UFBXI_SHADER_FEATURE_IF_AROUND_1) {
19926 feature->enabled = (prop->value_real >= 0.5f && prop->value_real <= 1.5f);
19927 }
19928 if (mapping_flags & UFBXI_SHADER_FEATURE_INVERTED) {
19929 feature->enabled = !feature->enabled;
19930 }
19931 if (mapping_flags & UFBXI_SHADER_FEATURE_IF_EXISTS) {
19932 feature->enabled = true;
19933 }
19934 }
19935 if (mapping_flags & UFBXI_SHADER_FEATURE_IF_TEXTURE) {
19936 ufbx_texture *texture = ufbx_find_prop_texture_len(material, name.data, name.length);
19937 if (texture) {
19938 feature->enabled = true;
19939 }
19940 }
19941 continue;
19942 }
19943
19944 ufbx_material_map *map = &maps[mapping->index];
19945
19946 if (flags & UFBXI_MAPPING_FETCH_VALUE) {
19947 if (prop && prop->type != UFBX_PROP_REFERENCE) {
19948 if ((mapping->flags & UFBXI_SHADER_MAPPING_MULTIPLY_VALUE) != 0) {
19949 map->value_vec4.x *= prop->value_vec4.x;
19950 map->value_int = ufbxi_f64_to_i64(map->value_vec4.x);
19951 } else {
19952 map->value_vec4 = prop->value_vec4;
19953 map->value_int = prop->value_int;
19954 }
19955 map->has_value = true;
19956 if (mapping->transform) {
19957 ufbxi_mat_transform_fn transform_fn = ufbxi_mat_transform_fns[mapping->transform];
19958 transform_fn(&map->value_vec4);
19959 }
19960
19961 uint32_t prop_flags = (uint32_t)prop->flags;
19962 if ((mapping->flags & UFBXI_SHADER_MAPPING_DEFAULT_W_1) != 0 && (prop_flags & UFBX_PROP_FLAG_VALUE_VEC4) == 0) {
19963 map->value_vec4.w = 1.0f;
19964 }
19965 if ((mapping->flags & UFBXI_SHADER_MAPPING_WIDEN_TO_RGB) != 0 && (prop_flags & UFBX_PROP_FLAG_VALUE_REAL) != 0) {
19966 map->value_vec3.y = map->value_vec3.x;
19967 map->value_vec3.z = map->value_vec3.x;
19968 }
19969 if ((prop_flags & UFBX_PROP_FLAG_VALUE_REAL) != 0) {
19970 map->value_components = 1;
19971 } else if ((prop_flags & UFBX_PROP_FLAG_VALUE_VEC2) != 0) {
19972 map->value_components = 2;
19973 } else if ((prop_flags & UFBX_PROP_FLAG_VALUE_VEC3) != 0) {
19974 map->value_components = 3;
19975 } else if ((prop_flags & UFBX_PROP_FLAG_VALUE_VEC4) != 0) {
19976 map->value_components = 4;
19977 } else {
19978 map->value_components = 0;
19979 }
19980 }
19981 }
19982
19983 if (flags & UFBXI_MAPPING_FETCH_TEXTURE) {
19984 ufbx_texture *texture = ufbx_find_prop_texture_len(material, name.data, name.length);
19985 if (texture) {
19986 map->texture = texture;
19987 map->texture_enabled = true;
19988 }
19989 }
19990
19991 if (flags & UFBXI_MAPPING_FETCH_TEXTURE_ENABLED) {
19992 if (prop) {
19993 map->texture_enabled = prop->value_int != 0;
19994 }
19995 }
19996 }
19997 }
19998 }
19999
20000 ufbxi_noinline static void ufbxi_update_factor(ufbx_material_map *factor_map, ufbx_material_map *color_map)
20001 {
20002 if (!factor_map->has_value) {
20003 if (color_map->has_value && !ufbxi_is_vec4_zero(color_map->value_vec4)) {
20004 factor_map->value_real = 1.0f;
20005 factor_map->value_int = 1;
20006 } else {
20007 factor_map->value_real = 0.0f;
20008 factor_map->value_int = 0;
20009 }
20010 }
20011 }
20012
20013 // Some material modes have toggleable roughness/glossiness mode, we read it initially
20014 // always as roughness and if a matching feature such as `roughness_as_glossiness` is set
20015 // we transfer the data into the glossiness and invert the roughness.
20016 typedef struct {
20017 uint8_t feature;
20018 uint8_t roughness_map;
20019 uint8_t glossiness_map;
20020 } ufbxi_glossiness_remap;
20021
20022 static const ufbxi_glossiness_remap ufbxi_glossiness_remaps[] = {
20023 { UFBX_MATERIAL_FEATURE_ROUGHNESS_AS_GLOSSINESS, UFBX_MATERIAL_PBR_ROUGHNESS, UFBX_MATERIAL_PBR_GLOSSINESS },
20024 { UFBX_MATERIAL_FEATURE_COAT_ROUGHNESS_AS_GLOSSINESS, UFBX_MATERIAL_PBR_COAT_ROUGHNESS, UFBX_MATERIAL_PBR_COAT_GLOSSINESS },
20025 { UFBX_MATERIAL_FEATURE_TRANSMISSION_ROUGHNESS_AS_GLOSSINESS, UFBX_MATERIAL_PBR_TRANSMISSION_ROUGHNESS, UFBX_MATERIAL_PBR_TRANSMISSION_GLOSSINESS },
20026 };
20027
20028 ufbxi_noinline static void ufbxi_fetch_maps(ufbx_scene *scene, ufbx_material *material)
20029 {
20030 (void)scene;
20031
20032 ufbx_shader *shader = material->shader;
20033 ufbx_assert((uint32_t)material->shader_type < UFBX_SHADER_TYPE_COUNT);
20034
20035 memset(&material->fbx, 0, sizeof(material->fbx));
20036 memset(&material->pbr, 0, sizeof(material->pbr));
20037 memset(&material->features, 0, sizeof(material->features));
20038
20039 const ufbxi_shader_mapping *base_mapping = ufbxi_base_fbx_mapping;
20040 size_t num_base_mapping = ufbxi_arraycount(ufbxi_base_fbx_mapping);
20041
20042 if (scene->metadata.file_format == UFBX_FILE_FORMAT_OBJ || scene->metadata.file_format == UFBX_FILE_FORMAT_MTL) {
20043 base_mapping = ufbxi_obj_fbx_mapping;
20044 num_base_mapping = ufbxi_arraycount(ufbxi_obj_fbx_mapping);
20045 }
20046
20047 ufbxi_fetch_mapping_maps(material, material->fbx.maps, NULL, NULL,
20048 base_mapping, num_base_mapping,
20049 ufbx_empty_string, ufbx_empty_string, ufbx_empty_string,
20050 UFBXI_MAPPING_FETCH_VALUE | UFBXI_MAPPING_FETCH_TEXTURE);
20051
20052 ufbxi_shader_mapping_list list = ufbxi_shader_pbr_mappings[material->shader_type];
20053
20054 for (uint32_t i = 0; i < UFBX_MATERIAL_FEATURE_COUNT; i++) {
20055 if ((list.default_features & (1u << i)) != 0) {
20056 material->features.features[i].enabled = true;
20057 }
20058 }
20059
20060 ufbx_string prefix = ufbx_empty_string;
20061 if (!shader) {
20062 prefix = material->shader_prop_prefix;
20063 }
20064
20065 if (list.texture_prefix.length > 0 || list.texture_suffix.length > 0) {
20066 ufbxi_fetch_mapping_maps(material, material->pbr.maps, NULL, shader,
20067 list.data, list.count, prefix, list.texture_prefix, list.texture_suffix,
20068 UFBXI_MAPPING_FETCH_TEXTURE);
20069 }
20070
20071 ufbxi_fetch_mapping_maps(material, material->pbr.maps, NULL, shader,
20072 list.data, list.count, prefix, ufbx_empty_string, ufbx_empty_string,
20073 UFBXI_MAPPING_FETCH_VALUE | UFBXI_MAPPING_FETCH_TEXTURE);
20074
20075 if (list.texture_enabled_prefix.length > 0 || list.texture_enabled_suffix.length > 0) {
20076 ufbxi_fetch_mapping_maps(material, material->pbr.maps, NULL, shader,
20077 list.data, list.count, prefix, list.texture_enabled_prefix, list.texture_enabled_suffix,
20078 UFBXI_MAPPING_FETCH_TEXTURE_ENABLED);
20079 }
20080
20081 ufbxi_fetch_mapping_maps(material, NULL, material->features.features, shader,
20082 list.features, list.feature_count, prefix, ufbx_empty_string, ufbx_empty_string,
20083 UFBXI_MAPPING_FETCH_FEATURE);
20084
20085 ufbxi_update_factor(&material->fbx.diffuse_factor, &material->fbx.diffuse_color);
20086 ufbxi_update_factor(&material->fbx.specular_factor, &material->fbx.specular_color);
20087 ufbxi_update_factor(&material->fbx.reflection_factor, &material->fbx.reflection_color);
20088 ufbxi_update_factor(&material->fbx.transparency_factor, &material->fbx.transparency_color);
20089 ufbxi_update_factor(&material->fbx.emission_factor, &material->fbx.emission_color);
20090 ufbxi_update_factor(&material->fbx.ambient_factor, &material->fbx.ambient_color);
20091
20092 ufbxi_update_factor(&material->pbr.base_factor, &material->pbr.base_color);
20093 ufbxi_update_factor(&material->pbr.specular_factor, &material->pbr.specular_color);
20094 ufbxi_update_factor(&material->pbr.emission_factor, &material->pbr.emission_color);
20095 ufbxi_update_factor(&material->pbr.sheen_factor, &material->pbr.sheen_color);
20096 ufbxi_update_factor(&material->pbr.thin_film_factor, &material->pbr.thin_film_thickness);
20097 ufbxi_update_factor(&material->pbr.transmission_factor, &material->pbr.transmission_color);
20098
20099 // Patch transmission roughness if only extra roughness is defined
20100 if (!material->pbr.transmission_roughness.has_value && material->pbr.roughness.has_value && material->pbr.transmission_extra_roughness.has_value) {
20101 material->pbr.transmission_roughness.value_real = material->pbr.roughness.value_real + material->pbr.transmission_extra_roughness.value_real;
20102 }
20103
20104 // Map roughness to glossiness and vice versa
20105 ufbxi_for(const ufbxi_glossiness_remap, remap, ufbxi_glossiness_remaps, ufbxi_arraycount(ufbxi_glossiness_remaps)) {
20106 ufbx_material_map *roughness = &material->pbr.maps[remap->roughness_map];
20107 ufbx_material_map *glossiness = &material->pbr.maps[remap->glossiness_map];
20108 if (material->features.features[remap->feature].enabled) {
20109 *glossiness = *roughness;
20110 memset(roughness, 0, sizeof(ufbx_material_map));
20111 if (glossiness->has_value) {
20112 roughness->value_real = 1.0f - glossiness->value_real;
20113 }
20114 } else {
20115 if (roughness->has_value) {
20116 glossiness->value_real = 1.0f - roughness->value_real;
20117 }
20118 }
20119 }
20120 }
20121
20122 typedef enum {
20123 UFBXI_CONSTRAINT_PROP_NODE,
20124 UFBXI_CONSTRAINT_PROP_IK_EFFECTOR,
20125 UFBXI_CONSTRAINT_PROP_IK_END_NODE,
20126 UFBXI_CONSTRAINT_PROP_AIM_UP,
20127 UFBXI_CONSTRAINT_PROP_TARGET,
20128 } ufbxi_constraint_prop_type;
20129
20130 typedef struct {
20131 ufbxi_constraint_prop_type type;
20132 const char *name;
20133 } ufbxi_constraint_prop;
20134
20135 static const ufbxi_constraint_prop ufbxi_constraint_props[] = {
20136 { UFBXI_CONSTRAINT_PROP_NODE, "Constrained Object" },
20137 { UFBXI_CONSTRAINT_PROP_NODE, "Constrained object (Child)" },
20138 { UFBXI_CONSTRAINT_PROP_NODE, "First Joint" },
20139 { UFBXI_CONSTRAINT_PROP_TARGET, "Source" },
20140 { UFBXI_CONSTRAINT_PROP_TARGET, "Source (Parent)" },
20141 { UFBXI_CONSTRAINT_PROP_TARGET, "Aim At Object" },
20142 { UFBXI_CONSTRAINT_PROP_TARGET, "Pole Vector Object" },
20143 { UFBXI_CONSTRAINT_PROP_IK_EFFECTOR, "Effector" },
20144 { UFBXI_CONSTRAINT_PROP_IK_END_NODE, "End Joint" },
20145 { UFBXI_CONSTRAINT_PROP_AIM_UP, "World Up Object" },
20146 };
20147
20148 ufbxi_nodiscard ufbxi_noinline static int ufbxi_add_constraint_prop(ufbxi_context *uc, ufbx_constraint *constraint, ufbx_node *node, const char *prop)
20149 {
20150 ufbxi_for(const ufbxi_constraint_prop, cprop, ufbxi_constraint_props, ufbxi_arraycount(ufbxi_constraint_props)) {
20151 if (strcmp(cprop->name, prop) != 0) continue;
20152 switch (cprop->type) {
20153 case UFBXI_CONSTRAINT_PROP_NODE: constraint->node = node; break;
20154 case UFBXI_CONSTRAINT_PROP_IK_EFFECTOR: constraint->ik_effector = node; break;
20155 case UFBXI_CONSTRAINT_PROP_IK_END_NODE: constraint->ik_end_node = node; break;
20156 case UFBXI_CONSTRAINT_PROP_AIM_UP: constraint->aim_up_node = node; break;
20157 case UFBXI_CONSTRAINT_PROP_TARGET: {
20158 ufbx_constraint_target *target = ufbxi_push_zero(&uc->tmp_stack, ufbx_constraint_target, 1);
20159 ufbxi_check(target);
20160 target->node = node;
20161 target->weight = 1.0f;
20162 target->transform = ufbx_identity_transform;
20163 } break;
20164 default:
20165 ufbxi_unreachable("Unexpected constraint prop");
20166 }
20167 }
20168
20169 return 1;
20170 }
20171
20172 ufbxi_nodiscard ufbxi_noinline static int ufbxi_finalize_nurbs_basis(ufbxi_context *uc, ufbx_nurbs_basis *basis)
20173 {
20174 if (basis->topology == UFBX_NURBS_TOPOLOGY_CLOSED) {
20175 basis->num_wrap_control_points = 1;
20176 } else if (basis->topology == UFBX_NURBS_TOPOLOGY_PERIODIC) {
20177 basis->num_wrap_control_points = basis->order - 1;
20178 } else {
20179 basis->num_wrap_control_points = 0;
20180 }
20181
20182 if (basis->order > 1) {
20183 size_t degree = basis->order - 1;
20184 ufbx_real_list knots = basis->knot_vector;
20185 if (knots.count >= 2*degree + 1) {
20186 basis->t_min = knots.data[degree];
20187 basis->t_max = knots.data[knots.count - degree - 1];
20188
20189 size_t max_spans = knots.count - 2*degree;
20190 ufbx_real *spans = ufbxi_push(&uc->result, ufbx_real, max_spans);
20191 ufbxi_check(spans);
20192
20193 ufbx_real prev = -UFBX_INFINITY;
20194 size_t num_spans = 0;
20195 for (size_t i = 0; i < max_spans; i++) {
20196 ufbx_real t = knots.data[degree + i];
20197 if (t != prev) {
20198 spans[num_spans++] = t;
20199 prev = t;
20200 }
20201 }
20202
20203 basis->spans.data = spans;
20204 basis->spans.count = num_spans;
20205 basis->valid = true;
20206 for (size_t i = 1; i < knots.count; i++) {
20207 if (knots.data[i - 1] > knots.data[i]) {
20208 basis->valid = false;
20209 break;
20210 }
20211 }
20212 }
20213 }
20214
20215 return 1;
20216 }
20217
20218 ufbxi_nodiscard ufbxi_noinline static int ufbxi_finalize_lod_group(ufbxi_context *uc, ufbx_lod_group *lod)
20219 {
20220 size_t num_levels = 0;
20221 for (size_t i = 0; i < lod->instances.count; i++) {
20222 num_levels = ufbxi_max_sz(num_levels, lod->instances.data[0]->children.count);
20223 }
20224
20225 char prop_name[64];
20226 for (size_t i = 0; ; i++) {
20227 int len = ufbxi_snprintf(prop_name, sizeof(prop_name), "Thresholds|Level%zu", i);
20228 ufbx_prop *prop = ufbx_find_prop_len(&lod->props, prop_name, (size_t)len);
20229 if (!prop) break;
20230 num_levels = ufbxi_max_sz(num_levels, i + 1);
20231 }
20232
20233 ufbx_lod_level *levels = ufbxi_push_zero(&uc->result, ufbx_lod_level, num_levels);
20234 ufbxi_check(levels);
20235
20236 lod->relative_distances = ufbx_find_bool(&lod->props, "ThresholdsUsedAsPercentage", false);
20237 lod->ignore_parent_transform = !ufbx_find_bool(&lod->props, "WorldSpace", true);
20238
20239 lod->use_distance_limit = ufbx_find_bool(&lod->props, "MinMaxDistance", false);
20240 lod->distance_limit_min = ufbx_find_real(&lod->props, "MinDistance", (ufbx_real)-100.0);
20241 lod->distance_limit_max = ufbx_find_real(&lod->props, "MaxDistance", (ufbx_real)100.0);
20242
20243 lod->lod_levels.data = levels;
20244 lod->lod_levels.count = num_levels;
20245
20246 for (size_t i = 0; i < num_levels; i++) {
20247 ufbx_lod_level *level = &levels[i];
20248
20249 if (i > 0) {
20250 int len = ufbxi_snprintf(prop_name, sizeof(prop_name), "Thresholds|Level%zu", i - 1);
20251 level->distance = ufbx_find_real_len(&lod->props, prop_name, (size_t)len, 0.0f);
20252 } else if (lod->relative_distances) {
20253 level->distance = (ufbx_real)100.0;
20254 }
20255
20256 {
20257 int len = ufbxi_snprintf(prop_name, sizeof(prop_name), "DisplayLevels|Level%zu", i);
20258 int64_t display = ufbx_find_int_len(&lod->props, prop_name, (size_t)len, 0);
20259 if (display >= 0 && display <= 2) {
20260 level->display = (ufbx_lod_display)display;
20261 }
20262 }
20263 }
20264
20265 return 1;
20266 }
20267
20268 ufbxi_nodiscard ufbxi_noinline static int ufbxi_generate_normals(ufbxi_context *uc, ufbx_mesh *mesh)
20269 {
20270 size_t num_indices = mesh->num_indices;
20271
20272 mesh->generated_normals = true;
20273
20274 ufbx_topo_edge *topo = ufbxi_push(&uc->tmp_stack, ufbx_topo_edge, num_indices);
20275 ufbxi_check(topo);
20276
20277 uint32_t *normal_indices = ufbxi_push(&uc->result, uint32_t, num_indices);
20278 ufbxi_check(normal_indices);
20279
20280 ufbx_compute_topology(mesh, topo, num_indices);
20281 size_t num_normals = ufbx_generate_normal_mapping(mesh, topo, num_indices, normal_indices, num_indices, false);
20282
20283 if (num_normals == mesh->num_vertices) {
20284 mesh->vertex_normal.unique_per_vertex = true;
20285 }
20286
20287 ufbx_vec3 *normal_data = ufbxi_push(&uc->result, ufbx_vec3, num_normals + 1);
20288 ufbxi_check(normal_data);
20289
20290 normal_data[0] = ufbx_zero_vec3;
20291 normal_data++;
20292
20293 ufbx_compute_normals(mesh, &mesh->vertex_position, normal_indices, num_indices, normal_data, num_normals);
20294
20295 mesh->vertex_normal.exists = true;
20296 mesh->vertex_normal.values.data = normal_data;
20297 mesh->vertex_normal.values.count = num_normals;
20298 mesh->vertex_normal.indices.data = normal_indices;
20299 mesh->vertex_normal.indices.count = num_indices;
20300 mesh->vertex_normal.value_reals = 3;
20301
20302 mesh->skinned_normal = mesh->vertex_normal;
20303
20304 ufbxi_pop(&uc->tmp_stack, ufbx_topo_edge, num_indices, NULL);
20305
20306 return 1;
20307 }
20308
20309 ufbxi_nodiscard ufbxi_noinline static int ufbxi_push_prop_prefix(ufbxi_context *uc, ufbx_string *dst, ufbx_string prefix)
20310 {
20311 size_t stack_size = 0;
20312 if (prefix.length > 0 && prefix.data[prefix.length - 1] != '|') {
20313 stack_size = prefix.length + 1;
20314 char *copy = ufbxi_push(&uc->tmp_stack, char, stack_size);
20315 ufbxi_check(copy);
20316 memcpy(copy, prefix.data, prefix.length);
20317 copy[prefix.length] = '|';
20318
20319 prefix.data = copy;
20320 prefix.length += 1;
20321 }
20322
20323 ufbxi_check(ufbxi_push_string_place_str(&uc->string_pool, &prefix, false));
20324 *dst = prefix;
20325
20326 if (stack_size > 0) {
20327 ufbxi_pop(&uc->tmp_stack, char, stack_size, NULL);
20328 }
20329
20330 return 1;
20331 }
20332
20333 ufbxi_nodiscard ufbxi_noinline static int ufbxi_shader_texture_find_prefix(ufbxi_context *uc, ufbx_texture *texture, ufbx_shader_texture *shader)
20334 {
20335 ufbx_string suffixes[3];
20336 size_t num_suffixes = 0;
20337
20338 suffixes[num_suffixes++] = ufbxi_str_c(" Parameters/Connections");
20339 if (shader->shader_name.length > 0) {
20340 suffixes[num_suffixes++] = shader->shader_name;
20341 }
20342 suffixes[num_suffixes++] = ufbxi_str_c("3dsMax|parameters");
20343
20344 ufbx_assert(num_suffixes <= ufbxi_arraycount(suffixes));
20345
20346 ufbxi_for(ufbx_string, p_suffix, suffixes, num_suffixes) {
20347 ufbx_string suffix = *p_suffix;
20348
20349 ufbxi_for_list(ufbx_prop, prop, texture->props.props) {
20350 if (prop->type != UFBX_PROP_COMPOUND) continue;
20351 if (ufbxi_ends_with(prop->name, suffix)) {
20352 ufbxi_check(ufbxi_push_prop_prefix(uc, &shader->prop_prefix, prop->name));
20353 return 1;
20354 }
20355 }
20356 }
20357
20358 // Pre-7000 files don't have explicit Compound properties, so let's look for
20359 // any property that has the suffix before the last `|` ...
20360 ufbxi_for(ufbx_string, p_suffix, suffixes, num_suffixes) {
20361 ufbx_string suffix = *p_suffix;
20362
20363 ufbxi_for_list(ufbx_prop, prop, texture->props.props) {
20364 ufbx_string name = prop->name;
20365 while (name.length > 0) {
20366 if (name.data[name.length - 1] == '|') {
20367 break;
20368 }
20369 name.length--;
20370 }
20371 if (name.length <= 1) continue;
20372 name.length--;
20373
20374 if (ufbxi_ends_with(name, suffix)) {
20375 ufbxi_check(ufbxi_push_prop_prefix(uc, &shader->prop_prefix, name));
20376 return 1;
20377 }
20378 }
20379 }
20380
20381 return 1;
20382 }
20383
20384 typedef struct {
20385 uint64_t shader_id;
20386 const char *shader_name;
20387 const char *input_name;
20388 } ufbxi_file_shader;
20389
20390 // Known shaders that represent sampled images.
20391 static const ufbxi_file_shader ufbxi_file_shaders[] = {
20392 { UINT64_C(0x7e73161fad53b12a), "ai_image", "filename" },
20393 { 0, "OSLBitmap", ufbxi_Filename },
20394 { 0, "OSLBitmap2", ufbxi_Filename },
20395 { 0, "OSLBitmap3", ufbxi_Filename },
20396 { 0, "UberBitmap", ufbxi_Filename },
20397 { 0, "UberBitmap2", ufbxi_Filename },
20398 };
20399
20400 ufbxi_noinline static void ufbxi_update_shader_texture(ufbx_texture *texture, ufbx_shader_texture *shader)
20401 {
20402 ufbxi_for_list(ufbx_shader_texture_input, input, shader->inputs) {
20403 ufbx_prop *prop = input->prop;
20404 if (prop) {
20405 input->prop = prop = ufbx_find_prop_len(&texture->props, prop->name.data, prop->name.length);
20406 input->value_vec4 = prop->value_vec4;
20407 input->value_int = prop->value_int;
20408 input->value_str = prop->value_str;
20409 input->value_blob = prop->value_blob;
20410 input->texture = (ufbx_texture*)ufbx_get_prop_element(&texture->element, input->prop, UFBX_ELEMENT_TEXTURE);
20411 }
20412
20413 prop = input->texture_prop;
20414 if (prop) {
20415 input->texture_prop = prop = ufbx_find_prop_len(&texture->props, prop->name.data, prop->name.length);
20416 ufbx_texture *tex = (ufbx_texture*)ufbx_get_prop_element(&texture->element, prop, UFBX_ELEMENT_TEXTURE);
20417 if (tex) input->texture = tex;
20418 }
20419
20420 input->texture_enabled = input->texture != NULL;
20421 prop = input->texture_enabled_prop;
20422 if (prop) {
20423 input->texture_enabled_prop = prop = ufbx_find_prop_len(&texture->props, prop->name.data, prop->name.length);
20424 input->texture_enabled = prop->value_int != 0;
20425 }
20426 }
20427
20428 if (shader->type == UFBX_SHADER_TEXTURE_SELECT_OUTPUT) {
20429 ufbx_shader_texture_input *map = ufbx_find_shader_texture_input(shader, "sourceMap");
20430 ufbx_shader_texture_input *index = ufbx_find_shader_texture_input(shader, "outputChannelIndex");
20431 if (index) {
20432 shader->main_texture_output_index = index->value_int;
20433 }
20434 if (map) {
20435 shader->main_texture = map->texture;
20436 map->texture_output_index = shader->main_texture_output_index;
20437 }
20438 }
20439 }
20440
20441 ufbxi_nodiscard ufbxi_noinline static int ufbxi_finalize_shader_texture(ufbxi_context *uc, ufbx_texture *texture)
20442 {
20443 uint32_t classid_a = (uint32_t)(uint64_t)ufbx_find_int(&texture->props, "3dsMax|ClassIDa", 0);
20444 uint32_t classid_b = (uint32_t)(uint64_t)ufbx_find_int(&texture->props, "3dsMax|ClassIDb", 0);
20445 uint64_t classid = (uint64_t)classid_a << 32u | classid_b;
20446
20447 ufbx_string max_texture = ufbx_find_string(&texture->props, "3dsMax|MaxTexture", ufbx_empty_string);
20448
20449 // Check first if the texture looks like it could be a shader.
20450 ufbx_shader_texture_type type = (ufbx_shader_texture_type)UFBX_SHADER_TEXTURE_TYPE_COUNT;
20451
20452 if (!strcmp(max_texture.data, "MULTIOUTPUT_TO_OSLMap") || classid == UINT64_C(0x896ef2fc44bd743f)) {
20453 type = UFBX_SHADER_TEXTURE_SELECT_OUTPUT;
20454 } else if (!strcmp(max_texture.data, "OSLMap") || classid == UINT64_C(0x7f9a7b9d6fcdf00d)) {
20455 type = UFBX_SHADER_TEXTURE_OSL;
20456 } else if (texture->type == UFBX_TEXTURE_FILE && texture->relative_filename.length == 0 && texture->absolute_filename.length == 0 && !texture->video) {
20457 type = UFBX_SHADER_TEXTURE_UNKNOWN;
20458 }
20459
20460 if ((uint32_t)type == UFBX_SHADER_TEXTURE_TYPE_COUNT) return 1;
20461
20462 ufbx_shader_texture *shader = ufbxi_push_zero(&uc->result, ufbx_shader_texture, 1);
20463 ufbxi_check(shader);
20464
20465 shader->type = type;
20466
20467 static const char *const name_props[] = {
20468 "3dsMax|params|OSLShaderName",
20469 };
20470
20471 static const char *const source_props[] = {
20472 "3dsMax|params|OSLCode",
20473 };
20474
20475 shader->shader_source.data = ufbxi_empty_char;
20476 shader->shader_name.data = ufbxi_empty_char;
20477
20478 ufbxi_nounroll for (size_t i = 0; i < ufbxi_arraycount(name_props); i++) {
20479 ufbx_prop *prop = ufbx_find_prop(&texture->props, name_props[i]);
20480 if (prop) {
20481 shader->shader_name = prop->value_str;
20482 break;
20483 }
20484 }
20485
20486 ufbxi_nounroll for (size_t i = 0; i < ufbxi_arraycount(source_props); i++) {
20487 ufbx_prop *prop = ufbx_find_prop(&texture->props, source_props[i]);
20488 if (prop) {
20489 shader->shader_source = prop->value_str;
20490 shader->raw_shader_source = prop->value_blob;
20491 break;
20492 }
20493 }
20494
20495 ufbxi_check(ufbxi_shader_texture_find_prefix(uc, texture, shader));
20496
20497 if (shader->shader_name.length == 0) {
20498 ufbx_string name = shader->prop_prefix;
20499 if (ufbxi_remove_suffix_c(&name, " Parameters/Connections|")) {
20500 size_t begin = name.length;
20501 while (begin > 0 && name.data[begin - 1] != '|') {
20502 begin--;
20503 }
20504
20505 shader->shader_name.data = name.data + begin;
20506 shader->shader_name.length = name.length - begin;
20507 ufbxi_check(ufbxi_push_string_place_str(&uc->string_pool, &shader->shader_name, false));
20508 }
20509 }
20510
20511 if (shader->shader_name.length == 0) {
20512 if (max_texture.length > 0) {
20513 shader->shader_name = max_texture;
20514 }
20515 }
20516
20517 if (classid != 0) {
20518 shader->shader_type_id = classid;
20519 }
20520
20521 if (shader->prop_prefix.length == 0) {
20522 // If we not find any shader properties so we might have guessed wrong.
20523 // We "leak" (freed with scene) the shader in this case but it's negligible.
20524 return 1;
20525 }
20526
20527 ufbxi_for_list(ufbx_prop, prop, texture->props.props) {
20528
20529 ufbx_string name = prop->name;
20530 if (!ufbxi_remove_prefix_str(&name, shader->prop_prefix)) continue;
20531
20532 // Check if this property is a modifier to an existing input.
20533 ufbx_string base_name = name;
20534 if (ufbxi_remove_suffix_c(&base_name, "_map") || ufbxi_remove_suffix_c(&base_name, ".shader")) {
20535 ufbx_shader_texture_input *base = ufbx_find_shader_texture_input_len(shader, base_name.data, base_name.length);
20536 if (base) {
20537 base->texture_prop = prop;
20538 continue;
20539 }
20540 } else if (ufbxi_remove_suffix_c(&base_name, ".connected") || ufbxi_remove_suffix_c(&base_name, "Enabled")) {
20541 ufbx_shader_texture_input *base = ufbx_find_shader_texture_input_len(shader, base_name.data, base_name.length);
20542 if (base) {
20543 base->texture_enabled_prop = prop;
20544 continue;
20545 }
20546 }
20547
20548 // Use `uc->tmp_arr` to store the texture inputs so we can search them while we insert new ones.
20549 ufbxi_check(ufbxi_grow_array(&uc->ator_tmp, &uc->tmp_arr, &uc->tmp_arr_size,
20550 (shader->inputs.count + 1) * sizeof(ufbx_shader_texture_input)));
20551 shader->inputs.data = (ufbx_shader_texture_input*)uc->tmp_arr;
20552
20553 // Add a new property
20554 ufbx_shader_texture_input *input = &shader->inputs.data[shader->inputs.count++];
20555 memset(input, 0, sizeof(ufbx_shader_texture_input));
20556
20557 // NOTE: This is a bit hackish, we are using a suffix of an interned string. It won't compare
20558 // pointer equal to the same string but that shouldn't matter..
20559 input->name = name;
20560
20561 // Connect the property only, values and textures etc are fetched in `ufbxi_update_shader_texture()`.
20562 input->prop = prop;
20563 }
20564
20565 // Retain the shader inputs
20566 shader->inputs.data = ufbxi_push_copy(&uc->result, ufbx_shader_texture_input, shader->inputs.count, shader->inputs.data);
20567 ufbxi_check(shader->inputs.data);
20568
20569 texture->shader = shader;
20570 texture->type = UFBX_TEXTURE_SHADER;
20571 uc->scene.metadata.num_shader_textures++;
20572
20573 if (!uc->opts.disable_quirks) {
20574 ufbxi_nounroll for (size_t i = 0; i < ufbxi_arraycount(ufbxi_file_shaders); i++) {
20575 const ufbxi_file_shader *fs = &ufbxi_file_shaders[i];
20576
20577 if ((fs->shader_id && shader->shader_type_id == fs->shader_id) || !strcmp(shader->shader_name.data, fs->shader_name)) {
20578 ufbx_shader_texture_input *input = ufbx_find_shader_texture_input(shader, fs->input_name);
20579 if (input) {
20580 // TODO: Support for specifying relative filename here if ever needed
20581 ufbx_prop *prop = input->prop;
20582 texture->absolute_filename = prop->value_str;
20583 texture->raw_absolute_filename = prop->value_blob;
20584 texture->type = UFBX_TEXTURE_FILE;
20585 break;
20586 }
20587 }
20588 }
20589 }
20590
20591 ufbxi_update_shader_texture(texture, shader);
20592
20593 return 1;
20594 }
20595
20596 ufbxi_noinline static void ufbxi_propagate_main_textures(ufbx_scene *scene)
20597 {
20598 // We need to do at least 2^(N-1) passes for N shader textures
20599 size_t mask = scene->metadata.num_shader_textures;
20600 while (mask) {
20601 mask >>= 1;
20602
20603 ufbxi_for_ptr_list(ufbx_texture, p_texture, scene->textures) {
20604 ufbx_texture *texture = *p_texture;
20605 ufbx_shader_texture *shader = texture->shader;
20606 if (!shader) continue;
20607
20608 ufbx_texture *main_tex = shader->main_texture;
20609 if (!main_tex || shader->main_texture_output_index != 0) continue;
20610
20611 ufbx_shader_texture *main_shader = main_tex->shader;
20612 if (!main_shader || !main_shader->main_texture) continue;
20613
20614 shader->main_texture = main_shader->main_texture;
20615 shader->main_texture_output_index = main_shader->main_texture_output_index;
20616 }
20617 }
20618
20619 // Remove cyclic main textures
20620 ufbxi_for_ptr_list(ufbx_texture, p_texture, scene->textures) {
20621 ufbx_texture *texture = *p_texture;
20622 ufbx_shader_texture *shader = texture->shader;
20623 if (!shader || !shader->main_texture || shader->main_texture_output_index != 0) continue;
20624 ufbx_texture *main_tex = shader->main_texture;
20625 if (main_tex && main_tex->shader && main_tex->shader->main_texture) {
20626 // Should have been propagated to `texture`
20627 shader->main_texture = NULL;
20628 }
20629 }
20630
20631 ufbxi_for_ptr_list(ufbx_texture, p_texture, scene->textures) {
20632 ufbx_texture *texture = *p_texture;
20633 ufbx_shader_texture *shader = texture->shader;
20634 if (!shader) continue;
20635
20636 ufbxi_for_list(ufbx_shader_texture_input, input, shader->inputs) {
20637 if (!input->texture || !input->texture->shader) continue;
20638 ufbx_shader_texture *input_shader = input->texture->shader;
20639 if (input_shader->main_texture) {
20640 input->texture = input_shader->main_texture;
20641 input->texture_output_index = input_shader->main_texture_output_index;
20642 }
20643 }
20644 }
20645
20646 ufbxi_for_ptr_list(ufbx_material, p_material, scene->materials) {
20647 ufbx_material *material = *p_material;
20648
20649 ufbxi_for_list(ufbx_material_texture, tex, material->textures) {
20650 ufbx_shader_texture *shader = tex->texture->shader;
20651 if (shader && shader->main_texture && shader->main_texture_output_index == 0) {
20652 tex->texture = shader->main_texture;
20653 }
20654 }
20655 }
20656 }
20657
20658 #define ufbxi_patch_empty(m_dst, m_len, m_src) \
20659 do { if (!(m_dst).m_len) m_dst = m_src; } while (0)
20660
20661 ufbxi_nodiscard ufbxi_noinline static int ufbxi_insert_texture_file(ufbxi_context *uc, ufbx_texture *texture)
20662 {
20663 texture->file_index = UFBX_NO_INDEX;
20664
20665 const char *key = NULL;
20666
20667 // HACK: Even the raw entries have a null terminator so we can offset the
20668 // pointer by one for relative filenames. This guarantees that an overlapping
20669 // absolute and relative filenames will get separate textures.
20670 if (texture->raw_absolute_filename.size > 0) {
20671 key = (const char*)texture->raw_absolute_filename.data;
20672 } else if (texture->raw_relative_filename.size > 0) {
20673 key = (const char*)texture->raw_relative_filename.data + 1;
20674 }
20675
20676 if (key == NULL) return 1;
20677 uint32_t hash = ufbxi_hash_ptr(key);
20678 ufbxi_texture_file_entry *entry = ufbxi_map_find(&uc->texture_file_map, ufbxi_texture_file_entry, hash, &key);
20679 if (!entry) {
20680 entry = ufbxi_map_insert(&uc->texture_file_map, ufbxi_texture_file_entry, hash, &key);
20681 ufbxi_check(entry);
20682
20683 ufbx_texture_file *file = ufbxi_push_zero(&uc->tmp, ufbx_texture_file, 1);
20684 ufbxi_check(file);
20685
20686 file->index = uc->texture_file_map.size - 1;
20687
20688 entry->key = key;
20689 entry->file = file;
20690 }
20691
20692 ufbx_texture_file *file = entry->file;
20693 texture->file_index = file->index;
20694 texture->has_file = true;
20695 ufbxi_patch_empty(file->filename, length, texture->filename);
20696 ufbxi_patch_empty(file->relative_filename, length, texture->relative_filename);
20697 ufbxi_patch_empty(file->absolute_filename, length, texture->absolute_filename);
20698 ufbxi_patch_empty(file->raw_filename, size, texture->raw_filename);
20699 ufbxi_patch_empty(file->raw_relative_filename, size, texture->raw_relative_filename);
20700 ufbxi_patch_empty(file->raw_absolute_filename, size, texture->raw_absolute_filename);
20701 ufbxi_patch_empty(file->content, size, texture->content);
20702
20703 return 1;
20704 }
20705
20706 ufbxi_nodiscard ufbxi_noinline static int ufbxi_pop_texture_files(ufbxi_context *uc)
20707 {
20708 uint32_t num_files = uc->texture_file_map.size;
20709 ufbx_texture_file *files = ufbxi_push(&uc->result, ufbx_texture_file, num_files);
20710 ufbxi_check(files);
20711
20712 uc->scene.texture_files.data = files;
20713 uc->scene.texture_files.count = num_files;
20714
20715 ufbxi_texture_file_entry *entries = (ufbxi_texture_file_entry*)uc->texture_file_map.items;
20716 for (size_t i = 0; i < num_files; i++) {
20717 memcpy(&files[i], entries[i].file, sizeof(ufbx_texture_file));
20718 }
20719
20720 return 1;
20721 }
20722
20723 typedef struct {
20724 ufbx_texture *texture;
20725 size_t order;
20726 } ufbxi_ordered_texture;
20727
20728 ufbxi_noinline static bool ufbxi_ordered_texture_less_texture(void *user, const void *va, const void *vb)
20729 {
20730 (void)user;
20731 const ufbxi_ordered_texture *a = (const ufbxi_ordered_texture*)va, *b = (const ufbxi_ordered_texture*)vb;
20732 return a->texture < b->texture;
20733 }
20734
20735 ufbxi_noinline static bool ufbxi_ordered_texture_less_order(void *user, const void *va, const void *vb)
20736 {
20737 (void)user;
20738 const ufbxi_ordered_texture *a = (const ufbxi_ordered_texture*)va, *b = (const ufbxi_ordered_texture*)vb;
20739 return a->order < b->order;
20740 }
20741
20742 ufbxi_nodiscard ufbxi_noinline static int ufbxi_deduplicate_textures(ufbxi_context *uc, ufbxi_buf *dst_buf, ufbxi_ordered_texture **p_dst, size_t *p_dst_count, size_t count)
20743 {
20744 ufbxi_ordered_texture *textures = ufbxi_push_pop(dst_buf, &uc->tmp_stack, ufbxi_ordered_texture, count);
20745 ufbxi_check(textures);
20746
20747 ufbxi_check(ufbxi_grow_array(&uc->ator_tmp, &uc->tmp_arr, &uc->tmp_arr_size, count * sizeof(ufbxi_ordered_texture)));
20748
20749 ufbxi_stable_sort(sizeof(ufbxi_ordered_texture), 16, textures, uc->tmp_arr, count, &ufbxi_ordered_texture_less_texture, NULL);
20750
20751 // Remove adjacent duplicates
20752 size_t dst_ix = 0;
20753 for (size_t src_ix = 0; src_ix < count; src_ix++) {
20754 if (src_ix > 0 && textures[src_ix - 1].texture == textures[src_ix].texture) {
20755 continue;
20756 } else {
20757 if (src_ix != dst_ix) {
20758 textures[dst_ix] = textures[src_ix];
20759 }
20760 dst_ix++;
20761 }
20762 }
20763
20764 size_t new_count = dst_ix;
20765 ufbxi_stable_sort(sizeof(ufbxi_ordered_texture), 16, textures, uc->tmp_arr, new_count, &ufbxi_ordered_texture_less_order, NULL);
20766
20767 *p_dst_count = new_count;
20768 *p_dst = textures;
20769
20770 return 1;
20771 }
20772
20773 typedef enum {
20774 UFBXI_FILE_TEXTURE_FETCH_INITIAL,
20775 UFBXI_FILE_TEXTURE_FETCH_STARTED,
20776 UFBXI_FILE_TEXTURE_FETCH_FINISHED,
20777 } ufbxi_file_texture_fetch_state;
20778
20779 // Populate `ufbx_texture.file_textures[]` arrays.
20780 ufbxi_nodiscard ufbxi_noinline static int ufbxi_fetch_file_textures(ufbxi_context *uc)
20781 {
20782 // We keep pointers to `ufbx_texture` in `tmp_stack` as a working set, since we don't know
20783 // how deep the shader graphs might be.
20784
20785 // Start by pushing all the textures into the stack
20786 size_t num_stack_textures = uc->scene.textures.count;
20787 ufbxi_check(ufbxi_push_copy(&uc->tmp_stack, ufbx_texture*, num_stack_textures, uc->scene.textures.data));
20788
20789 // Compressed `ufbxi_file_texture_fetch_state`
20790 uint8_t *states = ufbxi_push_zero(&uc->tmp, uint8_t, uc->scene.textures.count);
20791 ufbxi_check(states);
20792
20793 while (num_stack_textures-- > 0) {
20794 ufbx_texture *texture = NULL;
20795 ufbxi_pop(&uc->tmp_stack, ufbx_texture*, 1, &texture);
20796
20797 ufbxi_file_texture_fetch_state state = (ufbxi_file_texture_fetch_state)states[texture->typed_id];
20798 if (state == UFBXI_FILE_TEXTURE_FETCH_FINISHED) continue;
20799 ufbx_shader_texture *shader = texture->shader;
20800
20801 if (state == UFBXI_FILE_TEXTURE_FETCH_STARTED) {
20802 states[texture->typed_id] = UFBXI_FILE_TEXTURE_FETCH_FINISHED;
20803
20804 // HACK: Reuse `tmp_parse` for storing intermediate information as we can clear it.
20805 ufbxi_buf_clear(&uc->tmp_parse);
20806
20807 // Now all non-cyclical dependents should be processed.
20808 size_t num_deps = 0;
20809
20810 if (texture->type == UFBX_TEXTURE_FILE) {
20811 ufbxi_ordered_texture *dst = ufbxi_push(&uc->tmp_stack, ufbxi_ordered_texture, 1);
20812 ufbxi_check(dst);
20813 dst->texture = texture;
20814 dst->order = num_deps++;
20815 }
20816
20817 ufbxi_for_list(ufbx_texture_layer, layer, texture->layers) {
20818 ufbx_texture *dep_tex = layer->texture;
20819 if (dep_tex->file_textures.count > 0) {
20820 ufbxi_ordered_texture *dst = ufbxi_push(&uc->tmp_stack, ufbxi_ordered_texture, 1);
20821 ufbxi_check(dst);
20822 dst->texture = dep_tex;
20823 dst->order = num_deps++;
20824 }
20825 }
20826
20827 if (shader) {
20828 ufbxi_for_list(ufbx_shader_texture_input, input, shader->inputs) {
20829 ufbx_texture *dep_tex = input->texture;
20830 if (dep_tex && dep_tex->file_textures.count > 0) {
20831 ufbxi_ordered_texture *dst = ufbxi_push(&uc->tmp_stack, ufbxi_ordered_texture, 1);
20832 ufbxi_check(dst);
20833 dst->texture = dep_tex;
20834 dst->order = num_deps++;
20835 }
20836 }
20837 }
20838
20839 // Deduplicate the direct dependencies first
20840 ufbxi_ordered_texture *deps;
20841 ufbxi_check(ufbxi_deduplicate_textures(uc, &uc->tmp_parse, &deps, &num_deps, num_deps));
20842
20843 if (num_deps == 1) {
20844 // If we have only a single dependency (that is not the same one) we can just copy the pointer
20845 texture->file_textures = deps[0].texture->file_textures;
20846 } else {
20847 // Now collect all the file textures and deduplicate them
20848 size_t num_files = 0;
20849 ufbxi_for(ufbxi_ordered_texture, dep, deps, num_deps) {
20850 ufbxi_for_ptr_list(ufbx_texture, p_tex, dep->texture->file_textures) {
20851 ufbxi_ordered_texture *dst = ufbxi_push(&uc->tmp_stack, ufbxi_ordered_texture, 1);
20852 ufbxi_check(dst);
20853 dst->texture = *p_tex;
20854 dst->order = num_files++;
20855 }
20856 }
20857
20858 // Deduplicate the file textures
20859 ufbxi_ordered_texture *files;
20860 ufbxi_check(ufbxi_deduplicate_textures(uc, &uc->tmp_parse, &files, &num_files, num_files));
20861
20862 texture->file_textures.count = num_files;
20863 texture->file_textures.data = ufbxi_push(&uc->result, ufbx_texture*, num_files);
20864 ufbxi_check(texture->file_textures.data);
20865
20866 for (size_t i = 0; i < num_files; i++) {
20867 texture->file_textures.data[i] = files[i].texture;
20868 }
20869 }
20870
20871 } else {
20872 if (texture->type == UFBX_TEXTURE_FILE) {
20873 // Simple case: Just point to self
20874 texture->file_textures.count = 1;
20875 texture->file_textures.data = ufbxi_push(&uc->result, ufbx_texture*, 1);
20876 ufbxi_check(texture->file_textures.data);
20877 texture->file_textures.data[0] = texture;
20878
20879 // In simple cases we can quit here, for more complex file textures queue
20880 // the texture in case there are other file textures as inputs.
20881 if (!texture->shader) {
20882 states[texture->typed_id] = UFBXI_FILE_TEXTURE_FETCH_FINISHED;
20883 continue;
20884 }
20885 }
20886
20887 // Complex: Process all dependencies first
20888 states[texture->typed_id] = UFBXI_FILE_TEXTURE_FETCH_STARTED;
20889
20890 // Push self first so we can return after processing dependencies
20891 ufbxi_check(ufbxi_push_copy(&uc->tmp_stack, ufbx_texture*, 1, &texture));
20892 num_stack_textures++;
20893
20894 ufbxi_for_list(ufbx_texture_layer, layer, texture->layers) {
20895 ufbxi_check(ufbxi_push_copy(&uc->tmp_stack, ufbx_texture*, 1, &layer->texture));
20896 num_stack_textures++;
20897 }
20898
20899 if (shader) {
20900 ufbxi_for_list(ufbx_shader_texture_input, input, shader->inputs) {
20901 if (input->texture) {
20902 ufbxi_check(ufbxi_push_copy(&uc->tmp_stack, ufbx_texture*, 1, &input->texture));
20903 num_stack_textures++;
20904 }
20905 }
20906 }
20907 }
20908 }
20909
20910 return 1;
20911 }
20912
20913 ufbxi_nodiscard ufbxi_noinline static ufbx_node *ufbxi_get_geometry_transform_node(ufbx_element *element)
20914 {
20915 if (element->instances.count == 1) {
20916 ufbx_node *node = element->instances.data[0];
20917 if (node->has_geometry_transform) return node;
20918 }
20919 return NULL;
20920 }
20921
20922 ufbxi_noinline static void ufbxi_mirror_vec3_list(const void *v_list, ufbx_mirror_axis axis, size_t stride)
20923 {
20924 const ufbx_void_list *list = (const ufbx_void_list*)v_list;
20925 if (axis == UFBX_MIRROR_AXIS_NONE || !list || list->count == 0) return;
20926 if (!stride) stride = sizeof(ufbx_vec3);
20927
20928 void *ptr = (char*)list->data + (size_t)((int)axis - 1) * sizeof(ufbx_real);
20929 void *end = (char*)ptr + list->count * stride;
20930 while (ptr != end) {
20931 ufbx_real *v = (ufbx_real*)ptr;
20932 *v = -*v;
20933 ptr = (char*)ptr + stride;
20934 }
20935 }
20936
20937 ufbxi_noinline static void ufbxi_scale_vec3_list(const void *v_list, ufbx_real scale, size_t stride)
20938 {
20939 const ufbx_void_list *list = (const ufbx_void_list*)v_list;
20940 if (!list || list->count == 0) return;
20941 if (!stride) stride = sizeof(ufbx_vec3);
20942
20943 void *ptr = list->data, *end = (char*)ptr + list->count * stride;
20944 while (ptr != end) {
20945 ufbx_vec3 *v = (ufbx_vec3*)ptr;
20946 v->x *= scale;
20947 v->y *= scale;
20948 v->z *= scale;
20949 ptr = (char*)ptr + stride;
20950 }
20951 }
20952
20953 ufbxi_noinline static void ufbxi_transform_vec3_list(const void *v_list, const ufbx_matrix *matrix, size_t stride)
20954 {
20955 const ufbx_void_list *list = (const ufbx_void_list*)v_list;
20956 if (!list || list->count == 0) return;
20957 if (!stride) stride = sizeof(ufbx_vec3);
20958
20959 void *ptr = list->data, *end = (char*)ptr + list->count * stride;
20960 while (ptr != end) {
20961 ufbx_vec3 *v = (ufbx_vec3*)ptr;
20962 *v = ufbx_transform_position(matrix, *v);
20963 ptr = (char*)ptr + stride;
20964 }
20965 }
20966
20967 ufbxi_noinline static void ufbxi_normalize_vec3_list(const ufbx_vec3_list *list)
20968 {
20969 ufbxi_nounroll ufbxi_for_list(ufbx_vec3, normal, *list) {
20970 *normal = ufbxi_normalize3(*normal);
20971 }
20972 }
20973
20974 // Forward declare as we're kind of preprocessing ata here that would usually happen later.
20975 ufbxi_noinline static ufbx_transform ufbxi_get_geometry_transform(const ufbx_props *props, ufbx_node *node);
20976
20977 ufbxi_nodiscard ufbxi_noinline static int ufbxi_flip_attrib_winding(ufbxi_context *uc, ufbx_mesh *mesh, ufbx_uint32_list *indices, bool is_position)
20978 {
20979 // All zero, no flipping needed
20980 if (indices->data == uc->zero_indices || indices->count == 0) return 1;
20981
20982 if (indices->data == mesh->vertex_position.indices.data && !is_position) {
20983 // Sharing indices with vertex position, already flipped.
20984 return 1;
20985 } else if (indices->data == uc->consecutive_indices) {
20986 // Need to duplicate consecutive indices, but we can cache the per mesh.
20987 if (uc->tmp_mesh_consecutive_indices) {
20988 indices->data = uc->tmp_mesh_consecutive_indices;
20989 return 1;
20990 }
20991 indices->data = ufbxi_push_copy(&uc->result, uint32_t, indices->count, indices->data);
20992 ufbxi_check(indices->data);
20993 uc->tmp_mesh_consecutive_indices = indices->data;
20994 }
20995
20996 uint32_t *data = indices->data;
20997 ufbxi_for_list(ufbx_face, face, mesh->faces) {
20998 if (face->num_indices == 0) continue;
20999 size_t begin = face->index_begin + 1;
21000 size_t end = face->index_begin + face->num_indices - 1;
21001 while (begin < end) {
21002 uint32_t tmp = data[begin];
21003 data[begin] = data[end];
21004 data[end] = tmp;
21005 begin++;
21006 end--;
21007 }
21008 }
21009
21010 return 1;
21011 }
21012
21013 ufbxi_nodiscard ufbxi_noinline static int ufbxi_flip_winding(ufbxi_context *uc, ufbx_mesh *mesh)
21014 {
21015 uc->tmp_mesh_consecutive_indices = NULL;
21016 ufbxi_check(ufbxi_flip_attrib_winding(uc, mesh, &mesh->vertex_position.indices, true));
21017 ufbxi_check(ufbxi_flip_attrib_winding(uc, mesh, &mesh->vertex_normal.indices, false));
21018 ufbxi_check(ufbxi_flip_attrib_winding(uc, mesh, &mesh->vertex_crease.indices, false));
21019 if (mesh->uv_sets.count > 0) {
21020 ufbxi_for_list(ufbx_uv_set, set, mesh->uv_sets) {
21021 ufbxi_check(ufbxi_flip_attrib_winding(uc, mesh, &set->vertex_uv.indices, false));
21022 ufbxi_check(ufbxi_flip_attrib_winding(uc, mesh, &set->vertex_tangent.indices, false));
21023 ufbxi_check(ufbxi_flip_attrib_winding(uc, mesh, &set->vertex_bitangent.indices, false));
21024 }
21025 mesh->vertex_uv = mesh->uv_sets.data[0].vertex_uv;
21026 mesh->vertex_bitangent = mesh->uv_sets.data[0].vertex_bitangent;
21027 mesh->vertex_tangent = mesh->uv_sets.data[0].vertex_tangent;
21028 }
21029 if (mesh->color_sets.count > 0) {
21030 ufbxi_for_list(ufbx_color_set, set, mesh->color_sets) {
21031 ufbxi_check(ufbxi_flip_attrib_winding(uc, mesh, &set->vertex_color.indices, false));
21032 }
21033 mesh->vertex_color = mesh->color_sets.data[0].vertex_color;
21034 }
21035 ufbxi_check(ufbxi_flip_attrib_winding(uc, mesh, &mesh->skinned_position.indices, false));
21036 if (mesh->skinned_normal.indices.data != mesh->vertex_normal.indices.data) {
21037 ufbxi_check(ufbxi_flip_attrib_winding(uc, mesh, &mesh->skinned_normal.indices, false));
21038 }
21039
21040 ufbxi_update_vertex_first_index(mesh);
21041
21042 // Mapping from old index values to flipped ones, reserve index -1
21043 // (aka `UFBX_NO_INDEX`) for itself.
21044 if (mesh->edges.count > 0) {
21045 ufbxi_check(ufbxi_grow_array(&uc->ator_tmp, &uc->tmp_arr, &uc->tmp_arr_size, (mesh->num_indices + 1) * sizeof(uint32_t)));
21046 uint32_t *index_mapping = (uint32_t*)uc->tmp_arr + 1;
21047 index_mapping[-1] = UFBX_NO_INDEX;
21048 ufbxi_for_list(ufbx_face, face, mesh->faces) {
21049 if (face->num_indices == 0) continue;
21050 uint32_t begin = face->index_begin;
21051 uint32_t count = face->num_indices - 1;
21052 index_mapping[begin] = begin;
21053 for (uint32_t i = 0; i < count; i++) {
21054 index_mapping[begin + 1 + i] = begin + count - i;
21055 }
21056 }
21057
21058 ufbxi_for_list(ufbx_edge, p_edge, mesh->edges) {
21059 uint32_t a = index_mapping[(int32_t)p_edge->a];
21060 uint32_t b = index_mapping[(int32_t)p_edge->b];
21061 p_edge->a = b;
21062 p_edge->b = a;
21063 }
21064 }
21065
21066 return 1;
21067 }
21068
21069 ufbxi_nodiscard ufbxi_noinline static int ufbxi_modify_geometry(ufbxi_context *uc)
21070 {
21071 bool do_mirror = false;
21072 bool do_winding = uc->opts.reverse_winding;
21073 bool do_scale = false;
21074 bool do_geometry_transforms = false;
21075 if (uc->opts.geometry_transform_handling == UFBX_GEOMETRY_TRANSFORM_HANDLING_MODIFY_GEOMETRY
21076 || uc->opts.geometry_transform_handling == UFBX_GEOMETRY_TRANSFORM_HANDLING_MODIFY_GEOMETRY_NO_FALLBACK) {
21077 // Prefetch geometry transforms for processing, they will later be overwritten in `ufbxi_update_node()`.
21078 ufbxi_for_ptr_list(ufbx_node, p_node, uc->scene.nodes) {
21079 ufbx_node *node = *p_node;
21080 if (node->is_root) continue;
21081
21082 node->geometry_transform = ufbxi_get_geometry_transform(&node->props, node);
21083 if (!ufbxi_is_transform_identity(&node->geometry_transform)) {
21084 node->geometry_to_node = ufbx_transform_to_matrix(&node->geometry_transform);
21085 node->has_geometry_transform = true;
21086 } else {
21087 node->geometry_to_node = ufbx_identity_matrix;
21088 node->has_geometry_transform = false;
21089 }
21090 }
21091 do_geometry_transforms = true;
21092 }
21093 if (uc->mirror_axis != 0) {
21094 do_mirror = true;
21095 }
21096 if (uc->scene.metadata.geometry_scale != 1.0f) {
21097 do_scale = true;
21098 }
21099
21100 ufbx_real geometry_scale = uc->scene.metadata.geometry_scale;
21101 ufbx_mirror_axis mirror_axis = uc->mirror_axis;
21102
21103 ufbxi_for_ptr_list(ufbx_blend_shape, p_shape, uc->scene.blend_shapes) {
21104 ufbx_blend_shape *shape = *p_shape;
21105
21106 if (do_scale) {
21107 ufbxi_scale_vec3_list(&shape->position_offsets, geometry_scale, 0);
21108 }
21109
21110 if (do_mirror) {
21111 ufbxi_mirror_vec3_list(&shape->position_offsets, mirror_axis, 0);
21112 ufbxi_mirror_vec3_list(&shape->normal_offsets, mirror_axis, 0);
21113 }
21114 }
21115
21116 ufbxi_for_ptr_list(ufbx_mesh, p_mesh, uc->scene.meshes) {
21117 ufbx_mesh *mesh = *p_mesh;
21118
21119 if (do_scale) {
21120 ufbxi_scale_vec3_list(&mesh->vertex_position.values, geometry_scale, 0);
21121 }
21122
21123 bool do_flip_winding = do_winding;
21124 if (do_mirror) {
21125 ufbxi_mirror_vec3_list(&mesh->vertex_position.values, mirror_axis, 0);
21126 ufbxi_mirror_vec3_list(&mesh->vertex_normal.values, mirror_axis, 0);
21127 ufbxi_for_list(ufbx_uv_set, set, mesh->uv_sets) {
21128 ufbxi_mirror_vec3_list(&set->vertex_tangent.values, mirror_axis, 0);
21129 ufbxi_mirror_vec3_list(&set->vertex_bitangent.values, mirror_axis, 0);
21130 }
21131 if (!uc->opts.handedness_conversion_retain_winding) {
21132 do_flip_winding = !do_flip_winding;
21133 }
21134 }
21135
21136 // Flip face winding retaining the first vertex
21137 if (do_flip_winding) {
21138 mesh->reversed_winding = true;
21139 ufbxi_check(ufbxi_flip_winding(uc, mesh));
21140 }
21141
21142 ufbx_node *geo_node = ufbxi_get_geometry_transform_node(&mesh->element);
21143 if (do_geometry_transforms && geo_node) {
21144 ufbx_matrix tangent_matrix = geo_node->geometry_to_node;
21145 tangent_matrix.m03 = 0.0f;
21146 tangent_matrix.m13 = 0.0f;
21147 tangent_matrix.m23 = 0.0f;
21148 ufbx_matrix normal_matrix = ufbx_matrix_for_normals(&geo_node->geometry_to_node);
21149
21150 ufbxi_transform_vec3_list(&mesh->vertex_position.values, &geo_node->geometry_to_node, 0);
21151 ufbxi_transform_vec3_list(&mesh->vertex_normal.values, &normal_matrix, 0);
21152 ufbxi_normalize_vec3_list(&mesh->vertex_normal.values);
21153
21154 ufbxi_for_list(ufbx_uv_set, set, mesh->uv_sets) {
21155 ufbxi_transform_vec3_list(&set->vertex_tangent.values, &tangent_matrix, 0);
21156 ufbxi_transform_vec3_list(&set->vertex_bitangent.values, &tangent_matrix, 0);
21157 ufbxi_normalize_vec3_list(&set->vertex_tangent.values);
21158 ufbxi_normalize_vec3_list(&set->vertex_bitangent.values);
21159 }
21160 }
21161 }
21162
21163 ufbxi_for_ptr_list(ufbx_line_curve, p_curve, uc->scene.line_curves) {
21164 ufbx_line_curve *curve = *p_curve;
21165
21166 if (do_scale) {
21167 ufbxi_scale_vec3_list(&curve->control_points, geometry_scale, 0);
21168 }
21169
21170 if (do_mirror) {
21171 ufbxi_mirror_vec3_list(&curve->control_points, mirror_axis, 0);
21172 }
21173
21174 ufbx_node *geo_node = ufbxi_get_geometry_transform_node(&curve->element);
21175 if (do_geometry_transforms && geo_node) {
21176 ufbxi_transform_vec3_list(&curve->control_points, &geo_node->geometry_to_node, 0);
21177 }
21178 }
21179
21180 ufbxi_for_ptr_list(ufbx_nurbs_curve, p_curve, uc->scene.nurbs_curves) {
21181 ufbx_nurbs_curve *curve = *p_curve;
21182
21183 if (do_scale) {
21184 ufbxi_scale_vec3_list(&curve->control_points, geometry_scale, sizeof(ufbx_vec4));
21185 }
21186
21187 if (do_mirror) {
21188 ufbxi_mirror_vec3_list(&curve->control_points, mirror_axis, sizeof(ufbx_vec4));
21189 }
21190
21191 ufbx_node *geo_node = ufbxi_get_geometry_transform_node(&curve->element);
21192 if (do_geometry_transforms && geo_node) {
21193 ufbxi_transform_vec3_list(&curve->control_points, &geo_node->geometry_to_node, sizeof(ufbx_vec4));
21194 }
21195 }
21196
21197 ufbxi_for_ptr_list(ufbx_nurbs_surface, p_surface, uc->scene.nurbs_surfaces) {
21198 ufbx_nurbs_surface *surface = *p_surface;
21199
21200 if (do_scale) {
21201 ufbxi_scale_vec3_list(&surface->control_points, geometry_scale, sizeof(ufbx_vec4));
21202 }
21203
21204 if (do_mirror) {
21205 ufbxi_mirror_vec3_list(&surface->control_points, mirror_axis, sizeof(ufbx_vec4));
21206 }
21207
21208 ufbx_node *geo_node = ufbxi_get_geometry_transform_node(&surface->element);
21209 if (do_geometry_transforms && geo_node) {
21210 ufbxi_transform_vec3_list(&surface->control_points, &geo_node->geometry_to_node, sizeof(ufbx_vec4));
21211 }
21212 }
21213
21214 if (uc->opts.geometry_transform_handling != UFBX_GEOMETRY_TRANSFORM_HANDLING_PRESERVE) {
21215 // Reset all geometry transforms if we're not preserving them
21216 ufbx_props *defaults = NULL;
21217 ufbxi_for_ptr_list(ufbx_node, p_node, uc->scene.nodes) {
21218 ufbx_node *node = *p_node;
21219 if (!defaults) defaults = node->props.defaults;
21220
21221 if (node->has_geometry_transform) {
21222 ufbxi_set_own_prop_vec3_uniform(&node->props, ufbxi_GeometricTranslation, 0.0f);
21223 ufbxi_set_own_prop_vec3_uniform(&node->props, ufbxi_GeometricRotation, 0.0f);
21224 ufbxi_set_own_prop_vec3_uniform(&node->props, ufbxi_GeometricScaling, 1.0f);
21225 }
21226 }
21227
21228 if (defaults) {
21229 ufbxi_set_own_prop_vec3_uniform(defaults, ufbxi_GeometricTranslation, 0.0f);
21230 ufbxi_set_own_prop_vec3_uniform(defaults, ufbxi_GeometricRotation, 0.0f);
21231 ufbxi_set_own_prop_vec3_uniform(defaults, ufbxi_GeometricScaling, 1.0f);
21232 }
21233 }
21234
21235 return 1;
21236 }
21237
21238 ufbxi_noinline static void ufbxi_postprocess_scene(ufbxi_context *uc)
21239 {
21240 if (uc->opts.normalize_normals || uc->opts.normalize_tangents) {
21241 ufbxi_for_ptr_list(ufbx_mesh, p_mesh, uc->scene.meshes) {
21242 ufbx_mesh *mesh = *p_mesh;
21243 if (uc->opts.normalize_normals) {
21244 ufbxi_normalize_vec3_list(&mesh->vertex_normal.values);
21245 }
21246 if (uc->opts.normalize_tangents) {
21247 ufbxi_for_list(ufbx_uv_set, set, mesh->uv_sets) {
21248 ufbxi_normalize_vec3_list(&mesh->vertex_tangent.values);
21249 ufbxi_normalize_vec3_list(&mesh->vertex_bitangent.values);
21250 }
21251 }
21252 }
21253 }
21254
21255 if (uc->exporter == UFBX_EXPORTER_BLENDER_BINARY) {
21256 uc->scene.metadata.ortho_size_unit = 1.0f / uc->scene.metadata.geometry_scale;
21257 } else {
21258 uc->scene.metadata.ortho_size_unit = 30.0f;
21259 }
21260 }
21261
21262 ufbxi_noinline static size_t ufbxi_next_path_segment(const char *data, size_t begin, size_t length)
21263 {
21264 for (size_t i = begin; i < length; i++) {
21265 if (data[i] == '/' || data[i] == '\\') {
21266 return i;
21267 }
21268 }
21269 return length;
21270 }
21271
21272 ufbxi_nodiscard ufbxi_noinline static int ufbxi_absolute_to_relative_path(ufbxi_context *uc, ufbxi_strblob *p_dst, const ufbxi_strblob *p_rel, const ufbxi_strblob *p_src, bool raw)
21273 {
21274 const char *rel = ufbxi_strblob_data(p_rel, raw);
21275 const char *src = ufbxi_strblob_data(p_src, raw);
21276 size_t rel_length = ufbxi_strblob_length(p_rel, raw);
21277 size_t src_length = ufbxi_strblob_length(p_src, raw);
21278
21279 if (rel_length == 0 || src_length == 0) return 1;
21280
21281 // Absolute paths must start with the same character (either drive or '/')
21282 if (rel[0] != src[0]) return 1;
21283
21284 // Find the last directory of the path we want to be relative to
21285 while (rel_length > 0 && (rel[rel_length - 1] != '/' && rel[rel_length - 1] != '\\')) {
21286 rel_length--;
21287 }
21288
21289 if (rel_length == 0) return 1;
21290 char separator = rel[rel_length - 1];
21291
21292 size_t max_length = rel_length * 2 + src_length;
21293
21294 ufbxi_check(ufbxi_grow_array(&uc->ator_tmp, &uc->tmp_arr, &uc->tmp_arr_size, max_length));
21295 char *tmp = uc->tmp_arr;
21296 size_t tmp_length = 0;
21297
21298 size_t rel_begin = 0;
21299 size_t src_begin = 0;
21300 while (rel_begin < rel_length && src_begin < src_length) {
21301 size_t rel_end = ufbxi_next_path_segment(rel, rel_begin, rel_length);
21302 size_t src_end = ufbxi_next_path_segment(src, src_begin, src_length);
21303 if (rel_end != src_end || memcmp(rel + rel_begin, src + src_begin, src_end - src_begin) != 0) break;
21304
21305 rel_begin = rel_end + 1;
21306 src_begin = src_end + 1;
21307 }
21308
21309 while (rel_begin < rel_length) {
21310 size_t rel_end = ufbxi_next_path_segment(rel, rel_begin, rel_length);
21311 tmp[tmp_length++] = '.';
21312 tmp[tmp_length++] = '.';
21313 tmp[tmp_length++] = separator;
21314 rel_begin = rel_end + 1;
21315 }
21316
21317 while (src_begin < src_length) {
21318 size_t src_end = ufbxi_next_path_segment(src, src_begin, src_length);
21319 size_t len = src_end - src_begin;
21320
21321 memcpy(tmp + tmp_length, src + src_begin, len);
21322 tmp_length += len;
21323
21324 if (src_end < src_length) {
21325 tmp[tmp_length++] = separator;
21326 }
21327
21328 src_begin = src_end + 1;
21329 }
21330
21331 ufbx_assert(tmp_length <= max_length);
21332
21333 const char *dst = ufbxi_push_string(&uc->string_pool, tmp, tmp_length, NULL, true);
21334 ufbxi_check(dst);
21335
21336 ufbxi_strblob_set(p_dst, dst, tmp_length, raw);
21337
21338 return 1;
21339 }
21340
21341 ufbxi_nodiscard ufbxi_noinline static int ufbxi_resolve_filenames(ufbxi_context *uc, ufbxi_strblob *filename, ufbxi_strblob *absolute_filename, ufbxi_strblob *relative_filename, bool raw)
21342 {
21343 if (ufbxi_strblob_length(relative_filename, raw) == 0) {
21344 const ufbxi_strblob *original_file_path = raw
21345 ? (const ufbxi_strblob*)&uc->scene.metadata.raw_original_file_path
21346 : (const ufbxi_strblob*)&uc->scene.metadata.original_file_path;
21347
21348 ufbxi_check(ufbxi_absolute_to_relative_path(uc, relative_filename, original_file_path, absolute_filename, raw));
21349 }
21350
21351 ufbxi_check(ufbxi_resolve_relative_filename(uc, filename, relative_filename, raw));
21352
21353 return 1;
21354 }
21355
21356 ufbxi_noinline static bool ufbxi_file_content_less(void *user, const void *va, const void *vb)
21357 {
21358 (void)user;
21359 const ufbxi_file_content *a = (const ufbxi_file_content*)va, *b = (const ufbxi_file_content*)vb;
21360 return ufbxi_str_less(a->absolute_filename, b->absolute_filename);
21361 }
21362
21363 ufbxi_nodiscard ufbxi_noinline static int ufbxi_sort_file_contents(ufbxi_context *uc, ufbxi_file_content *content, size_t count)
21364 {
21365 ufbxi_check(ufbxi_grow_array(&uc->ator_tmp, &uc->tmp_arr, &uc->tmp_arr_size, count * sizeof(ufbxi_file_content)));
21366 ufbxi_stable_sort(sizeof(ufbxi_file_content), 32, content, uc->tmp_arr, count, &ufbxi_file_content_less, NULL);
21367 return 1;
21368 }
21369
21370 ufbxi_nodiscard ufbxi_noinline static int ufbxi_push_file_content(ufbxi_context *uc, ufbx_string *p_filename, ufbx_blob *p_data)
21371 {
21372 if (p_data->size == 0 || p_filename->length == 0) return 1;
21373 ufbxi_file_content *content = ufbxi_push(&uc->tmp_stack, ufbxi_file_content, 1);
21374 ufbxi_check(content);
21375
21376 content->absolute_filename = *p_filename;
21377 content->content = *p_data;
21378 return 1;
21379 }
21380
21381 ufbxi_noinline static void ufbxi_fetch_file_content(ufbxi_context *uc, ufbx_string *p_filename, ufbx_blob *p_data)
21382 {
21383 if (p_data->size > 0) return;
21384 ufbx_string filename = *p_filename;
21385 size_t index = SIZE_MAX;
21386 ufbxi_macro_lower_bound_eq(ufbxi_file_content, 8, &index, uc->file_content, 0, uc->num_file_content,
21387 ( ufbxi_str_less(a->absolute_filename, filename) ),
21388 ( a->absolute_filename.data == filename.data ));
21389 if (index != SIZE_MAX) {
21390 *p_data = uc->file_content[index].content;
21391 }
21392 }
21393
21394 ufbxi_nodiscard ufbxi_noinline static int ufbxi_resolve_file_content(ufbxi_context *uc)
21395 {
21396 size_t initial_stack = uc->tmp_stack.num_items;
21397
21398 ufbxi_for_ptr_list(ufbx_video, p_video, uc->scene.videos) {
21399 ufbx_video *video = *p_video;
21400 ufbxi_check(ufbxi_resolve_filenames(uc, (ufbxi_strblob*)&video->filename, (ufbxi_strblob*)&video->absolute_filename, (ufbxi_strblob*)&video->relative_filename, false));
21401 ufbxi_check(ufbxi_resolve_filenames(uc, (ufbxi_strblob*)&video->raw_filename, (ufbxi_strblob*)&video->raw_absolute_filename, (ufbxi_strblob*)&video->raw_relative_filename, true));
21402 ufbxi_check(ufbxi_push_file_content(uc, &video->absolute_filename, &video->content));
21403 }
21404
21405 ufbxi_for_ptr_list(ufbx_audio_clip, p_clip, uc->scene.audio_clips) {
21406 ufbx_audio_clip *clip = *p_clip;
21407 clip->absolute_filename = ufbx_find_string(&clip->props, "Path", ufbx_empty_string);
21408 clip->relative_filename = ufbx_find_string(&clip->props, "RelPath", ufbx_empty_string);
21409 clip->raw_absolute_filename = ufbx_find_blob(&clip->props, "Path", ufbx_empty_blob);
21410 clip->raw_relative_filename = ufbx_find_blob(&clip->props, "RelPath", ufbx_empty_blob);
21411 ufbxi_check(ufbxi_resolve_filenames(uc, (ufbxi_strblob*)&clip->filename, (ufbxi_strblob*)&clip->absolute_filename, (ufbxi_strblob*)&clip->relative_filename, false));
21412 ufbxi_check(ufbxi_resolve_filenames(uc, (ufbxi_strblob*)&clip->raw_filename, (ufbxi_strblob*)&clip->raw_absolute_filename, (ufbxi_strblob*)&clip->raw_relative_filename, true));
21413 ufbxi_check(ufbxi_push_file_content(uc, &clip->absolute_filename, &clip->content));
21414 }
21415
21416 uc->num_file_content = uc->tmp_stack.num_items - initial_stack;
21417 uc->file_content = ufbxi_push_pop(&uc->tmp, &uc->tmp_stack, ufbxi_file_content, uc->num_file_content);
21418 ufbxi_check(uc->file_content);
21419 ufbxi_check(ufbxi_sort_file_contents(uc, uc->file_content, uc->num_file_content));
21420
21421 ufbxi_for_ptr_list(ufbx_video, p_video, uc->scene.videos) {
21422 ufbx_video *video = *p_video;
21423 ufbxi_fetch_file_content(uc, &video->absolute_filename, &video->content);
21424 }
21425
21426 ufbxi_for_ptr_list(ufbx_audio_clip, p_clip, uc->scene.audio_clips) {
21427 ufbx_audio_clip *clip = *p_clip;
21428 ufbxi_fetch_file_content(uc, &clip->absolute_filename, &clip->content);
21429 }
21430
21431 return 1;
21432 }
21433
21434 ufbxi_nodiscard ufbxi_noinline static int ufbxi_validate_indices(ufbxi_context *uc, ufbx_uint32_list *indices, size_t max_index)
21435 {
21436 if (max_index == 0 && uc->opts.index_error_handling == UFBX_INDEX_ERROR_HANDLING_CLAMP) {
21437 indices->data = NULL;
21438 indices->count = 0;
21439 return 1;
21440 }
21441
21442 ufbxi_nounroll ufbxi_for_list(uint32_t, p_ix, *indices) {
21443 uint32_t ix = *p_ix;
21444 if (ix >= max_index) {
21445 ufbxi_check(ufbxi_fix_index(uc, p_ix, ix, max_index));
21446 }
21447 }
21448
21449 return 1;
21450 }
21451
21452 static bool ufbxi_material_part_usage_less(void *user, const void *va, const void *vb)
21453 {
21454 ufbx_mesh_part *parts = (ufbx_mesh_part*)user;
21455 uint32_t a = *(const uint32_t*)va, b = *(const uint32_t*)vb;
21456 ufbx_mesh_part *pa = &parts[a];
21457 ufbx_mesh_part *pb = &parts[b];
21458 if (pa->face_indices.count == 0 || pb->face_indices.count == 0) {
21459 if (pa->face_indices.count == pb->face_indices.count) return a < b;
21460 return pa->face_indices.count > pb->face_indices.count;
21461 }
21462 return pa->face_indices.data[0] < pb->face_indices.data[0];
21463 }
21464
21465 ufbxi_nodiscard static ufbxi_noinline int ufbxi_finalize_mesh_material(ufbxi_buf *buf, ufbx_error *error, ufbx_mesh *mesh)
21466 {
21467 size_t num_materials = mesh->materials.count;
21468 size_t num_parts = mesh->material_parts.count;
21469 size_t num_faces = mesh->faces.count;
21470
21471 ufbx_mesh_part *parts = mesh->material_parts.data;
21472 ufbx_assert(!parts || (mesh->material_parts.count == num_materials) || (mesh->material_parts.count == 1 && num_materials == 0));
21473
21474 uint32_t *face_material = mesh->face_material.data;
21475
21476 // Count the number of faces and triangles per material
21477 ufbxi_nounroll for (size_t i = 0; i < num_faces; i++) {
21478 ufbx_face face = mesh->faces.data[i];
21479 uint32_t mat_ix = 0;
21480
21481 if (face_material) {
21482 mat_ix = face_material[i];
21483 if (mat_ix >= num_materials) {
21484 face_material[i] = 0;
21485 mat_ix = 0;
21486 }
21487 }
21488
21489 if (parts) {
21490 ufbxi_mesh_part_add_face(&parts[mat_ix], face.num_indices);
21491 }
21492 }
21493
21494 if (parts) {
21495 // Allocate per-material buffers (clear `num_faces` to 0 to re-use it as
21496 // an index when fetching the face indices).
21497 uint32_t part_index = 0;
21498 ufbxi_for(ufbx_mesh_part, part, parts, num_parts) {
21499 part->index = part_index++;
21500 part->face_indices.count = part->num_faces;
21501 part->face_indices.data = ufbxi_push(buf, uint32_t, part->num_faces);
21502 ufbxi_check_err(error, part->face_indices.data);
21503 part->num_faces = 0;
21504 }
21505
21506 // Fetch the per-material face indices
21507 ufbxi_nounroll for (size_t i = 0; i < num_faces; i++) {
21508 uint32_t mat_ix = face_material ? face_material[i] : 0;
21509 if (mat_ix < num_parts) {
21510 ufbx_mesh_part *part = &parts[mat_ix];
21511 part->face_indices.data[part->num_faces++] = (uint32_t)i;
21512 }
21513 }
21514
21515 mesh->material_part_usage_order.count = num_parts;
21516 mesh->material_part_usage_order.data = ufbxi_push(buf, uint32_t, num_parts);
21517 ufbxi_check_err(error, mesh->material_part_usage_order.data);
21518 for (size_t i = 0; i < num_parts; i++) {
21519 mesh->material_part_usage_order.data[i] = (uint32_t)i;
21520 }
21521 ufbxi_unstable_sort(mesh->material_part_usage_order.data, num_parts, sizeof(uint32_t), &ufbxi_material_part_usage_less, parts);
21522 }
21523
21524 return 1;
21525 }
21526
21527 typedef struct {
21528 ufbxi_refcount refcount;
21529 ufbx_anim anim;
21530 uint32_t magic;
21531 } ufbxi_anim_imp;
21532
21533 ufbxi_nodiscard ufbxi_noinline static int ufbxi_push_anim(ufbxi_context *uc, ufbx_anim **p_anim, ufbx_anim_layer **layers, size_t num_layers)
21534 {
21535 ufbx_anim *anim = ufbxi_push_zero(&uc->result, ufbx_anim, 1);
21536 ufbxi_check(anim);
21537
21538 anim->layers.data = layers;
21539 anim->layers.count = num_layers;
21540
21541 *p_anim = anim;
21542 return 1;
21543 }
21544
21545 ufbxi_nodiscard ufbxi_noinline static int ufbxi_finalize_scene(ufbxi_context *uc)
21546 {
21547 size_t num_elements = uc->num_elements;
21548
21549 uc->scene.elements.count = num_elements;
21550 uc->scene.elements.data = ufbxi_push(&uc->result, ufbx_element*, num_elements);
21551 ufbxi_check(uc->scene.elements.data);
21552
21553 uc->scene.metadata.element_buffer_size = uc->tmp_element_byte_offset;
21554 char *element_data = (char*)ufbxi_push_pop(&uc->result, &uc->tmp_elements, uint64_t, uc->tmp_element_byte_offset/8);
21555 ufbxi_check(element_data);
21556
21557 size_t *element_offsets = ufbxi_push_pop(&uc->tmp, &uc->tmp_element_offsets, size_t, uc->tmp_element_offsets.num_items);
21558 ufbxi_buf_free(&uc->tmp_element_offsets);
21559 ufbxi_check(element_offsets);
21560 for (size_t i = 0; i < num_elements; i++) {
21561 ufbx_element *element = (ufbx_element*)(element_data + element_offsets[i]);
21562
21563 if (element->type == UFBX_ELEMENT_NODE) {
21564 ufbx_node *node = (ufbx_node*)element;
21565 if (node->scale_helper) {
21566 ufbxi_node_extra *extra = (ufbxi_node_extra*)ufbxi_get_element_extra(uc, node->element_id);
21567 ufbx_assert(extra);
21568 node->scale_helper = (ufbx_node*)(element_data + element_offsets[extra->scale_helper_id]);
21569 }
21570 }
21571
21572 uc->scene.elements.data[i] = element;
21573 }
21574
21575 uc->scene.elements.count = num_elements;
21576 ufbxi_buf_free(&uc->tmp_element_offsets);
21577 ufbxi_buf_free(&uc->tmp_elements);
21578
21579 uc->tmp_element_flag = ufbxi_push_zero(&uc->tmp, uint8_t, num_elements);
21580 ufbxi_check(uc->tmp_element_flag);
21581
21582 uc->scene.metadata.original_file_path = ufbx_find_string(&uc->scene.metadata.scene_props, "DocumentUrl", ufbx_empty_string);
21583 uc->scene.metadata.raw_original_file_path = ufbx_find_blob(&uc->scene.metadata.scene_props, "DocumentUrl", ufbx_empty_blob);
21584
21585 // Resolve and add the connections to elements
21586 ufbxi_check(ufbxi_resolve_connections(uc));
21587 ufbxi_check(ufbxi_add_connections_to_elements(uc));
21588 ufbxi_check(ufbxi_linearize_nodes(uc));
21589
21590 for (size_t type = 0; type < UFBX_ELEMENT_TYPE_COUNT; type++) {
21591 size_t num_typed = uc->tmp_typed_element_offsets[type].num_items;
21592 size_t *typed_offsets = ufbxi_push_pop(&uc->tmp, &uc->tmp_typed_element_offsets[type], size_t, num_typed);
21593 ufbxi_buf_free(&uc->tmp_typed_element_offsets[type]);
21594 ufbxi_check(typed_offsets);
21595
21596 ufbx_element_list *typed_elems = &uc->scene.elements_by_type[type];
21597 typed_elems->count = num_typed;
21598 typed_elems->data = ufbxi_push(&uc->result, ufbx_element*, num_typed);
21599 ufbxi_check(typed_elems->data);
21600
21601 for (size_t i = 0; i < num_typed; i++) {
21602 typed_elems->data[i] = (ufbx_element*)(element_data + typed_offsets[i]);
21603 }
21604
21605 ufbxi_buf_free(&uc->tmp_typed_element_offsets[type]);
21606 }
21607
21608 // Create named elements
21609 uc->scene.elements_by_name.count = num_elements;
21610 uc->scene.elements_by_name.data = ufbxi_push(&uc->result, ufbx_name_element, num_elements);
21611 ufbxi_check(uc->scene.elements_by_name.data);
21612
21613 for (size_t i = 0; i < num_elements; i++) {
21614
21615 ufbx_element *elem = uc->scene.elements.data[i];
21616 ufbx_name_element *name_elem = &uc->scene.elements_by_name.data[i];
21617
21618 name_elem->name = elem->name;
21619 name_elem->type = elem->type;
21620 name_elem->_internal_key = ufbxi_get_name_key(elem->name.data, elem->name.length);
21621 name_elem->element = elem;
21622 }
21623
21624 ufbxi_check(ufbxi_sort_name_elements(uc, uc->scene.elements_by_name.data, num_elements));
21625
21626 // Setup node children arrays and attribute pointers/lists
21627 ufbxi_for_ptr_list(ufbx_node, p_node, uc->scene.nodes) {
21628 ufbx_node *node = *p_node, *parent = node->parent;
21629 if (parent) {
21630 parent->children.count++;
21631 if (parent->children.data == NULL) {
21632 parent->children.data = p_node;
21633 }
21634
21635 if (node->is_geometry_transform_helper) {
21636 parent->geometry_transform_helper = node;
21637 }
21638
21639 // Force top-level nodes to have `UFBX_INHERIT_MODE_NORMAL` to make unit scaling work.
21640 if (parent->is_root && uc->opts.space_conversion == UFBX_SPACE_CONVERSION_TRANSFORM_ROOT && uc->opts.inherit_mode_handling == UFBX_INHERIT_MODE_HANDLING_PRESERVE) {
21641 node->original_inherit_mode = UFBX_INHERIT_MODE_NORMAL;
21642 node->inherit_mode = UFBX_INHERIT_MODE_NORMAL;
21643 }
21644
21645 // RrSs nodes inherit scale from their parent, Rrs ignore the scale of
21646 // their _immediate_ parent, potentially multiple if chained.
21647 if (node->original_inherit_mode == UFBX_INHERIT_MODE_COMPONENTWISE_SCALE) {
21648 node->inherit_scale_node = parent;
21649 } else if (node->original_inherit_mode == UFBX_INHERIT_MODE_IGNORE_PARENT_SCALE) {
21650 node->inherit_scale_node = parent->inherit_scale_node;
21651 }
21652 }
21653
21654 ufbx_connection_list conns = ufbxi_find_dst_connections(&node->element, NULL);
21655
21656 ufbxi_for_list(ufbx_connection, conn, conns) {
21657 ufbx_element *elem = conn->src;
21658 ufbx_element_type type = elem->type;
21659 if (!(type >= UFBX_ELEMENT_TYPE_FIRST_ATTRIB && type <= UFBX_ELEMENT_TYPE_LAST_ATTRIB)) continue;
21660
21661 size_t index = node->all_attribs.count++;
21662 if (index == 0) {
21663 node->attrib = elem;
21664 node->attrib_type = type;
21665 } else {
21666 if (index == 1) {
21667 ufbxi_check(ufbxi_push_copy(&uc->tmp_stack, ufbx_element*, 1, &node->attrib));
21668 }
21669 ufbxi_check(ufbxi_push_copy(&uc->tmp_stack, ufbx_element*, 1, &elem));
21670 }
21671
21672 switch (elem->type) {
21673 case UFBX_ELEMENT_MESH: node->mesh = (ufbx_mesh*)elem; break;
21674 case UFBX_ELEMENT_LIGHT: node->light = (ufbx_light*)elem; break;
21675 case UFBX_ELEMENT_CAMERA: node->camera = (ufbx_camera*)elem; break;
21676 case UFBX_ELEMENT_BONE: node->bone = (ufbx_bone*)elem; break;
21677 default: /* No shorthand */ break;
21678 }
21679 }
21680
21681 if (node->all_attribs.count > 1) {
21682 node->all_attribs.data = ufbxi_push_pop(&uc->result, &uc->tmp_stack, ufbx_element*, node->all_attribs.count);
21683 ufbxi_check(node->all_attribs.data);
21684 } else if (node->all_attribs.count == 1) {
21685 node->all_attribs.data = &node->attrib;
21686 }
21687
21688 ufbxi_check(ufbxi_fetch_dst_elements(uc, &node->materials, &node->element, false, false, NULL, UFBX_ELEMENT_MATERIAL));
21689 }
21690
21691 // Resolve bind pose bones that don't use the normal connection system
21692 ufbxi_for_ptr_list(ufbx_pose, p_pose, uc->scene.poses) {
21693 ufbx_pose *pose = *p_pose;
21694
21695 // HACK: Transport `ufbxi_tmp_bone_pose` array through the `ufbx_bone_pose` pointer
21696 size_t num_bones = pose->bone_poses.count;
21697 ufbxi_tmp_bone_pose *tmp_poses = (ufbxi_tmp_bone_pose*)pose->bone_poses.data;
21698 pose->bone_poses.data = ufbxi_push(&uc->result, ufbx_bone_pose, num_bones);
21699 ufbxi_check(pose->bone_poses.data);
21700
21701 // Filter only found bones
21702 pose->bone_poses.count = 0;
21703 for (size_t i = 0; i < num_bones; i++) {
21704 ufbx_element *elem = ufbxi_find_element_by_fbx_id(uc, tmp_poses[i].bone_fbx_id);
21705 if (!elem || elem->type != UFBX_ELEMENT_NODE) continue;
21706
21707 ufbx_node *node = (ufbx_node*)elem;
21708 ufbx_bone_pose *bone = &pose->bone_poses.data[pose->bone_poses.count++];
21709 bone->bone_node = node;
21710 bone->bone_to_world = tmp_poses[i].bone_to_world;
21711
21712 if (pose->is_bind_pose) {
21713 if (node->bind_pose == NULL) {
21714 node->bind_pose = pose;
21715 }
21716
21717 ufbx_connection_list node_conns = ufbxi_find_src_connections(elem, NULL);
21718 ufbxi_for_list(ufbx_connection, conn, node_conns) {
21719 if (conn->dst->type != UFBX_ELEMENT_SKIN_CLUSTER) continue;
21720 ufbx_skin_cluster *cluster = (ufbx_skin_cluster*)conn->dst;
21721 if (ufbxi_matrix_all_zero(&cluster->bind_to_world)) {
21722 cluster->bind_to_world = bone->bone_to_world;
21723 }
21724 }
21725 }
21726 }
21727 ufbxi_check(ufbxi_sort_bone_poses(uc, pose));
21728 }
21729
21730 // Fetch pointers that may break elements
21731
21732 // Setup node attribute instances
21733 for (int type = UFBX_ELEMENT_TYPE_FIRST_ATTRIB; type <= UFBX_ELEMENT_TYPE_LAST_ATTRIB; type++) {
21734 ufbxi_for_ptr_list(ufbx_element, p_elem, uc->scene.elements_by_type[type]) {
21735 ufbx_element *elem = *p_elem;
21736 ufbxi_check(ufbxi_fetch_src_elements(uc, &elem->instances, elem, false, true, NULL, UFBX_ELEMENT_NODE));
21737 }
21738 }
21739
21740 bool search_node = uc->version < 7000;
21741
21742 ufbxi_for_ptr_list(ufbx_skin_cluster, p_cluster, uc->scene.skin_clusters) {
21743 ufbx_skin_cluster *cluster = *p_cluster;
21744 cluster->bone_node = (ufbx_node*)ufbxi_fetch_dst_element(&cluster->element, false, NULL, UFBX_ELEMENT_NODE);
21745 }
21746
21747 ufbxi_for_ptr_list(ufbx_skin_deformer, p_skin, uc->scene.skin_deformers) {
21748 ufbx_skin_deformer *skin = *p_skin;
21749 ufbxi_check(ufbxi_fetch_dst_elements(uc, &skin->clusters, &skin->element, false, true, NULL, UFBX_ELEMENT_SKIN_CLUSTER));
21750
21751 // Remove clusters without a valid `bone`
21752 if (!uc->opts.connect_broken_elements) {
21753 size_t num_broken = 0;
21754 for (size_t i = 0; i < skin->clusters.count; i++) {
21755 if (!skin->clusters.data[i]->bone_node) {
21756 num_broken++;
21757 } else if (num_broken > 0) {
21758 skin->clusters.data[i - num_broken] = skin->clusters.data[i];
21759 }
21760 }
21761 skin->clusters.count -= num_broken;
21762 }
21763
21764 size_t total_weights = 0;
21765 ufbxi_for_ptr_list(ufbx_skin_cluster, p_cluster, skin->clusters) {
21766 ufbx_skin_cluster *cluster = *p_cluster;
21767 ufbxi_check(SIZE_MAX - total_weights > cluster->num_weights);
21768 total_weights += cluster->num_weights;
21769 }
21770
21771 size_t num_vertices = 0;
21772
21773 // Iterate through meshes so we can pad the vertices to the largest one
21774 {
21775 ufbx_connection_list conns = ufbxi_find_src_connections(&skin->element, NULL);
21776 ufbxi_for_list(ufbx_connection, conn, conns) {
21777 ufbx_mesh *mesh = NULL;
21778 if (conn->dst_prop.length > 0) continue;
21779 if (conn->dst->type == UFBX_ELEMENT_MESH) {
21780 mesh = (ufbx_mesh*)conn->dst;
21781 } else if (conn->dst->type == UFBX_ELEMENT_NODE) {
21782 ufbx_node *node = (ufbx_node*)conn->dst;
21783 if (node->geometry_transform_helper) node = node->geometry_transform_helper;
21784 mesh = node->mesh;
21785 }
21786 if (!mesh) continue;
21787 num_vertices = ufbxi_max_sz(num_vertices, mesh->num_vertices);
21788 }
21789 }
21790
21791 if (!uc->opts.skip_skin_vertices) {
21792 skin->vertices.count = num_vertices;
21793 skin->vertices.data = ufbxi_push_zero(&uc->result, ufbx_skin_vertex, num_vertices);
21794 ufbxi_check(skin->vertices.data);
21795
21796 skin->weights.count = total_weights;
21797 skin->weights.data = ufbxi_push_zero(&uc->result, ufbx_skin_weight, total_weights);
21798 ufbxi_check(skin->weights.data);
21799
21800 bool retain_all = !uc->opts.clean_skin_weights;
21801
21802 // Count the number of weights per vertex
21803 ufbxi_for_ptr_list(ufbx_skin_cluster, p_cluster, skin->clusters) {
21804 ufbx_skin_cluster *cluster = *p_cluster;
21805 for (size_t i = 0; i < cluster->num_weights; i++) {
21806 uint32_t vertex = cluster->vertices.data[i];
21807 if (vertex < num_vertices && (retain_all || cluster->weights.data[i] > 0.0f)) {
21808 skin->vertices.data[vertex].num_weights++;
21809 }
21810 }
21811 }
21812
21813 ufbx_real default_dq = skin->skinning_method == UFBX_SKINNING_METHOD_DUAL_QUATERNION ? 1.0f : 0.0f;
21814
21815 // Prefix sum to assign the vertex weight offsets and set up default DQ values
21816 uint32_t offset = 0;
21817 uint32_t max_weights = 0;
21818 for (size_t i = 0; i < num_vertices; i++) {
21819 skin->vertices.data[i].weight_begin = offset;
21820 skin->vertices.data[i].dq_weight = default_dq;
21821 uint32_t num_weights = skin->vertices.data[i].num_weights;
21822 offset += num_weights;
21823 skin->vertices.data[i].num_weights = 0;
21824
21825 if (num_weights > max_weights) max_weights = num_weights;
21826 }
21827 ufbx_assert(offset <= total_weights);
21828 skin->max_weights_per_vertex = max_weights;
21829
21830 // Copy the DQ weights to vertices
21831 for (size_t i = 0; i < skin->num_dq_weights; i++) {
21832 uint32_t vertex = skin->dq_vertices.data[i];
21833 if (vertex < num_vertices) {
21834 skin->vertices.data[vertex].dq_weight = skin->dq_weights.data[i];
21835 }
21836 }
21837
21838 // Copy the weights to vertices
21839 uint32_t cluster_index = 0;
21840 ufbxi_for_ptr_list(ufbx_skin_cluster, p_cluster, skin->clusters) {
21841 ufbx_skin_cluster *cluster = *p_cluster;
21842 for (size_t i = 0; i < cluster->num_weights; i++) {
21843 uint32_t vertex = cluster->vertices.data[i];
21844 if (vertex < num_vertices && (retain_all || cluster->weights.data[i] > 0.0f)) {
21845 uint32_t local_index = skin->vertices.data[vertex].num_weights++;
21846 uint32_t index = skin->vertices.data[vertex].weight_begin + local_index;
21847 skin->weights.data[index].cluster_index = cluster_index;
21848 skin->weights.data[index].weight = cluster->weights.data[i];
21849 }
21850 }
21851 cluster_index++;
21852 }
21853
21854 // Sort the vertex weights by descending weight value
21855 ufbxi_check(ufbxi_sort_skin_weights(uc, skin));
21856 }
21857 }
21858
21859 ufbxi_for_ptr_list(ufbx_blend_deformer, p_blend, uc->scene.blend_deformers) {
21860 ufbx_blend_deformer *blend = *p_blend;
21861 ufbxi_check(ufbxi_fetch_dst_elements(uc, &blend->channels, &blend->element, false, true, NULL, UFBX_ELEMENT_BLEND_CHANNEL));
21862 }
21863
21864 ufbxi_for_ptr_list(ufbx_cache_deformer, p_deformer, uc->scene.cache_deformers) {
21865 ufbx_cache_deformer *deformer = *p_deformer;
21866 deformer->channel = ufbx_find_string(&deformer->props, "ChannelName", ufbx_empty_string);
21867 deformer->file = (ufbx_cache_file*)ufbxi_fetch_dst_element(&deformer->element, false, NULL, UFBX_ELEMENT_CACHE_FILE);
21868 }
21869
21870 ufbxi_for_ptr_list(ufbx_cache_file, p_cache, uc->scene.cache_files) {
21871 ufbx_cache_file *cache = *p_cache;
21872
21873 cache->absolute_filename = ufbx_find_string(&cache->props, "CacheAbsoluteFileName", ufbx_empty_string);
21874 cache->relative_filename = ufbx_find_string(&cache->props, "CacheFileName", ufbx_empty_string);
21875
21876 cache->raw_absolute_filename = ufbx_find_blob(&cache->props, "CacheAbsoluteFileName", ufbx_empty_blob);
21877 cache->raw_relative_filename = ufbx_find_blob(&cache->props, "CacheFileName", ufbx_empty_blob);
21878
21879 int64_t type = ufbx_find_int(&cache->props, "CacheFileType", 0);
21880 if (type >= 0 && type <= UFBX_CACHE_FILE_FORMAT_MC) {
21881 cache->format = (ufbx_cache_file_format)type;
21882 }
21883
21884 ufbxi_check(ufbxi_resolve_filenames(uc, (ufbxi_strblob*)&cache->filename, (ufbxi_strblob*)&cache->absolute_filename, (ufbxi_strblob*)&cache->relative_filename, false));
21885 ufbxi_check(ufbxi_resolve_filenames(uc, (ufbxi_strblob*)&cache->raw_filename, (ufbxi_strblob*)&cache->raw_absolute_filename, (ufbxi_strblob*)&cache->raw_relative_filename, true));
21886 }
21887
21888 ufbx_assert(uc->tmp_full_weights.num_items == uc->scene.blend_channels.count);
21889 ufbx_real_list *full_weights = ufbxi_push_pop(&uc->tmp, &uc->tmp_full_weights, ufbx_real_list, uc->tmp_full_weights.num_items);
21890 ufbxi_buf_free(&uc->tmp_full_weights);
21891 ufbxi_check(full_weights);
21892
21893 ufbxi_for_ptr_list(ufbx_blend_channel, p_channel, uc->scene.blend_channels) {
21894 ufbx_blend_channel *channel = *p_channel;
21895
21896 ufbxi_check(ufbxi_fetch_blend_keyframes(uc, &channel->keyframes, &channel->element));
21897
21898 for (size_t i = 0; i < channel->keyframes.count; i++) {
21899 ufbx_blend_keyframe *key = &channel->keyframes.data[i];
21900 key->target_weight = 1.0f;
21901 if (i < full_weights->count) {
21902 if (!uc->blender_full_weights) {
21903 key->target_weight = full_weights->data[i] / (ufbx_real)100.0;
21904 } else if (full_weights->count == key->shape->num_offsets) {
21905 if (i == 0) {
21906 // Duplicate `index_data` for modification if we retain DOM
21907 if (uc->opts.retain_dom) {
21908 full_weights->data = ufbxi_push_copy(&uc->result, ufbx_real, full_weights->count, full_weights->data);
21909 ufbxi_check(full_weights->data);
21910 }
21911 ufbxi_for_list(ufbx_real, p_weight, *full_weights) {
21912 *p_weight /= (ufbx_real)100.0;
21913 }
21914 }
21915 key->shape->offset_weights = *full_weights;
21916 }
21917 }
21918 }
21919
21920 ufbxi_check(ufbxi_sort_blend_keyframes(uc, channel->keyframes.data, channel->keyframes.count));
21921 full_weights++;
21922
21923 if (channel->keyframes.count > 0) {
21924 channel->target_shape = channel->keyframes.data[channel->keyframes.count - 1].shape;
21925 }
21926 }
21927
21928 {
21929 // Generate and patch procedural index buffers
21930 uint32_t *zero_indices = ufbxi_push(&uc->result, uint32_t, uc->max_zero_indices);
21931 uint32_t *consecutive_indices = ufbxi_push(&uc->result, uint32_t, uc->max_consecutive_indices);
21932 ufbxi_check(zero_indices && consecutive_indices);
21933
21934 memset(zero_indices, 0, sizeof(uint32_t) * uc->max_zero_indices);
21935 for (size_t i = 0; i < uc->max_consecutive_indices; i++) {
21936 consecutive_indices[i] = (uint32_t)i;
21937 }
21938
21939 uc->zero_indices = zero_indices;
21940 uc->consecutive_indices = consecutive_indices;
21941
21942 ufbxi_for_ptr_list(ufbx_mesh, p_mesh, uc->scene.meshes) {
21943 ufbx_mesh *mesh = *p_mesh;
21944
21945 ufbxi_patch_index_pointer(uc, &mesh->vertex_position.indices.data);
21946 ufbxi_patch_index_pointer(uc, &mesh->vertex_normal.indices.data);
21947 ufbxi_patch_index_pointer(uc, &mesh->vertex_color.indices.data);
21948 ufbxi_patch_index_pointer(uc, &mesh->vertex_crease.indices.data);
21949 ufbxi_patch_index_pointer(uc, &mesh->face_material.data);
21950 ufbxi_patch_index_pointer(uc, &mesh->face_group.data);
21951
21952 ufbxi_patch_index_pointer(uc, &mesh->skinned_position.indices.data);
21953 ufbxi_patch_index_pointer(uc, &mesh->skinned_normal.indices.data);
21954
21955 ufbxi_for_list(ufbx_uv_set, set, mesh->uv_sets) {
21956 ufbxi_patch_index_pointer(uc, &set->vertex_uv.indices.data);
21957 ufbxi_patch_index_pointer(uc, &set->vertex_bitangent.indices.data);
21958 ufbxi_patch_index_pointer(uc, &set->vertex_tangent.indices.data);
21959 }
21960
21961 ufbxi_for_list(ufbx_color_set, set, mesh->color_sets) {
21962 ufbxi_patch_index_pointer(uc, &set->vertex_color.indices.data);
21963 }
21964
21965 // Generate normals if necessary
21966 if (!mesh->vertex_normal.exists && uc->opts.generate_missing_normals) {
21967 ufbxi_check(ufbxi_generate_normals(uc, mesh));
21968 }
21969
21970 // Assign first UV and color sets as the "canonical" ones
21971 if (mesh->uv_sets.count > 0) {
21972 mesh->vertex_uv = mesh->uv_sets.data[0].vertex_uv;
21973 mesh->vertex_bitangent = mesh->uv_sets.data[0].vertex_bitangent;
21974 mesh->vertex_tangent = mesh->uv_sets.data[0].vertex_tangent;
21975 }
21976 if (mesh->color_sets.count > 0) {
21977 mesh->vertex_color = mesh->color_sets.data[0].vertex_color;
21978 }
21979
21980 if (mesh->face_group_parts.count == 1) {
21981 ufbxi_patch_index_pointer(uc, &mesh->face_group_parts.data[0].face_indices.data);
21982 }
21983
21984 ufbxi_check(ufbxi_fetch_mesh_materials(uc, &mesh->materials, &mesh->element, true));
21985
21986 // Patch materials to instances if necessary
21987 if (mesh->materials.count > 0) {
21988 ufbxi_for_ptr_list(ufbx_node, p_node, mesh->instances) {
21989 ufbx_node *node = *p_node;
21990 if (node->materials.count < mesh->materials.count && mesh->materials.data[0] != NULL) {
21991 ufbx_material **materials = ufbxi_push(&uc->result, ufbx_material*, mesh->materials.count);
21992 ufbxi_check(materials);
21993 ufbxi_nounroll for (size_t i = 0; i < node->materials.count; i++) {
21994 materials[i] = node->materials.data[i];
21995 }
21996 ufbxi_nounroll for (size_t i = node->materials.count; i < mesh->materials.count; i++) {
21997 materials[i] = mesh->materials.data[i];
21998 }
21999 node->materials.data = materials;
22000 node->materials.count = mesh->materials.count;
22001 }
22002 }
22003 }
22004
22005 if (uc->retain_mesh_parts) {
22006 size_t num_parts = ufbxi_max_sz(mesh->materials.count, 1);
22007 mesh->material_parts.data = ufbxi_push_zero(&uc->result, ufbx_mesh_part, num_parts);
22008 ufbxi_check(mesh->material_parts.data);
22009 mesh->material_parts.count = num_parts;
22010 }
22011
22012 if (mesh->materials.count <= 1) {
22013 // Use the shared consecutive index buffer for mesh faces if there's only one material
22014 // See HACK(consecutive-faces) in `ufbxi_read_mesh()`.
22015 if (mesh->material_parts.count > 0) {
22016 ufbx_mesh_part *part = &mesh->material_parts.data[0];
22017 part->num_faces = mesh->num_faces;
22018 part->num_triangles = mesh->num_triangles;
22019 part->num_empty_faces = mesh->num_empty_faces;
22020 part->num_point_faces = mesh->num_point_faces;
22021 part->num_line_faces = mesh->num_line_faces;
22022 part->face_indices.data = uc->consecutive_indices;
22023 part->face_indices.count = mesh->num_faces;
22024 mesh->material_part_usage_order.data = uc->zero_indices;
22025 mesh->material_part_usage_order.count = 1;
22026 }
22027
22028 if (mesh->materials.count == 1) {
22029 mesh->face_material.data = uc->zero_indices;
22030 mesh->face_material.count = mesh->num_faces;
22031 } else {
22032 mesh->face_material.data = NULL;
22033 mesh->face_material.count = 0;
22034 }
22035 } else if (mesh->materials.count > 0) {
22036 ufbxi_check(ufbxi_finalize_mesh_material(&uc->result, &uc->error, mesh));
22037 }
22038
22039 // Fetch deformers
22040 ufbxi_check(ufbxi_fetch_dst_elements(uc, &mesh->skin_deformers, &mesh->element, search_node, true, NULL, UFBX_ELEMENT_SKIN_DEFORMER));
22041 ufbxi_check(ufbxi_fetch_dst_elements(uc, &mesh->blend_deformers, &mesh->element, search_node, true, NULL, UFBX_ELEMENT_BLEND_DEFORMER));
22042 ufbxi_check(ufbxi_fetch_dst_elements(uc, &mesh->cache_deformers, &mesh->element, search_node, true, NULL, UFBX_ELEMENT_CACHE_DEFORMER));
22043 ufbxi_check(ufbxi_fetch_deformers(uc, &mesh->all_deformers, &mesh->element, search_node));
22044
22045 // Vertex position must always exist if not explicitly allowed to be missing
22046 if (!mesh->vertex_position.exists && !uc->opts.allow_missing_vertex_position) {
22047 ufbxi_check(mesh->num_indices == 0);
22048 mesh->vertex_position.exists = true;
22049 mesh->vertex_position.unique_per_vertex = true;
22050 mesh->skinned_position.exists = true;
22051 mesh->skinned_position.unique_per_vertex = true;
22052 }
22053
22054 // Update metadata
22055 if (mesh->max_face_triangles > uc->scene.metadata.max_face_triangles) {
22056 uc->scene.metadata.max_face_triangles = mesh->max_face_triangles;
22057 }
22058 }
22059 }
22060
22061 ufbxi_for_ptr_list(ufbx_stereo_camera, p_stereo, uc->scene.stereo_cameras) {
22062 ufbx_stereo_camera *stereo = *p_stereo;
22063 stereo->left = (ufbx_camera*)ufbxi_fetch_dst_element(&stereo->element, search_node, ufbxi_LeftCamera, UFBX_ELEMENT_CAMERA);
22064 stereo->right = (ufbx_camera*)ufbxi_fetch_dst_element(&stereo->element, search_node, ufbxi_RightCamera, UFBX_ELEMENT_CAMERA);
22065 }
22066
22067 ufbxi_for_ptr_list(ufbx_nurbs_curve, p_curve, uc->scene.nurbs_curves) {
22068 ufbx_nurbs_curve *curve = *p_curve;
22069 ufbxi_check(ufbxi_finalize_nurbs_basis(uc, &curve->basis));
22070 }
22071
22072 ufbxi_for_ptr_list(ufbx_nurbs_surface, p_surface, uc->scene.nurbs_surfaces) {
22073 ufbx_nurbs_surface *surface = *p_surface;
22074 ufbxi_check(ufbxi_finalize_nurbs_basis(uc, &surface->basis_u));
22075 ufbxi_check(ufbxi_finalize_nurbs_basis(uc, &surface->basis_v));
22076
22077 surface->material = (ufbx_material*)ufbxi_fetch_dst_element(&surface->element, true, NULL, UFBX_ELEMENT_MATERIAL);
22078 }
22079
22080 ufbxi_for_ptr_list(ufbx_anim_stack, p_stack, uc->scene.anim_stacks) {
22081 ufbx_anim_stack *stack = *p_stack;
22082 ufbxi_check(ufbxi_fetch_dst_elements(uc, &stack->layers, &stack->element, false, true, NULL, UFBX_ELEMENT_ANIM_LAYER));
22083
22084 ufbxi_check(ufbxi_push_anim(uc, &stack->anim, stack->layers.data, stack->layers.count));
22085 }
22086
22087 ufbxi_for_ptr_list(ufbx_anim_layer, p_layer, uc->scene.anim_layers) {
22088 ufbx_anim_layer *layer = *p_layer;
22089 ufbxi_check(ufbxi_fetch_dst_elements(uc, &layer->anim_values, &layer->element, false, true, NULL, UFBX_ELEMENT_ANIM_VALUE));
22090
22091 ufbxi_check(ufbxi_push_anim(uc, &layer->anim, p_layer, 1));
22092
22093 uint32_t min_id = UINT32_MAX, max_id = 0;
22094
22095 // Combine the animated properties with elements (potentially duplicates!)
22096 size_t num_anim_props = 0;
22097 ufbxi_for_ptr_list(ufbx_anim_value, p_value, layer->anim_values) {
22098 ufbx_anim_value *value = *p_value;
22099 ufbxi_for_list(ufbx_connection, ac, value->element.connections_src) {
22100 if (ac->src_prop.length == 0 && ac->dst_prop.length > 0) {
22101 ufbx_anim_prop *aprop = ufbxi_push(&uc->tmp_stack, ufbx_anim_prop, 1);
22102 uint32_t id = ac->dst->element_id;
22103 min_id = ufbxi_min32(min_id, id);
22104 max_id = ufbxi_max32(max_id, id);
22105 uint32_t id_mask = ufbxi_arraycount(layer->_element_id_bitmask) - 1;
22106 layer->_element_id_bitmask[(id >> 5) & id_mask] |= 1u << (id & 31);
22107 ufbxi_check(aprop);
22108 aprop->anim_value = value;
22109 aprop->element = ac->dst;
22110 aprop->_internal_key = ufbxi_get_name_key(ac->dst_prop.data, ac->dst_prop.length);
22111 aprop->prop_name = ac->dst_prop;
22112 num_anim_props++;
22113 }
22114 }
22115 }
22116
22117 if (min_id != UINT32_MAX) {
22118 layer->_min_element_id = min_id;
22119 layer->_max_element_id = max_id;
22120 }
22121
22122 switch (ufbxi_find_int(&layer->props, ufbxi_BlendMode, 0)) {
22123 case 0: // Additive
22124 layer->blended = true;
22125 layer->additive = true;
22126 break;
22127 case 1: // Override
22128 layer->blended = false;
22129 layer->additive = false;
22130 break;
22131 case 2: // Override Passthrough
22132 layer->blended = true;
22133 layer->additive = false;
22134 break;
22135 default: // Unknown
22136 layer->blended = false;
22137 layer->additive = false;
22138 break;
22139 }
22140
22141 ufbx_prop *weight_prop = ufbxi_find_prop(&layer->props, ufbxi_Weight);
22142 if (weight_prop) {
22143 layer->weight = weight_prop->value_real / (ufbx_real)100.0;
22144 if (layer->weight < 0.0f) layer->weight = 0.0f;
22145 if (layer->weight > 0.99999f) layer->weight = 1.0f;
22146 layer->weight_is_animated = (weight_prop->flags & UFBX_PROP_FLAG_ANIMATED) != 0;
22147 } else {
22148 layer->weight = 1.0f;
22149 layer->weight_is_animated = false;
22150 }
22151 layer->compose_rotation = ufbxi_find_int(&layer->props, ufbxi_RotationAccumulationMode, 0) == 0;
22152 layer->compose_scale = ufbxi_find_int(&layer->props, ufbxi_ScaleAccumulationMode, 0) == 0;
22153
22154 // Add a dummy NULL element animated prop at the end so we can iterate
22155 // animated props without worrying about boundary conditions..
22156 {
22157 ufbx_anim_prop *aprop = ufbxi_push_zero(&uc->tmp_stack, ufbx_anim_prop, 1);
22158 ufbxi_check(aprop);
22159 }
22160
22161 layer->anim_props.data = ufbxi_push_pop(&uc->result, &uc->tmp_stack, ufbx_anim_prop, num_anim_props + 1);
22162 ufbxi_check(layer->anim_props.data);
22163 layer->anim_props.count = num_anim_props;
22164 ufbxi_check(ufbxi_sort_anim_props(uc, layer->anim_props.data, layer->anim_props.count));
22165 }
22166
22167 ufbxi_for_ptr_list(ufbx_anim_value, p_value, uc->scene.anim_values) {
22168 ufbx_anim_value *value = *p_value;
22169
22170 // TODO: Search for things like d|Visibility with a constructed name
22171 value->default_value.x = ufbxi_find_real(&value->props, ufbxi_X, value->default_value.x);
22172 value->default_value.x = ufbxi_find_real(&value->props, ufbxi_d_X, value->default_value.x);
22173 value->default_value.y = ufbxi_find_real(&value->props, ufbxi_Y, value->default_value.y);
22174 value->default_value.y = ufbxi_find_real(&value->props, ufbxi_d_Y, value->default_value.y);
22175 value->default_value.z = ufbxi_find_real(&value->props, ufbxi_Z, value->default_value.z);
22176 value->default_value.z = ufbxi_find_real(&value->props, ufbxi_d_Z, value->default_value.z);
22177
22178 ufbxi_for_list(ufbx_connection, conn, value->element.connections_dst) {
22179 if (conn->src->type == UFBX_ELEMENT_ANIM_CURVE && conn->src_prop.length == 0) {
22180 ufbx_anim_curve *curve = (ufbx_anim_curve*)conn->src;
22181
22182 uint32_t index = 0;
22183 const char *name = conn->dst_prop.data;
22184 if (name == ufbxi_Y || name == ufbxi_d_Y) index = 1;
22185 if (name == ufbxi_Z || name == ufbxi_d_Z) index = 2;
22186
22187 ufbx_prop *prop = ufbx_find_prop_len(&value->props, conn->dst_prop.data, conn->dst_prop.length);
22188 if (prop) {
22189 value->default_value.v[index] = prop->value_real;
22190 }
22191 value->curves[index] = curve;
22192 }
22193 }
22194 }
22195
22196 ufbxi_for_ptr_list(ufbx_anim_curve, p_curve, uc->scene.anim_curves) {
22197 ufbx_anim_curve *curve = *p_curve;
22198 if (curve->keyframes.count > 0) {
22199 curve->min_time = curve->keyframes.data[0].time;
22200 curve->max_time = curve->keyframes.data[curve->keyframes.count - 1].time;
22201 }
22202 }
22203
22204 ufbxi_for_ptr_list(ufbx_shader, p_shader, uc->scene.shaders) {
22205 ufbx_shader *shader = *p_shader;
22206 ufbxi_check(ufbxi_fetch_dst_elements(uc, &shader->bindings, &shader->element, false, false, NULL, UFBX_ELEMENT_SHADER_BINDING));
22207
22208 ufbx_prop *api = ufbx_find_prop(&shader->props, "RenderAPI");
22209 if (api) {
22210 if (!strcmp(api->value_str.data, "ARNOLD_SHADER_ID")) {
22211 shader->type = UFBX_SHADER_ARNOLD_STANDARD_SURFACE;
22212 } else if (!strcmp(api->value_str.data, "OSL")) {
22213 shader->type = UFBX_SHADER_OSL_STANDARD_SURFACE;
22214 } else if (!strcmp(api->value_str.data, "SFX_PBS_SHADER")) {
22215 shader->type = UFBX_SHADER_SHADERFX_GRAPH;
22216 }
22217 }
22218 }
22219
22220 ufbxi_for_ptr_list(ufbx_material, p_material, uc->scene.materials) {
22221 ufbx_material *material = *p_material;
22222 material->shader = (ufbx_shader*)ufbxi_fetch_src_element(&material->element, false, NULL, UFBX_ELEMENT_SHADER);
22223
22224 if (!strcmp(material->shading_model_name.data, "lambert") || !strcmp(material->shading_model_name.data, "Lambert")) {
22225 material->shader_type = UFBX_SHADER_FBX_LAMBERT;
22226 } else if (!strcmp(material->shading_model_name.data, "phong") || !strcmp(material->shading_model_name.data, "Phong")) {
22227 material->shader_type = UFBX_SHADER_FBX_PHONG;
22228 }
22229
22230 if (material->shader) {
22231 material->shader_type = material->shader->type;
22232 } else {
22233 if (uc->opts.use_blender_pbr_material && uc->exporter == UFBX_EXPORTER_BLENDER_BINARY && uc->exporter_version >= ufbx_pack_version(4,12,0)) {
22234 material->shader_type = UFBX_SHADER_BLENDER_PHONG;
22235 }
22236
22237 // TODO: Is this too strict?
22238 if (material->shader_type == UFBX_SHADER_UNKNOWN) {
22239 uint32_t classid_a = (uint32_t)(uint64_t)ufbx_find_int(&material->props, "3dsMax|ClassIDa", 0);
22240 uint32_t classid_b = (uint32_t)(uint64_t)ufbx_find_int(&material->props, "3dsMax|ClassIDb", 0);
22241 if (classid_a == 0x3d6b1cecu && classid_b == 0xdeadc001u) {
22242 material->shader_type = UFBX_SHADER_3DS_MAX_PHYSICAL_MATERIAL;
22243 material->shader_prop_prefix.data = "3dsMax|Parameters|";
22244 material->shader_prop_prefix.length = strlen("3dsMax|Parameters|");
22245 } else if (classid_a == 0xf1551e33u && classid_b == 0x37fb1337u) {
22246 material->shader_type = UFBX_SHADER_OPENPBR_MATERIAL;
22247 material->shader_prop_prefix.data = "3dsMax|Parameters|";
22248 material->shader_prop_prefix.length = strlen("3dsMax|Parameters|");
22249 } else if (classid_a == 0x38420192u && classid_b == 0x45fe4e1bu) {
22250 material->shader_type = UFBX_SHADER_GLTF_MATERIAL;
22251 material->shader_prop_prefix.data = "3dsMax|";
22252 material->shader_prop_prefix.length = strlen("3dsMax|");
22253 } else if (classid_a == 0xd00f1e00u && classid_b == 0xbe77e500u) {
22254 material->shader_type = UFBX_SHADER_3DS_MAX_PBR_METAL_ROUGH;
22255 material->shader_prop_prefix.data = "3dsMax|main|";
22256 material->shader_prop_prefix.length = strlen("3dsMax|main|");
22257 } else if (classid_a == 0xd00f1e00u && classid_b == 0x01dbad33u) {
22258 material->shader_type = UFBX_SHADER_3DS_MAX_PBR_SPEC_GLOSS;
22259 material->shader_prop_prefix.data = "3dsMax|main|";
22260 material->shader_prop_prefix.length = strlen("3dsMax|main|");
22261 }
22262 }
22263 }
22264
22265 ufbxi_check(ufbxi_fetch_textures(uc, &material->textures, &material->element, false));
22266 }
22267
22268 // Ugh.. Patch the textures from meshes for legacy LayerElement-style textures
22269 {
22270 ufbxi_for_ptr_list(ufbx_mesh, p_mesh, uc->scene.meshes) {
22271 ufbx_mesh *mesh = *p_mesh;
22272 size_t num_materials = mesh->materials.count;
22273
22274 ufbxi_mesh_extra *extra = (ufbxi_mesh_extra*)ufbxi_get_element_extra(uc, mesh->element.element_id);
22275 if (!extra) continue;
22276 if (num_materials == 0) continue;
22277
22278 // TODO: This leaks currently to result, probably doesn't matter..
22279 ufbx_texture_list textures;
22280 ufbxi_check(ufbxi_fetch_dst_elements(uc, &textures, &mesh->element, true, false, NULL, UFBX_ELEMENT_TEXTURE));
22281
22282 size_t num_material_textures = 0;
22283 ufbxi_for(ufbxi_tmp_mesh_texture, tex, extra->texture_arr, extra->texture_count) {
22284 if (tex->all_same) {
22285 int32_t texture_id = tex->num_faces > 0 ? (int32_t)tex->face_texture[0] : 0;
22286 if (texture_id >= 0 && (size_t)texture_id < textures.count) {
22287 ufbxi_tmp_material_texture *mat_texs = ufbxi_push(&uc->tmp_stack, ufbxi_tmp_material_texture, num_materials);
22288 ufbxi_check(mat_texs);
22289 num_material_textures += num_materials;
22290 for (size_t i = 0; i < num_materials; i++) {
22291 mat_texs[i].material_id = (int32_t)i;
22292 mat_texs[i].texture_id = texture_id;
22293 mat_texs[i].prop_name = tex->prop_name;
22294 }
22295 }
22296 } else if (mesh->face_material.count) {
22297 size_t num_faces = ufbxi_min_sz(tex->num_faces, mesh->num_faces);
22298 int32_t prev_material = -1;
22299 int32_t prev_texture = -1;
22300 for (size_t i = 0; i < num_faces; i++) {
22301 int32_t texture_id = (int32_t)tex->face_texture[i];
22302 int32_t material_id = (int32_t)mesh->face_material.data[i];
22303 if (texture_id < 0 || (size_t)texture_id >= textures.count) continue;
22304 if (material_id < 0 || (size_t)material_id >= num_materials) continue;
22305 if (material_id == prev_material && texture_id == prev_texture) continue;
22306 prev_material = material_id;
22307 prev_texture = texture_id;
22308
22309 ufbxi_tmp_material_texture *mat_tex = ufbxi_push(&uc->tmp_stack, ufbxi_tmp_material_texture, 1);
22310 ufbxi_check(mat_tex);
22311 mat_tex->material_id = material_id;
22312 mat_tex->texture_id = texture_id;
22313 mat_tex->prop_name = tex->prop_name;
22314 num_material_textures++;
22315 }
22316 }
22317 }
22318
22319 // Push a sentinel material texture to the end so we don't need to
22320 // duplicate the material texture flushing code twice.
22321 {
22322 ufbxi_tmp_material_texture *mat_tex = ufbxi_push(&uc->tmp_stack, ufbxi_tmp_material_texture, 1);
22323 ufbxi_check(mat_tex);
22324 mat_tex->material_id = -1;
22325 mat_tex->texture_id = -1;
22326 mat_tex->prop_name = ufbx_empty_string;
22327 }
22328
22329 ufbxi_tmp_material_texture *mat_texs = ufbxi_push_pop(&uc->tmp, &uc->tmp_stack, ufbxi_tmp_material_texture, num_material_textures + 1);
22330 ufbxi_check(mat_texs);
22331 ufbxi_check(ufbxi_sort_tmp_material_textures(uc, mat_texs, num_material_textures));
22332
22333 int32_t prev_material = -2;
22334 int32_t prev_texture = -2;
22335 const char *prev_prop = NULL;
22336 size_t num_textures_in_material = 0;
22337 for (size_t i = 0; i < num_material_textures + 1; i++) {
22338 ufbxi_tmp_material_texture mat_tex = mat_texs[i];
22339 if (mat_tex.material_id != prev_material) {
22340 if (prev_material >= 0 && num_textures_in_material > 0) {
22341 ufbx_material *mat = mesh->materials.data[prev_material];
22342 if (mat && mat->textures.count == 0) {
22343 ufbx_material_texture *texs = ufbxi_push_pop(&uc->result, &uc->tmp_stack, ufbx_material_texture, num_textures_in_material);
22344 ufbxi_check(texs);
22345 mat->textures.data = texs;
22346 mat->textures.count = num_textures_in_material;
22347 } else {
22348 ufbxi_pop(&uc->tmp_stack, ufbx_material_texture, num_textures_in_material, NULL);
22349 }
22350 }
22351
22352 if (mat_tex.material_id < 0) break;
22353 prev_material = mat_tex.material_id;
22354 prev_texture = -1;
22355 prev_prop = NULL;
22356 num_textures_in_material = 0;
22357 }
22358 if (mat_tex.texture_id == prev_texture && mat_tex.prop_name.data == prev_prop) continue;
22359 prev_texture = mat_tex.texture_id;
22360 prev_prop = mat_tex.prop_name.data;
22361
22362 ufbx_material_texture *tex = ufbxi_push(&uc->tmp_stack, ufbx_material_texture, 1);
22363 ufbxi_check(tex);
22364 ufbx_assert(prev_texture >= 0 && (size_t)prev_texture < textures.count);
22365 tex->texture = textures.data[prev_texture];
22366 tex->shader_prop = tex->material_prop = mat_tex.prop_name;
22367 num_textures_in_material++;
22368 }
22369 }
22370 }
22371
22372 ufbxi_check(ufbxi_resolve_file_content(uc));
22373
22374 ufbxi_for_ptr_list(ufbx_texture, p_texture, uc->scene.textures) {
22375 ufbx_texture *texture = *p_texture;
22376 ufbxi_texture_extra *extra = (ufbxi_texture_extra*)ufbxi_get_element_extra(uc, texture->element.element_id);
22377
22378 ufbx_prop *uv_set = ufbxi_find_prop(&texture->props, ufbxi_UVSet);
22379 if (uv_set) {
22380 texture->uv_set = uv_set->value_str;
22381 } else {
22382 texture->uv_set = ufbx_empty_string;
22383 }
22384
22385 texture->video = (ufbx_video*)ufbxi_fetch_dst_element(&texture->element, false, NULL, UFBX_ELEMENT_VIDEO);
22386 if (texture->video) {
22387 texture->content = texture->video->content;
22388 }
22389
22390 ufbxi_check(ufbxi_finalize_shader_texture(uc, texture));
22391
22392 ufbxi_check(ufbxi_resolve_filenames(uc, (ufbxi_strblob*)&texture->filename, (ufbxi_strblob*)&texture->absolute_filename, (ufbxi_strblob*)&texture->relative_filename, false));
22393 ufbxi_check(ufbxi_resolve_filenames(uc, (ufbxi_strblob*)&texture->raw_filename, (ufbxi_strblob*)&texture->raw_absolute_filename, (ufbxi_strblob*)&texture->raw_relative_filename, true));
22394
22395 // Fetch layered texture layers and patch alphas/blend modes
22396 if (texture->type == UFBX_TEXTURE_LAYERED) {
22397 ufbxi_check(ufbxi_fetch_texture_layers(uc, &texture->layers, &texture->element));
22398 if (extra) {
22399 for (size_t i = 0, num = ufbxi_min_sz(extra->num_alphas, texture->layers.count); i < num; i++) {
22400 texture->layers.data[i].alpha = extra->alphas[i];
22401 }
22402 for (size_t i = 0, num = ufbxi_min_sz(extra->num_blend_modes, texture->layers.count); i < num; i++) {
22403 int32_t mode = extra->blend_modes[i];
22404 if (mode >= 0 && mode < UFBX_BLEND_OVERLAY) {
22405 texture->layers.data[i].blend_mode = (ufbx_blend_mode)mode;
22406 }
22407 }
22408 }
22409 }
22410
22411 ufbxi_check(ufbxi_insert_texture_file(uc, texture));
22412 }
22413
22414 ufbxi_propagate_main_textures(&uc->scene);
22415 ufbxi_check(ufbxi_pop_texture_files(uc));
22416
22417 // Second pass to fetch material maps
22418 ufbxi_for_ptr_list(ufbx_material, p_material, uc->scene.materials) {
22419 ufbx_material *material = *p_material;
22420
22421 ufbxi_check(ufbxi_sort_material_textures(uc, material->textures.data, material->textures.count));
22422 ufbxi_fetch_maps(&uc->scene, material);
22423
22424 // Fetch `ufbx_material_texture.shader_prop` names
22425 if (material->shader) {
22426 ufbxi_for_ptr_list(ufbx_shader_binding, p_binding, material->shader->bindings) {
22427 ufbx_shader_binding *binding = *p_binding;
22428
22429 ufbxi_for_list(ufbx_shader_prop_binding, prop, binding->prop_bindings) {
22430 ufbx_string name = prop->material_prop;
22431
22432 size_t index = SIZE_MAX;
22433 ufbxi_macro_lower_bound_eq(ufbx_material_texture, 4, &index, material->textures.data, 0, material->textures.count,
22434 ( ufbxi_str_less(a->material_prop, name) ), ( a->material_prop.data == name.data ));
22435 for (; index < material->textures.count && material->textures.data[index].shader_prop.data == name.data; index++) {
22436 material->textures.data[index].shader_prop = prop->shader_prop;
22437 }
22438 }
22439 }
22440 }
22441 }
22442
22443 ufbxi_for_ptr_list(ufbx_display_layer, p_layer, uc->scene.display_layers) {
22444 ufbx_display_layer *layer = *p_layer;
22445 ufbxi_check(ufbxi_fetch_dst_elements(uc, &layer->nodes, &layer->element, false, true, NULL, UFBX_ELEMENT_NODE));
22446 }
22447
22448 ufbxi_for_ptr_list(ufbx_selection_set, p_set, uc->scene.selection_sets) {
22449 ufbx_selection_set *set = *p_set;
22450 ufbxi_check(ufbxi_fetch_dst_elements(uc, &set->nodes, &set->element, false, true, NULL, UFBX_ELEMENT_SELECTION_NODE));
22451 }
22452
22453 ufbxi_for_ptr_list(ufbx_selection_node, p_node, uc->scene.selection_nodes) {
22454 ufbx_selection_node *node = *p_node;
22455 node->target_node = (ufbx_node*)ufbxi_fetch_dst_element(&node->element, false, NULL, UFBX_ELEMENT_NODE);
22456 node->target_mesh = (ufbx_mesh*)ufbxi_fetch_dst_element(&node->element, false, NULL, UFBX_ELEMENT_MESH);
22457 if (!node->target_mesh && node->target_node) {
22458 node->target_mesh = node->target_node->mesh;
22459 } else if (!node->target_node && node->target_mesh && node->target_mesh->instances.count > 0) {
22460 node->target_node = node->target_mesh->instances.data[0];
22461 }
22462
22463 ufbx_mesh *mesh = node->target_mesh;
22464 if (mesh) {
22465 ufbxi_check(ufbxi_validate_indices(uc, &node->vertices, mesh->num_vertices));
22466 ufbxi_check(ufbxi_validate_indices(uc, &node->edges, mesh->num_edges));
22467 ufbxi_check(ufbxi_validate_indices(uc, &node->faces, mesh->num_faces));
22468 }
22469 }
22470
22471 ufbxi_for_ptr_list(ufbx_constraint, p_constraint, uc->scene.constraints) {
22472 ufbx_constraint *constraint = *p_constraint;
22473
22474 size_t tmp_base = uc->tmp_stack.num_items;
22475
22476 // Find property connections in _both_ src and dst connections as they are inconsistent
22477 // in pre-7000 files. For example "Constrained Object" is a "PO" connection in 6100.
22478 ufbxi_for_list(ufbx_connection, conn, constraint->element.connections_src) {
22479 if (conn->src_prop.length == 0 || conn->dst->type != UFBX_ELEMENT_NODE) continue;
22480 ufbxi_check(ufbxi_add_constraint_prop(uc, constraint, (ufbx_node*)conn->dst, conn->src_prop.data));
22481 }
22482 ufbxi_for_list(ufbx_connection, conn, constraint->element.connections_dst) {
22483 if (conn->dst_prop.length == 0 || conn->src->type != UFBX_ELEMENT_NODE) continue;
22484 ufbxi_check(ufbxi_add_constraint_prop(uc, constraint, (ufbx_node*)conn->src, conn->dst_prop.data));
22485 }
22486
22487 size_t num_targets = uc->tmp_stack.num_items - tmp_base;
22488 constraint->targets.count = num_targets;
22489 constraint->targets.data = ufbxi_push_pop(&uc->result, &uc->tmp_stack, ufbx_constraint_target, num_targets);
22490 ufbxi_check(constraint->targets.data);
22491 }
22492
22493 ufbxi_for_ptr_list(ufbx_audio_layer, p_layer, uc->scene.audio_layers) {
22494 ufbx_audio_layer *layer = *p_layer;
22495 ufbxi_check(ufbxi_fetch_dst_elements(uc, &layer->clips, &layer->element, false, true, NULL, UFBX_ELEMENT_AUDIO_CLIP));
22496 }
22497
22498 ufbxi_for_ptr_list(ufbx_lod_group, p_lod, uc->scene.lod_groups) {
22499 ufbxi_check(ufbxi_finalize_lod_group(uc, *p_lod));
22500 }
22501
22502 ufbxi_check(ufbxi_fetch_file_textures(uc));
22503
22504 // NOTE: This will be patched over in `ufbxi_update_scene()` if there are `anim_layers`
22505 if (uc->scene.anim_layers.count == 0) {
22506 ufbxi_check(ufbxi_push_anim(uc, &uc->scene.anim, NULL, 0));
22507 }
22508
22509 uc->scene.metadata.ktime_second = uc->ktime_sec;
22510
22511 // Maya seems to use scale of 100/3, Blender binary uses exactly 33, ASCII has always value of 1.0
22512 if (uc->version < 6000) {
22513 uc->scene.metadata.bone_prop_size_unit = 1.0f;
22514 } else if (uc->exporter == UFBX_EXPORTER_BLENDER_BINARY) {
22515 uc->scene.metadata.bone_prop_size_unit = 33.0f;
22516 } else if (uc->exporter == UFBX_EXPORTER_BLENDER_ASCII) {
22517 uc->scene.metadata.bone_prop_size_unit = 1.0f;
22518 } else {
22519 uc->scene.metadata.bone_prop_size_unit = (ufbx_real)(100.0/3.0);
22520 }
22521 if (uc->exporter == UFBX_EXPORTER_BLENDER_ASCII) {
22522 uc->scene.metadata.bone_prop_limb_length_relative = false;
22523 } else {
22524 uc->scene.metadata.bone_prop_limb_length_relative = true;
22525 }
22526
22527 return 1;
22528 }
22529
22530 // -- Interpret the read scene
22531
22532 static ufbxi_forceinline void ufbxi_add_translate(ufbx_transform *t, ufbx_vec3 v)
22533 {
22534 t->translation.x += v.x;
22535 t->translation.y += v.y;
22536 t->translation.z += v.z;
22537 }
22538
22539 static ufbxi_forceinline void ufbxi_sub_translate(ufbx_transform *t, ufbx_vec3 v)
22540 {
22541 t->translation.x -= v.x;
22542 t->translation.y -= v.y;
22543 t->translation.z -= v.z;
22544 }
22545
22546 static ufbxi_forceinline void ufbxi_mul_scale(ufbx_transform *t, ufbx_vec3 v)
22547 {
22548 t->translation.x *= v.x;
22549 t->translation.y *= v.y;
22550 t->translation.z *= v.z;
22551 t->scale.x *= v.x;
22552 t->scale.y *= v.y;
22553 t->scale.z *= v.z;
22554 }
22555
22556 static ufbxi_forceinline void ufbxi_mul_scale_real(ufbx_transform *t, ufbx_real v)
22557 {
22558 t->translation.x *= v;
22559 t->translation.y *= v;
22560 t->translation.z *= v;
22561 t->scale.x *= v;
22562 t->scale.y *= v;
22563 t->scale.z *= v;
22564 }
22565
22566 static ufbxi_noinline ufbx_quat ufbxi_mul_quat(ufbx_quat a, ufbx_quat b)
22567 {
22568 ufbx_quat r;
22569 r.x = a.w*b.x + a.x*b.w + a.y*b.z - a.z*b.y;
22570 r.y = a.w*b.y - a.x*b.z + a.y*b.w + a.z*b.x;
22571 r.z = a.w*b.z + a.x*b.y - a.y*b.x + a.z*b.w;
22572 r.w = a.w*b.w - a.x*b.x - a.y*b.y - a.z*b.z;
22573 return r;
22574 }
22575
22576 static ufbxi_forceinline void ufbxi_add_weighted_vec3(ufbx_vec3 *r, ufbx_vec3 b, ufbx_real w)
22577 {
22578 r->x += b.x * w;
22579 r->y += b.y * w;
22580 r->z += b.z * w;
22581 }
22582
22583 static ufbxi_forceinline void ufbxi_add_weighted_quat(ufbx_quat *r, ufbx_quat b, ufbx_real w)
22584 {
22585 r->x += b.x * w;
22586 r->y += b.y * w;
22587 r->z += b.z * w;
22588 r->w += b.w * w;
22589 }
22590
22591 static ufbxi_noinline void ufbxi_add_weighted_mat(ufbx_matrix *r, const ufbx_matrix *b, ufbx_real w)
22592 {
22593 ufbxi_add_weighted_vec3(&r->cols[0], b->cols[0], w);
22594 ufbxi_add_weighted_vec3(&r->cols[1], b->cols[1], w);
22595 ufbxi_add_weighted_vec3(&r->cols[2], b->cols[2], w);
22596 ufbxi_add_weighted_vec3(&r->cols[3], b->cols[3], w);
22597 }
22598
22599 static void ufbxi_mul_rotate(ufbx_transform *t, ufbx_vec3 v, ufbx_rotation_order order)
22600 {
22601 if (ufbxi_is_vec3_zero(v)) return;
22602
22603 ufbx_quat q = ufbx_euler_to_quat(v, order);
22604 if (t->rotation.w != 1.0) {
22605 t->rotation = ufbxi_mul_quat(q, t->rotation);
22606 } else {
22607 t->rotation = q;
22608 }
22609
22610 if (!ufbxi_is_vec3_zero(t->translation)) {
22611 t->translation = ufbx_quat_rotate_vec3(q, t->translation);
22612 }
22613 }
22614
22615 static void ufbxi_mul_rotate_quat(ufbx_transform *t, ufbx_quat q)
22616 {
22617 if (ufbxi_is_quat_identity(q)) return;
22618
22619 if (t->rotation.w != 1.0) {
22620 t->rotation = ufbxi_mul_quat(q, t->rotation);
22621 } else {
22622 t->rotation = q;
22623 }
22624
22625 if (!ufbxi_is_vec3_zero(t->translation)) {
22626 t->translation = ufbx_quat_rotate_vec3(q, t->translation);
22627 }
22628 }
22629
22630 static void ufbxi_mul_inv_rotate(ufbx_transform *t, ufbx_vec3 v, ufbx_rotation_order order)
22631 {
22632 if (ufbxi_is_vec3_zero(v)) return;
22633
22634 ufbx_quat q = ufbx_euler_to_quat(v, order);
22635 q.x = -q.x; q.y = -q.y; q.z = -q.z;
22636 if (t->rotation.w != 1.0) {
22637 t->rotation = ufbxi_mul_quat(q, t->rotation);
22638 } else {
22639 t->rotation = q;
22640 }
22641
22642 if (!ufbxi_is_vec3_zero(t->translation)) {
22643 t->translation = ufbx_quat_rotate_vec3(q, t->translation);
22644 }
22645 }
22646
22647 // -- Updating state from properties
22648
22649 ufbxi_forceinline static void ufbxi_mirror_translation(ufbx_vec3 *p_vec, ufbx_mirror_axis axis)
22650 {
22651 ufbxi_dev_assert(axis);
22652 p_vec->v[axis - 1] = -p_vec->v[axis - 1];
22653 }
22654
22655 ufbxi_forceinline static void ufbxi_mirror_rotation(ufbx_quat *p_quat, ufbx_mirror_axis axis)
22656 {
22657 ufbxi_dev_assert(axis);
22658 p_quat->v[axis % 3] = -p_quat->v[axis % 3];
22659 p_quat->v[(axis + 1) % 3] = -p_quat->v[(axis + 1) % 3];
22660 }
22661
22662 ufbxi_noinline static ufbx_transform ufbxi_get_geometry_transform(const ufbx_props *props, ufbx_node *node)
22663 {
22664 ufbx_vec3 translation = ufbxi_find_vec3(props, ufbxi_GeometricTranslation, 0.0f, 0.0f, 0.0f);
22665 ufbx_vec3 rotation = ufbxi_find_vec3(props, ufbxi_GeometricRotation, 0.0f, 0.0f, 0.0f);
22666 ufbx_vec3 scaling = ufbxi_find_vec3(props, ufbxi_GeometricScaling, 1.0f, 1.0f, 1.0f);
22667
22668 ufbx_transform t = { { 0,0,0 }, { 0,0,0,1 }, { 1,1,1 }};
22669
22670 // WorldTransform = ParentWorldTransform * T * R * S * (OT * OR * OS)
22671
22672 ufbxi_mul_scale(&t, scaling);
22673 ufbxi_mul_rotate(&t, rotation, UFBX_ROTATION_ORDER_XYZ);
22674 ufbxi_add_translate(&t, translation);
22675
22676 if (node->has_adjust_transform) {
22677 t.translation.x *= node->adjust_translation_scale;
22678 t.translation.y *= node->adjust_translation_scale;
22679 t.translation.z *= node->adjust_translation_scale;
22680 }
22681
22682 if (node->adjust_mirror_axis) {
22683 ufbxi_mirror_translation(&t.translation, node->adjust_mirror_axis);
22684 ufbxi_mirror_rotation(&t.rotation, node->adjust_mirror_axis);
22685 }
22686
22687 return t;
22688 }
22689
22690 ufbxi_noinline static ufbx_transform ufbxi_get_transform(const ufbx_props *props, ufbx_rotation_order order, const ufbx_node *node, const ufbx_vec3 *translation_scale)
22691 {
22692 ufbx_vec3 scale_pivot = ufbxi_find_vec3(props, ufbxi_ScalingPivot, 0.0f, 0.0f, 0.0f);
22693 ufbx_vec3 rot_pivot = ufbxi_find_vec3(props, ufbxi_RotationPivot, 0.0f, 0.0f, 0.0f);
22694 ufbx_vec3 scale_offset = ufbxi_find_vec3(props, ufbxi_ScalingOffset, 0.0f, 0.0f, 0.0f);
22695 ufbx_vec3 rot_offset = ufbxi_find_vec3(props, ufbxi_RotationOffset, 0.0f, 0.0f, 0.0f);
22696
22697 ufbx_vec3 translation = ufbxi_find_vec3(props, ufbxi_Lcl_Translation, 0.0f, 0.0f, 0.0f);
22698 ufbx_vec3 rotation = ufbxi_find_vec3(props, ufbxi_Lcl_Rotation, 0.0f, 0.0f, 0.0f);
22699 ufbx_vec3 scaling = ufbxi_find_vec3(props, ufbxi_Lcl_Scaling, 1.0f, 1.0f, 1.0f);
22700
22701 ufbx_vec3 pre_rotation = ufbxi_find_vec3(props, ufbxi_PreRotation, 0.0f, 0.0f, 0.0f);
22702 ufbx_vec3 post_rotation = ufbxi_find_vec3(props, ufbxi_PostRotation, 0.0f, 0.0f, 0.0f);
22703
22704 ufbx_transform t = { { 0,0,0 }, { 0,0,0,1 }, { 1,1,1 }};
22705
22706 // WorldTransform = ParentWorldTransform * T * Roff * Rp * Rpre * R * Rpost * Rp-1 * Soff * Sp * S * Sp-1
22707 // NOTE: Rpost is inverted (!) after converting from PostRotation Euler angles
22708
22709 if (translation_scale) {
22710 translation.x *= translation_scale->x;
22711 translation.y *= translation_scale->y;
22712 translation.z *= translation_scale->z;
22713 }
22714
22715 if (node->has_adjust_transform) {
22716 ufbxi_mul_rotate_quat(&t, node->adjust_post_rotation);
22717 ufbxi_mul_scale_real(&t, node->adjust_post_scale);
22718 }
22719
22720 ufbxi_sub_translate(&t, scale_pivot);
22721 ufbxi_mul_scale(&t, scaling);
22722 ufbxi_add_translate(&t, scale_pivot);
22723
22724 ufbxi_add_translate(&t, scale_offset);
22725
22726 ufbxi_sub_translate(&t, rot_pivot);
22727 ufbxi_mul_inv_rotate(&t, post_rotation, UFBX_ROTATION_ORDER_XYZ);
22728 ufbxi_mul_rotate(&t, rotation, order);
22729 ufbxi_mul_rotate(&t, pre_rotation, UFBX_ROTATION_ORDER_XYZ);
22730 ufbxi_add_translate(&t, rot_pivot);
22731
22732 ufbxi_add_translate(&t, rot_offset);
22733
22734 ufbxi_add_translate(&t, translation);
22735
22736 if (node->has_adjust_transform) {
22737 ufbxi_add_translate(&t, node->adjust_pre_translation);
22738 ufbxi_mul_rotate_quat(&t, node->adjust_pre_rotation);
22739 ufbxi_mul_scale_real(&t, node->adjust_pre_scale);
22740 t.translation.x *= node->adjust_translation_scale;
22741 t.translation.y *= node->adjust_translation_scale;
22742 t.translation.z *= node->adjust_translation_scale;
22743 }
22744
22745 if (node->adjust_mirror_axis) {
22746 ufbxi_mirror_translation(&t.translation, node->adjust_mirror_axis);
22747 ufbxi_mirror_rotation(&t.rotation, node->adjust_mirror_axis);
22748 }
22749
22750 return t;
22751 }
22752
22753 ufbxi_noinline static ufbx_quat ufbxi_get_rotation(const ufbx_props *props, ufbx_rotation_order order, const ufbx_node *node)
22754 {
22755 ufbx_vec3 rotation = ufbxi_find_vec3(props, ufbxi_Lcl_Rotation, 0.0f, 0.0f, 0.0f);
22756 ufbx_vec3 pre_rotation = ufbxi_find_vec3(props, ufbxi_PreRotation, 0.0f, 0.0f, 0.0f);
22757 ufbx_vec3 post_rotation = ufbxi_find_vec3(props, ufbxi_PostRotation, 0.0f, 0.0f, 0.0f);
22758
22759 ufbx_transform t = { { 0,0,0 }, { 0,0,0,1 }, { 1,1,1 }};
22760
22761 if (node->has_adjust_transform) {
22762 ufbxi_mul_rotate_quat(&t, node->adjust_post_rotation);
22763 }
22764
22765 ufbxi_mul_inv_rotate(&t, post_rotation, UFBX_ROTATION_ORDER_XYZ);
22766 ufbxi_mul_rotate(&t, rotation, order);
22767 ufbxi_mul_rotate(&t, pre_rotation, UFBX_ROTATION_ORDER_XYZ);
22768
22769 if (node->has_adjust_transform) {
22770 ufbxi_mul_rotate_quat(&t, node->adjust_pre_rotation);
22771 }
22772
22773 if (node->adjust_mirror_axis) {
22774 ufbxi_mirror_rotation(&t.rotation, node->adjust_mirror_axis);
22775 }
22776
22777 return t.rotation;
22778 }
22779
22780 ufbxi_noinline static ufbx_vec3 ufbxi_get_scale(const ufbx_props *props, const ufbx_node *node)
22781 {
22782 ufbx_vec3 scaling = ufbxi_find_vec3(props, ufbxi_Lcl_Scaling, 1.0f, 1.0f, 1.0f);
22783
22784 ufbx_transform t = { { 0,0,0 }, { 0,0,0,1 }, { 1,1,1 }};
22785
22786 if (node->has_adjust_transform) {
22787 ufbxi_mul_scale_real(&t, node->adjust_post_scale);
22788 }
22789
22790 ufbxi_mul_scale(&t, scaling);
22791
22792 if (node->has_adjust_transform) {
22793 ufbxi_mul_scale_real(&t, node->adjust_pre_scale);
22794 }
22795
22796 return t.scale;
22797 }
22798
22799 ufbxi_noinline static ufbx_transform ufbxi_get_texture_transform(const ufbx_props *props)
22800 {
22801 ufbx_vec3 scale_pivot = ufbxi_find_vec3(props, ufbxi_TextureScalingPivot, 0.0f, 0.0f, 0.0f);
22802 ufbx_vec3 rot_pivot = ufbxi_find_vec3(props, ufbxi_TextureRotationPivot, 0.0f, 0.0f, 0.0f);
22803
22804 ufbx_vec3 translation = ufbxi_find_vec3(props, ufbxi_Translation, 0.0f, 0.0f, 0.0f);
22805 ufbx_vec3 rotation = ufbxi_find_vec3(props, ufbxi_Rotation, 0.0f, 0.0f, 0.0f);
22806 ufbx_vec3 scaling = ufbxi_find_vec3(props, ufbxi_Scaling, 1.0f, 1.0f, 1.0f);
22807
22808 ufbx_transform t = { { 0,0,0 }, { 0,0,0,1 }, { 1,1,1 }};
22809
22810 ufbxi_sub_translate(&t, scale_pivot);
22811 ufbxi_mul_scale(&t, scaling);
22812 ufbxi_add_translate(&t, scale_pivot);
22813
22814 ufbxi_sub_translate(&t, rot_pivot);
22815 ufbxi_mul_rotate(&t, rotation, UFBX_ROTATION_ORDER_XYZ);
22816 ufbxi_add_translate(&t, rot_pivot);
22817
22818 ufbxi_add_translate(&t, translation);
22819
22820 if (ufbxi_find_int(props, ufbxi_UVSwap, 0) != 0) {
22821 const ufbx_vec3 swap_scale = { -1.0f, 0.0f, 0.0f };
22822 const ufbx_vec3 swap_rotate = { 0.0f, 0.0f, -90.0f };
22823 ufbxi_mul_scale(&t, swap_scale);
22824 ufbxi_mul_rotate(&t, swap_rotate, UFBX_ROTATION_ORDER_XYZ);
22825 }
22826
22827 return t;
22828 }
22829
22830 ufbxi_noinline static ufbx_transform ufbxi_get_constraint_transform(const ufbx_props *props)
22831 {
22832 ufbx_vec3 translation = ufbxi_find_vec3(props, ufbxi_Translation, 0.0f, 0.0f, 0.0f);
22833 ufbx_vec3 rotation = ufbxi_find_vec3(props, ufbxi_Rotation, 0.0f, 0.0f, 0.0f);
22834 ufbx_vec3 rotation_offset = ufbxi_find_vec3(props, ufbxi_RotationOffset, 0.0f, 0.0f, 0.0f);
22835 ufbx_vec3 scaling = ufbxi_find_vec3(props, ufbxi_Scaling, 1.0f, 1.0f, 1.0f);
22836
22837 ufbx_transform t = { { 0,0,0 }, { 0,0,0,1 }, { 1,1,1 }};
22838
22839 ufbxi_mul_scale(&t, scaling);
22840 ufbxi_mul_rotate(&t, rotation, UFBX_ROTATION_ORDER_XYZ);
22841 ufbxi_mul_rotate(&t, rotation_offset, UFBX_ROTATION_ORDER_XYZ);
22842 ufbxi_add_translate(&t, translation);
22843
22844 return t;
22845 }
22846
22847 ufbxi_noinline static void ufbxi_update_node(ufbx_node *node, const ufbx_transform_override *overrides, size_t num_overrides)
22848 {
22849 node->rotation_order = (ufbx_rotation_order)ufbxi_find_enum(&node->props, ufbxi_RotationOrder, UFBX_ROTATION_ORDER_XYZ, UFBX_ROTATION_ORDER_SPHERIC);
22850 node->euler_rotation = ufbxi_find_vec3(&node->props, ufbxi_Lcl_Rotation, 0.0f, 0.0f, 0.0f);
22851
22852 if (!node->is_root) {
22853 const ufbx_vec3 *transform_scale = NULL;
22854 if (node->parent && node->parent->scale_helper) {
22855 transform_scale = &node->parent->scale_helper->local_transform.scale;
22856 }
22857 node->local_transform = ufbxi_get_transform(&node->props, node->rotation_order, node, transform_scale);
22858 if (node->is_scale_helper && node->parent && node->parent->inherit_scale_node) {
22859 ufbx_node *scale_parent = node->parent->inherit_scale_node;
22860 if (scale_parent->scale_helper) {
22861 ufbx_vec3 inherit_scale = scale_parent->scale_helper->local_transform.scale;
22862 node->local_transform.scale.x *= inherit_scale.x;
22863 node->local_transform.scale.y *= inherit_scale.y;
22864 node->local_transform.scale.z *= inherit_scale.z;
22865 }
22866 }
22867
22868 if (num_overrides > 0) {
22869 uint32_t typed_id = node->typed_id;
22870 size_t override_ix = SIZE_MAX;
22871 ufbxi_macro_lower_bound_eq(ufbx_transform_override, 16, &override_ix, overrides, 0, num_overrides,
22872 ( a->node_id < typed_id ), ( a->node_id == typed_id ));
22873 if (override_ix != SIZE_MAX) {
22874 node->local_transform = overrides[override_ix].transform;
22875 }
22876 }
22877 node->node_to_parent = ufbx_transform_to_matrix(&node->local_transform);
22878 node->geometry_transform = ufbxi_get_geometry_transform(&node->props, node);
22879 } else {
22880 node->geometry_transform = ufbx_identity_transform;
22881 }
22882
22883 ufbx_matrix unscaled_node_to_parent = ufbxi_unscaled_transform_to_matrix(&node->local_transform);
22884
22885 node->inherit_scale = node->local_transform.scale;
22886
22887 ufbx_node *parent = node->parent;
22888 if (parent) {
22889 if (node->inherit_mode == UFBX_INHERIT_MODE_NORMAL) {
22890 node->node_to_world = ufbx_matrix_mul(&parent->node_to_world, &node->node_to_parent);
22891 node->unscaled_node_to_world = ufbx_matrix_mul(&parent->node_to_world, &unscaled_node_to_parent);
22892 } else {
22893 ufbx_transform transform = node->local_transform;
22894
22895 ufbx_vec3 parent_scale = ufbxi_one_vec3;
22896 if (node->inherit_scale_node) {
22897 parent_scale = node->inherit_scale_node->inherit_scale;
22898 }
22899
22900 transform.scale.x *= parent_scale.x;
22901 transform.scale.y *= parent_scale.y;
22902 transform.scale.z *= parent_scale.z;
22903 transform.translation.x *= parent->inherit_scale.x;
22904 transform.translation.y *= parent->inherit_scale.y;
22905 transform.translation.z *= parent->inherit_scale.z;
22906
22907 ufbx_matrix node_to_unscaled_parent = ufbx_transform_to_matrix(&transform);
22908 ufbx_matrix unscaled_node_to_unscaled_parent = ufbxi_unscaled_transform_to_matrix(&transform);
22909
22910 node->inherit_scale = transform.scale;
22911 node->node_to_world = ufbx_matrix_mul(&parent->unscaled_node_to_world, &node_to_unscaled_parent);
22912 node->unscaled_node_to_world = ufbx_matrix_mul(&parent->unscaled_node_to_world, &unscaled_node_to_unscaled_parent);
22913 }
22914 } else {
22915 node->node_to_world = node->node_to_parent;
22916 node->unscaled_node_to_world = unscaled_node_to_parent;
22917 }
22918
22919 if (!ufbxi_is_transform_identity(&node->geometry_transform)) {
22920 node->geometry_to_node = ufbx_transform_to_matrix(&node->geometry_transform);
22921 node->geometry_to_world = ufbx_matrix_mul(&node->node_to_world, &node->geometry_to_node);
22922 node->has_geometry_transform = true;
22923 } else {
22924 node->geometry_to_node = ufbx_identity_matrix;
22925 node->geometry_to_world = node->node_to_world;
22926 node->has_geometry_transform = false;
22927 }
22928
22929 node->visible = ufbxi_find_int(&node->props, ufbxi_Visibility, 1) != 0;
22930 }
22931
22932 ufbxi_noinline static void ufbxi_update_light(ufbx_light *light)
22933 {
22934 // NOTE: FBX seems to store intensities 100x of what's specified in at least
22935 // Maya and Blender, should there be a quirks mode to not do this for specific
22936 // exporters. Does the FBX SDK do this transparently as well?
22937 light->intensity = ufbxi_find_real(&light->props, ufbxi_Intensity, (ufbx_real)100.0) / (ufbx_real)100.0;
22938
22939 light->color = ufbxi_find_vec3(&light->props, ufbxi_Color, 1.0f, 1.0f, 1.0f);
22940 light->type = (ufbx_light_type)ufbxi_find_enum(&light->props, ufbxi_LightType, 0, UFBX_LIGHT_VOLUME);
22941 light->decay = (ufbx_light_decay)ufbxi_find_enum(&light->props, ufbxi_DecayType, UFBX_LIGHT_DECAY_NONE, UFBX_LIGHT_DECAY_CUBIC);
22942 light->area_shape = (ufbx_light_area_shape)ufbxi_find_enum(&light->props, ufbxi_AreaLightShape, 0, UFBX_LIGHT_AREA_SHAPE_SPHERE);
22943 light->inner_angle = ufbxi_find_real(&light->props, ufbxi_HotSpot, 0.0f);
22944 light->inner_angle = ufbxi_find_real(&light->props, ufbxi_InnerAngle, light->inner_angle);
22945 light->outer_angle = ufbxi_find_real(&light->props, ufbxi_Cone_angle, 0.0f);
22946 light->outer_angle = ufbxi_find_real(&light->props, ufbxi_ConeAngle, light->outer_angle);
22947 light->outer_angle = ufbxi_find_real(&light->props, ufbxi_OuterAngle, light->outer_angle);
22948 light->cast_light = ufbxi_find_int(&light->props, ufbxi_CastLight, 1) != 0;
22949 light->cast_shadows = ufbxi_find_int(&light->props, ufbxi_CastShadows, 0) != 0;
22950 }
22951
22952 typedef struct {
22953 // 1/1000 decimal fixed point for size
22954 uint16_t film_size_x, film_size_y;
22955 } ufbxi_aperture_format;
22956
22957 static const ufbxi_aperture_format ufbxi_aperture_formats[] = {
22958 { 1000, 1000, }, // UFBX_APERTURE_FORMAT_CUSTOM
22959 { 404, 295, }, // UFBX_APERTURE_FORMAT_16MM_THEATRICAL
22960 { 493, 292, }, // UFBX_APERTURE_FORMAT_SUPER_16MM
22961 { 864, 630, }, // UFBX_APERTURE_FORMAT_35MM_ACADEMY
22962 { 816, 612, }, // UFBX_APERTURE_FORMAT_35MM_TV_PROJECTION
22963 { 980, 735, }, // UFBX_APERTURE_FORMAT_35MM_FULL_APERTURE
22964 { 825, 446, }, // UFBX_APERTURE_FORMAT_35MM_185_PROJECTION
22965 { 864, 732, }, // UFBX_APERTURE_FORMAT_35MM_ANAMORPHIC
22966 { 2066, 906, }, // UFBX_APERTURE_FORMAT_70MM_PROJECTION
22967 { 1485, 991, }, // UFBX_APERTURE_FORMAT_VISTAVISION
22968 { 2080, 1480, }, // UFBX_APERTURE_FORMAT_DYNAVISION
22969 { 2772, 2072, }, // UFBX_APERTURE_FORMAT_IMAX
22970 };
22971
22972 ufbxi_noinline static void ufbxi_update_camera(ufbx_scene *scene, ufbx_camera *camera)
22973 {
22974 camera->projection_mode = (ufbx_projection_mode)ufbxi_find_enum(&camera->props, ufbxi_CameraProjectionType, 0, UFBX_PROJECTION_MODE_ORTHOGRAPHIC);
22975 camera->aspect_mode = (ufbx_aspect_mode)ufbxi_find_enum(&camera->props, ufbxi_AspectRatioMode, 0, UFBX_ASPECT_MODE_FIXED_HEIGHT);
22976 camera->aperture_mode = (ufbx_aperture_mode)ufbxi_find_enum(&camera->props, ufbxi_ApertureMode, UFBX_APERTURE_MODE_VERTICAL, UFBX_APERTURE_MODE_FOCAL_LENGTH);
22977 camera->aperture_format = (ufbx_aperture_format)ufbxi_find_enum(&camera->props, ufbxi_ApertureFormat, UFBX_APERTURE_FORMAT_CUSTOM, UFBX_APERTURE_FORMAT_IMAX);
22978 camera->gate_fit = (ufbx_gate_fit)ufbxi_find_enum(&camera->props, ufbxi_GateFit, 0, UFBX_GATE_FIT_STRETCH);
22979
22980 camera->near_plane = ufbxi_find_real(&camera->props, ufbxi_NearPlane, 0.0f);
22981 camera->far_plane = ufbxi_find_real(&camera->props, ufbxi_FarPlane, 0.0f);
22982
22983 // Search both W/H and Width/Height but prefer the latter
22984 ufbx_real aspect_x = ufbxi_find_real(&camera->props, ufbxi_AspectW, 0.0f);
22985 ufbx_real aspect_y = ufbxi_find_real(&camera->props, ufbxi_AspectH, 0.0f);
22986 aspect_x = ufbxi_find_real(&camera->props, ufbxi_AspectWidth, aspect_x);
22987 aspect_y = ufbxi_find_real(&camera->props, ufbxi_AspectHeight, aspect_y);
22988
22989 ufbx_real fov = ufbxi_find_real(&camera->props, ufbxi_FieldOfView, 0.0f);
22990 ufbx_real fov_x = ufbxi_find_real(&camera->props, ufbxi_FieldOfViewX, 0.0f);
22991 ufbx_real fov_y = ufbxi_find_real(&camera->props, ufbxi_FieldOfViewY, 0.0f);
22992
22993 ufbx_real focal_length = ufbxi_find_real(&camera->props, ufbxi_FocalLength, 0.0f);
22994 ufbx_real ortho_extent = scene->metadata.ortho_size_unit * ufbxi_find_real(&camera->props, ufbxi_OrthoZoom, 1.0f);
22995
22996 ufbxi_aperture_format format = ufbxi_aperture_formats[camera->aperture_format];
22997 ufbx_vec2 film_size = { (ufbx_real)format.film_size_x * (ufbx_real)0.001, (ufbx_real)format.film_size_y * (ufbx_real)0.001 };
22998 ufbx_real squeeze_ratio = camera->aperture_format == UFBX_APERTURE_FORMAT_35MM_ANAMORPHIC ? 2.0f : 1.0f;
22999
23000 film_size.x = ufbxi_find_real(&camera->props, ufbxi_FilmWidth, film_size.x);
23001 film_size.y = ufbxi_find_real(&camera->props, ufbxi_FilmHeight, film_size.y);
23002 squeeze_ratio = ufbxi_find_real(&camera->props, ufbxi_FilmSqueezeRatio, squeeze_ratio);
23003
23004 if (aspect_x <= 0.0f && aspect_y <= 0.0f) {
23005 aspect_x = film_size.x > 0.0f ? film_size.x : 1.0f;
23006 aspect_y = film_size.y > 0.0f ? film_size.y : 1.0f;
23007 } else if (aspect_x <= 0.0f) {
23008 if (film_size.x > 0.0f && film_size.y > 0.0f) {
23009 aspect_x = aspect_y / film_size.y * film_size.x;
23010 } else {
23011 aspect_x = aspect_y;
23012 }
23013 } else if (aspect_y <= 0.0f) {
23014 if (film_size.x > 0.0f && film_size.y > 0.0f) {
23015 aspect_y = aspect_x / film_size.x * film_size.y;
23016 } else {
23017 aspect_y = aspect_x;
23018 }
23019 }
23020
23021 film_size.y *= squeeze_ratio;
23022
23023 // TODO: Should this be done always?
23024 ortho_extent *= scene->metadata.geometry_scale;
23025 camera->near_plane *= scene->metadata.geometry_scale;
23026 camera->far_plane *= scene->metadata.geometry_scale;
23027
23028 camera->focal_length_mm = focal_length;
23029 camera->film_size_inch = film_size;
23030 camera->squeeze_ratio = squeeze_ratio;
23031 camera->orthographic_extent = ortho_extent;
23032
23033 switch (camera->aspect_mode) {
23034 case UFBX_ASPECT_MODE_WINDOW_SIZE:
23035 case UFBX_ASPECT_MODE_FIXED_RATIO:
23036 camera->resolution_is_pixels = false;
23037 camera->resolution.x = aspect_x;
23038 camera->resolution.y = aspect_y;
23039 break;
23040 case UFBX_ASPECT_MODE_FIXED_RESOLUTION:
23041 camera->resolution_is_pixels = true;
23042 camera->resolution.x = aspect_x;
23043 camera->resolution.y = aspect_y;
23044 break;
23045 case UFBX_ASPECT_MODE_FIXED_WIDTH:
23046 camera->resolution_is_pixels = true;
23047 camera->resolution.x = aspect_x;
23048 camera->resolution.y = aspect_x * aspect_y;
23049 break;
23050 case UFBX_ASPECT_MODE_FIXED_HEIGHT:
23051 camera->resolution_is_pixels = true;
23052 camera->resolution.x = aspect_y * aspect_x;
23053 camera->resolution.y = aspect_y;
23054 break;
23055 default:
23056 ufbxi_unreachable("Unexpected aspect mode");
23057 }
23058
23059 ufbx_real aspect_ratio = camera->resolution.x / camera->resolution.y;
23060 ufbx_real film_ratio = film_size.x / film_size.y;
23061
23062 camera->aspect_ratio = aspect_ratio;
23063
23064 ufbx_gate_fit effective_fit = camera->gate_fit;
23065 if (effective_fit == UFBX_GATE_FIT_FILL) {
23066 effective_fit = aspect_ratio > film_ratio ? UFBX_GATE_FIT_HORIZONTAL : UFBX_GATE_FIT_VERTICAL;
23067 } else if (effective_fit == UFBX_GATE_FIT_OVERSCAN) {
23068 effective_fit = aspect_ratio < film_ratio ? UFBX_GATE_FIT_HORIZONTAL : UFBX_GATE_FIT_VERTICAL;
23069 }
23070
23071 switch (effective_fit) {
23072 case UFBX_GATE_FIT_NONE:
23073 camera->aperture_size_inch = camera->film_size_inch;
23074 camera->orthographic_size.x = ortho_extent;
23075 camera->orthographic_size.y = ortho_extent;
23076 break;
23077 case UFBX_GATE_FIT_VERTICAL:
23078 camera->aperture_size_inch.x = camera->film_size_inch.y * aspect_ratio;
23079 camera->aperture_size_inch.y = camera->film_size_inch.y;
23080 camera->orthographic_size.x = ortho_extent * aspect_ratio;
23081 camera->orthographic_size.y = ortho_extent;
23082 break;
23083 case UFBX_GATE_FIT_HORIZONTAL:
23084 camera->aperture_size_inch.x = camera->film_size_inch.x;
23085 camera->aperture_size_inch.y = camera->film_size_inch.x / aspect_ratio;
23086 camera->orthographic_size.x = ortho_extent;
23087 camera->orthographic_size.y = ortho_extent / aspect_ratio;
23088 break;
23089 case UFBX_GATE_FIT_FILL:
23090 case UFBX_GATE_FIT_OVERSCAN:
23091 camera->aperture_size_inch = camera->film_size_inch;
23092 camera->orthographic_size.x = ortho_extent;
23093 camera->orthographic_size.y = ortho_extent;
23094 ufbxi_unreachable("Unreachable, set to vertical/horizontal above");
23095 break;
23096 case UFBX_GATE_FIT_STRETCH:
23097 camera->aperture_size_inch = camera->film_size_inch;
23098 camera->orthographic_size.x = ortho_extent;
23099 camera->orthographic_size.y = ortho_extent;
23100 // TODO: Not sure what to do here...
23101 break;
23102 default:
23103 ufbxi_unreachable("Unexpected gate fit");
23104 }
23105
23106 switch (camera->aperture_mode) {
23107 case UFBX_APERTURE_MODE_HORIZONTAL_AND_VERTICAL:
23108 camera->field_of_view_deg.x = fov_x;
23109 camera->field_of_view_deg.y = fov_y;
23110 camera->field_of_view_tan.x = (ufbx_real)ufbx_tan((double)(fov_x * (UFBXI_DEG_TO_RAD * 0.5f)));
23111 camera->field_of_view_tan.y = (ufbx_real)ufbx_tan((double)(fov_y * (UFBXI_DEG_TO_RAD * 0.5f)));
23112 break;
23113 case UFBX_APERTURE_MODE_HORIZONTAL:
23114 camera->field_of_view_deg.x = fov;
23115 camera->field_of_view_tan.x = (ufbx_real)ufbx_tan((double)(fov * (UFBXI_DEG_TO_RAD * 0.5f)));
23116 camera->field_of_view_tan.y = camera->field_of_view_tan.x / aspect_ratio;
23117 camera->field_of_view_deg.y = (ufbx_real)ufbx_atan((double)camera->field_of_view_tan.y) * UFBXI_RAD_TO_DEG * 2.0f;
23118 break;
23119 case UFBX_APERTURE_MODE_VERTICAL:
23120 camera->field_of_view_deg.y = fov;
23121 camera->field_of_view_tan.y = (ufbx_real)ufbx_tan((double)(fov * (UFBXI_DEG_TO_RAD * 0.5f)));
23122 camera->field_of_view_tan.x = camera->field_of_view_tan.y * aspect_ratio;
23123 camera->field_of_view_deg.x = (ufbx_real)ufbx_atan((double)camera->field_of_view_tan.x) * UFBXI_RAD_TO_DEG * 2.0f;
23124 break;
23125 case UFBX_APERTURE_MODE_FOCAL_LENGTH:
23126 camera->field_of_view_tan.x = camera->aperture_size_inch.x / (camera->focal_length_mm * UFBXI_MM_TO_INCH) * 0.5f;
23127 camera->field_of_view_tan.y = camera->aperture_size_inch.y / (camera->focal_length_mm * UFBXI_MM_TO_INCH) * 0.5f;
23128 camera->field_of_view_deg.x = (ufbx_real)ufbx_atan((double)camera->field_of_view_tan.x) * UFBXI_RAD_TO_DEG * 2.0f;
23129 camera->field_of_view_deg.y = (ufbx_real)ufbx_atan((double)camera->field_of_view_tan.y) * UFBXI_RAD_TO_DEG * 2.0f;
23130 break;
23131 default:
23132 ufbxi_unreachable("Unexpected aperture mode");
23133 }
23134
23135 if (camera->projection_mode == UFBX_PROJECTION_MODE_PERSPECTIVE) {
23136 camera->projection_plane = camera->field_of_view_tan;
23137 } else {
23138 camera->projection_plane = camera->orthographic_size;
23139 }
23140 }
23141
23142 ufbxi_noinline static void ufbxi_update_bone(ufbx_scene *scene, ufbx_bone *bone)
23143 {
23144 ufbx_real unit = scene->metadata.bone_prop_size_unit;
23145
23146 bone->radius = ufbxi_find_real(&bone->props, ufbxi_Size, unit) / unit;
23147 if (scene->metadata.bone_prop_limb_length_relative) {
23148 bone->relative_length = ufbxi_find_real(&bone->props, ufbxi_LimbLength, 1.0f);
23149 } else {
23150 bone->relative_length = 1.0f;
23151 }
23152 }
23153
23154 ufbxi_noinline static void ufbxi_update_line_curve(ufbx_line_curve *line)
23155 {
23156 line->color = ufbxi_find_vec3(&line->props, ufbxi_Color, 1.0f, 1.0f, 1.0f);
23157 }
23158
23159 ufbxi_noinline static void ufbxi_update_pose(ufbx_pose *pose)
23160 {
23161 ufbxi_for_list(ufbx_bone_pose, bone, pose->bone_poses) {
23162 ufbx_node *node = bone->bone_node;
23163
23164 const ufbx_matrix *parent_to_world = &ufbx_identity_matrix;
23165 ufbx_bone_pose *bone_pose = ufbx_get_bone_pose(pose, node->parent);
23166 if (bone_pose) {
23167 parent_to_world = &bone_pose->bone_to_world;
23168 } else if (node->parent) {
23169 parent_to_world = &node->parent->node_to_world;
23170 }
23171
23172 ufbx_matrix world_to_parent = ufbx_matrix_invert(parent_to_world);
23173 bone->bone_to_parent = ufbx_matrix_mul(&world_to_parent, &bone->bone_to_world);
23174 }
23175 }
23176
23177 ufbxi_noinline static void ufbxi_update_skin_cluster(ufbx_skin_cluster *cluster)
23178 {
23179 if (cluster->bone_node) {
23180 cluster->geometry_to_world = ufbx_matrix_mul(&cluster->bone_node->node_to_world, &cluster->geometry_to_bone);
23181 } else {
23182 cluster->geometry_to_world = ufbx_matrix_mul(&cluster->bind_to_world, &cluster->geometry_to_bone);
23183 }
23184 cluster->geometry_to_world_transform = ufbx_matrix_to_transform(&cluster->geometry_to_world);
23185 }
23186
23187 ufbxi_noinline static void ufbxi_update_blend_channel(ufbx_blend_channel *channel)
23188 {
23189 ufbx_real weight = ufbxi_find_real(&channel->props, ufbxi_DeformPercent, 0.0f) * (ufbx_real)0.01;
23190 channel->weight = weight;
23191
23192 ptrdiff_t num_keys = (ptrdiff_t)channel->keyframes.count;
23193 if (num_keys > 0) {
23194 ufbx_blend_keyframe *keys = channel->keyframes.data;
23195
23196 // Reset the effective weights to zero and find the split around zero
23197 ptrdiff_t last_negative = -1;
23198 for (ptrdiff_t i = 0; i < num_keys; i++) {
23199 keys[i].effective_weight = (ufbx_real)0.0;
23200 if (keys[i].target_weight < 0.0) last_negative = i;
23201 }
23202
23203 // Find either the next or last keyframe away from zero
23204 ufbx_blend_keyframe zero_key = { NULL };
23205 ufbx_blend_keyframe *prev = &zero_key, *next = &zero_key;
23206 if (weight > 0.0) {
23207 if (last_negative >= 0) prev = &keys[last_negative];
23208 for (ptrdiff_t i = last_negative + 1; i < num_keys; i++) {
23209 prev = next;
23210 next = &keys[i];
23211 if (next->target_weight > weight) break;
23212 }
23213 } else {
23214 if (last_negative + 1 < num_keys) prev = &keys[last_negative + 1];
23215 for (ptrdiff_t i = last_negative; i >= 0; i--) {
23216 prev = next;
23217 next = &keys[i];
23218 if (next->target_weight < weight) break;
23219 }
23220 }
23221
23222 // Linearly interpolate between the endpoints with the weight
23223 ufbx_real delta = next->target_weight - prev->target_weight;
23224 if (delta != 0.0) {
23225 ufbx_real t = (weight - prev->target_weight) / delta;
23226 prev->effective_weight = 1.0f - t;
23227 next->effective_weight = t;
23228 }
23229 }
23230 }
23231
23232 ufbxi_noinline static void ufbxi_update_material(ufbx_scene *scene, ufbx_material *material)
23233 {
23234 if (material->props.num_animated > 0) {
23235 ufbxi_fetch_maps(scene, material);
23236 }
23237 }
23238
23239 ufbxi_noinline static void ufbxi_update_texture(ufbx_texture *texture)
23240 {
23241 texture->uv_transform = ufbxi_get_texture_transform(&texture->props);
23242 if (!ufbxi_is_transform_identity(&texture->uv_transform)) {
23243 texture->has_uv_transform = true;
23244 texture->texture_to_uv = ufbx_transform_to_matrix(&texture->uv_transform);
23245 texture->uv_to_texture = ufbx_matrix_invert(&texture->texture_to_uv);
23246 } else {
23247 texture->has_uv_transform = false;
23248 texture->texture_to_uv = ufbx_identity_matrix;
23249 texture->uv_to_texture = ufbx_identity_matrix;
23250 }
23251 texture->wrap_u = (ufbx_wrap_mode)ufbxi_find_enum(&texture->props, ufbxi_WrapModeU, 0, UFBX_WRAP_CLAMP);
23252 texture->wrap_v = (ufbx_wrap_mode)ufbxi_find_enum(&texture->props, ufbxi_WrapModeV, 0, UFBX_WRAP_CLAMP);
23253
23254 if (texture->shader) {
23255 ufbxi_update_shader_texture(texture, texture->shader);
23256 }
23257 }
23258
23259 ufbxi_noinline static void ufbxi_update_anim_stack(ufbx_scene *scene, ufbx_anim_stack *stack)
23260 {
23261 ufbx_prop *begin, *end;
23262 begin = ufbxi_find_prop(&stack->props, ufbxi_LocalStart);
23263 end = ufbxi_find_prop(&stack->props, ufbxi_LocalStop);
23264 if (!begin || !end) {
23265 begin = ufbxi_find_prop(&stack->props, ufbxi_ReferenceStart);
23266 end = ufbxi_find_prop(&stack->props, ufbxi_ReferenceStop);
23267 }
23268
23269 if (begin && end) {
23270 stack->time_begin = (double)begin->value_int / (double)scene->metadata.ktime_second;
23271 stack->time_end = (double)end->value_int / (double)scene->metadata.ktime_second;
23272 }
23273
23274 stack->anim->time_begin = stack->time_begin;
23275 stack->anim->time_end = stack->time_end;
23276 }
23277
23278 ufbxi_noinline static void ufbxi_update_display_layer(ufbx_display_layer *layer)
23279 {
23280 layer->visible = ufbxi_find_int(&layer->props, ufbxi_Show, 1) != 0;
23281 layer->frozen = ufbxi_find_int(&layer->props, ufbxi_Freeze, 1) != 0;
23282 layer->ui_color = ufbxi_find_vec3(&layer->props, ufbxi_Color, 0.8f, 0.8f, 0.8f);
23283 }
23284
23285 ufbxi_noinline static void ufbxi_find_bool3(bool *dst, ufbx_props *props, const char *name, bool default_value)
23286 {
23287 size_t name_len = strlen(name);
23288 char local[64];
23289 ufbx_assert(name_len < sizeof(local) - 2);
23290 memcpy(local, name, name_len);
23291
23292 size_t local_len = name_len + 1;
23293 local[local_len] = '\0';
23294
23295 int64_t def = default_value ? 1 : 0;
23296 local[name_len] = 'X';
23297 dst[0] = ufbx_find_int_len(props, local, local_len, def) != 0;
23298 local[name_len] = 'Y';
23299 dst[1] = ufbx_find_int_len(props, local, local_len, def) != 0;
23300 local[name_len] = 'Z';
23301 dst[2] = ufbx_find_int_len(props, local, local_len, def) != 0;
23302 }
23303
23304 ufbxi_noinline static void ufbxi_update_constraint(ufbx_constraint *constraint)
23305 {
23306 ufbx_props *props = &constraint->props;
23307 ufbx_constraint_type constraint_type = constraint->type;
23308
23309 constraint->transform_offset = ufbxi_get_constraint_transform(props);
23310
23311 constraint->weight = ufbxi_find_real(props, ufbxi_Weight, (ufbx_real)100.0) / (ufbx_real)100.0;
23312
23313 ufbxi_for_list(ufbx_constraint_target, target, constraint->targets) {
23314 ufbx_node *node = target->node;
23315
23316 ufbx_real weight_scale = (ufbx_real)100.0;
23317 if (constraint_type == UFBX_CONSTRAINT_SINGLE_CHAIN_IK) {
23318 // IK weights seem to be not scaled 100x?
23319 weight_scale = (ufbx_real)1.0;
23320 }
23321
23322 ufbx_prop *prop; // ufbxi_uninit
23323 ufbx_string parts[2]; // ufbxi_uninit
23324 parts[0] = node->name;
23325 parts[1] = ufbxi_str_c(".Weight");
23326 prop = ufbx_find_prop_concat(props, parts, 2);
23327 target->weight = (prop ? prop->value_real : weight_scale) / weight_scale;
23328
23329 if (constraint_type == UFBX_CONSTRAINT_PARENT) {
23330 parts[1] = ufbxi_str_c(".Offset T");
23331 prop = ufbx_find_prop_concat(props, parts, 2);
23332 ufbx_vec3 t = prop ? prop->value_vec3 : ufbx_zero_vec3;
23333 parts[1] = ufbxi_str_c(".Offset R");
23334 prop = ufbx_find_prop_concat(props, parts, 2);
23335 ufbx_vec3 r = prop ? prop->value_vec3 : ufbx_zero_vec3;
23336 parts[1] = ufbxi_str_c(".Offset S");
23337 prop = ufbx_find_prop_concat(props, parts, 2);
23338 ufbx_vec3 s = prop ? prop->value_vec3 : ufbxi_one_vec3;
23339
23340 target->transform.translation = t;
23341 target->transform.rotation = ufbx_euler_to_quat(r, UFBX_ROTATION_ORDER_XYZ);
23342 target->transform.scale = s;
23343 }
23344 }
23345
23346 constraint->active = ufbx_find_int(props, "Active", 1) != 0;
23347 if (constraint_type == UFBX_CONSTRAINT_AIM) {
23348 ufbxi_find_bool3(constraint->constrain_rotation, props, "Affect", 1);
23349
23350 const ufbx_vec3 default_aim = { 1.0f, 0.0f, 0.0f };
23351 const ufbx_vec3 default_up = { 0.0f, 1.0f, 0.0f };
23352
23353 int64_t up_type = ufbx_find_int(props, "WorldUpType", 0);
23354 if (up_type >= 0 && up_type < UFBX_CONSTRAINT_AIM_UP_NONE) {
23355 constraint->aim_up_type = (ufbx_constraint_aim_up_type)up_type;
23356 }
23357 constraint->aim_vector = ufbx_find_vec3(props, "AimVector", default_aim);
23358 constraint->aim_up_vector = ufbx_find_vec3(props, "UpVector", default_up);
23359
23360 } else if (constraint_type == UFBX_CONSTRAINT_PARENT) {
23361 ufbxi_find_bool3(constraint->constrain_translation, props, "AffectTranslation", 1);
23362 ufbxi_find_bool3(constraint->constrain_rotation, props, "AffectRotation", 1);
23363 ufbxi_find_bool3(constraint->constrain_scale, props, "AffectScale", 0);
23364 } else if (constraint_type == UFBX_CONSTRAINT_POSITION) {
23365 ufbxi_find_bool3(constraint->constrain_translation, props, "Affect", 1);
23366 } else if (constraint_type == UFBX_CONSTRAINT_ROTATION) {
23367 ufbxi_find_bool3(constraint->constrain_rotation, props, "Affect", 1);
23368 } else if (constraint_type == UFBX_CONSTRAINT_SCALE) {
23369 ufbxi_find_bool3(constraint->constrain_scale, props, "Affect", 1);
23370 } else if (constraint_type == UFBX_CONSTRAINT_SINGLE_CHAIN_IK) {
23371 constraint->constrain_rotation[0] = true;
23372 constraint->constrain_rotation[1] = true;
23373 constraint->constrain_rotation[2] = true;
23374 constraint->ik_pole_vector = ufbx_find_vec3(props, "PoleVectorType", ufbx_zero_vec3);
23375 }
23376 }
23377
23378 ufbxi_noinline static void ufbxi_update_anim(ufbx_scene *scene)
23379 {
23380 if (scene->anim_stacks.count > 0) {
23381 scene->anim = scene->anim_stacks.data[0]->anim;
23382 }
23383 }
23384
23385 static ufbxi_forceinline void ufbxi_mirror_matrix_dst(ufbx_matrix *m, ufbx_mirror_axis axis)
23386 {
23387 if (axis == 0) return;
23388 int32_t ax = (int32_t)axis - 1;
23389 m->cols[0].v[ax] = -m->cols[0].v[ax];
23390 m->cols[1].v[ax] = -m->cols[1].v[ax];
23391 m->cols[2].v[ax] = -m->cols[2].v[ax];
23392 m->cols[3].v[ax] = -m->cols[3].v[ax];
23393 }
23394
23395 static ufbxi_forceinline void ufbxi_mirror_matrix_src(ufbx_matrix *m, ufbx_mirror_axis axis)
23396 {
23397 if (axis == 0) return;
23398 int32_t ax = (int32_t)axis - 1;
23399 m->cols[ax].x = -m->cols[ax].x;
23400 m->cols[ax].y = -m->cols[ax].y;
23401 m->cols[ax].z = -m->cols[ax].z;
23402 }
23403
23404 static ufbxi_noinline void ufbxi_mirror_matrix(ufbx_matrix *m, ufbx_mirror_axis axis)
23405 {
23406 if (axis == 0) return;
23407 ufbxi_mirror_matrix_src(m, axis);
23408 ufbxi_mirror_matrix_dst(m, axis);
23409 }
23410
23411 ufbxi_noinline static void ufbxi_update_initial_clusters(ufbx_scene *scene)
23412 {
23413 ufbxi_for_ptr_list(ufbx_skin_cluster, p_cluster, scene->skin_clusters) {
23414 ufbx_skin_cluster *cluster = *p_cluster;
23415 cluster->geometry_to_bone = cluster->mesh_node_to_bone;
23416 }
23417
23418 ufbx_mirror_axis mirror_axis = scene->metadata.mirror_axis;
23419 ufbx_real geometry_scale = scene->metadata.geometry_scale;
23420
23421 // Space conversion for bind matrices
23422 {
23423 ufbx_matrix world_to_units;
23424 ufbx_real translation_scale = 1.0f;
23425
23426 if (scene->metadata.space_conversion == UFBX_SPACE_CONVERSION_TRANSFORM_ROOT && scene->metadata.mirror_axis == UFBX_MIRROR_AXIS_NONE) {
23427 world_to_units = scene->root_node->node_to_parent;
23428 } else {
23429 ufbx_transform root_transform;
23430 root_transform.translation = ufbx_zero_vec3;
23431 root_transform.rotation = scene->metadata.root_rotation;
23432 root_transform.scale.x = scene->metadata.root_scale;
23433 root_transform.scale.y = scene->metadata.root_scale;
23434 root_transform.scale.z = scene->metadata.root_scale;
23435 world_to_units = ufbx_transform_to_matrix(&root_transform);
23436 translation_scale = scene->metadata.geometry_scale;
23437 }
23438
23439 ufbxi_for_ptr_list(ufbx_skin_cluster, p_cluster, scene->skin_clusters) {
23440 ufbx_skin_cluster *cluster = *p_cluster;
23441 cluster->bind_to_world = ufbx_matrix_mul(&world_to_units, &cluster->bind_to_world);
23442 cluster->bind_to_world.cols[3].x *= translation_scale;
23443 cluster->bind_to_world.cols[3].y *= translation_scale;
23444 cluster->bind_to_world.cols[3].z *= translation_scale;
23445 ufbxi_mirror_matrix(&cluster->bind_to_world, mirror_axis);
23446 }
23447
23448 ufbxi_for_ptr_list(ufbx_pose, p_pose, scene->poses) {
23449 ufbxi_for_list(ufbx_bone_pose, pose, (*p_pose)->bone_poses) {
23450 pose->bone_to_world = ufbx_matrix_mul(&world_to_units, &pose->bone_to_world);
23451 pose->bone_to_world.cols[3].x *= translation_scale;
23452 pose->bone_to_world.cols[3].y *= translation_scale;
23453 pose->bone_to_world.cols[3].z *= translation_scale;
23454 ufbxi_mirror_matrix(&pose->bone_to_world, mirror_axis);
23455 }
23456 }
23457 }
23458
23459 // Patch initial `mesh_node_to_bone`
23460 ufbxi_for_ptr_list(ufbx_skin_cluster, p_cluster, scene->skin_clusters) {
23461 ufbx_skin_cluster *cluster = *p_cluster;
23462
23463 ufbx_skin_deformer *skin = (ufbx_skin_deformer*)ufbxi_fetch_src_element(&cluster->element, false, NULL, UFBX_ELEMENT_SKIN_DEFORMER);
23464 if (!skin) continue;
23465
23466 ufbx_node *node = (ufbx_node*)ufbxi_fetch_src_element(&skin->element, false, NULL, UFBX_ELEMENT_NODE);
23467 if (!node) {
23468 ufbx_mesh *mesh = (ufbx_mesh*)ufbxi_fetch_src_element(&skin->element, false, NULL, UFBX_ELEMENT_MESH);
23469 if (mesh && mesh->instances.count > 0) {
23470 node = mesh->instances.data[0];
23471 }
23472 }
23473 if (!node) continue;
23474
23475 // Normalize to the non-helper node
23476 if (node->is_geometry_transform_helper) {
23477 node = node->parent;
23478 }
23479
23480 if (ufbxi_matrix_all_zero(&cluster->mesh_node_to_bone)) {
23481 // If `mesh_node_to_bone` is not explicitly specified compute it from bind pose.
23482 ufbx_matrix world_to_bind = ufbx_matrix_invert(&cluster->bind_to_world);
23483 cluster->mesh_node_to_bone = ufbx_matrix_mul(&world_to_bind, &node->node_to_world);
23484 } else {
23485 // If `mesh_node_to_bone` is explicit, we may need to modify it for space conversion.
23486 ufbxi_mirror_matrix(&cluster->mesh_node_to_bone, mirror_axis);
23487 if (geometry_scale != 1.0f) {
23488 cluster->mesh_node_to_bone.cols[3].x *= geometry_scale;
23489 cluster->mesh_node_to_bone.cols[3].y *= geometry_scale;
23490 cluster->mesh_node_to_bone.cols[3].z *= geometry_scale;
23491 }
23492 }
23493
23494 // HACK: Account for geometry transforms by looking at the transform of the
23495 // helper node if one is present. I don't think this is exactly how the skinning
23496 // matrices are formed.
23497 // TODO: Add a test with moving the skinned mesh root around.
23498 if (node->geometry_transform_helper) {
23499 ufbx_node *geo_node = node->geometry_transform_helper;
23500 cluster->geometry_to_bone = ufbx_matrix_mul(&cluster->mesh_node_to_bone, &geo_node->node_to_parent);
23501 } else if (node->has_geometry_transform) {
23502 cluster->geometry_to_bone = ufbx_matrix_mul(&cluster->mesh_node_to_bone, &node->geometry_to_node);
23503 } else {
23504 cluster->geometry_to_bone = cluster->mesh_node_to_bone;
23505 }
23506 }
23507 }
23508
23509 ufbxi_noinline static ufbx_coordinate_axis ufbxi_find_axis(const ufbx_props *props, const char *axis_name, const char *sign_name)
23510 {
23511 int64_t axis = ufbxi_find_int(props, axis_name, 3);
23512 int64_t sign = ufbxi_find_int(props, sign_name, 2);
23513
23514 switch (axis) {
23515 case 0: return sign > 0 ? UFBX_COORDINATE_AXIS_POSITIVE_X : UFBX_COORDINATE_AXIS_NEGATIVE_X;
23516 case 1: return sign > 0 ? UFBX_COORDINATE_AXIS_POSITIVE_Y : UFBX_COORDINATE_AXIS_NEGATIVE_Y;
23517 case 2: return sign > 0 ? UFBX_COORDINATE_AXIS_POSITIVE_Z : UFBX_COORDINATE_AXIS_NEGATIVE_Z;
23518 default: return UFBX_COORDINATE_AXIS_UNKNOWN;
23519 }
23520 }
23521
23522 static const ufbx_real ufbxi_time_mode_fps[] = {
23523 30.0f, // UFBX_TIME_MODE_DEFAULT
23524 120.0f, // UFBX_TIME_MODE_120_FPS
23525 100.0f, // UFBX_TIME_MODE_100_FPS
23526 60.0f, // UFBX_TIME_MODE_60_FPS
23527 50.0f, // UFBX_TIME_MODE_50_FPS
23528 48.0f, // UFBX_TIME_MODE_48_FPS
23529 30.0f, // UFBX_TIME_MODE_30_FPS
23530 30.0f, // UFBX_TIME_MODE_30_FPS_DROP
23531 29.97f, // UFBX_TIME_MODE_NTSC_DROP_FRAME
23532 29.97f, // UFBX_TIME_MODE_NTSC_FULL_FRAME
23533 25.0f, // UFBX_TIME_MODE_PAL
23534 24.0f, // UFBX_TIME_MODE_24_FPS
23535 1000.0f, // UFBX_TIME_MODE_1000_FPS
23536 23.976f, // UFBX_TIME_MODE_FILM_FULL_FRAME
23537 24.0f, // UFBX_TIME_MODE_CUSTOM
23538 96.0f, // UFBX_TIME_MODE_96_FPS
23539 72.0f, // UFBX_TIME_MODE_72_FPS
23540 59.94f, // UFBX_TIME_MODE_59_94_FPS
23541 };
23542
23543 // Returns whether a non-identity matrix was needed
23544 static ufbxi_noinline bool ufbxi_axis_matrix(ufbx_matrix *mat, ufbx_coordinate_axes src, ufbx_coordinate_axes dst)
23545 {
23546 uint32_t src_x = (uint32_t)src.right;
23547 uint32_t dst_x = (uint32_t)dst.right;
23548 uint32_t src_y = (uint32_t)src.up;
23549 uint32_t dst_y = (uint32_t)dst.up;
23550 uint32_t src_z = (uint32_t)src.front;
23551 uint32_t dst_z = (uint32_t)dst.front;
23552
23553 if (src_x == dst_x && src_y == dst_y && src_z == dst_z) return false;
23554
23555 // Remap axes (axis enum divided by 2) potentially flipping if the signs (enum parity) doesn't match
23556 memset(mat, 0, sizeof(ufbx_matrix));
23557 mat->cols[src_x >> 1].v[dst_x >> 1] = ((src_x ^ dst_x) & 1) == 0 ? 1.0f : -1.0f;
23558 mat->cols[src_y >> 1].v[dst_y >> 1] = ((src_y ^ dst_y) & 1) == 0 ? 1.0f : -1.0f;
23559 mat->cols[src_z >> 1].v[dst_z >> 1] = ((src_z ^ dst_z) & 1) == 0 ? 1.0f : -1.0f;
23560
23561 return true;
23562 }
23563
23564 ufbxi_noinline static void ufbxi_update_adjust_transforms(ufbxi_context *uc, ufbx_scene *scene)
23565 {
23566 ufbx_transform root_transform = ufbx_identity_transform;
23567 if (!ufbxi_matrix_all_zero(&uc->axis_matrix)) {
23568 root_transform = ufbx_matrix_to_transform(&uc->axis_matrix);
23569 }
23570 root_transform.scale.x *= uc->unit_scale;
23571 root_transform.scale.y *= uc->unit_scale;
23572 root_transform.scale.z *= uc->unit_scale;
23573
23574 ufbx_space_conversion conversion = uc->opts.space_conversion;
23575
23576 ufbx_quat light_post_rotation = ufbx_identity_quat;
23577 ufbx_quat camera_post_rotation = ufbx_identity_quat;
23578 ufbx_vec3 light_direction = { 0.0f, -1.0f, 0.0f };
23579 bool has_light_transform = false;
23580 bool has_camera_transform = false;
23581
23582 if (ufbx_coordinate_axes_valid(uc->opts.target_light_axes)) {
23583 ufbx_matrix mat; // ufbxi_uninit
23584 ufbx_coordinate_axes light_axes = {
23585 UFBX_COORDINATE_AXIS_POSITIVE_X,
23586 UFBX_COORDINATE_AXIS_NEGATIVE_Z,
23587 UFBX_COORDINATE_AXIS_POSITIVE_Y,
23588 };
23589 if (ufbxi_axis_matrix(&mat, uc->opts.target_light_axes, light_axes)) {
23590 light_post_rotation = ufbx_matrix_to_transform(&mat).rotation;
23591
23592 ufbx_matrix inv = ufbx_matrix_invert(&mat);
23593 light_direction = ufbx_transform_direction(&inv, light_direction);
23594 has_light_transform = true;
23595 }
23596 }
23597
23598 if (ufbx_coordinate_axes_valid(uc->opts.target_camera_axes)) {
23599 ufbx_matrix mat; // ufbxi_uninit
23600 ufbx_coordinate_axes camera_axes = {
23601 UFBX_COORDINATE_AXIS_POSITIVE_Z,
23602 UFBX_COORDINATE_AXIS_POSITIVE_Y,
23603 UFBX_COORDINATE_AXIS_NEGATIVE_X,
23604 };
23605 if (ufbxi_axis_matrix(&mat, uc->opts.target_camera_axes, camera_axes)) {
23606 camera_post_rotation = ufbx_matrix_to_transform(&mat).rotation;
23607 has_camera_transform = true;
23608 }
23609 }
23610
23611 ufbxi_for_ptr_list(ufbx_light, p_light, scene->lights) {
23612 ufbx_light *light = *p_light;
23613 light->local_direction.x = 0.0f;
23614 light->local_direction.y = -1.0f;
23615 light->local_direction.z = 0.0f;
23616 }
23617
23618 scene->metadata.space_conversion = conversion;
23619 scene->metadata.geometry_transform_handling = uc->opts.geometry_transform_handling;
23620 scene->metadata.inherit_mode_handling = uc->opts.inherit_mode_handling;
23621 scene->metadata.pivot_handling = uc->opts.pivot_handling;
23622 scene->metadata.handedness_conversion_axis = uc->opts.handedness_conversion_axis;
23623
23624 ufbx_real root_scale = ufbxi_min3(root_transform.scale);
23625 if (conversion == UFBX_SPACE_CONVERSION_MODIFY_GEOMETRY) {
23626 scene->metadata.geometry_scale = root_scale;
23627 scene->metadata.root_scale = 1.0f;
23628 } else {
23629 scene->metadata.geometry_scale = 1.0f;
23630 scene->metadata.root_scale = root_scale;
23631 }
23632 scene->metadata.root_rotation = root_transform.rotation;
23633
23634 ufbxi_for_ptr_list(ufbx_node, p_node, scene->nodes) {
23635 ufbx_node *node = *p_node;
23636
23637 node->adjust_post_rotation = ufbx_identity_quat;
23638 node->adjust_pre_rotation = ufbx_identity_quat;
23639 node->adjust_pre_scale = 1.0f;
23640 node->adjust_post_scale = 1.0f;
23641 node->adjust_translation_scale = 1.0f;
23642
23643 if (conversion == UFBX_SPACE_CONVERSION_ADJUST_TRANSFORMS) {
23644 if (node->node_depth <= 1 && !node->is_root) {
23645 node->adjust_pre_rotation = root_transform.rotation;
23646 node->adjust_pre_scale = root_scale;
23647 node->has_adjust_transform = true;
23648 node->has_root_adjust_transform = true;
23649 }
23650 } else if (conversion == UFBX_SPACE_CONVERSION_MODIFY_GEOMETRY) {
23651 if (!node->is_root) {
23652 if (node->node_depth <= 1) {
23653 node->adjust_pre_rotation = root_transform.rotation;
23654 }
23655 node->adjust_translation_scale = root_scale;
23656 node->has_adjust_transform = true;
23657 }
23658 }
23659
23660 if (node->parent) {
23661 // We are not inheriting local scale, so propagate root scale manually and
23662 // apply scale compensation if necessary.
23663 ufbx_node *parent = node->parent;
23664 if (parent->has_root_adjust_transform && node->inherit_mode == UFBX_INHERIT_MODE_IGNORE_PARENT_SCALE) {
23665 node->adjust_post_scale *= root_scale;
23666 node->has_adjust_transform = true;
23667 node->has_root_adjust_transform = true;
23668 }
23669 if (parent->is_scale_compensate_parent && node->original_inherit_mode == UFBX_INHERIT_MODE_IGNORE_PARENT_SCALE) {
23670 ufbx_vec3 scale = ufbxi_find_vec3(&parent->props, ufbxi_Lcl_Scaling, 1.0f, 1.0f, 1.0f);
23671 ufbx_real size = scale.x;
23672 if (ufbx_fabs(scale.y - 1.0f) < ufbx_fabs(size - 1.0f)) size = scale.y;
23673 if (ufbx_fabs(scale.z - 1.0f) < ufbx_fabs(size - 1.0f)) size = scale.z;
23674 node->adjust_post_scale *= 1.0f / size;
23675 node->has_adjust_transform = true;
23676 }
23677 }
23678
23679 if (node->all_attribs.count == 1) {
23680 if (has_light_transform && node->light) {
23681 node->adjust_post_rotation = light_post_rotation;
23682 node->light->local_direction = light_direction;
23683 node->has_adjust_transform = true;
23684 }
23685 if (has_camera_transform && node->camera) {
23686 node->adjust_post_rotation = camera_post_rotation;
23687 node->camera->projection_axes = uc->opts.target_camera_axes;
23688 node->has_adjust_transform = true;
23689 }
23690 }
23691 }
23692 }
23693
23694 ufbxi_noinline static void ufbxi_update_scene(ufbx_scene *scene, bool initial, const ufbx_transform_override *transform_overrides, size_t num_transform_overrides)
23695 {
23696 ufbxi_for_ptr_list(ufbx_node, p_node, scene->nodes) {
23697 ufbxi_update_node(*p_node, transform_overrides, num_transform_overrides);
23698 }
23699
23700 ufbxi_for_ptr_list(ufbx_light, p_light, scene->lights) {
23701 ufbxi_update_light(*p_light);
23702 }
23703
23704 ufbxi_for_ptr_list(ufbx_camera, p_camera, scene->cameras) {
23705 ufbxi_update_camera(scene, *p_camera);
23706 }
23707
23708 ufbxi_for_ptr_list(ufbx_bone, p_bone, scene->bones) {
23709 ufbxi_update_bone(scene, *p_bone);
23710 }
23711
23712 ufbxi_for_ptr_list(ufbx_line_curve, p_line, scene->line_curves) {
23713 ufbxi_update_line_curve(*p_line);
23714 }
23715
23716 if (initial) {
23717 ufbxi_update_initial_clusters(scene);
23718
23719 ufbxi_for_ptr_list(ufbx_pose, p_pose, scene->poses) {
23720 ufbxi_update_pose(*p_pose);
23721 }
23722 }
23723
23724 ufbxi_for_ptr_list(ufbx_skin_cluster, p_cluster, scene->skin_clusters) {
23725 ufbxi_update_skin_cluster(*p_cluster);
23726 }
23727
23728 ufbxi_for_ptr_list(ufbx_blend_channel, p_channel, scene->blend_channels) {
23729 ufbxi_update_blend_channel(*p_channel);
23730 }
23731
23732 ufbxi_for_ptr_list(ufbx_texture, p_texture, scene->textures) {
23733 ufbxi_update_texture(*p_texture);
23734 }
23735
23736 ufbxi_propagate_main_textures(scene);
23737
23738 ufbxi_for_ptr_list(ufbx_material, p_material, scene->materials) {
23739 ufbxi_update_material(scene, *p_material);
23740 }
23741
23742 ufbxi_for_ptr_list(ufbx_anim_stack, p_stack, scene->anim_stacks) {
23743 ufbxi_update_anim_stack(scene, *p_stack);
23744 }
23745
23746 ufbxi_for_ptr_list(ufbx_display_layer, p_layer, scene->display_layers) {
23747 ufbxi_update_display_layer(*p_layer);
23748 }
23749
23750 ufbxi_for_ptr_list(ufbx_constraint, p_constraint, scene->constraints) {
23751 ufbxi_update_constraint(*p_constraint);
23752 }
23753
23754 ufbxi_update_anim(scene);
23755 }
23756
23757 static ufbxi_noinline void ufbxi_update_scene_metadata(ufbx_metadata *metadata)
23758 {
23759 ufbx_props *props = &metadata->scene_props;
23760 metadata->original_application.vendor = ufbx_find_string(props, "Original|ApplicationVendor", ufbx_empty_string);
23761 metadata->original_application.name = ufbx_find_string(props, "Original|ApplicationName", ufbx_empty_string);
23762 metadata->original_application.version = ufbx_find_string(props, "Original|ApplicationVersion", ufbx_empty_string);
23763 metadata->latest_application.vendor = ufbx_find_string(props, "LastSaved|ApplicationVendor", ufbx_empty_string);
23764 metadata->latest_application.name = ufbx_find_string(props, "LastSaved|ApplicationName", ufbx_empty_string);
23765 metadata->latest_application.version = ufbx_find_string(props, "LastSaved|ApplicationVersion", ufbx_empty_string);
23766 }
23767
23768 static const ufbx_real ufbxi_pow10_targets[] = {
23769 0.0f,
23770 (ufbx_real)1e-8, (ufbx_real)1e-7, (ufbx_real)1e-6, (ufbx_real)1e-5,
23771 (ufbx_real)1e-4, (ufbx_real)1e-3, (ufbx_real)1e-2, (ufbx_real)1e-1,
23772 (ufbx_real)1e+0, (ufbx_real)1e+1, (ufbx_real)1e+2, (ufbx_real)1e+3,
23773 (ufbx_real)1e+4, (ufbx_real)1e+5, (ufbx_real)1e+6, (ufbx_real)1e+7,
23774 (ufbx_real)1e+8, (ufbx_real)1e+9,
23775 };
23776
23777 static ufbxi_noinline ufbx_real ufbxi_round_if_near(const ufbx_real *targets, size_t num_targets, ufbx_real value)
23778 {
23779 for (size_t i = 0; i < num_targets; i++) {
23780 double target = targets[i];
23781 double error = target * 9.5367431640625e-7;
23782 if (error < 0.0) error = -error;
23783 if (error < 7.52316384526264005e-37) error = 7.52316384526264005e-37;
23784 if (value >= target - error && value <= target + error) {
23785 return (ufbx_real)target;
23786 }
23787 }
23788 return value;
23789 }
23790
23791 static ufbxi_noinline void ufbxi_update_scene_settings(ufbx_scene_settings *settings)
23792 {
23793 ufbx_real unit_scale_factor = ufbxi_find_real(&settings->props, ufbxi_UnitScaleFactor, 1.0f);
23794 ufbx_real original_unit_scale_factor = ufbxi_find_real(&settings->props, ufbxi_OriginalUnitScaleFactor, unit_scale_factor);
23795
23796 settings->axes.up = ufbxi_find_axis(&settings->props, ufbxi_UpAxis, ufbxi_UpAxisSign);
23797 settings->axes.front = ufbxi_find_axis(&settings->props, ufbxi_FrontAxis, ufbxi_FrontAxisSign);
23798 settings->axes.right = ufbxi_find_axis(&settings->props, ufbxi_CoordAxis, ufbxi_CoordAxisSign);
23799 settings->unit_meters = ufbxi_round_if_near(ufbxi_pow10_targets, ufbxi_arraycount(ufbxi_pow10_targets), unit_scale_factor * (ufbx_real)0.01);
23800 settings->original_unit_meters = ufbxi_round_if_near(ufbxi_pow10_targets, ufbxi_arraycount(ufbxi_pow10_targets), original_unit_scale_factor * (ufbx_real)0.01);
23801 settings->frames_per_second = ufbxi_find_real(&settings->props, ufbxi_CustomFrameRate, 24.0f);
23802 settings->ambient_color = ufbxi_find_vec3(&settings->props, ufbxi_AmbientColor, 0.0f, 0.0f, 0.0f);
23803 settings->original_axis_up = ufbxi_find_axis(&settings->props, ufbxi_OriginalUpAxis, ufbxi_OriginalUpAxisSign);
23804
23805 ufbx_prop *default_camera = ufbxi_find_prop(&settings->props, ufbxi_DefaultCamera);
23806 if (default_camera) {
23807 settings->default_camera = default_camera->value_str;
23808 } else {
23809 settings->default_camera = ufbx_empty_string;
23810 }
23811
23812 settings->time_mode = (ufbx_time_mode)ufbxi_find_enum(&settings->props, ufbxi_TimeMode, UFBX_TIME_MODE_24_FPS, UFBX_TIME_MODE_59_94_FPS);
23813 settings->time_protocol = (ufbx_time_protocol)ufbxi_find_enum(&settings->props, ufbxi_TimeProtocol, UFBX_TIME_PROTOCOL_DEFAULT, UFBX_TIME_PROTOCOL_DEFAULT);
23814 settings->snap_mode = (ufbx_snap_mode)ufbxi_find_enum(&settings->props, ufbxi_SnapOnFrameMode, UFBX_SNAP_MODE_NONE, UFBX_SNAP_MODE_SNAP_AND_PLAY);
23815
23816 if (settings->time_mode != UFBX_TIME_MODE_CUSTOM) {
23817 settings->frames_per_second = ufbxi_time_mode_fps[settings->time_mode];
23818 }
23819 }
23820
23821 static ufbxi_noinline void ufbxi_update_scene_settings_obj(ufbxi_context *uc)
23822 {
23823 ufbx_scene_settings *settings = &uc->scene.settings;
23824 settings->original_unit_meters = settings->unit_meters = uc->opts.obj_unit_meters;
23825 if (ufbx_coordinate_axes_valid(uc->opts.obj_axes)) {
23826 settings->axes = uc->opts.obj_axes;
23827 } else {
23828 settings->axes.right = UFBX_COORDINATE_AXIS_UNKNOWN;
23829 settings->axes.up = UFBX_COORDINATE_AXIS_UNKNOWN;
23830 settings->axes.front = UFBX_COORDINATE_AXIS_UNKNOWN;
23831 }
23832 }
23833
23834 // -- Geometry caches
23835
23836 #if UFBXI_FEATURE_GEOMETRY_CACHE
23837
23838 typedef struct {
23839 ufbxi_refcount refcount;
23840 ufbx_geometry_cache cache;
23841 uint32_t magic;
23842 bool owned_by_scene;
23843
23844 ufbxi_buf string_buf;
23845 } ufbxi_geometry_cache_imp;
23846
23847 ufbx_static_assert(geometry_cache_imp_offset, offsetof(ufbxi_geometry_cache_imp, cache) == sizeof(ufbxi_refcount));
23848
23849 typedef struct {
23850 ufbx_string name;
23851 ufbx_string interpretation;
23852 uint32_t sample_rate;
23853 uint32_t start_time;
23854 uint32_t end_time;
23855 uint32_t current_time;
23856 uint32_t consecutive_fails;
23857 bool try_load;
23858 } ufbxi_cache_tmp_channel;
23859
23860 typedef enum {
23861 UFBXI_CACHE_XML_TYPE_NONE,
23862 UFBXI_CACHE_XML_TYPE_FILE_PER_FRAME,
23863 UFBXI_CACHE_XML_TYPE_SINGLE_FILE,
23864 } ufbxi_cache_xml_type;
23865
23866 typedef enum {
23867 UFBXI_CACHE_XML_FORMAT_NONE,
23868 UFBXI_CACHE_XML_FORMAT_MCC,
23869 UFBXI_CACHE_XML_FORMAT_MCX,
23870 } ufbxi_cache_xml_format;
23871
23872 typedef struct {
23873 ufbx_error error;
23874 ufbx_string filename;
23875 bool owned_by_scene;
23876 bool ignore_if_not_found;
23877
23878 ufbx_geometry_cache_opts opts;
23879
23880 ufbxi_allocator *ator_tmp;
23881 ufbxi_allocator ator_result;
23882
23883 ufbxi_buf result;
23884 ufbxi_buf tmp;
23885 ufbxi_buf tmp_stack;
23886
23887 ufbxi_cache_tmp_channel *channels;
23888 size_t num_channels;
23889
23890 // Temporary array
23891 char *tmp_arr;
23892 size_t tmp_arr_size;
23893
23894 ufbxi_string_pool string_pool;
23895
23896 ufbx_open_file_cb open_file_cb;
23897
23898 double frames_per_second;
23899
23900 ufbx_string stream_filename;
23901 ufbx_stream stream;
23902
23903 bool mc_for8;
23904
23905 ufbx_string xml_filename;
23906 uint32_t xml_ticks_per_frame;
23907 ufbxi_cache_xml_type xml_type;
23908 ufbxi_cache_xml_format xml_format;
23909
23910 ufbx_string channel_name;
23911
23912 char *name_buf;
23913 size_t name_cap;
23914
23915 uint64_t file_offset;
23916 const char *pos, *pos_end;
23917
23918 ufbx_geometry_cache cache;
23919 ufbxi_geometry_cache_imp *imp;
23920
23921 char buffer[128];
23922 } ufbxi_cache_context;
23923
23924 ufbxi_nodiscard static ufbxi_noinline int ufbxi_cache_read(ufbxi_cache_context *cc, void *dst, size_t size, bool allow_eof)
23925 {
23926 size_t buffered = ufbxi_min_sz(ufbxi_to_size(cc->pos_end - cc->pos), size);
23927 memcpy(dst, cc->pos, buffered);
23928 cc->pos += buffered;
23929 size -= buffered;
23930 cc->file_offset += buffered;
23931 if (size == 0) return 1;
23932 dst = (char*)dst + buffered;
23933
23934 if (size >= sizeof(cc->buffer)) {
23935 size_t num_read = cc->stream.read_fn(cc->stream.user, dst, size);
23936 ufbxi_check_err_msg(&cc->error, num_read <= size, "IO error");
23937 if (!allow_eof) {
23938 ufbxi_check_err_msg(&cc->error, num_read == size, "Truncated file");
23939 }
23940 cc->file_offset += num_read;
23941 size -= num_read;
23942 dst = (char*)dst + num_read;
23943 } else {
23944 size_t num_read = cc->stream.read_fn(cc->stream.user, cc->buffer, sizeof(cc->buffer));
23945 ufbxi_check_err_msg(&cc->error, num_read <= sizeof(cc->buffer), "IO error");
23946 if (!allow_eof) {
23947 ufbxi_check_err_msg(&cc->error, num_read >= size, "Truncated file");
23948 }
23949 cc->pos = cc->buffer;
23950 cc->pos_end = cc->buffer + sizeof(cc->buffer);
23951
23952 memcpy(dst, cc->pos, size);
23953 cc->pos += size;
23954 cc->file_offset += size;
23955
23956 size_t num_written = ufbxi_min_sz(size, num_read);
23957 size -= num_written;
23958 dst = (char*)dst + num_written;
23959 }
23960
23961 if (size > 0) {
23962 memset(dst, 0, size);
23963 }
23964
23965 return 1;
23966 }
23967
23968 ufbxi_nodiscard static ufbxi_noinline int ufbxi_cache_skip(ufbxi_cache_context *cc, uint64_t size)
23969 {
23970 cc->file_offset += size;
23971
23972 uint64_t buffered = ufbxi_min64((uint64_t)(cc->pos_end - cc->pos), size);
23973 cc->pos += buffered;
23974 size -= buffered;
23975
23976 if (cc->stream.skip_fn) {
23977 while (size >= UFBXI_MAX_SKIP_SIZE) {
23978 size -= UFBXI_MAX_SKIP_SIZE;
23979 ufbxi_check_err_msg(&cc->error, cc->stream.skip_fn(cc->stream.user, UFBXI_MAX_SKIP_SIZE - 1), "Truncated file");
23980
23981 // Check that we can read at least one byte in case the file is broken
23982 // and causes us to seek indefinitely forwards as `fseek()` does not
23983 // report if we hit EOF...
23984 char single_byte[1]; // ufbxi_uninit
23985 size_t num_read = cc->stream.read_fn(cc->stream.user, single_byte, 1);
23986 ufbxi_check_err_msg(&cc->error, num_read <= 1, "IO error");
23987 ufbxi_check_err_msg(&cc->error, num_read == 1, "Truncated file");
23988 }
23989
23990 if (size > 0) {
23991 ufbxi_check_err_msg(&cc->error, cc->stream.skip_fn(cc->stream.user, (size_t)size), "Truncated file");
23992 }
23993
23994 } else {
23995 char skip_buf[2048]; // ufbxi_uninit
23996 while (size > 0) {
23997 size_t to_skip = (size_t)ufbxi_min64(size, sizeof(skip_buf));
23998 size -= to_skip;
23999 ufbxi_check_err_msg(&cc->error, cc->stream.read_fn(cc->stream.user, skip_buf, to_skip), "Truncated file");
24000 }
24001 }
24002
24003 return 1;
24004 }
24005
24006 #define ufbxi_cache_mc_tag(a,b,c,d) ((uint32_t)(a)<<24u | (uint32_t)(b)<<16 | (uint32_t)(c)<<8u | (uint32_t)(d))
24007
24008 ufbxi_nodiscard static ufbxi_noinline int ufbxi_cache_mc_read_tag(ufbxi_cache_context *cc, uint32_t *p_tag)
24009 {
24010 char buf[4]; // ufbxi_uninit
24011 ufbxi_check_err(&cc->error, ufbxi_cache_read(cc, buf, 4, true));
24012 *p_tag = (uint32_t)(uint8_t)buf[0]<<24u | (uint32_t)(uint8_t)buf[1]<<16 | (uint32_t)(uint8_t)buf[2]<<8u | (uint32_t)(uint8_t)buf[3];
24013 if (*p_tag == ufbxi_cache_mc_tag('F','O','R','8')) {
24014 cc->mc_for8 = true;
24015 }
24016 return 1;
24017 }
24018
24019 ufbxi_nodiscard static ufbxi_noinline int ufbxi_cache_mc_read_u32(ufbxi_cache_context *cc, uint32_t *p_value)
24020 {
24021 char buf[4]; // ufbxi_uninit
24022 ufbxi_check_err(&cc->error, ufbxi_cache_read(cc, buf, 4, false));
24023 *p_value = (uint32_t)(uint8_t)buf[0]<<24u | (uint32_t)(uint8_t)buf[1]<<16 | (uint32_t)(uint8_t)buf[2]<<8u | (uint32_t)(uint8_t)buf[3];
24024 if (cc->mc_for8) {
24025 ufbxi_check_err(&cc->error, ufbxi_cache_read(cc, buf, 4, false));
24026 }
24027 return 1;
24028 }
24029
24030 ufbxi_nodiscard static ufbxi_noinline int ufbxi_cache_mc_read_u64(ufbxi_cache_context *cc, uint64_t *p_value)
24031 {
24032 if (!cc->mc_for8) {
24033 uint32_t v32; // ufbxi_uninit
24034 ufbxi_check_err(&cc->error, ufbxi_cache_mc_read_u32(cc, &v32));
24035 *p_value = v32;
24036 } else {
24037 char buf[8]; // ufbxi_uninit
24038 ufbxi_check_err(&cc->error, ufbxi_cache_read(cc, buf, 8, false));
24039 uint32_t hi = (uint32_t)(uint8_t)buf[0]<<24u | (uint32_t)(uint8_t)buf[1]<<16 | (uint32_t)(uint8_t)buf[2]<<8u | (uint32_t)(uint8_t)buf[3];
24040 uint32_t lo = (uint32_t)(uint8_t)buf[4]<<24u | (uint32_t)(uint8_t)buf[5]<<16 | (uint32_t)(uint8_t)buf[6]<<8u | (uint32_t)(uint8_t)buf[7];
24041 *p_value = (uint64_t)hi << 32u | (uint64_t)lo;
24042 }
24043 return 1;
24044 }
24045
24046 static const uint8_t ufbxi_cache_data_format_size[] = {
24047 0, 4, 12, 8, 24,
24048 };
24049
24050 ufbxi_nodiscard static ufbxi_noinline int ufbxi_cache_load_mc(ufbxi_cache_context *cc)
24051 {
24052 uint32_t version = 0, time_start = 0, time_end = 0;
24053 uint32_t count = 0, time = 0;
24054 char skip_buf[8]; // ufbxi_uninit
24055
24056 for (;;) {
24057 uint32_t tag; // ufbxi_uninit
24058 uint64_t size; // ufbxi_uninit
24059 ufbxi_check_err(&cc->error, ufbxi_cache_mc_read_tag(cc, &tag));
24060 if (tag == 0) break;
24061
24062 if (tag == ufbxi_cache_mc_tag('C','A','C','H') || tag == ufbxi_cache_mc_tag('M','Y','C','H')) {
24063 continue;
24064 }
24065 if (cc->mc_for8) {
24066 ufbxi_check_err(&cc->error, ufbxi_cache_read(cc, skip_buf, 4, false));
24067 }
24068
24069 ufbxi_check_err(&cc->error, ufbxi_cache_mc_read_u64(cc, &size));
24070 uint64_t begin = cc->file_offset;
24071
24072 size_t alignment = cc->mc_for8 ? 8 : 4;
24073
24074 ufbx_cache_data_format format = UFBX_CACHE_DATA_FORMAT_UNKNOWN;
24075 switch (tag) {
24076 case ufbxi_cache_mc_tag('F','O','R','4'): cc->mc_for8 = false; break;
24077 case ufbxi_cache_mc_tag('F','O','R','8'): cc->mc_for8 = true; break;
24078 case ufbxi_cache_mc_tag('V','R','S','N'): ufbxi_check_err(&cc->error, ufbxi_cache_mc_read_u32(cc, &version)); break;
24079 case ufbxi_cache_mc_tag('S','T','I','M'):
24080 ufbxi_check_err(&cc->error, ufbxi_cache_mc_read_u32(cc, &time_start));
24081 time = time_start;
24082 break;
24083 case ufbxi_cache_mc_tag('E','T','I','M'): ufbxi_check_err(&cc->error, ufbxi_cache_mc_read_u32(cc, &time_end)); break;
24084 case ufbxi_cache_mc_tag('T','I','M','E'): ufbxi_check_err(&cc->error, ufbxi_cache_mc_read_u32(cc, &time)); break;
24085 case ufbxi_cache_mc_tag('C','H','N','M'): {
24086 ufbxi_check_err(&cc->error, size > 0 && size < SIZE_MAX);
24087 size_t length = (size_t)size - 1;
24088 size_t padded_length = ((size_t)size + alignment - 1) & ~(alignment - 1);
24089 ufbxi_check_err(&cc->error, ufbxi_grow_array(cc->ator_tmp, &cc->name_buf, &cc->name_cap, padded_length));
24090 ufbxi_check_err(&cc->error, ufbxi_cache_read(cc, cc->name_buf, padded_length, false));
24091 cc->channel_name.data = cc->name_buf;
24092 cc->channel_name.length = length;
24093 ufbxi_check_err(&cc->error, ufbxi_push_string_place_str(&cc->string_pool, &cc->channel_name, false));
24094 } break;
24095 case ufbxi_cache_mc_tag('S','I','Z','E'): ufbxi_check_err(&cc->error, ufbxi_cache_mc_read_u32(cc, &count)); break;
24096 case ufbxi_cache_mc_tag('F','V','C','A'): format = UFBX_CACHE_DATA_FORMAT_VEC3_FLOAT; break;
24097 case ufbxi_cache_mc_tag('D','V','C','A'): format = UFBX_CACHE_DATA_FORMAT_VEC3_DOUBLE; break;
24098 case ufbxi_cache_mc_tag('F','B','C','A'): format = UFBX_CACHE_DATA_FORMAT_REAL_FLOAT; break;
24099 case ufbxi_cache_mc_tag('D','B','C','A'): format = UFBX_CACHE_DATA_FORMAT_REAL_DOUBLE; break;
24100 case ufbxi_cache_mc_tag('D','B','L','A'): format = UFBX_CACHE_DATA_FORMAT_REAL_DOUBLE; break;
24101 default: ufbxi_fail_err(&cc->error, "Unknown tag");
24102 }
24103
24104 if (format != UFBX_CACHE_DATA_FORMAT_UNKNOWN) {
24105 ufbx_cache_frame *frame = ufbxi_push_zero(&cc->tmp_stack, ufbx_cache_frame, 1);
24106 ufbxi_check_err(&cc->error, frame);
24107
24108 uint32_t elem_size = ufbxi_cache_data_format_size[format];
24109 uint64_t total_size = (uint64_t)elem_size * (uint64_t)count;
24110 ufbxi_check_err(&cc->error, size >= elem_size * count);
24111
24112 frame->channel = cc->channel_name;
24113 frame->time = (double)time * (1.0/6000.0);
24114 frame->filename = cc->stream_filename;
24115 frame->data_format = format;
24116 frame->data_encoding = UFBX_CACHE_DATA_ENCODING_BIG_ENDIAN;
24117 frame->data_offset = cc->file_offset;
24118 frame->data_count = count;
24119 frame->data_element_bytes = elem_size;
24120 frame->data_total_bytes = total_size;
24121 frame->file_format = UFBX_CACHE_FILE_FORMAT_MC;
24122
24123 uint64_t end = begin + ((size + alignment - 1) & ~(uint64_t)(alignment - 1));
24124 ufbxi_check_err(&cc->error, end >= cc->file_offset);
24125 uint64_t left = end - cc->file_offset;
24126 ufbxi_check_err(&cc->error, ufbxi_cache_skip(cc, left));
24127 }
24128 }
24129
24130 return 1;
24131 }
24132
24133 ufbxi_nodiscard static ufbxi_noinline int ufbxi_cache_load_pc2(ufbxi_cache_context *cc)
24134 {
24135 char header[32]; // ufbxi_uninit
24136 ufbxi_check_err(&cc->error, ufbxi_cache_read(cc, header, sizeof(header), false));
24137
24138 uint32_t version = ufbxi_read_u32(header + 12);
24139 uint32_t num_points = ufbxi_read_u32(header + 16);
24140 double start_frame = ufbxi_read_f32(header + 20);
24141 double frames_per_sample = ufbxi_read_f32(header + 24);
24142 uint32_t num_samples = ufbxi_read_u32(header + 28);
24143
24144 (void)version;
24145
24146 ufbx_cache_frame *frames = ufbxi_push_zero(&cc->tmp_stack, ufbx_cache_frame, num_samples);
24147 ufbxi_check_err(&cc->error, frames);
24148
24149 uint64_t total_points = (uint64_t)num_points * (uint64_t)num_samples;
24150 ufbxi_check_err(&cc->error, total_points < UINT64_MAX / 12);
24151
24152 uint64_t offset = cc->file_offset;
24153
24154 // Skip almost to the end of the data and try to read one byte as there's
24155 // nothing after the data so we can't detect EOF..
24156 if (total_points > 0) {
24157 char last_byte[1]; // ufbxi_uninit
24158 ufbxi_check_err(&cc->error, ufbxi_cache_skip(cc, total_points * 12 - 1));
24159 ufbxi_check_err(&cc->error, ufbxi_cache_read(cc, last_byte, 1, false));
24160 }
24161
24162 for (uint32_t i = 0; i < num_samples; i++) {
24163 ufbx_cache_frame *frame = &frames[i];
24164
24165 double sample_frame = start_frame + (double)i * frames_per_sample;
24166 frame->channel = cc->channel_name;
24167 frame->time = sample_frame / cc->frames_per_second;
24168 frame->filename = cc->stream_filename;
24169 frame->data_format = UFBX_CACHE_DATA_FORMAT_VEC3_FLOAT;
24170 frame->data_encoding = UFBX_CACHE_DATA_ENCODING_LITTLE_ENDIAN;
24171 frame->data_offset = offset;
24172 frame->data_count = num_points;
24173 frame->data_element_bytes = 12;
24174 frame->data_total_bytes = num_points * 12;
24175 frame->file_format = UFBX_CACHE_FILE_FORMAT_PC2;
24176 offset += num_points * 12;
24177 }
24178
24179 return 1;
24180 }
24181
24182 static ufbxi_noinline bool ufbxi_tmp_channel_less(void *user, const void *va, const void *vb)
24183 {
24184 (void)user;
24185 const ufbxi_cache_tmp_channel *a = (const ufbxi_cache_tmp_channel *)va, *b = (const ufbxi_cache_tmp_channel *)vb;
24186 return ufbxi_str_less(a->name, b->name);
24187 }
24188
24189 static ufbxi_noinline int ufbxi_cache_sort_tmp_channels(ufbxi_cache_context *cc, ufbxi_cache_tmp_channel *channels, size_t count)
24190 {
24191 ufbxi_check_err(&cc->error, ufbxi_grow_array(cc->ator_tmp, &cc->tmp_arr, &cc->tmp_arr_size, count * sizeof(ufbxi_cache_tmp_channel)));
24192 ufbxi_stable_sort(sizeof(ufbxi_cache_tmp_channel), 16, channels, cc->tmp_arr, count, &ufbxi_tmp_channel_less, NULL);
24193 return 1;
24194 }
24195
24196 ufbxi_nodiscard static ufbxi_noinline int ufbxi_cache_load_xml_imp(ufbxi_cache_context *cc, ufbxi_xml_document *doc)
24197 {
24198 cc->xml_ticks_per_frame = 250;
24199 cc->xml_filename = cc->stream_filename;
24200
24201 ufbxi_xml_tag *tag_root = ufbxi_xml_find_child(doc->root, "Autodesk_Cache_File");
24202 if (tag_root) {
24203 ufbxi_xml_tag *tag_type = ufbxi_xml_find_child(tag_root, "cacheType");
24204 ufbxi_xml_tag *tag_fps = ufbxi_xml_find_child(tag_root, "cacheTimePerFrame");
24205 ufbxi_xml_tag *tag_channels = ufbxi_xml_find_child(tag_root, "Channels");
24206
24207 size_t num_extra = 0;
24208 ufbxi_for(ufbxi_xml_tag, tag, tag_root->children, tag_root->num_children) {
24209 if (tag->num_children != 1) continue;
24210 if (strcmp(tag->name.data, "extra") != 0) continue;
24211 ufbx_string *extra = ufbxi_push(&cc->tmp_stack, ufbx_string, 1);
24212 ufbxi_check_err(&cc->error, extra);
24213 *extra = tag->children[0].text;
24214 ufbxi_check_err(&cc->error, ufbxi_push_string_place_str(&cc->string_pool, extra, false));
24215 num_extra++;
24216 }
24217 cc->cache.extra_info.count = num_extra;
24218 cc->cache.extra_info.data = ufbxi_push_pop(&cc->result, &cc->tmp_stack, ufbx_string, num_extra);
24219 ufbxi_check_err(&cc->error, cc->cache.extra_info.data);
24220
24221 if (tag_type) {
24222 ufbxi_xml_attrib *type = ufbxi_xml_find_attrib(tag_type, "Type");
24223 ufbxi_xml_attrib *format = ufbxi_xml_find_attrib(tag_type, "Format");
24224 if (type) {
24225 if (!strcmp(type->value.data, "OneFilePerFrame")) {
24226 cc->xml_type = UFBXI_CACHE_XML_TYPE_FILE_PER_FRAME;
24227 } else if (!strcmp(type->value.data, "OneFile")) {
24228 cc->xml_type = UFBXI_CACHE_XML_TYPE_SINGLE_FILE;
24229 }
24230 }
24231 if (format) {
24232 if (!strcmp(format->value.data, "mcc")) {
24233 cc->xml_format = UFBXI_CACHE_XML_FORMAT_MCC;
24234 } else if (!strcmp(format->value.data, "mcx")) {
24235 cc->xml_format = UFBXI_CACHE_XML_FORMAT_MCX;
24236 }
24237 }
24238 }
24239
24240 if (tag_fps) {
24241 ufbxi_xml_attrib *fps = ufbxi_xml_find_attrib(tag_fps, "TimePerFrame");
24242 if (fps) {
24243 uint32_t value = ufbxi_parse_uint32_radix(fps->value.data, 10);
24244 if (value > 0) {
24245 cc->xml_ticks_per_frame = value;
24246 }
24247 }
24248 }
24249
24250 if (tag_channels) {
24251 cc->channels = ufbxi_push_zero(&cc->tmp, ufbxi_cache_tmp_channel, tag_channels->num_children);
24252 ufbxi_check_err(&cc->error, cc->channels);
24253
24254 ufbxi_for(ufbxi_xml_tag, tag, tag_channels->children, tag_channels->num_children) {
24255 ufbxi_xml_attrib *name = ufbxi_xml_find_attrib(tag, "ChannelName");
24256 ufbxi_xml_attrib *type = ufbxi_xml_find_attrib(tag, "ChannelType");
24257 ufbxi_xml_attrib *interpretation = ufbxi_xml_find_attrib(tag, "ChannelInterpretation");
24258 if (!(name && type && interpretation)) continue;
24259
24260 ufbxi_cache_tmp_channel *channel = &cc->channels[cc->num_channels++];
24261 channel->name = name->value;
24262 channel->interpretation = interpretation->value;
24263 ufbxi_check_err(&cc->error, ufbxi_push_string_place_str(&cc->string_pool, &channel->name, false));
24264 ufbxi_check_err(&cc->error, ufbxi_push_string_place_str(&cc->string_pool, &channel->interpretation, false));
24265
24266 ufbxi_xml_attrib *sampling_rate = ufbxi_xml_find_attrib(tag, "SamplingRate");
24267 ufbxi_xml_attrib *start_time = ufbxi_xml_find_attrib(tag, "StartTime");
24268 ufbxi_xml_attrib *end_time = ufbxi_xml_find_attrib(tag, "EndTime");
24269 if (sampling_rate && start_time && end_time) {
24270 channel->sample_rate = ufbxi_parse_uint32_radix(sampling_rate->value.data, 10);
24271 channel->start_time = ufbxi_parse_uint32_radix(start_time->value.data, 10);
24272 channel->end_time = ufbxi_parse_uint32_radix(end_time->value.data, 10);
24273 channel->current_time = channel->start_time;
24274 channel->try_load = true;
24275 }
24276 }
24277 }
24278 }
24279
24280 ufbxi_check_err(&cc->error, ufbxi_cache_sort_tmp_channels(cc, cc->channels, cc->num_channels));
24281 return 1;
24282 }
24283
24284 ufbxi_nodiscard static ufbxi_noinline int ufbxi_cache_load_xml(ufbxi_cache_context *cc)
24285 {
24286 ufbxi_xml_load_opts opts = { 0 };
24287 opts.ator = cc->ator_tmp;
24288 opts.read_fn = cc->stream.read_fn;
24289 opts.read_user = cc->stream.user;
24290 opts.prefix = cc->pos;
24291 opts.prefix_length = ufbxi_to_size(cc->pos_end - cc->pos);
24292 ufbxi_xml_document *doc = ufbxi_load_xml(&opts, &cc->error);
24293 ufbxi_check_err(&cc->error, doc);
24294
24295 int xml_ok = ufbxi_cache_load_xml_imp(cc, doc);
24296 ufbxi_free_xml(doc);
24297 ufbxi_check_err(&cc->error, xml_ok);
24298
24299 return 1;
24300 }
24301
24302 ufbxi_nodiscard static ufbxi_noinline int ufbxi_cache_load_file(ufbxi_cache_context *cc, ufbx_string filename)
24303 {
24304 cc->stream_filename = filename;
24305 ufbxi_check_err(&cc->error, ufbxi_push_string_place_str(&cc->string_pool, &cc->stream_filename, false));
24306
24307 // Assume all files have at least 16 bytes of header
24308 size_t magic_len = cc->stream.read_fn(cc->stream.user, cc->buffer, 16);
24309 ufbxi_check_err_msg(&cc->error, magic_len <= 16, "IO error");
24310 ufbxi_check_err_msg(&cc->error, magic_len == 16, "Truncated file");
24311 cc->pos = cc->buffer;
24312 cc->pos_end = cc->buffer + 16;
24313
24314 cc->file_offset = 0;
24315
24316 if (!memcmp(cc->buffer, "POINTCACHE2", 11)) {
24317 ufbxi_check_err(&cc->error, ufbxi_cache_load_pc2(cc));
24318 } else if (!memcmp(cc->buffer, "FOR4", 4) || !memcmp(cc->buffer, "FOR8", 4)) {
24319 ufbxi_check_err(&cc->error, ufbxi_cache_load_mc(cc));
24320 } else {
24321 ufbxi_check_err(&cc->error, ufbxi_cache_load_xml(cc));
24322 }
24323
24324 return 1;
24325 }
24326
24327 ufbxi_nodiscard static ufbxi_noinline int ufbxi_cache_try_open_file(ufbxi_cache_context *cc, ufbx_string filename, const ufbx_blob *original_filename, bool *p_found)
24328 {
24329 memset(&cc->stream, 0, sizeof(cc->stream));
24330 ufbxi_regression_assert(strlen(filename.data) == filename.length);
24331 if (!ufbxi_open_file(&cc->open_file_cb, &cc->stream, filename.data, filename.length, original_filename, cc->ator_tmp, UFBX_OPEN_FILE_GEOMETRY_CACHE)) {
24332 return 1;
24333 }
24334
24335 int ok = ufbxi_cache_load_file(cc, filename);
24336 *p_found = true;
24337
24338 if (cc->stream.close_fn) {
24339 cc->stream.close_fn(cc->stream.user);
24340 }
24341
24342 return ok;
24343 }
24344
24345 ufbxi_nodiscard static ufbxi_noinline int ufbxi_cache_load_frame_files(ufbxi_cache_context *cc)
24346 {
24347 if (cc->xml_filename.length == 0) return 1;
24348
24349 const char *extension = NULL;
24350 switch (cc->xml_format) {
24351 case UFBXI_CACHE_XML_FORMAT_MCC: extension = "mc"; break;
24352 case UFBXI_CACHE_XML_FORMAT_MCX: extension = "mcx"; break;
24353 default: return 1;
24354 }
24355
24356 // Ensure worst case space for `path/filenameFrame123Tick456.mcx`
24357 size_t name_buf_len = cc->xml_filename.length + 64;
24358 char *name_buf = ufbxi_push(&cc->tmp, char, name_buf_len);
24359 ufbxi_check_err(&cc->error, name_buf);
24360
24361 // Find the prefix before `.xml`
24362 size_t prefix_len = cc->xml_filename.length;
24363 for (size_t i = prefix_len; i > 0; --i) {
24364 if (cc->xml_filename.data[i - 1] == '.') {
24365 prefix_len = i - 1;
24366 break;
24367 }
24368 }
24369 memcpy(name_buf, cc->xml_filename.data, prefix_len);
24370
24371 char *suffix_data = name_buf + prefix_len;
24372 size_t suffix_len = name_buf_len - prefix_len;
24373
24374 ufbx_string filename;
24375 filename.data = name_buf;
24376
24377 if (cc->xml_type == UFBXI_CACHE_XML_TYPE_SINGLE_FILE) {
24378 filename.length = prefix_len + (size_t)ufbxi_snprintf(suffix_data, suffix_len, ".%s", extension);
24379 bool found = false;
24380 ufbxi_check_err(&cc->error, ufbxi_cache_try_open_file(cc, filename, NULL, &found));
24381 } else if (cc->xml_type == UFBXI_CACHE_XML_TYPE_FILE_PER_FRAME) {
24382 uint32_t lowest_time = 0;
24383 for (;;) {
24384 // Find the first `time >= lowest_time` value that has data in some channel
24385 uint32_t time = UINT32_MAX;
24386 ufbxi_for(ufbxi_cache_tmp_channel, chan, cc->channels, cc->num_channels) {
24387 if (!chan->try_load || chan->consecutive_fails > 10) continue;
24388 uint32_t sample_rate = chan->sample_rate ? chan->sample_rate : cc->xml_ticks_per_frame;
24389 if (chan->current_time < lowest_time) {
24390 uint32_t delta = (lowest_time - chan->current_time - 1) / sample_rate;
24391 chan->current_time += delta * sample_rate;
24392 if (UINT32_MAX - chan->current_time >= sample_rate) {
24393 chan->current_time += sample_rate;
24394 } else {
24395 chan->try_load = false;
24396 continue;
24397 }
24398 }
24399 if (chan->current_time <= chan->end_time) {
24400 time = ufbxi_min32(time, chan->current_time);
24401 }
24402 }
24403 if (time == UINT32_MAX) break;
24404
24405 // Try to load a file at the specified frame/tick
24406 uint32_t frame = time / cc->xml_ticks_per_frame;
24407 uint32_t tick = time % cc->xml_ticks_per_frame;
24408 if (tick == 0) {
24409 filename.length = prefix_len + (size_t)ufbxi_snprintf(suffix_data, suffix_len, "Frame%u.%s", frame, extension);
24410 } else {
24411 filename.length = prefix_len + (size_t)ufbxi_snprintf(suffix_data, suffix_len, "Frame%uTick%u.%s", frame, tick, extension);
24412 }
24413 bool found = false;
24414 ufbxi_check_err(&cc->error, ufbxi_cache_try_open_file(cc, filename, NULL, &found));
24415
24416 // Update channel status
24417 ufbxi_for(ufbxi_cache_tmp_channel, chan, cc->channels, cc->num_channels) {
24418 if (chan->current_time == time) {
24419 chan->consecutive_fails = found ? 0 : chan->consecutive_fails + 1;
24420 }
24421 }
24422
24423 lowest_time = time + 1;
24424 }
24425 }
24426
24427 return 1;
24428 }
24429
24430 static ufbxi_noinline bool ufbxi_cmp_cache_frame_less(void *user, const void *va, const void *vb)
24431 {
24432 (void)user;
24433 const ufbx_cache_frame *a = (const ufbx_cache_frame *)va, *b = (const ufbx_cache_frame *)vb;
24434 if (a->channel.data != b->channel.data) {
24435 // Channel names should be interned
24436 ufbxi_regression_assert(!ufbxi_str_equal(a->channel, b->channel));
24437 return ufbxi_str_less(a->channel, b->channel);
24438 }
24439 return a->time < b->time;
24440 }
24441
24442 static ufbxi_noinline int ufbxi_cache_sort_frames(ufbxi_cache_context *cc, ufbx_cache_frame *frames, size_t count)
24443 {
24444 ufbxi_check_err(&cc->error, ufbxi_grow_array(cc->ator_tmp, &cc->tmp_arr, &cc->tmp_arr_size, count * sizeof(ufbx_cache_frame)));
24445 ufbxi_stable_sort(sizeof(ufbx_cache_frame), 16, frames, cc->tmp_arr, count, &ufbxi_cmp_cache_frame_less, NULL);
24446 return 1;
24447 }
24448
24449 typedef struct {
24450 ufbx_cache_interpretation interpretation;
24451 const char *pattern;
24452 } ufbxi_cache_interpretation_name;
24453
24454 static const ufbxi_cache_interpretation_name ufbxi_cache_interpretation_names[] = {
24455 { UFBX_CACHE_INTERPRETATION_POINTS, "\\cpoints?" },
24456 { UFBX_CACHE_INTERPRETATION_VERTEX_POSITION, "\\cpositions?" },
24457 { UFBX_CACHE_INTERPRETATION_VERTEX_NORMAL, "\\cnormals?" },
24458 };
24459
24460 static ufbxi_noinline int ufbxi_cache_setup_channels(ufbxi_cache_context *cc)
24461 {
24462 ufbxi_cache_tmp_channel *tmp_chan = cc->channels, *tmp_end = ufbxi_add_ptr(tmp_chan, cc->num_channels);
24463
24464 size_t begin = 0, num_channels = 0;
24465 while (begin < cc->cache.frames.count) {
24466 ufbx_cache_frame *frame = &cc->cache.frames.data[begin];
24467 size_t end = begin + 1;
24468 while (end < cc->cache.frames.count && cc->cache.frames.data[end].channel.data == frame->channel.data) {
24469 end++;
24470 }
24471
24472 ufbx_cache_channel *chan = ufbxi_push_zero(&cc->tmp_stack, ufbx_cache_channel, 1);
24473 ufbxi_check_err(&cc->error, chan);
24474
24475 chan->name = frame->channel;
24476 chan->interpretation_name = ufbx_empty_string;
24477 chan->frames.data = frame;
24478 chan->frames.count = end - begin;
24479
24480 while (tmp_chan < tmp_end && ufbxi_str_less(tmp_chan->name, chan->name)) {
24481 tmp_chan++;
24482 }
24483 if (tmp_chan < tmp_end && ufbxi_str_equal(tmp_chan->name, chan->name)) {
24484 chan->interpretation_name = tmp_chan->interpretation;
24485 }
24486
24487 if (frame->file_format == UFBX_CACHE_FILE_FORMAT_PC2) {
24488 chan->interpretation = UFBX_CACHE_INTERPRETATION_VERTEX_POSITION;
24489 } else {
24490 ufbxi_for(const ufbxi_cache_interpretation_name, name, ufbxi_cache_interpretation_names, ufbxi_arraycount(ufbxi_cache_interpretation_names)) {
24491 if (ufbxi_match(&chan->interpretation_name, name->pattern)) {
24492 chan->interpretation = name->interpretation;
24493 break;
24494 }
24495 }
24496 }
24497
24498 ufbx_mirror_axis mirror_axis = UFBX_MIRROR_AXIS_NONE;
24499 ufbx_real scale_factor = 1.0f;
24500 if (chan->interpretation != UFBX_CACHE_INTERPRETATION_UNKNOWN) {
24501 mirror_axis = cc->opts.mirror_axis;
24502 if (cc->opts.use_scale_factor) {
24503 scale_factor = cc->opts.scale_factor;
24504 }
24505 }
24506 chan->mirror_axis = mirror_axis;
24507 chan->scale_factor = scale_factor;
24508 ufbxi_for_list(ufbx_cache_frame, f, chan->frames) {
24509 f->mirror_axis = mirror_axis;
24510 f->scale_factor = scale_factor;
24511 }
24512
24513 num_channels++;
24514 begin = end;
24515 }
24516
24517 cc->cache.channels.data = ufbxi_push_pop(&cc->result, &cc->tmp_stack, ufbx_cache_channel, num_channels);
24518 ufbxi_check_err(&cc->error, cc->cache.channels.data);
24519 cc->cache.channels.count = num_channels;
24520
24521 return 1;
24522 }
24523
24524
24525 static ufbxi_noinline int ufbxi_cache_load_imp(ufbxi_cache_context *cc, ufbx_string filename)
24526 {
24527 cc->tmp.ator = cc->ator_tmp;
24528 cc->tmp_stack.ator = cc->ator_tmp;
24529
24530 cc->channel_name.data = ufbxi_empty_char;
24531
24532 if (!cc->open_file_cb.fn) {
24533 cc->open_file_cb.fn = ufbx_default_open_file;
24534 }
24535
24536 // Make sure the filename we pass to `open_file_fn()` is NULL-terminated
24537 char *filename_data = ufbxi_push(&cc->tmp, char, filename.length + 1);
24538 ufbxi_check_err(&cc->error, filename_data);
24539 memcpy(filename_data, filename.data, filename.length);
24540 filename_data[filename.length] = '\0';
24541 ufbx_string filename_copy = { filename_data, filename.length };
24542
24543 // TODO: NULL termination!
24544 bool found = false;
24545 ufbxi_check_err(&cc->error, ufbxi_cache_try_open_file(cc, filename_copy, NULL, &found));
24546 if (!found) {
24547 ufbxi_set_err_info(&cc->error, filename.data, filename.length);
24548 ufbxi_fail_err_msg(&cc->error, "open_file_fn()", "File not found");
24549 }
24550
24551 cc->cache.root_filename = cc->stream_filename;
24552
24553 ufbxi_check_err(&cc->error, ufbxi_cache_load_frame_files(cc));
24554
24555 size_t num_frames = cc->tmp_stack.num_items;
24556 cc->cache.frames.count = num_frames;
24557 cc->cache.frames.data = ufbxi_push_pop(&cc->result, &cc->tmp_stack, ufbx_cache_frame, num_frames);
24558 ufbxi_check_err(&cc->error, cc->cache.frames.data);
24559
24560 ufbxi_check_err(&cc->error, ufbxi_cache_sort_frames(cc, cc->cache.frames.data, cc->cache.frames.count));
24561 ufbxi_check_err(&cc->error, ufbxi_cache_setup_channels(cc));
24562
24563 // Must be last allocation!
24564 cc->imp = ufbxi_push(&cc->result, ufbxi_geometry_cache_imp, 1);
24565 ufbxi_check_err(&cc->error, cc->imp);
24566
24567 ufbxi_init_ref(&cc->imp->refcount, UFBXI_CACHE_IMP_MAGIC, NULL);
24568
24569 cc->imp->cache = cc->cache;
24570 cc->imp->magic = UFBXI_CACHE_IMP_MAGIC;
24571 cc->imp->owned_by_scene = cc->owned_by_scene;
24572 cc->imp->refcount.ator = cc->ator_result;
24573 cc->imp->refcount.buf = cc->result;
24574 cc->imp->refcount.buf.ator = &cc->imp->refcount.ator;
24575 cc->imp->string_buf = cc->string_pool.buf;
24576 cc->imp->string_buf.ator = &cc->imp->refcount.ator;
24577
24578 return 1;
24579 }
24580
24581 ufbxi_noinline static ufbx_geometry_cache *ufbxi_cache_load(ufbxi_cache_context *cc, ufbx_string filename)
24582 {
24583 int ok = ufbxi_cache_load_imp(cc, filename);
24584
24585 ufbxi_buf_free(&cc->tmp);
24586 ufbxi_buf_free(&cc->tmp_stack);
24587 ufbxi_free(cc->ator_tmp, char, cc->name_buf, cc->name_cap);
24588 ufbxi_free(cc->ator_tmp, char, cc->tmp_arr, cc->tmp_arr_size);
24589 if (!cc->owned_by_scene) {
24590 ufbxi_string_pool_temp_free(&cc->string_pool);
24591 ufbxi_free_ator(cc->ator_tmp);
24592 }
24593
24594 if (ok) {
24595 return &cc->imp->cache;
24596 } else {
24597 ufbxi_fix_error_type(&cc->error, "Failed to load geometry cache", NULL);
24598 if (!cc->owned_by_scene) {
24599 ufbxi_buf_free(&cc->string_pool.buf);
24600 ufbxi_free_ator(&cc->ator_result);
24601 }
24602 return NULL;
24603 }
24604 }
24605
24606 ufbxi_noinline static ufbx_geometry_cache *ufbxi_load_geometry_cache(ufbx_string filename, const ufbx_geometry_cache_opts *user_opts, ufbx_error *p_error)
24607 {
24608 ufbx_geometry_cache_opts opts; // ufbxi_uninit
24609 if (user_opts) {
24610 opts = *user_opts;
24611 } else {
24612 memset(&opts, 0, sizeof(opts));
24613 }
24614
24615 ufbxi_cache_context cc = { UFBX_ERROR_NONE };
24616 ufbxi_allocator ator_tmp = { 0 };
24617 ufbxi_init_ator(&cc.error, &ator_tmp, &opts.temp_allocator, "temp");
24618 ufbxi_init_ator(&cc.error, &cc.ator_result, &opts.result_allocator, "result");
24619 cc.ator_tmp = &ator_tmp;
24620
24621 cc.opts = opts;
24622
24623 cc.open_file_cb = opts.open_file_cb;
24624
24625 cc.string_pool.error = &cc.error;
24626 ufbxi_map_init(&cc.string_pool.map, cc.ator_tmp, &ufbxi_map_cmp_string, NULL);
24627 cc.string_pool.buf.ator = &cc.ator_result;
24628 cc.string_pool.buf.unordered = true;
24629 cc.string_pool.initial_size = 64;
24630 cc.result.ator = &cc.ator_result;
24631
24632 cc.frames_per_second = opts.frames_per_second > 0.0 ? opts.frames_per_second : 30.0;
24633
24634 ufbx_geometry_cache *cache = ufbxi_cache_load(&cc, filename);
24635 if (p_error) {
24636 if (cache) {
24637 ufbxi_clear_error(p_error);
24638 } else {
24639 *p_error = cc.error;
24640 }
24641 }
24642 return cache;
24643 }
24644
24645 static ufbxi_noinline void ufbxi_free_geometry_cache_imp(ufbxi_geometry_cache_imp *imp)
24646 {
24647 ufbx_assert(imp->magic == UFBXI_CACHE_IMP_MAGIC);
24648 ufbxi_buf_free(&imp->string_buf);
24649 }
24650
24651 #else
24652
24653 typedef struct {
24654 ufbxi_refcount refcount;
24655 uint32_t magic;
24656 bool owned_by_scene;
24657 } ufbxi_geometry_cache_imp;
24658
24659 static ufbxi_noinline ufbx_geometry_cache *ufbxi_load_geometry_cache(ufbx_string filename, const ufbx_geometry_cache_opts *user_opts, ufbx_error *p_error)
24660 {
24661 if (p_error) {
24662 memset(p_error, 0, sizeof(ufbx_error));
24663 ufbxi_fmt_err_info(p_error, "UFBX_ENABLE_GEOMETRY_CACHE");
24664 ufbxi_report_err_msg(p_error, "UFBXI_FEATURE_GEOMETRY_CACHE", "Feature disabled");
24665 }
24666 return NULL;
24667 }
24668
24669 static ufbxi_forceinline void ufbxi_free_geometry_cache_imp(ufbxi_geometry_cache_imp *imp)
24670 {
24671 }
24672
24673 #endif
24674
24675 // -- External files
24676
24677 typedef enum {
24678 UFBXI_EXTERNAL_FILE_GEOMETRY_CACHE,
24679 } ufbxi_external_file_type;
24680
24681 typedef struct {
24682 ufbxi_external_file_type type;
24683 ufbx_string filename;
24684 ufbx_string absolute_filename;
24685 size_t index;
24686 void *data;
24687 size_t data_size;
24688 } ufbxi_external_file;
24689
24690 static bool ufbxi_less_external_file(void *user, const void *va, const void *vb)
24691 {
24692 (void)user;
24693 const ufbxi_external_file *a = (const ufbxi_external_file*)va, *b = (const ufbxi_external_file*)vb;
24694 if (a->type != b->type) return a->type < b->type;
24695 int cmp = ufbxi_str_cmp(a->filename, b->filename);
24696 if (cmp != 0) return cmp < 0;
24697 if (a->index != b->index) return a->index < b->index;
24698 return false;
24699 }
24700
24701 ufbxi_nodiscard static ufbxi_noinline int ufbxi_load_external_cache(ufbxi_context *uc, ufbxi_external_file *file)
24702 {
24703 #if UFBXI_FEATURE_GEOMETRY_CACHE
24704 ufbxi_cache_context cc = { UFBX_ERROR_NONE };
24705 cc.owned_by_scene = true;
24706
24707 cc.open_file_cb = uc->opts.open_file_cb;
24708 cc.frames_per_second = uc->scene.settings.frames_per_second;
24709
24710 // Temporarily "borrow" allocators for the geometry cache
24711 cc.ator_tmp = &uc->ator_tmp;
24712 cc.string_pool = uc->string_pool;
24713 cc.result = uc->result;
24714
24715 cc.opts.mirror_axis = uc->mirror_axis;
24716 cc.opts.use_scale_factor = true;
24717 cc.opts.scale_factor = uc->scene.metadata.geometry_scale;
24718
24719 ufbx_geometry_cache *cache = ufbxi_cache_load(&cc, file->filename);
24720 if (!cache) {
24721 if (cc.error.type == UFBX_ERROR_FILE_NOT_FOUND) {
24722 memset(&cc.error, 0, sizeof(cc.error));
24723 cache = ufbxi_cache_load(&cc, file->absolute_filename);
24724 }
24725 }
24726
24727 // Return the "borrowed" allocators
24728 uc->string_pool = cc.string_pool;
24729 uc->result = cc.result;
24730
24731 if (!cache) {
24732 if (cc.error.type == UFBX_ERROR_FILE_NOT_FOUND) {
24733 if (uc->opts.ignore_missing_external_files) {
24734 ufbxi_check(ufbxi_warnf(UFBX_WARNING_MISSING_EXTERNAL_FILE, "Failed to open geometry cache: %s", file->filename.data));
24735 return 1;
24736 } else {
24737 cc.error.type = UFBX_ERROR_EXTERNAL_FILE_NOT_FOUND;
24738 cc.error.description.data = "External file not found";
24739 cc.error.description.length = strlen("External file not found");
24740 }
24741 }
24742
24743 uc->error = cc.error;
24744 return 0;
24745 }
24746
24747 file->data = cache;
24748 return 1;
24749 #else
24750 if (uc->opts.ignore_missing_external_files) return 1;
24751
24752 ufbxi_fmt_err_info(&uc->error, "UFBX_ENABLE_GEOMETRY_CACHE");
24753 ufbxi_fail_msg("UFBXI_FEATURE_GEOMETRY_CACHE", "Feature disabled");
24754 #endif
24755 }
24756
24757 static ufbxi_noinline ufbxi_external_file *ufbxi_find_external_file(ufbxi_external_file *files, size_t num_files, ufbxi_external_file_type type, const char *name)
24758 {
24759 size_t ix = SIZE_MAX;
24760 ufbxi_macro_lower_bound_eq(ufbxi_external_file, 32, &ix, files, 0, num_files,
24761 ( type != a->type ? type < a->type : strcmp(a->filename.data, name) < 0 ),
24762 ( a->type == type && a->filename.data == name ));
24763 return ix != SIZE_MAX ? &files[ix] : NULL;
24764 }
24765
24766 ufbxi_nodiscard static ufbxi_noinline int ufbxi_load_external_files(ufbxi_context *uc)
24767 {
24768 size_t num_files = 0;
24769
24770 // Gather external files to deduplicate them
24771 ufbxi_for_ptr_list(ufbx_cache_file, p_cache, uc->scene.cache_files) {
24772 ufbx_cache_file *cache = *p_cache;
24773 if (cache->filename.length > 0) {
24774 ufbxi_external_file *file = ufbxi_push_zero(&uc->tmp_stack, ufbxi_external_file, 1);
24775 ufbxi_check(file);
24776 file->index = num_files++;
24777 file->type = UFBXI_EXTERNAL_FILE_GEOMETRY_CACHE;
24778 file->filename = cache->filename;
24779 file->absolute_filename = cache->absolute_filename;
24780 }
24781 }
24782
24783 // Sort and load the external files
24784 ufbxi_external_file *files = ufbxi_push_pop(&uc->tmp, &uc->tmp_stack, ufbxi_external_file, num_files);
24785 ufbxi_check(files);
24786 ufbxi_unstable_sort(files, num_files, sizeof(ufbxi_external_file), &ufbxi_less_external_file, NULL);
24787
24788 ufbxi_external_file_type prev_type = UFBXI_EXTERNAL_FILE_GEOMETRY_CACHE;
24789 const char *prev_name = NULL;
24790 ufbxi_for(ufbxi_external_file, file, files, num_files) {
24791 if (file->filename.data == prev_name && file->type == prev_type) continue;
24792 if (file->type == UFBXI_EXTERNAL_FILE_GEOMETRY_CACHE) {
24793 ufbxi_check(ufbxi_load_external_cache(uc, file));
24794 }
24795 prev_name = file->filename.data;
24796 prev_type = file->type;
24797 }
24798
24799 // Patch the loaded files
24800 ufbxi_for_ptr_list(ufbx_cache_file, p_cache, uc->scene.cache_files) {
24801 ufbx_cache_file *cache = *p_cache;
24802 ufbxi_external_file *file = ufbxi_find_external_file(files, num_files,
24803 UFBXI_EXTERNAL_FILE_GEOMETRY_CACHE, cache->filename.data);
24804 if (file && file->data) {
24805 cache->external_cache = (ufbx_geometry_cache*)file->data;
24806 }
24807 }
24808
24809 // Patch the geometry deformers
24810 ufbxi_for_ptr_list(ufbx_cache_deformer, p_deformer, uc->scene.cache_deformers) {
24811 ufbx_cache_deformer *deformer = *p_deformer;
24812 if (!deformer->file || !deformer->file->external_cache) continue;
24813 ufbx_geometry_cache *cache = deformer->file->external_cache;
24814 deformer->external_cache = cache;
24815
24816 // HACK: It seems like channels may be connected even if the name is wrong
24817 // and they work when exporting from Marvelous to Maya...
24818 if (cache->channels.count == 1) {
24819 deformer->external_channel = &cache->channels.data[0];
24820 } else {
24821 ufbx_string channel = deformer->channel;
24822 size_t ix = SIZE_MAX;
24823 ufbxi_macro_lower_bound_eq(ufbx_cache_channel, 16, &ix, cache->channels.data, 0, cache->channels.count,
24824 ( ufbxi_str_less(a->name, channel) ), ( a->name.data == channel.data ));
24825 if (ix != SIZE_MAX) {
24826 deformer->external_channel = &cache->channels.data[ix];
24827 }
24828 }
24829 }
24830
24831 return 1;
24832 }
24833
24834 static ufbxi_noinline void ufbxi_transform_to_axes(ufbxi_context *uc, ufbx_coordinate_axes dst_axes)
24835 {
24836 if (!ufbx_coordinate_axes_valid(uc->scene.settings.axes)) return;
24837 if (!ufbxi_axis_matrix(&uc->axis_matrix, uc->scene.settings.axes, dst_axes)) return;
24838
24839 if (ufbx_matrix_determinant(&uc->axis_matrix) < 0.0f) {
24840 if (uc->opts.handedness_conversion_axis != UFBX_MIRROR_AXIS_NONE) {
24841 ufbx_mirror_axis mirror_axis = uc->opts.handedness_conversion_axis;
24842 uc->mirror_axis = mirror_axis;
24843 uc->scene.metadata.mirror_axis = uc->mirror_axis;
24844
24845 ufbxi_mirror_matrix_dst(&uc->axis_matrix, uc->mirror_axis);
24846 ufbxi_dev_assert(ufbx_matrix_determinant(&uc->axis_matrix) >= 0.0f);
24847
24848 ufbxi_for_ptr_list(ufbx_node, p_node, uc->scene.nodes) {
24849 ufbx_node *node = *p_node;
24850 if (!node->is_root) {
24851 node->adjust_mirror_axis = mirror_axis;
24852 }
24853 }
24854 }
24855 }
24856
24857 if (uc->opts.space_conversion == UFBX_SPACE_CONVERSION_TRANSFORM_ROOT) {
24858 ufbx_matrix axis_mat = uc->axis_matrix;
24859 if (!ufbxi_is_transform_identity(&uc->scene.root_node->local_transform)) {
24860 ufbx_matrix root_mat = ufbx_transform_to_matrix(&uc->scene.root_node->local_transform);
24861 axis_mat = ufbx_matrix_mul(&root_mat, &axis_mat);
24862 }
24863
24864 ufbxi_mirror_matrix(&axis_mat, uc->mirror_axis);
24865
24866 uc->scene.root_node->local_transform = ufbx_matrix_to_transform(&axis_mat);
24867 uc->scene.root_node->node_to_parent = axis_mat;
24868 }
24869 }
24870
24871 static ufbxi_noinline int ufbxi_scale_units(ufbxi_context *uc, ufbx_real target_meters)
24872 {
24873 if (uc->scene.settings.unit_meters <= 0.0f) return 1;
24874 target_meters = ufbxi_round_if_near(ufbxi_pow10_targets, ufbxi_arraycount(ufbxi_pow10_targets), target_meters);
24875
24876 ufbx_real ratio = uc->scene.settings.unit_meters / target_meters;
24877 ratio = ufbxi_round_if_near(ufbxi_pow10_targets, ufbxi_arraycount(ufbxi_pow10_targets), ratio);
24878 if (ratio == 1.0f) return 1;
24879
24880 uc->unit_scale = ratio;
24881
24882 if (uc->opts.space_conversion == UFBX_SPACE_CONVERSION_TRANSFORM_ROOT) {
24883 uc->scene.root_node->local_transform.scale.x *= ratio;
24884 uc->scene.root_node->local_transform.scale.y *= ratio;
24885 uc->scene.root_node->local_transform.scale.z *= ratio;
24886 uc->scene.root_node->node_to_parent.m00 *= ratio;
24887 uc->scene.root_node->node_to_parent.m01 *= ratio;
24888 uc->scene.root_node->node_to_parent.m02 *= ratio;
24889 uc->scene.root_node->node_to_parent.m10 *= ratio;
24890 uc->scene.root_node->node_to_parent.m11 *= ratio;
24891 uc->scene.root_node->node_to_parent.m12 *= ratio;
24892 uc->scene.root_node->node_to_parent.m20 *= ratio;
24893 uc->scene.root_node->node_to_parent.m21 *= ratio;
24894 uc->scene.root_node->node_to_parent.m22 *= ratio;
24895 }
24896
24897 return 1;
24898 }
24899
24900 // -- Curve evaluation
24901
24902 static ufbxi_forceinline double ufbxi_find_cubic_bezier_t(double p1, double p2, double x0)
24903 {
24904 double p1_3 = p1 * 3.0, p2_3 = p2 * 3.0;
24905 double a = p1_3 - p2_3 + 1.0;
24906 double b = p2_3 - p1_3 - p1_3;
24907 double c = p1_3;
24908
24909 double a_3 = 3.0*a, b_2 = 2.0*b;
24910 double t = x0;
24911 double x1, t2, t3;
24912
24913 // Manually unroll three iterations of Newton-Rhapson, this is enough
24914 // for most tangents
24915 t2 = t*t; t3 = t2*t; x1 = a*t3 + b*t2 + c*t - x0;
24916 t -= x1 / (a_3*t2 + b_2*t + c);
24917
24918 t2 = t*t; t3 = t2*t; x1 = a*t3 + b*t2 + c*t - x0;
24919 t -= x1 / (a_3*t2 + b_2*t + c);
24920
24921 t2 = t*t; t3 = t2*t; x1 = a*t3 + b*t2 + c*t - x0;
24922 t -= x1 / (a_3*t2 + b_2*t + c);
24923
24924 // 4 ULP from 1.0
24925 const double eps = 8.881784197001252e-16;
24926 if (ufbx_fabs(x1) <= eps) return t;
24927
24928 // Perform more iterations until we reach desired accuracy
24929 for (size_t i = 0; i < 4; i++) {
24930
24931 t2 = t*t; t3 = t2*t; x1 = a*t3 + b*t2 + c*t - x0;
24932 t -= x1 / (a_3*t2 + b_2*t + c);
24933
24934 t2 = t*t; t3 = t2*t; x1 = a*t3 + b*t2 + c*t - x0;
24935 t -= x1 / (a_3*t2 + b_2*t + c);
24936
24937 if (ufbx_fabs(x1) <= eps) return t;
24938 }
24939
24940 return t;
24941 }
24942
24943 ufbxi_nodiscard static ufbxi_noinline int ufbxi_evaluate_skinning(ufbx_scene *scene, ufbx_error *error, ufbxi_buf *buf_result, ufbxi_buf *buf_tmp,
24944 double time, bool load_caches, ufbx_geometry_cache_data_opts *cache_opts)
24945 {
24946 #if UFBXI_FEATURE_SKINNING_EVALUATION
24947 size_t max_skinned_indices = 0;
24948
24949 ufbxi_for_ptr_list(ufbx_mesh, p_mesh, scene->meshes) {
24950 ufbx_mesh *mesh = *p_mesh;
24951 if (mesh->blend_deformers.count == 0 && mesh->skin_deformers.count == 0 && (mesh->cache_deformers.count == 0 || !load_caches)) continue;
24952 max_skinned_indices = ufbxi_max_sz(max_skinned_indices, mesh->num_indices);
24953 }
24954
24955 ufbx_topo_edge *topo = ufbxi_push(buf_tmp, ufbx_topo_edge, max_skinned_indices);
24956 ufbxi_check_err(error, topo);
24957
24958 ufbxi_for_ptr_list(ufbx_mesh, p_mesh, scene->meshes) {
24959 ufbx_mesh *mesh = *p_mesh;
24960 if (mesh->blend_deformers.count == 0 && mesh->skin_deformers.count == 0 && (mesh->cache_deformers.count == 0 || !load_caches)) continue;
24961 if (mesh->num_vertices == 0) continue;
24962
24963 size_t num_vertices = mesh->num_vertices;
24964 ufbx_vec3 *result_pos = ufbxi_push(buf_result, ufbx_vec3, num_vertices + 1);
24965 ufbxi_check_err(error, result_pos);
24966
24967 result_pos[0] = ufbx_zero_vec3;
24968 result_pos++;
24969
24970 bool cached_position = false, cached_normals = false;
24971 if (load_caches && mesh->cache_deformers.count > 0) {
24972 ufbxi_for_ptr_list(ufbx_cache_deformer, p_cache, mesh->cache_deformers) {
24973 ufbx_cache_channel *channel = (*p_cache)->external_channel;
24974 if (!channel) continue;
24975
24976 if ((channel->interpretation == UFBX_CACHE_INTERPRETATION_VERTEX_POSITION || channel->interpretation == UFBX_CACHE_INTERPRETATION_POINTS) && !cached_position) {
24977 size_t num_read = ufbx_sample_geometry_cache_vec3(channel, time, result_pos, num_vertices, cache_opts);
24978 if (num_read == num_vertices) {
24979 mesh->skinned_is_local = true;
24980 cached_position = true;
24981 }
24982 } else if (channel->interpretation == UFBX_CACHE_INTERPRETATION_VERTEX_NORMAL && !cached_normals) {
24983 // TODO: Is this right at all?
24984 size_t num_normals = mesh->skinned_normal.values.count;
24985 ufbx_vec3 *normal_data = ufbxi_push(buf_result, ufbx_vec3, num_normals + 1);
24986 ufbxi_check_err(error, normal_data);
24987 normal_data[0] = ufbx_zero_vec3;
24988 normal_data++;
24989
24990 size_t num_read = ufbx_sample_geometry_cache_vec3(channel, time, normal_data, num_normals, cache_opts);
24991 if (num_read == num_normals) {
24992 cached_normals = true;
24993 mesh->skinned_normal.values.data = normal_data;
24994 }
24995 }
24996 }
24997 }
24998
24999 if (!cached_position) {
25000 memcpy(result_pos, mesh->vertices.data, num_vertices * sizeof(ufbx_vec3));
25001
25002 ufbxi_for_ptr_list(ufbx_blend_deformer, p_blend, mesh->blend_deformers) {
25003 ufbx_add_blend_vertex_offsets(*p_blend, result_pos, num_vertices, 1.0f);
25004 }
25005
25006 // TODO: What should we do about multiple skins??
25007 if (mesh->skin_deformers.count > 0) {
25008 ufbx_matrix *fallback = mesh->instances.count > 0 ? &mesh->instances.data[0]->geometry_to_world : NULL;
25009 ufbx_skin_deformer *skin = mesh->skin_deformers.data[0];
25010 for (size_t i = 0; i < num_vertices; i++) {
25011 ufbx_matrix mat = ufbx_get_skin_vertex_matrix(skin, i, fallback);
25012 result_pos[i] = ufbx_transform_position(&mat, result_pos[i]);
25013 }
25014
25015 mesh->skinned_is_local = false;
25016 }
25017 }
25018
25019 mesh->skinned_position.values.data = result_pos;
25020
25021 if (!cached_normals) {
25022 size_t num_indices = mesh->num_indices;
25023 uint32_t *normal_indices = ufbxi_push(buf_result, uint32_t, num_indices);
25024 ufbxi_check_err(error, normal_indices);
25025
25026 ufbx_compute_topology(mesh, topo, num_indices);
25027 size_t num_normals = ufbx_generate_normal_mapping(mesh, topo, num_indices, normal_indices, num_indices, false);
25028
25029 if (num_normals == mesh->num_vertices) {
25030 mesh->skinned_normal.unique_per_vertex = true;
25031 }
25032
25033 ufbx_vec3 *normal_data = ufbxi_push(buf_result, ufbx_vec3, num_normals + 1);
25034 ufbxi_check_err(error, normal_data);
25035
25036 normal_data[0] = ufbx_zero_vec3;
25037 normal_data++;
25038
25039 ufbx_compute_normals(mesh, &mesh->skinned_position, normal_indices, num_indices, normal_data, num_normals);
25040
25041 mesh->generated_normals = true;
25042 mesh->skinned_normal.exists = true;
25043 mesh->skinned_normal.values.data = normal_data;
25044 mesh->skinned_normal.values.count = num_normals;
25045 mesh->skinned_normal.indices.data = normal_indices;
25046 mesh->skinned_normal.indices.count = num_indices;
25047 mesh->skinned_normal.value_reals = 3;
25048 }
25049 }
25050
25051 return 1;
25052 #else
25053 ufbxi_fmt_err_info(error, "UFBX_ENABLE_SKINNING_EVALUATION");
25054 ufbxi_report_err_msg(error, "UFBXI_FEATURE_SKINNING_EVALUATION", "Feature disabled");
25055 return 0;
25056 #endif
25057 }
25058
25059 ufbxi_nodiscard static ufbxi_noinline int ufbxi_fixup_opts_string(ufbxi_context *uc, ufbx_string *str, bool push)
25060 {
25061 if (str->length > 0) {
25062 if (str->length == SIZE_MAX) {
25063 str->length = str->data ? strlen(str->data) : 0;
25064 }
25065 if (push) {
25066 ufbxi_check(ufbxi_push_string_place_str(&uc->string_pool, str, false));
25067 }
25068 } else {
25069 str->data = ufbxi_empty_char;
25070 }
25071
25072 return 1;
25073 }
25074
25075 ufbxi_nodiscard static ufbxi_noinline int ufbxi_resolve_warning_elements(ufbxi_context *uc)
25076 {
25077 size_t num_elements = uc->tmp_element_id.num_items;
25078 uint32_t *element_ids = ufbxi_push_pop(&uc->tmp, &uc->tmp_element_id, uint32_t, num_elements);
25079 ufbxi_check(element_ids);
25080
25081 ufbxi_for_list(ufbx_warning, warning, uc->scene.metadata.warnings) {
25082 uint32_t element_id = warning->element_id;
25083 // Decode `element_id`, see HACK(warning-element) in `ufbxi_vwarnf_imp()` for the encoding.
25084 if ((element_id & 0x80000000u) != 0 && element_id != ~0u) {
25085 warning->element_id = element_ids[element_id & ~0x80000000u];
25086 }
25087 }
25088
25089 return 1;
25090 }
25091
25092 ufbxi_nodiscard static ufbxi_noinline int ufbxi_load_imp(ufbxi_context *uc)
25093 {
25094 // Check for deferred failure
25095 if (uc->deferred_failure) return 0;
25096 if (uc->deferred_load) {
25097 ufbx_stream stream = { 0 };
25098 ufbx_open_file_opts opts = { 0 };
25099 const char *filename = uc->load_filename;
25100 size_t filename_len = uc->load_filename_len;
25101 bool ok = false;
25102 if (filename_len == SIZE_MAX) {
25103 opts.filename_null_terminated = true;
25104 filename_len = strlen(filename);
25105 }
25106 if (uc->opts.filename.length == 0 || uc->opts.filename.data == NULL) {
25107 uc->opts.filename.data = filename;
25108 uc->opts.filename.length = filename_len;
25109 }
25110 ufbx_error error;
25111 error.type = UFBX_ERROR_NONE;
25112 if (uc->opts.open_main_file_with_default || uc->opts.open_file_cb.fn == &ufbx_default_open_file) {
25113 ufbx_open_file_context ctx = (ufbx_open_file_context)&uc->ator_tmp;
25114 ok = ufbx_open_file_ctx(&stream, ctx, filename, filename_len, &opts, &error);
25115 } else {
25116 ok = ufbxi_open_file(&uc->opts.open_file_cb, &stream, uc->load_filename, filename_len, NULL, &uc->ator_tmp, UFBX_OPEN_FILE_MAIN_MODEL);
25117 }
25118 if (!ok) {
25119 if (error.type != UFBX_ERROR_NONE) {
25120 // cppcheck-suppress uninitStructMember
25121 uc->error = error;
25122 } else {
25123 ufbxi_set_err_info(&uc->error, filename, filename_len);
25124 }
25125 ufbxi_fail_msg("open_file_fn()", "File not found");
25126 }
25127 uc->read_fn = stream.read_fn;
25128 uc->skip_fn = stream.skip_fn;
25129 uc->size_fn = stream.size_fn;
25130 uc->close_fn = stream.close_fn;
25131 uc->read_user = stream.user;
25132 }
25133
25134 if (uc->opts.progress_cb.fn && uc->progress_bytes_total == 0 && uc->size_fn) {
25135 uint64_t total = uc->size_fn(uc->read_user);
25136 ufbxi_check(total != UINT64_MAX);
25137 uc->progress_bytes_total = total;
25138 }
25139
25140 ufbxi_check(uc->opts.path_separator >= 0x20 && uc->opts.path_separator <= 0x7e);
25141
25142 ufbxi_check(ufbxi_fixup_opts_string(uc, &uc->opts.filename, false));
25143 ufbxi_check(ufbxi_fixup_opts_string(uc, &uc->opts.obj_mtl_path, true));
25144 ufbxi_check(ufbxi_fixup_opts_string(uc, &uc->opts.geometry_transform_helper_name, true));
25145 ufbxi_check(ufbxi_fixup_opts_string(uc, &uc->opts.scale_helper_name, true));
25146
25147 ufbxi_check(ufbxi_thread_pool_init(&uc->thread_pool, &uc->error, &uc->ator_tmp, &uc->opts.thread_opts));
25148
25149 if (!uc->opts.allow_unsafe) {
25150 ufbxi_check_msg(uc->opts.index_error_handling != UFBX_INDEX_ERROR_HANDLING_UNSAFE_IGNORE, "Unsafe options");
25151 ufbxi_check_msg(uc->opts.unicode_error_handling != UFBX_UNICODE_ERROR_HANDLING_UNSAFE_IGNORE, "Unsafe options");
25152 } else {
25153 uc->scene.metadata.is_unsafe = true;
25154 }
25155
25156 if (uc->opts.index_error_handling == UFBX_INDEX_ERROR_HANDLING_NO_INDEX) {
25157 uc->scene.metadata.may_contain_no_index = true;
25158 }
25159
25160 uc->retain_mesh_parts = !uc->opts.ignore_geometry && !uc->opts.skip_mesh_parts;
25161 uc->scene.metadata.may_contain_missing_vertex_position = uc->opts.allow_missing_vertex_position;
25162 uc->scene.metadata.may_contain_broken_elements = uc->opts.connect_broken_elements;
25163
25164 uc->scene.metadata.creator.data = ufbxi_empty_char;
25165
25166 uc->unit_scale = 1.0f;
25167 if (uc->data == NULL) {
25168 ufbxi_dev_assert(uc->data_begin == NULL);
25169 uc->data_begin = uc->data = ufbxi_zero_size_buffer;
25170 }
25171
25172 uc->retain_vertex_w = (uc->opts.retain_dom || uc->opts.retain_vertex_attrib_w) && !uc->opts.ignore_geometry;
25173
25174 ufbxi_check(ufbxi_load_strings(uc));
25175 ufbxi_check(ufbxi_load_maps(uc));
25176 ufbxi_check(ufbxi_determine_format(uc));
25177
25178 ufbx_file_format format = uc->scene.metadata.file_format;
25179
25180 if (format == UFBX_FILE_FORMAT_FBX) {
25181 ufbxi_check(ufbxi_begin_parse(uc));
25182 if (uc->version < 6000) {
25183 ufbxi_check(ufbxi_read_legacy_root(uc));
25184 } else {
25185 ufbxi_check(ufbxi_read_root(uc));
25186 }
25187 if (!ufbxi_supports_version(uc->version)) {
25188 ufbxi_check(ufbxi_warnf(UFBX_WARNING_UNSUPPORTED_VERSION, "Unsupported FBX version (%u)", uc->version));
25189 }
25190 ufbxi_update_scene_metadata(&uc->scene.metadata);
25191 ufbxi_check(ufbxi_init_file_paths(uc));
25192 } else if (format == UFBX_FILE_FORMAT_OBJ) {
25193 ufbxi_check(ufbxi_obj_load(uc));
25194 ufbxi_update_scene_metadata(&uc->scene.metadata);
25195 } else if (format == UFBX_FILE_FORMAT_MTL) {
25196 ufbxi_check(ufbxi_mtl_load(uc));
25197 ufbxi_update_scene_metadata(&uc->scene.metadata);
25198 }
25199
25200 // Fake DOM root if necessary
25201 if (uc->opts.retain_dom && !uc->scene.dom_root) {
25202 ufbx_dom_node *dom_root = ufbxi_push_zero(&uc->result, ufbx_dom_node, 1);
25203 ufbxi_check(dom_root);
25204 dom_root->name.data = ufbxi_empty_char;
25205 uc->scene.dom_root = dom_root;
25206 }
25207
25208 ufbxi_check(ufbxi_pre_finalize_scene(uc));
25209
25210 // We can free `tmp_parse` already here as all parsing is done by now.
25211 ufbxi_buf_free(&uc->tmp_parse);
25212
25213 ufbxi_check(ufbxi_finalize_scene(uc));
25214
25215 ufbxi_update_scene_settings(&uc->scene.settings);
25216 if (uc->scene.metadata.file_format == UFBX_FILE_FORMAT_OBJ) {
25217 ufbxi_update_scene_settings_obj(uc);
25218 }
25219
25220 // Axis conversion
25221 if (ufbx_coordinate_axes_valid(uc->opts.target_axes)) {
25222 ufbxi_transform_to_axes(uc, uc->opts.target_axes);
25223 }
25224
25225 // Unit conversion
25226 if (uc->opts.target_unit_meters > 0.0f) {
25227 ufbxi_check(ufbxi_scale_units(uc, uc->opts.target_unit_meters));
25228 }
25229
25230 // TODO: This could be done in evaluate as well with refactoring
25231 ufbxi_update_adjust_transforms(uc, &uc->scene);
25232
25233 ufbxi_check(ufbxi_modify_geometry(uc));
25234 ufbxi_postprocess_scene(uc);
25235
25236 ufbxi_update_scene(&uc->scene, true, NULL, 0);
25237
25238 // Force a non-NULL anim pointer
25239 if (!uc->scene.anim) {
25240 uc->scene.anim = ufbxi_push_zero(&uc->result, ufbx_anim, 1);
25241 }
25242
25243 if (uc->opts.load_external_files) {
25244 ufbxi_check(ufbxi_load_external_files(uc));
25245 }
25246
25247 // Evaluate skinning if requested
25248 if (uc->opts.evaluate_skinning) {
25249 ufbx_geometry_cache_data_opts cache_opts = { 0 };
25250 cache_opts.open_file_cb = uc->opts.open_file_cb;
25251 ufbxi_check(ufbxi_evaluate_skinning(&uc->scene, &uc->error, &uc->result, &uc->tmp,
25252 0.0, uc->opts.load_external_files && uc->opts.evaluate_caches, &cache_opts));
25253 }
25254
25255 // Pop warnings to metadata
25256 ufbxi_check(ufbxi_pop_warnings(&uc->warnings, &uc->scene.metadata.warnings, uc->scene.metadata.has_warning));
25257 ufbxi_check(ufbxi_resolve_warning_elements(uc));
25258
25259 // Copy local data to the scene
25260 uc->scene.metadata.version = uc->version;
25261 uc->scene.metadata.ascii = uc->from_ascii;
25262 uc->scene.metadata.big_endian = uc->file_big_endian;
25263 uc->scene.metadata.geometry_ignored = uc->opts.ignore_geometry;
25264 uc->scene.metadata.animation_ignored = uc->opts.ignore_animation;
25265 uc->scene.metadata.embedded_ignored = uc->opts.ignore_embedded;
25266
25267 // Retain the scene, this must be the final allocation as we copy
25268 // `ator_result` to `ufbx_scene_imp`.
25269 ufbxi_scene_imp *imp = ufbxi_push(&uc->result, ufbxi_scene_imp, 1);
25270 ufbxi_check(imp);
25271
25272 ufbxi_init_ref(&imp->refcount, UFBXI_SCENE_IMP_MAGIC, NULL);
25273
25274 imp->magic = UFBXI_SCENE_IMP_MAGIC;
25275 imp->scene = uc->scene;
25276 imp->refcount.ator = uc->ator_result;
25277 imp->refcount.ator.error = NULL;
25278
25279 // Copy retained buffers and translate the allocator struct to the one
25280 // contained within `ufbxi_scene_imp`
25281 imp->refcount.buf = uc->result;
25282 imp->refcount.buf.ator = &imp->refcount.ator;
25283 imp->string_buf = uc->string_pool.buf;
25284 imp->string_buf.ator = &imp->refcount.ator;
25285
25286 imp->scene.metadata.result_memory_used = imp->refcount.ator.current_size;
25287 imp->scene.metadata.temp_memory_used = uc->ator_tmp.current_size;
25288 imp->scene.metadata.result_allocs = imp->refcount.ator.num_allocs;
25289 imp->scene.metadata.temp_allocs = uc->ator_tmp.num_allocs;
25290
25291 ufbxi_for_ptr_list(ufbx_element, p_elem, imp->scene.elements) {
25292 (*p_elem)->scene = &imp->scene;
25293 }
25294
25295 uc->scene_imp = imp;
25296
25297 return 1;
25298 }
25299
25300 static ufbxi_noinline void ufbxi_free_temp(ufbxi_context *uc)
25301 {
25302 ufbxi_thread_pool_free(&uc->thread_pool);
25303
25304 ufbxi_string_pool_temp_free(&uc->string_pool);
25305 ufbxi_buf_free(&uc->warnings.tmp_stack);
25306
25307 ufbxi_map_free(&uc->prop_type_map);
25308 ufbxi_map_free(&uc->fbx_id_map);
25309 ufbxi_map_free(&uc->ptr_fbx_id_map);
25310 ufbxi_map_free(&uc->texture_file_map);
25311 ufbxi_map_free(&uc->anim_stack_map);
25312 ufbxi_map_free(&uc->fbx_attr_map);
25313 ufbxi_map_free(&uc->node_prop_set);
25314 ufbxi_map_free(&uc->dom_node_map);
25315
25316 ufbxi_buf_free(&uc->tmp);
25317 ufbxi_buf_free(&uc->tmp_parse);
25318 for (size_t i = 0; i < UFBX_THREAD_GROUP_COUNT; i++) {
25319 ufbxi_buf_free(&uc->tmp_thread_parse[i]);
25320 }
25321 ufbxi_buf_free(&uc->tmp_stack);
25322 ufbxi_buf_free(&uc->tmp_connections);
25323 ufbxi_buf_free(&uc->tmp_node_ids);
25324 ufbxi_buf_free(&uc->tmp_elements);
25325 ufbxi_buf_free(&uc->tmp_element_offsets);
25326 ufbxi_buf_free(&uc->tmp_element_fbx_ids);
25327 ufbxi_buf_free(&uc->tmp_element_ptrs);
25328 for (size_t i = 0; i < UFBX_ELEMENT_TYPE_COUNT; i++) {
25329 ufbxi_buf_free(&uc->tmp_typed_element_offsets[i]);
25330 }
25331 ufbxi_buf_free(&uc->tmp_mesh_textures);
25332 ufbxi_buf_free(&uc->tmp_full_weights);
25333 ufbxi_buf_free(&uc->tmp_dom_nodes);
25334 ufbxi_buf_free(&uc->tmp_element_id);
25335 ufbxi_buf_free(&uc->tmp_ascii_spans);
25336
25337 ufbxi_free(&uc->ator_tmp, ufbxi_node, uc->top_nodes, uc->top_nodes_cap);
25338 ufbxi_free(&uc->ator_tmp, void*, uc->element_extra_arr, uc->element_extra_cap);
25339
25340 ufbxi_free(&uc->ator_tmp, char, uc->ascii.token.str_data, uc->ascii.token.str_cap);
25341 ufbxi_free(&uc->ator_tmp, char, uc->ascii.prev_token.str_data, uc->ascii.prev_token.str_cap);
25342
25343 ufbxi_free(&uc->ator_tmp, char, uc->read_buffer, uc->read_buffer_size);
25344 ufbxi_free(&uc->ator_tmp, char, uc->tmp_arr, uc->tmp_arr_size);
25345 ufbxi_free(&uc->ator_tmp, char, uc->swap_arr, uc->swap_arr_size);
25346
25347 ufbxi_obj_free(uc);
25348
25349 ufbxi_free_ator(&uc->ator_tmp);
25350 }
25351
25352 static ufbxi_noinline void ufbxi_free_result(ufbxi_context *uc)
25353 {
25354 ufbxi_buf_free(&uc->result);
25355 ufbxi_buf_free(&uc->string_pool.buf);
25356
25357 ufbxi_free_ator(&uc->ator_result);
25358 }
25359
25360 static ufbxi_noinline ufbx_scene *ufbxi_load(ufbxi_context *uc, const ufbx_load_opts *user_opts, ufbx_error *p_error)
25361 {
25362 // Test endianness
25363 {
25364 uint8_t buf[2];
25365 uint16_t val = 0xbbaa;
25366 memcpy(buf, &val, 2);
25367 uc->local_big_endian = buf[0] == 0xbb;
25368 }
25369
25370 uc->double_parse_flags = ufbxi_parse_double_init_flags();
25371
25372 if (user_opts) {
25373 uc->opts = *user_opts;
25374 } else {
25375 memset(&uc->opts, 0, sizeof(uc->opts));
25376 }
25377
25378 if (uc->opts.file_size_estimate) {
25379 uc->progress_bytes_total = uc->opts.file_size_estimate;
25380 }
25381
25382 if (uc->opts.ignore_all_content) {
25383 uc->opts.ignore_geometry = true;
25384 uc->opts.ignore_animation = true;
25385 uc->opts.ignore_embedded = true;
25386 }
25387
25388 ufbx_inflate_retain inflate_retain;
25389 inflate_retain.initialized = false;
25390
25391 ufbxi_init_ator(&uc->error, &uc->ator_tmp, &uc->opts.temp_allocator, "temp");
25392 ufbxi_init_ator(&uc->error, &uc->ator_result, &uc->opts.result_allocator, "result");
25393
25394 if (uc->opts.read_buffer_size == 0) {
25395 uc->opts.read_buffer_size = 0x4000;
25396 }
25397 if (uc->opts.read_buffer_size <= 32) {
25398 uc->opts.read_buffer_size = 32;
25399 }
25400
25401 if (uc->opts.file_format_lookahead == 0) {
25402 uc->opts.file_format_lookahead = 0x4000;
25403 } else if (uc->opts.file_format_lookahead < UFBXI_MIN_FILE_FORMAT_LOOKAHEAD) {
25404 uc->opts.file_format_lookahead = UFBXI_MIN_FILE_FORMAT_LOOKAHEAD;
25405 }
25406
25407 if (!uc->opts.path_separator) {
25408 uc->opts.path_separator = UFBX_PATH_SEPARATOR;
25409 }
25410
25411 if (!uc->opts.progress_cb.fn || uc->opts.progress_interval_hint >= SIZE_MAX) {
25412 uc->progress_interval = SIZE_MAX;
25413 } else if (uc->opts.progress_interval_hint > 0) {
25414 uc->progress_interval = (size_t)uc->opts.progress_interval_hint;
25415 } else {
25416 uc->progress_interval = 0x4000;
25417 }
25418
25419 if (!uc->opts.open_file_cb.fn) {
25420 uc->opts.open_file_cb.fn = &ufbx_default_open_file;
25421 }
25422
25423 if (!uc->opts.thread_opts.memory_limit) {
25424 uc->opts.thread_opts.memory_limit = 32*1024*1024;
25425 }
25426
25427 uc->synthetic_id_counter = UFBXI_SYNTHETIC_ID_START;
25428
25429 uc->string_pool.error = &uc->error;
25430 ufbxi_map_init(&uc->string_pool.map, &uc->ator_tmp, &ufbxi_map_cmp_string, NULL);
25431 uc->string_pool.buf.ator = &uc->ator_result;
25432 uc->string_pool.buf.unordered = true;
25433 uc->string_pool.initial_size = 1024;
25434 uc->string_pool.error_handling = uc->opts.unicode_error_handling;
25435
25436 ufbxi_map_init(&uc->prop_type_map, &uc->ator_tmp, &ufbxi_map_cmp_const_char_ptr, NULL);
25437 ufbxi_map_init(&uc->fbx_id_map, &uc->ator_tmp, &ufbxi_map_cmp_uint64, NULL);
25438 ufbxi_map_init(&uc->ptr_fbx_id_map, &uc->ator_tmp, &ufbxi_map_cmp_ptr_id, NULL);
25439 ufbxi_map_init(&uc->texture_file_map, &uc->ator_tmp, &ufbxi_map_cmp_const_char_ptr, NULL);
25440 ufbxi_map_init(&uc->anim_stack_map, &uc->ator_tmp, &ufbxi_map_cmp_const_char_ptr, NULL);
25441 ufbxi_map_init(&uc->fbx_attr_map, &uc->ator_tmp, &ufbxi_map_cmp_uint64, NULL);
25442 ufbxi_map_init(&uc->node_prop_set, &uc->ator_tmp, &ufbxi_map_cmp_const_char_ptr, NULL);
25443 ufbxi_map_init(&uc->dom_node_map, &uc->ator_tmp, &ufbxi_map_cmp_uintptr, NULL);
25444
25445 uc->tmp.ator = &uc->ator_tmp;
25446 uc->tmp_parse.ator = &uc->ator_tmp;
25447 uc->tmp_stack.ator = &uc->ator_tmp;
25448 uc->tmp_connections.ator = &uc->ator_tmp;
25449 uc->tmp_node_ids.ator = &uc->ator_tmp;
25450 uc->tmp_elements.ator = &uc->ator_tmp;
25451 uc->tmp_element_offsets.ator = &uc->ator_tmp;
25452 uc->tmp_element_fbx_ids.ator = &uc->ator_tmp;
25453 uc->tmp_element_ptrs.ator = &uc->ator_tmp;
25454 for (size_t i = 0; i < UFBX_ELEMENT_TYPE_COUNT; i++) {
25455 uc->tmp_typed_element_offsets[i].ator = &uc->ator_tmp;
25456 }
25457 uc->tmp_mesh_textures.ator = &uc->ator_tmp;
25458 uc->tmp_full_weights.ator = &uc->ator_tmp;
25459 uc->tmp_dom_nodes.ator = &uc->ator_tmp;
25460 uc->tmp_element_id.ator = &uc->ator_tmp;
25461 uc->tmp_ascii_spans.ator = &uc->ator_tmp;
25462
25463 for (size_t i = 0; i < UFBX_THREAD_GROUP_COUNT; i++) {
25464 uc->tmp_thread_parse[i].ator = &uc->ator_tmp;
25465 uc->tmp_thread_parse[i].unordered = true;
25466 uc->tmp_thread_parse[i].clearable = true;
25467 }
25468
25469 uc->result.ator = &uc->ator_result;
25470
25471 uc->tmp.unordered = true;
25472 uc->tmp_parse.unordered = true;
25473 uc->tmp_parse.clearable = true;
25474 uc->result.unordered = true;
25475
25476 uc->warnings.error = &uc->error;
25477 uc->warnings.result = &uc->result;
25478 uc->warnings.tmp_stack.ator = &uc->ator_tmp;
25479 uc->string_pool.warnings = &uc->warnings;
25480
25481 // Set zero size `swap_arr` to a non-NULL buffer so we can tell the difference between empty
25482 // array and an allocation failure.
25483 uc->swap_arr = (char*)ufbxi_zero_size_buffer;
25484
25485 // NOTE: Though `inflate_retain` leaks out of the scope we don't use it outside this function.
25486 // cppcheck-suppress autoVariables
25487 uc->inflate_retain = &inflate_retain;
25488
25489 int ok = ufbxi_load_imp(uc);
25490
25491 if (uc->close_fn) {
25492 uc->close_fn(uc->read_user);
25493 }
25494
25495 ufbxi_free_temp(uc);
25496
25497 if (ok) {
25498 if (p_error) {
25499 ufbxi_clear_error(p_error);
25500 }
25501 return &uc->scene_imp->scene;
25502 } else {
25503 ufbxi_fix_error_type(&uc->error, "Failed to load", p_error);
25504 if (p_error && p_error->type == UFBX_ERROR_UNKNOWN && uc->scene.metadata.file_format == UFBX_FILE_FORMAT_FBX && !ufbxi_supports_version(uc->version)) {
25505 p_error->description.data = "Unsupported version";
25506 p_error->description.length = strlen("Unsupported version");
25507 p_error->type = UFBX_ERROR_UNSUPPORTED_VERSION;
25508 ufbxi_fmt_err_info(p_error, "%u", uc->version);
25509 }
25510 ufbxi_free_result(uc);
25511 return NULL;
25512 }
25513 }
25514
25515 // -- Animation evaluation
25516
25517 static ufbxi_forceinline bool ufbxi_override_less_than_prop(const ufbx_prop_override *over, uint32_t element_id, const ufbx_prop *prop)
25518 {
25519 if (over->element_id != element_id) return over->element_id < element_id;
25520 if (over->_internal_key != prop->_internal_key) return over->_internal_key < prop->_internal_key;
25521 return strcmp(over->prop_name.data, prop->name.data);
25522 }
25523
25524 static ufbxi_forceinline bool ufbxi_override_equals_to_prop(const ufbx_prop_override *over, uint32_t element_id, const ufbx_prop *prop)
25525 {
25526 if (over->element_id != element_id) return false;
25527 if (over->_internal_key != prop->_internal_key) return false;
25528 return !strcmp(over->prop_name.data, prop->name.data);
25529 }
25530
25531 static ufbxi_noinline bool ufbxi_find_prop_override(const ufbx_prop_override_list *overrides, uint32_t element_id, ufbx_prop *prop)
25532 {
25533 size_t ix = SIZE_MAX;
25534 ufbxi_macro_lower_bound_eq(ufbx_prop_override, 16, &ix, overrides->data, 0, overrides->count,
25535 ( ufbxi_override_less_than_prop(a, element_id, prop) ),
25536 ( ufbxi_override_equals_to_prop(a, element_id, prop) ));
25537
25538 if (ix != SIZE_MAX) {
25539 const ufbx_prop_override *over = &overrides->data[ix];
25540 const uint32_t clear_flags = UFBX_PROP_FLAG_NO_VALUE | UFBX_PROP_FLAG_NOT_FOUND;
25541 prop->flags = (ufbx_prop_flags)(((uint32_t)prop->flags & ~clear_flags) | UFBX_PROP_FLAG_OVERRIDDEN);
25542 prop->value_vec4 = over->value;
25543 prop->value_real_arr[3] = 0.0f;
25544 prop->value_int = over->value_int;
25545 prop->value_str = over->value_str;
25546 prop->value_blob.data = prop->value_str.data;
25547 prop->value_blob.size = prop->value_str.length;
25548 return true;
25549 } else {
25550 return false;
25551 }
25552 }
25553
25554 static ufbxi_noinline ufbx_prop_override_list ufbxi_find_element_prop_overrides(const ufbx_prop_override_list *overrides, uint32_t element_id)
25555 {
25556 size_t begin = overrides->count, end = begin;
25557
25558 ufbxi_macro_lower_bound_eq(ufbx_prop_override, 32, &begin, overrides->data, 0, overrides->count,
25559 (a->element_id < element_id),
25560 (a->element_id == element_id));
25561
25562 ufbxi_macro_upper_bound_eq(ufbx_prop_override, 32, &end, overrides->data, begin, overrides->count,
25563 (a->element_id == element_id));
25564
25565 ufbx_prop_override_list result = { overrides->data + begin, end - begin };
25566 return result;
25567 }
25568
25569 typedef struct ufbxi_anim_layer_combine_ctx {
25570 const ufbx_anim *anim;
25571 const ufbx_element *element;
25572 double time;
25573 ufbx_rotation_order rotation_order;
25574 bool has_rotation_order;
25575 } ufbxi_anim_layer_combine_ctx;
25576
25577 static ufbxi_noinline double ufbxi_pow_abs(double v, double e)
25578 {
25579 if (e <= 0.0) return 1.0;
25580 if (e >= 1.0) return v;
25581 double sign = v < 0.0 ? -1.0 : 1.0;
25582 return sign * ufbx_pow(v * sign, e);
25583 }
25584
25585 // Recursion is limited by the fact that we recurse only when the property name is "Lcl Rotation"
25586 // and when recursing we always evaluate the property "RotationOrder"
25587 static ufbxi_noinline void ufbxi_combine_anim_layer(ufbxi_anim_layer_combine_ctx *ctx, ufbx_anim_layer *layer, ufbx_real weight, const char *prop_name, ufbx_vec3 *result, const ufbx_vec3 *value)
25588 ufbxi_recursive_function_void(ufbxi_combine_anim_layer, (ctx, layer, weight, prop_name, result, value), 2,
25589 (ufbxi_anim_layer_combine_ctx *ctx, ufbx_anim_layer *layer, ufbx_real weight, const char *prop_name, ufbx_vec3 *result, const ufbx_vec3 *value))
25590 {
25591 if (layer->compose_rotation && layer->blended && prop_name == ufbxi_Lcl_Rotation && !ctx->has_rotation_order) {
25592 ufbx_prop rp = ufbx_evaluate_prop_len(ctx->anim, ctx->element, ufbxi_RotationOrder, sizeof(ufbxi_RotationOrder) - 1, ctx->time);
25593 // NOTE: Defaults to 0 (UFBX_ROTATION_XYZ) gracefully if property is not found
25594 if (rp.value_int >= 0 && rp.value_int <= UFBX_ROTATION_ORDER_SPHERIC) {
25595 ctx->rotation_order = (ufbx_rotation_order)rp.value_int;
25596 } else {
25597 ctx->rotation_order = UFBX_ROTATION_ORDER_XYZ;
25598 }
25599 ctx->has_rotation_order = true;
25600 }
25601
25602 if (layer->additive) {
25603 if (layer->compose_scale && prop_name == ufbxi_Lcl_Scaling) {
25604 result->x *= (ufbx_real)ufbxi_pow_abs(value->x, weight);
25605 result->y *= (ufbx_real)ufbxi_pow_abs(value->y, weight);
25606 result->z *= (ufbx_real)ufbxi_pow_abs(value->z, weight);
25607 } else if (layer->compose_rotation && prop_name == ufbxi_Lcl_Rotation) {
25608 ufbx_quat a = ufbx_euler_to_quat(*result, ctx->rotation_order);
25609 ufbx_quat b = ufbx_euler_to_quat(*value, ctx->rotation_order);
25610 b = ufbx_quat_slerp(ufbx_identity_quat, b, weight);
25611 ufbx_quat res = ufbxi_mul_quat(a, b);
25612 *result = ufbx_quat_to_euler(res, ctx->rotation_order);
25613 } else {
25614 result->x += value->x * weight;
25615 result->y += value->y * weight;
25616 result->z += value->z * weight;
25617 }
25618 } else if (layer->blended) {
25619 ufbx_real res_weight = 1.0f - weight;
25620 if (layer->compose_scale && prop_name == ufbxi_Lcl_Scaling) {
25621 result->x = (ufbx_real)(ufbxi_pow_abs(result->x, res_weight) * ufbxi_pow_abs(value->x, weight));
25622 result->y = (ufbx_real)(ufbxi_pow_abs(result->y, res_weight) * ufbxi_pow_abs(value->y, weight));
25623 result->z = (ufbx_real)(ufbxi_pow_abs(result->z, res_weight) * ufbxi_pow_abs(value->z, weight));
25624 } else if (layer->compose_rotation && prop_name == ufbxi_Lcl_Rotation) {
25625 ufbx_quat a = ufbx_euler_to_quat(*result, ctx->rotation_order);
25626 ufbx_quat b = ufbx_euler_to_quat(*value, ctx->rotation_order);
25627 ufbx_quat res = ufbx_quat_slerp(a, b, weight);
25628 *result = ufbx_quat_to_euler(res, ctx->rotation_order);
25629 } else {
25630 result->x = result->x * res_weight + value->x * weight;
25631 result->y = result->y * res_weight + value->y * weight;
25632 result->z = result->z * res_weight + value->z * weight;
25633 }
25634 } else {
25635 *result = *value;
25636 }
25637 }
25638
25639 static ufbxi_forceinline bool ufbxi_anim_layer_might_contain_id(const ufbx_anim_layer *layer, uint32_t id)
25640 {
25641 uint32_t id_mask = ufbxi_arraycount(layer->_element_id_bitmask) - 1;
25642 bool ok = id - layer->_min_element_id <= (layer->_max_element_id - layer->_min_element_id);
25643 ok &= (layer->_element_id_bitmask[(id >> 5) & id_mask] & (1u << (id & 31))) != 0;
25644 return ok;
25645 }
25646
25647 static ufbxi_noinline void ufbxi_evaluate_props(const ufbx_anim *anim, const ufbx_element *element, double time, ufbx_prop *props, size_t num_props, uint32_t flags)
25648 {
25649 ufbxi_anim_layer_combine_ctx combine_ctx = { anim, element, time };
25650
25651 uint32_t element_id = element->element_id;
25652 size_t num_layers = anim->layers.count;
25653 for (size_t layer_ix = 0; layer_ix < num_layers; layer_ix++) {
25654 ufbx_anim_layer *layer = anim->layers.data[layer_ix];
25655 if (!ufbxi_anim_layer_might_contain_id(layer, element_id)) continue;
25656
25657 // Find the weight for the current layer
25658 // TODO: Should this be searched from multiple layers?
25659 ufbx_real weight = layer_ix < anim->override_layer_weights.count ? anim->override_layer_weights.data[layer_ix] : layer->weight;
25660 if (layer->weight_is_animated && layer->blended) {
25661 ufbx_anim_prop *weight_aprop = ufbxi_find_anim_prop_start(layer, &layer->element);
25662 if (weight_aprop) {
25663 weight = ufbx_evaluate_anim_value_real_flags(weight_aprop->anim_value, time, flags) / (ufbx_real)100.0;
25664 if (weight < 0.0f) weight = 0.0f;
25665 if (weight > 0.99999f) weight = 1.0f;
25666 }
25667 }
25668
25669 ufbx_anim_prop *aprop = ufbxi_find_anim_prop_start(layer, element);
25670 if (!aprop) continue;
25671
25672 for (size_t i = 0; i < num_props; i++) {
25673 ufbx_prop *prop = &props[i];
25674
25675 // Don't evaluate on top of overridden properties
25676 if ((prop->flags & UFBX_PROP_FLAG_OVERRIDDEN) != 0) continue;
25677
25678 // Connections override animation by default
25679 if ((prop->flags & UFBX_PROP_FLAG_CONNECTED) != 0 && !anim->ignore_connections) continue;
25680
25681 // Skip until we reach `aprop >= prop`
25682 // NOTE: No need to check for end as `anim_props` is terminated with a NULL sentinel.
25683 while (aprop->element == element && aprop->_internal_key < prop->_internal_key) aprop++;
25684 if (aprop->prop_name.data != prop->name.data) {
25685 while (aprop->element == element && strcmp(aprop->prop_name.data, prop->name.data) < 0) aprop++;
25686 }
25687
25688 // TODO: Should we skip the blending for the first layer _per property_
25689 // This could be done by having `UFBX_PROP_FLAG_ANIMATION_EVALUATED`
25690 // that gets set for the first layer of animation that is applied.
25691 if (aprop->prop_name.data == prop->name.data) {
25692 ufbx_vec3 v = ufbx_evaluate_anim_value_vec3_flags(aprop->anim_value, time, flags);
25693 if (layer_ix == 0) {
25694 prop->value_vec3 = v;
25695 } else {
25696 ufbxi_combine_anim_layer(&combine_ctx, layer, weight, prop->name.data, &prop->value_vec3, &v);
25697 }
25698 }
25699 }
25700 }
25701
25702 ufbxi_for(ufbx_prop, prop, props, num_props) {
25703 if (prop->flags & UFBX_PROP_FLAG_OVERRIDDEN) continue;
25704 prop->value_int = ufbxi_f64_to_i64(prop->value_real);
25705 }
25706 }
25707
25708 // Recursion limited by not calling `ufbx_evaluate_prop_len()` with a connected property,
25709 // meaning it will never call `ufbxi_evaluate_connected_prop()` again indirectly.
25710 static ufbxi_noinline void ufbxi_evaluate_connected_prop(ufbx_prop *prop, const ufbx_anim *anim, const ufbx_element *element, const char *name, double time, uint32_t flags)
25711 ufbxi_recursive_function_void(ufbxi_evaluate_connected_prop, (prop, anim, element, name, time, flags), 3,
25712 (ufbx_prop *prop, const ufbx_anim *anim, const ufbx_element *element, const char *name, double time, uint32_t flags))
25713 {
25714 ufbx_connection *conn = ufbxi_find_prop_connection(element, name);
25715
25716 for (size_t i = 0; i < 1000 && conn; i++) {
25717 ufbx_connection *next_conn = ufbxi_find_prop_connection(conn->src, conn->src_prop.data);
25718 if (!next_conn) break;
25719 conn = next_conn;
25720 }
25721
25722 // Found a non-cyclic connection
25723 if (conn && !ufbxi_find_prop_connection(conn->src, conn->src_prop.data)) {
25724 ufbx_prop ep = ufbx_evaluate_prop_len_flags(anim, conn->src, conn->src_prop.data, conn->src_prop.length, time, flags);
25725 prop->value_vec4 = ep.value_vec4;
25726 prop->value_int = ep.value_int;
25727 prop->value_str = ep.value_str;
25728 prop->value_blob = ep.value_blob;
25729 } else {
25730 // Connection not found, maybe it's animated?
25731 prop->flags = (ufbx_prop_flags)((uint32_t)prop->flags & ~(uint32_t)UFBX_PROP_FLAG_CONNECTED);
25732 }
25733 }
25734
25735 typedef struct {
25736 const ufbx_prop *prop, *prop_end;
25737 const ufbx_prop_override *over, *over_end;
25738 ufbx_prop tmp;
25739 } ufbxi_prop_iter;
25740
25741 static ufbxi_noinline void ufbxi_init_prop_iter_slow(ufbxi_prop_iter *iter, const ufbx_anim *anim, const ufbx_element *element)
25742 {
25743 iter->prop = element->props.props.data;
25744 iter->prop_end = element->props.props.data + element->props.props.count;
25745
25746 ufbx_prop_override_list over = ufbxi_find_element_prop_overrides(&anim->prop_overrides, element->element_id);
25747 iter->over = over.data;
25748 iter->over_end = over.data + over.count;
25749 if (over.count > 0) {
25750 memset(&iter->tmp, 0, sizeof(ufbx_prop));
25751 }
25752 }
25753
25754 static ufbxi_forceinline void ufbxi_init_prop_iter(ufbxi_prop_iter *iter, const ufbx_anim *anim, const ufbx_element *element)
25755 {
25756 iter->prop = element->props.props.data;
25757 iter->prop_end = ufbxi_add_ptr(element->props.props.data, element->props.props.count);
25758 iter->over = iter->over_end = NULL;
25759 if (anim->prop_overrides.count > 0) {
25760 ufbxi_init_prop_iter_slow(iter, anim, element);
25761 }
25762 }
25763
25764 static ufbxi_noinline const ufbx_prop *ufbxi_next_prop_slow(ufbxi_prop_iter *iter)
25765 {
25766 const ufbx_prop *prop = iter->prop;
25767 const ufbx_prop_override *over = iter->over;
25768 if (prop == iter->prop_end && over == iter->over_end) return NULL;
25769
25770 // We can use `UINT32_MAX` as a terminating key (aka prefix) as prop names must
25771 // be valid UTF-8 and the byte sequence "\xff\xff\xff\xff" is not valid.
25772 uint32_t prop_key = prop != iter->prop_end ? prop->_internal_key : UINT32_MAX;
25773 uint32_t over_key = over != iter->over_end ? over->_internal_key : UINT32_MAX;
25774
25775 int cmp = 0;
25776 if (prop_key != over_key) {
25777 cmp = prop_key < over_key ? -1 : 1;
25778 } else {
25779 cmp = strcmp(prop->name.data, over->prop_name.data);
25780 }
25781
25782 if (cmp >= 0) {
25783 ufbx_prop *dst = &iter->tmp;
25784 dst->name = over->prop_name;
25785 dst->_internal_key = over->_internal_key;
25786 dst->type = UFBX_PROP_UNKNOWN;
25787 dst->flags = UFBX_PROP_FLAG_OVERRIDDEN;
25788 dst->value_str = over->value_str;
25789 dst->value_blob.data = dst->value_str.data;
25790 dst->value_blob.size = dst->value_str.length;
25791 dst->value_int = over->value_int;
25792 dst->value_vec4 = over->value;
25793 iter->over = over + 1;
25794 if (cmp == 0) {
25795 iter->prop = prop + 1;
25796 }
25797 return dst;
25798 } else {
25799 iter->prop = prop + 1;
25800 return prop;
25801 }
25802 }
25803
25804 static ufbxi_forceinline const ufbx_prop *ufbxi_next_prop(ufbxi_prop_iter *iter)
25805 {
25806 if (iter->over == iter->over_end) {
25807 if (iter->prop == iter->prop_end) return NULL;
25808 return iter->prop++;
25809 } else {
25810 return ufbxi_next_prop_slow(iter);
25811 }
25812 }
25813
25814 static ufbxi_noinline ufbx_props ufbxi_evaluate_selected_props(const ufbx_anim *anim, const ufbx_element *element, double time, ufbx_prop *props, const char *const *prop_names, size_t max_props, uint32_t flags)
25815 {
25816 const char *name = prop_names[0];
25817 uint32_t key = ufbxi_get_name_key_c(name);
25818 size_t num_props = 0;
25819
25820 #if defined(UFBX_REGRESSION)
25821 for (size_t i = 1; i < max_props; i++) {
25822 ufbx_assert(strcmp(prop_names[i - 1], prop_names[i]) < 0);
25823 }
25824 #endif
25825
25826 size_t name_ix = 0;
25827
25828 ufbxi_prop_iter iter; // ufbxi_uninit
25829 ufbxi_init_prop_iter(&iter, anim, element);
25830 const ufbx_prop *prop = NULL;
25831 while ((prop = ufbxi_next_prop(&iter)) != NULL) {
25832 while (name_ix < max_props) {
25833 if (key > prop->_internal_key) break;
25834 if (name == prop->name.data) {
25835 if ((prop->flags & UFBX_PROP_FLAG_CONNECTED) != 0 && !anim->ignore_connections) {
25836 ufbx_prop *dst = &props[num_props++];
25837 *dst = *prop;
25838 ufbxi_evaluate_connected_prop(dst, anim, element, name, time, flags);
25839 } else if ((prop->flags & (UFBX_PROP_FLAG_ANIMATED|UFBX_PROP_FLAG_OVERRIDDEN)) != 0) {
25840 props[num_props++] = *prop;
25841 }
25842 break;
25843 } else if (strcmp(name, prop->name.data) < 0) {
25844 name_ix++;
25845 if (name_ix < max_props) {
25846 name = prop_names[name_ix];
25847 key = ufbxi_get_name_key_c(name);
25848 }
25849 } else {
25850 break;
25851 }
25852 }
25853 }
25854
25855 ufbxi_evaluate_props(anim, element, time, props, num_props, flags);
25856
25857 ufbx_props prop_list;
25858 prop_list.props.data = props;
25859 prop_list.props.count = prop_list.num_animated = num_props;
25860 prop_list.defaults = (ufbx_props*)&element->props;
25861 return prop_list;
25862 }
25863
25864 // Recursion limited by not calling `ufbx_evaluate_curve()` with `UFBX_EVALUATE_FLAG_NO_EXTRAPOLATION`.
25865 static ufbxi_noinline ufbx_real ufbxi_extrapolate_curve(const ufbx_anim_curve *curve, double real_time, uint32_t flags)
25866 ufbxi_recursive_function(ufbx_real, ufbxi_extrapolate_curve, (curve, real_time, flags), 3,
25867 (const ufbx_anim_curve *curve, double real_time, uint32_t flags))
25868 {
25869 bool pre = real_time < curve->min_time;
25870 const ufbx_keyframe *key;
25871 ufbx_extrapolation ext;
25872 if (pre) {
25873 key = &curve->keyframes.data[0];
25874 ext = curve->pre_extrapolation;
25875 } else {
25876 key = &curve->keyframes.data[curve->keyframes.count - 1];
25877 ext = curve->post_extrapolation;
25878 }
25879
25880 if (ext.mode == UFBX_EXTRAPOLATION_CONSTANT) {
25881 return key->value;
25882 } else if (ext.mode == UFBX_EXTRAPOLATION_SLOPE) {
25883 ufbx_tangent tangent = *(pre ? &key->right : &key->left);
25884 return key->value + (ufbx_real)(tangent.dy * ((real_time - key->time) / tangent.dx));
25885 } else if (ext.repeat_count == 0) {
25886 return key->value;
25887 }
25888
25889 // Perform all operations in KTime ticks to be frame perfect
25890 double scale = (double)curve->element.scene->metadata.ktime_second;
25891 double min_time = ufbx_rint(curve->min_time * scale);
25892 double max_time = ufbx_rint(curve->max_time * scale);
25893 double time = real_time * scale;
25894
25895 double delta = pre ? min_time - time : time - max_time;
25896 double duration = max_time - min_time;
25897
25898 // Require at least one KTime unit
25899 if (!(duration >= 1.0)) return key->value;
25900
25901 double rep = delta / duration;
25902 double rep_n = ufbx_floor(rep);
25903 double rep_d = delta - rep_n * duration;
25904
25905 if (ext.repeat_count > 0 && rep_n >= (double)ext.repeat_count) {
25906 // Clamp to the repeat count to handle mirroring
25907 rep_n = (double)(ext.repeat_count - 1);
25908 rep_d = duration;
25909 }
25910
25911 if (ext.mode == UFBX_EXTRAPOLATION_MIRROR) {
25912 double rep_parity = rep_n*0.5 - ufbx_floor(rep_n*0.5);
25913 if (rep_parity <= 0.25) {
25914 rep_d = duration - rep_d;
25915 }
25916 }
25917
25918 if (pre) rep_d = duration - rep_d;
25919 double new_time = (min_time + rep_d) / scale;
25920
25921 ufbx_real value = ufbx_evaluate_curve_flags(curve, new_time, key->value, flags | UFBX_EVALUATE_FLAG_NO_EXTRAPOLATION);
25922
25923 if (ext.mode == UFBX_EXTRAPOLATION_REPEAT_RELATIVE) {
25924 ufbx_real val_delta = curve->keyframes.data[curve->keyframes.count - 1].value - curve->keyframes.data[0].value;
25925 if (pre) val_delta = -val_delta;
25926 value += val_delta * (ufbx_real)(rep_n + 1.0);
25927 }
25928
25929 return value;
25930 }
25931
25932 #if UFBXI_FEATURE_SCENE_EVALUATION
25933
25934 typedef struct {
25935 char *src_element;
25936 char *dst_element;
25937
25938 ufbxi_scene_imp *src_imp;
25939 ufbx_scene src_scene;
25940 ufbx_evaluate_opts opts;
25941 ufbx_anim *anim;
25942 double time;
25943
25944 ufbx_error error;
25945
25946 // Allocators
25947 ufbxi_allocator ator_result;
25948 ufbxi_allocator ator_tmp;
25949
25950 ufbxi_buf result;
25951 ufbxi_buf tmp;
25952
25953 ufbx_scene scene;
25954
25955 ufbxi_scene_imp *scene_imp;
25956 } ufbxi_eval_context;
25957
25958 static ufbxi_forceinline ufbx_element *ufbxi_translate_element(ufbxi_eval_context *ec, void *elem)
25959 {
25960 return elem ? (ufbx_element*)(ec->dst_element + ((char*)elem - ec->src_element)) : NULL;
25961 }
25962
25963 ufbxi_nodiscard static ufbxi_noinline int ufbxi_translate_element_list(ufbxi_eval_context *ec, void *p_list)
25964 {
25965 ufbx_element_list *list = (ufbx_element_list*)p_list;
25966 size_t count = list->count;
25967 ufbx_element **src = list->data;
25968 ufbx_element **dst = ufbxi_push(&ec->result, ufbx_element*, count);
25969 ufbxi_check_err(&ec->error, dst);
25970 list->data = dst;
25971 for (size_t i = 0; i < count; i++) {
25972 dst[i] = ufbxi_translate_element(ec, src[i]);
25973 }
25974 return 1;
25975 }
25976
25977 static ufbxi_noinline void ufbxi_translate_maps(ufbxi_eval_context *ec, ufbx_material_map *maps, size_t count)
25978 {
25979 ufbxi_nounroll ufbxi_for(ufbx_material_map, map, maps, count) {
25980 map->texture = (ufbx_texture*)ufbxi_translate_element(ec, map->texture);
25981 }
25982 }
25983
25984 ufbxi_nodiscard static ufbxi_noinline int ufbxi_translate_anim(ufbxi_eval_context *ec, ufbx_anim **p_anim)
25985 {
25986 ufbx_anim *anim = ufbxi_push_copy(&ec->result, ufbx_anim, 1, *p_anim);
25987 ufbxi_check_err(&ec->error, anim);
25988 ufbxi_check_err(&ec->error, ufbxi_translate_element_list(ec, &anim->layers));
25989 *p_anim = anim;
25990 return 1;
25991 }
25992
25993 ufbxi_nodiscard static ufbxi_noinline int ufbxi_evaluate_imp(ufbxi_eval_context *ec)
25994 {
25995 ec->scene = ec->src_scene;
25996 size_t num_elements = ec->scene.elements.count;
25997
25998 char *element_data = (char*)ufbxi_push(&ec->result, uint64_t, ec->scene.metadata.element_buffer_size/8);
25999 ufbxi_check_err(&ec->error, element_data);
26000
26001 ec->scene.elements.data = ufbxi_push(&ec->result, ufbx_element*, num_elements);
26002 ufbxi_check_err(&ec->error, ec->scene.elements.data);
26003
26004 ec->src_element = (char*)ec->src_scene.elements.data[0];
26005 ec->dst_element = element_data;
26006
26007 for (size_t i = 0; i < UFBX_ELEMENT_TYPE_COUNT; i++) {
26008 ec->scene.elements_by_type[i].data = ufbxi_push(&ec->result, ufbx_element*, ec->scene.elements_by_type[i].count);
26009 ufbxi_check_err(&ec->error, ec->scene.elements_by_type[i].data);
26010 }
26011
26012 size_t num_connections = ec->scene.connections_dst.count;
26013 ec->scene.connections_src.data = ufbxi_push(&ec->result, ufbx_connection, num_connections);
26014 ec->scene.connections_dst.data = ufbxi_push(&ec->result, ufbx_connection, num_connections);
26015 ufbxi_check_err(&ec->error, ec->scene.connections_src.data);
26016 ufbxi_check_err(&ec->error, ec->scene.connections_dst.data);
26017 for (size_t i = 0; i < num_connections; i++) {
26018 ufbx_connection *src = &ec->scene.connections_src.data[i];
26019 ufbx_connection *dst = &ec->scene.connections_dst.data[i];
26020 *src = ec->src_scene.connections_src.data[i];
26021 *dst = ec->src_scene.connections_dst.data[i];
26022 src->src = ufbxi_translate_element(ec, src->src);
26023 src->dst = ufbxi_translate_element(ec, src->dst);
26024 dst->src = ufbxi_translate_element(ec, dst->src);
26025 dst->dst = ufbxi_translate_element(ec, dst->dst);
26026 }
26027
26028 ec->scene.elements_by_name.data = ufbxi_push(&ec->result, ufbx_name_element, num_elements);
26029 ufbxi_check_err(&ec->error, ec->scene.elements_by_name.data);
26030
26031 ec->scene.root_node = (ufbx_node*)ufbxi_translate_element(ec, ec->scene.root_node);
26032 ufbxi_check_err(&ec->error, ufbxi_translate_anim(ec, &ec->scene.anim));
26033
26034 for (size_t i = 0; i < num_elements; i++) {
26035 ufbx_element *src = ec->src_scene.elements.data[i];
26036 ufbx_element *dst = ufbxi_translate_element(ec, src);
26037 size_t size = ufbx_element_type_size[src->type];
26038 ufbx_assert(size > 0);
26039 memcpy(dst, src, size);
26040
26041 ec->scene.elements.data[i] = dst;
26042 ec->scene.elements_by_type[src->type].data[src->typed_id] = dst;
26043
26044 dst->connections_src.data = ec->scene.connections_src.data + (dst->connections_src.data - ec->src_scene.connections_src.data);
26045 dst->connections_dst.data = ec->scene.connections_dst.data + (dst->connections_dst.data - ec->src_scene.connections_dst.data);
26046 if (dst->instances.count > 0) {
26047 ufbxi_check_err(&ec->error, ufbxi_translate_element_list(ec, &dst->instances));
26048 }
26049
26050 ufbx_name_element named = ec->src_scene.elements_by_name.data[i];
26051 named.element = ufbxi_translate_element(ec, named.element);
26052 ec->scene.elements_by_name.data[i] = named;
26053 }
26054
26055 ufbxi_for_ptr_list(ufbx_node, p_node, ec->scene.nodes) {
26056 ufbx_node *node = *p_node;
26057 node->parent = (ufbx_node*)ufbxi_translate_element(ec, node->parent);
26058 ufbxi_check_err(&ec->error, ufbxi_translate_element_list(ec, &node->children));
26059
26060 node->attrib = ufbxi_translate_element(ec, node->attrib);
26061 node->mesh = (ufbx_mesh*)ufbxi_translate_element(ec, node->mesh);
26062 node->light = (ufbx_light*)ufbxi_translate_element(ec, node->light);
26063 node->camera = (ufbx_camera*)ufbxi_translate_element(ec, node->camera);
26064 node->bone = (ufbx_bone*)ufbxi_translate_element(ec, node->bone);
26065 node->inherit_scale_node = (ufbx_node*)ufbxi_translate_element(ec, node->inherit_scale_node);
26066 node->scale_helper = (ufbx_node*)ufbxi_translate_element(ec, node->scale_helper);
26067 node->bind_pose = (ufbx_pose*)ufbxi_translate_element(ec, node->bind_pose);
26068
26069 if (node->all_attribs.count > 1) {
26070 ufbxi_check_err(&ec->error, ufbxi_translate_element_list(ec, &node->all_attribs));
26071 } else if (node->all_attribs.count == 1) {
26072 node->all_attribs.data = &node->attrib;
26073 }
26074
26075 node->geometry_transform_helper = (ufbx_node*)ufbxi_translate_element(ec, node->geometry_transform_helper);
26076
26077 ufbxi_check_err(&ec->error, ufbxi_translate_element_list(ec, &node->materials));
26078 }
26079
26080 ufbxi_for_ptr_list(ufbx_mesh, p_mesh, ec->scene.meshes) {
26081 ufbx_mesh *mesh = *p_mesh;
26082
26083 ufbxi_check_err(&ec->error, ufbxi_translate_element_list(ec, &mesh->materials));
26084 ufbxi_check_err(&ec->error, ufbxi_translate_element_list(ec, &mesh->skin_deformers));
26085 ufbxi_check_err(&ec->error, ufbxi_translate_element_list(ec, &mesh->blend_deformers));
26086 ufbxi_check_err(&ec->error, ufbxi_translate_element_list(ec, &mesh->cache_deformers));
26087 ufbxi_check_err(&ec->error, ufbxi_translate_element_list(ec, &mesh->all_deformers));
26088 }
26089
26090 ufbxi_for_ptr_list(ufbx_stereo_camera, p_stereo, ec->scene.stereo_cameras) {
26091 ufbx_stereo_camera *stereo = *p_stereo;
26092 stereo->left = (ufbx_camera*)ufbxi_translate_element(ec, stereo->left);
26093 stereo->right = (ufbx_camera*)ufbxi_translate_element(ec, stereo->right);
26094 }
26095
26096 ufbxi_for_ptr_list(ufbx_skin_deformer, p_skin, ec->scene.skin_deformers) {
26097 ufbx_skin_deformer *skin = *p_skin;
26098 ufbxi_check_err(&ec->error, ufbxi_translate_element_list(ec, &skin->clusters));
26099 }
26100
26101 ufbxi_for_ptr_list(ufbx_skin_cluster, p_cluster, ec->scene.skin_clusters) {
26102 ufbx_skin_cluster *cluster = *p_cluster;
26103 cluster->bone_node = (ufbx_node*)ufbxi_translate_element(ec, cluster->bone_node);
26104 }
26105
26106 ufbxi_for_ptr_list(ufbx_blend_deformer, p_blend, ec->scene.blend_deformers) {
26107 ufbx_blend_deformer *blend = *p_blend;
26108 ufbxi_check_err(&ec->error, ufbxi_translate_element_list(ec, &blend->channels));
26109 }
26110
26111 ufbxi_for_ptr_list(ufbx_blend_channel, p_chan, ec->scene.blend_channels) {
26112 ufbx_blend_channel *chan = *p_chan;
26113
26114 ufbx_blend_keyframe *keys = ufbxi_push(&ec->result, ufbx_blend_keyframe, chan->keyframes.count);
26115 ufbxi_check_err(&ec->error, keys);
26116 for (size_t i = 0; i < chan->keyframes.count; i++) {
26117 keys[i] = chan->keyframes.data[i];
26118 keys[i].shape = (ufbx_blend_shape*)ufbxi_translate_element(ec, keys[i].shape);
26119 }
26120 chan->keyframes.data = keys;
26121 chan->target_shape = (ufbx_blend_shape*)ufbxi_translate_element(ec, chan->target_shape);
26122 }
26123
26124 ufbxi_for_ptr_list(ufbx_cache_deformer, p_deformer, ec->scene.cache_deformers) {
26125 ufbx_cache_deformer *deformer = *p_deformer;
26126 deformer->file = (ufbx_cache_file*)ufbxi_translate_element(ec, deformer->file);
26127 }
26128
26129 ufbxi_for_ptr_list(ufbx_material, p_material, ec->scene.materials) {
26130 ufbx_material *material = *p_material;
26131
26132 material->shader = (ufbx_shader*)ufbxi_translate_element(ec, material->shader);
26133 ufbxi_translate_maps(ec, material->fbx.maps, UFBX_MATERIAL_FBX_MAP_COUNT);
26134 ufbxi_translate_maps(ec, material->pbr.maps, UFBX_MATERIAL_PBR_MAP_COUNT);
26135
26136 ufbx_material_texture *textures = ufbxi_push(&ec->result, ufbx_material_texture, material->textures.count);
26137 ufbxi_check_err(&ec->error, textures);
26138 for (size_t i = 0; i < material->textures.count; i++) {
26139 textures[i] = material->textures.data[i];
26140 textures[i].texture = (ufbx_texture*)ufbxi_translate_element(ec, textures[i].texture);
26141 }
26142 material->textures.data = textures;
26143 }
26144
26145 ufbxi_for_ptr_list(ufbx_texture, p_texture, ec->scene.textures) {
26146 ufbx_texture *texture = *p_texture;
26147 texture->video = (ufbx_video*)ufbxi_translate_element(ec, texture->video);
26148
26149 ufbx_texture_layer *layers = ufbxi_push(&ec->result, ufbx_texture_layer, texture->layers.count);
26150 ufbxi_check_err(&ec->error, layers);
26151 for (size_t i = 0; i < texture->layers.count; i++) {
26152 layers[i] = texture->layers.data[i];
26153 layers[i].texture = (ufbx_texture*)ufbxi_translate_element(ec, layers[i].texture);
26154 }
26155 texture->layers.data = layers;
26156
26157 ufbxi_check_err(&ec->error, ufbxi_translate_element_list(ec, &texture->file_textures));
26158
26159 if (texture->shader) {
26160 ufbx_shader_texture *shader = texture->shader;
26161 shader = ufbxi_push_copy(&ec->result, ufbx_shader_texture, 1, shader);
26162 ufbxi_check_err(&ec->error, shader);
26163 texture->shader = shader;
26164
26165 ufbx_shader_texture_input *inputs = ufbxi_push_copy(&ec->result, ufbx_shader_texture_input, shader->inputs.count, shader->inputs.data);
26166 ufbxi_check_err(&ec->error, inputs);
26167 shader->inputs.data = inputs;
26168 }
26169 }
26170
26171 ufbxi_for_ptr_list(ufbx_shader, p_shader, ec->scene.shaders) {
26172 ufbx_shader *shader = *p_shader;
26173 ufbxi_check_err(&ec->error, ufbxi_translate_element_list(ec, &shader->bindings));
26174 }
26175
26176 ufbxi_for_ptr_list(ufbx_display_layer, p_layer, ec->scene.display_layers) {
26177 ufbx_display_layer *layer = *p_layer;
26178
26179 ufbxi_check_err(&ec->error, ufbxi_translate_element_list(ec, &layer->nodes));
26180 }
26181
26182 ufbxi_for_ptr_list(ufbx_selection_set, p_set, ec->scene.selection_sets) {
26183 ufbx_selection_set *set = *p_set;
26184
26185 ufbxi_check_err(&ec->error, ufbxi_translate_element_list(ec, &set->nodes));
26186 }
26187
26188 ufbxi_for_ptr_list(ufbx_selection_node, p_node, ec->scene.selection_nodes) {
26189 ufbx_selection_node *node = *p_node;
26190
26191 node->target_node = (ufbx_node*)ufbxi_translate_element(ec, node->target_node);
26192 node->target_mesh = (ufbx_mesh*)ufbxi_translate_element(ec, node->target_mesh);
26193 }
26194
26195 ufbxi_for_ptr_list(ufbx_constraint, p_constraint, ec->scene.constraints) {
26196 ufbx_constraint *constraint = *p_constraint;
26197
26198 constraint->node = (ufbx_node*)ufbxi_translate_element(ec, constraint->node);
26199 constraint->aim_up_node = (ufbx_node*)ufbxi_translate_element(ec, constraint->aim_up_node);
26200 constraint->ik_effector = (ufbx_node*)ufbxi_translate_element(ec, constraint->ik_effector);
26201 constraint->ik_end_node = (ufbx_node*)ufbxi_translate_element(ec, constraint->ik_end_node);
26202
26203 ufbx_constraint_target *targets = ufbxi_push(&ec->result, ufbx_constraint_target, constraint->targets.count);
26204 ufbxi_check_err(&ec->error, targets);
26205 for (size_t i = 0; i < constraint->targets.count; i++) {
26206 targets[i] = constraint->targets.data[i];
26207 targets[i].node = (ufbx_node*)ufbxi_translate_element(ec, targets[i].node);
26208 }
26209 constraint->targets.data = targets;
26210 }
26211
26212 ufbxi_for_ptr_list(ufbx_audio_layer, p_layer, ec->scene.audio_layers) {
26213 ufbx_audio_layer *layer = *p_layer;
26214
26215 ufbxi_check_err(&ec->error, ufbxi_translate_element_list(ec, &layer->clips));
26216 }
26217
26218 ufbxi_for_ptr_list(ufbx_anim_stack, p_stack, ec->scene.anim_stacks) {
26219 ufbx_anim_stack *stack = *p_stack;
26220
26221 ufbxi_check_err(&ec->error, ufbxi_translate_element_list(ec, &stack->layers));
26222 ufbxi_check_err(&ec->error, ufbxi_translate_anim(ec, &stack->anim));
26223 }
26224
26225 ufbxi_for_ptr_list(ufbx_anim_layer, p_layer, ec->scene.anim_layers) {
26226 ufbx_anim_layer *layer = *p_layer;
26227
26228 ufbxi_check_err(&ec->error, ufbxi_translate_element_list(ec, &layer->anim_values));
26229 ufbx_anim_prop *props = ufbxi_push(&ec->result, ufbx_anim_prop, layer->anim_props.count + 1);
26230 ufbxi_check_err(&ec->error, props);
26231 for (size_t i = 0; i < layer->anim_props.count; i++) {
26232 props[i] = layer->anim_props.data[i];
26233 props[i].element = ufbxi_translate_element(ec, props[i].element);
26234 props[i].anim_value = (ufbx_anim_value*)ufbxi_translate_element(ec, props[i].anim_value);
26235 }
26236 // Maintain NULL sentinel
26237 memset(props + layer->anim_props.count, 0, sizeof(ufbx_anim_prop));
26238 layer->anim_props.data = props;
26239 }
26240
26241 ufbxi_for_ptr_list(ufbx_pose, p_pose, ec->scene.poses) {
26242 ufbx_pose *pose = *p_pose;
26243
26244 ufbx_bone_pose *bones = ufbxi_push(&ec->result, ufbx_bone_pose, pose->bone_poses.count);
26245 ufbxi_check_err(&ec->error, bones);
26246 for (size_t i = 0; i < pose->bone_poses.count; i++) {
26247 bones[i] = pose->bone_poses.data[i];
26248 bones[i].bone_node = (ufbx_node*)ufbxi_translate_element(ec, bones[i].bone_node);
26249 }
26250 pose->bone_poses.data = bones;
26251 }
26252
26253 ufbxi_check_err(&ec->error, ufbxi_translate_anim(ec, &ec->anim));
26254
26255 ufbxi_for_ptr_list(ufbx_anim_value, p_value, ec->scene.anim_values) {
26256 ufbx_anim_value *value = *p_value;
26257 value->curves[0] = (ufbx_anim_curve*)ufbxi_translate_element(ec, value->curves[0]);
26258 value->curves[1] = (ufbx_anim_curve*)ufbxi_translate_element(ec, value->curves[1]);
26259 value->curves[2] = (ufbx_anim_curve*)ufbxi_translate_element(ec, value->curves[2]);
26260 }
26261
26262 ufbx_anim anim = *ec->anim;
26263 ufbx_prop_override *over = anim.prop_overrides.data, *over_end = ufbxi_add_ptr(over, anim.prop_overrides.count);
26264
26265 // Evaluate the properties
26266 ufbxi_for_ptr_list(ufbx_element, p_elem, ec->scene.elements) {
26267 ufbx_element *elem = *p_elem;
26268 size_t num_animated = elem->props.num_animated;
26269 size_t num_override = 0;
26270
26271 // Setup the overrides for this element if found
26272 while (over != over_end && over->element_id == elem->element_id) {
26273 num_override++;
26274 over++;
26275 }
26276
26277 num_animated += num_override;
26278 if (num_animated == 0) continue;
26279
26280 anim.prop_overrides.data = ufbxi_sub_ptr(over, num_override);
26281 anim.prop_overrides.count = num_override;
26282
26283 ufbx_prop *props = ufbxi_push(&ec->result, ufbx_prop, num_animated);
26284 ufbxi_check_err(&ec->error, props);
26285
26286 elem->props = ufbx_evaluate_props_flags(&anim, elem, ec->time, props, num_animated, ec->opts.evaluate_flags);
26287 elem->props.defaults = &ec->src_scene.elements.data[elem->element_id]->props;
26288 }
26289
26290 // Update all derived values
26291 ufbxi_update_scene(&ec->scene, false, anim.transform_overrides.data, anim.transform_overrides.count);
26292
26293 // Evaluate skinning if requested
26294 if (ec->opts.evaluate_skinning) {
26295 ufbx_geometry_cache_data_opts cache_opts = { 0 };
26296 cache_opts.open_file_cb = ec->opts.open_file_cb;
26297 ufbxi_check_err(&ec->error, ufbxi_evaluate_skinning(&ec->scene, &ec->error, &ec->result, &ec->tmp,
26298 ec->time, ec->opts.load_external_files && ec->opts.evaluate_caches, &cache_opts));
26299 }
26300
26301 // Retain the scene, this must be the final allocation as we copy
26302 // `ator_result` to `ufbx_scene_imp`.
26303 ufbxi_scene_imp *imp = ufbxi_push_zero(&ec->result, ufbxi_scene_imp, 1);
26304 ufbxi_check_err(&ec->error, imp);
26305
26306 ufbx_assert(ec->src_imp->magic == UFBXI_SCENE_IMP_MAGIC);
26307 ufbxi_init_ref(&imp->refcount, UFBXI_SCENE_IMP_MAGIC, &ec->src_imp->refcount);
26308
26309 imp->magic = UFBXI_SCENE_IMP_MAGIC;
26310 imp->scene = ec->scene;
26311 imp->refcount.ator = ec->ator_result;
26312 imp->refcount.ator.error = NULL;
26313
26314 // Copy retained buffers and translate the allocator struct to the one
26315 // contained within `ufbxi_scene_imp`
26316 imp->refcount.buf = ec->result;
26317 imp->refcount.buf.ator = &imp->refcount.ator;
26318
26319 imp->scene.metadata.result_memory_used = imp->refcount.ator.current_size;
26320 imp->scene.metadata.temp_memory_used = ec->ator_tmp.current_size;
26321 imp->scene.metadata.result_allocs = imp->refcount.ator.num_allocs;
26322 imp->scene.metadata.temp_allocs = ec->ator_tmp.num_allocs;
26323
26324 ufbxi_for_ptr_list(ufbx_element, p_elem, imp->scene.elements) {
26325 (*p_elem)->scene = &imp->scene;
26326 }
26327
26328 ec->scene_imp = imp;
26329 ec->result.ator = &ec->ator_result;
26330
26331 return 1;
26332 }
26333
26334 ufbxi_nodiscard static ufbxi_noinline ufbx_scene *ufbxi_evaluate_scene(ufbxi_eval_context *ec, ufbx_scene *scene, const ufbx_anim *anim, double time, const ufbx_evaluate_opts *user_opts, ufbx_error *p_error)
26335 {
26336 if (user_opts) {
26337 ec->opts = *user_opts;
26338 } else {
26339 memset(&ec->opts, 0, sizeof(ec->opts));
26340 }
26341
26342 ec->src_imp = ufbxi_get_imp(ufbxi_scene_imp, scene);
26343 ec->src_scene = *scene;
26344 ec->anim = anim ? (ufbx_anim*)anim : scene->anim;
26345 ec->time = time;
26346
26347 ufbxi_init_ator(&ec->error, &ec->ator_tmp, &ec->opts.temp_allocator, "temp");
26348 ufbxi_init_ator(&ec->error, &ec->ator_result, &ec->opts.result_allocator, "result");
26349
26350 ec->result.ator = &ec->ator_result;
26351 ec->tmp.ator = &ec->ator_tmp;
26352
26353 ec->result.unordered = true;
26354 ec->tmp.unordered = true;
26355
26356 if (ufbxi_evaluate_imp(ec)) {
26357 ufbxi_buf_free(&ec->tmp);
26358 ufbxi_free_ator(&ec->ator_tmp);
26359 if (p_error) {
26360 ufbxi_clear_error(p_error);
26361 }
26362 return &ec->scene_imp->scene;
26363 } else {
26364 ufbxi_fix_error_type(&ec->error, "Failed to evaluate", p_error);
26365 ufbxi_buf_free(&ec->tmp);
26366 ufbxi_buf_free(&ec->result);
26367 ufbxi_free_ator(&ec->ator_tmp);
26368 ufbxi_free_ator(&ec->ator_result);
26369 return NULL;
26370 }
26371 }
26372
26373 #endif
26374
26375 typedef struct {
26376 ufbx_error error;
26377 ufbxi_allocator ator_result;
26378 ufbxi_buf result;
26379 const ufbx_scene *scene;
26380 ufbx_anim_opts opts;
26381
26382 ufbx_anim anim;
26383 ufbxi_anim_imp *imp;
26384 } ufbxi_create_anim_context;
26385
26386 ufbxi_nodiscard static ufbxi_noinline int ufbxi_check_string(ufbx_error *error, ufbx_string *dst, const ufbx_string *src)
26387 {
26388 size_t length = src->length != SIZE_MAX ? src->length : strlen(src->data);
26389 const char *data = length != 0 ? src->data : ufbxi_empty_char;
26390 if (length > 0) {
26391 size_t valid_length = ufbxi_utf8_valid_length(data, length);
26392 ufbxi_check_err_msg(error, valid_length == length, "Invalid UTF-8");
26393 }
26394
26395 dst->data = data;
26396 dst->length = length;
26397 return 1;
26398 }
26399
26400 ufbxi_nodiscard static ufbxi_noinline int ufbxi_push_anim_string(ufbxi_create_anim_context *ac, ufbx_string *str)
26401 {
26402 size_t length = str->length;
26403 if (length > 0) {
26404 char *copy = ufbxi_push(&ac->result, char, length + 1);
26405 ufbxi_check_err(&ac->error, copy);
26406 memcpy(copy, str->data, length);
26407 copy[str->length] = '\0';
26408 str->data = copy;
26409 } else {
26410 ufbx_assert(str->data == ufbxi_empty_char);
26411 }
26412
26413 return 1;
26414 }
26415
26416 static bool ufbxi_prop_override_prop_name_less(void *user, const void *va, const void *vb)
26417 {
26418 (void)user;
26419 const ufbx_prop_override *a = (const ufbx_prop_override*)va, *b = (const ufbx_prop_override*)vb;
26420 if (a->_internal_key != b->_internal_key) return a->_internal_key < b->_internal_key;
26421 return ufbxi_str_less(a->prop_name, b->prop_name);
26422 }
26423
26424 static bool ufbxi_prop_override_less(void *user, const void *va, const void *vb)
26425 {
26426 (void)user;
26427 const ufbx_prop_override *a = (const ufbx_prop_override*)va, *b = (const ufbx_prop_override*)vb;
26428 if (a->element_id != b->element_id) return a->element_id < b->element_id;
26429 if (a->_internal_key != b->_internal_key) return a->_internal_key < b->_internal_key;
26430 return strcmp(a->prop_name.data, b->prop_name.data) < 0;
26431 }
26432
26433 static bool ufbxi_transform_override_less(void *user, const void *va, const void *vb)
26434 {
26435 (void)user;
26436 const ufbx_transform_override *a = (const ufbx_transform_override*)va, *b = (const ufbx_transform_override*)vb;
26437 return a->node_id < b->node_id;
26438 }
26439
26440 ufbxi_nodiscard static ufbxi_noinline int ufbxi_create_anim_imp(ufbxi_create_anim_context *ac)
26441 {
26442 const ufbx_scene *scene = ac->scene;
26443 ufbx_anim *anim = &ac->anim;
26444
26445 ufbxi_init_ator(&ac->error, &ac->ator_result, &ac->opts.result_allocator, "result");
26446 ac->result.unordered = true;
26447 ac->result.ator = &ac->ator_result;
26448
26449 anim->ignore_connections = ac->opts.ignore_connections;
26450 anim->custom = true;
26451
26452 size_t num_layers = ac->opts.layer_ids.count;
26453 anim->layers.count = num_layers;
26454 anim->layers.data = ufbxi_push_zero(&ac->result, ufbx_anim_layer*, num_layers);
26455 ufbxi_check_err(&ac->error, anim->layers.data);
26456
26457 if (ac->opts.override_layer_weights.count > 0) {
26458 ufbxi_check_err_msg(&ac->error, ac->opts.override_layer_weights.count == num_layers, "override_layer_weights[] count must match layer_ids[] count");
26459 anim->override_layer_weights.data = ufbxi_push_copy(&ac->result, ufbx_real, num_layers, ac->opts.override_layer_weights.data);
26460 ufbxi_check_err(&ac->error, anim->override_layer_weights.data);
26461 anim->override_layer_weights.count = num_layers;
26462 }
26463
26464 for (size_t i = 0; i < num_layers; i++) {
26465 uint32_t index = ac->opts.layer_ids.data[i];
26466 ufbxi_check_err_msg(&ac->error, index < scene->anim_layers.count, "layer_ids out of bounds");
26467 anim->layers.data[i] = ac->scene->anim_layers.data[index];
26468 }
26469
26470 ufbx_const_prop_override_desc_list prop_overrides = ac->opts.prop_overrides;
26471 if (prop_overrides.count > 0) {
26472 anim->prop_overrides.count = prop_overrides.count;
26473 anim->prop_overrides.data = ufbxi_push_zero(&ac->result, ufbx_prop_override, prop_overrides.count);
26474 ufbxi_check_err(&ac->error, anim->prop_overrides.data);
26475
26476 for (size_t i = 0; i < prop_overrides.count; i++) {
26477 const ufbx_prop_override_desc *src = &prop_overrides.data[i];
26478 ufbx_prop_override *dst = &anim->prop_overrides.data[i];
26479
26480 dst->element_id = src->element_id;
26481 dst->value = src->value;
26482 dst->value_int = src->value_int;
26483
26484 if (dst->value.x != 0.0f && dst->value_int == 0) {
26485 dst->value_int = (int64_t)dst->value.x;
26486 } else if (dst->value_int != 0 && dst->value.x == 0.0f) {
26487 dst->value.x = (ufbx_real)dst->value_int;
26488 }
26489
26490 ufbxi_check_err(&ac->error, ufbxi_check_string(&ac->error, &dst->prop_name, &src->prop_name));
26491 ufbxi_check_err(&ac->error, ufbxi_check_string(&ac->error, &dst->value_str, &src->value_str));
26492
26493 dst->_internal_key = ufbxi_get_name_key(dst->prop_name.data, dst->prop_name.length);
26494 }
26495
26496 // Sort `anim->prop_overrides` first by `prop_name` only so we can deduplicate and
26497 // convert them to global strings in `ufbxi_strings[]` if possible.
26498 ufbxi_unstable_sort(anim->prop_overrides.data, anim->prop_overrides.count, sizeof(ufbx_prop_override), &ufbxi_prop_override_prop_name_less, NULL);
26499
26500 const ufbx_string *global_str = ufbxi_strings, *global_end = global_str + ufbxi_arraycount(ufbxi_strings);
26501 ufbx_string prev_name = { ufbxi_empty_char };
26502 ufbxi_for_list(ufbx_prop_override, over, anim->prop_overrides) {
26503 if (over->value_str.length > 0) {
26504 ufbxi_check_err(&ac->error, ufbxi_push_anim_string(ac, &over->value_str));
26505 }
26506
26507 if (ufbxi_str_equal(over->prop_name, prev_name)) {
26508 over->prop_name = prev_name;
26509 continue;
26510 }
26511
26512 while (global_str != global_end && ufbxi_str_less(*global_str, over->prop_name)) {
26513 ++global_str;
26514 }
26515
26516 if (global_str != global_end && ufbxi_str_equal(*global_str, over->prop_name)) {
26517 over->prop_name = *global_str;
26518 } else {
26519 ufbxi_check_err(&ac->error, ufbxi_push_anim_string(ac, &over->prop_name));
26520 }
26521
26522 prev_name = over->prop_name;
26523 }
26524
26525 // Sort `anim->prop_overrides` to the actual order expected by evaluation.
26526 ufbxi_unstable_sort(anim->prop_overrides.data, anim->prop_overrides.count, sizeof(ufbx_prop_override), &ufbxi_prop_override_less, NULL);
26527
26528 for (size_t i = 1; i < prop_overrides.count; i++) {
26529 const ufbx_prop_override *prev = &anim->prop_overrides.data[i - 1];
26530 const ufbx_prop_override *next = &anim->prop_overrides.data[i];
26531 if (prev->element_id == next->element_id && prev->prop_name.data == next->prop_name.data) {
26532 ufbxi_fmt_err_info(&ac->error, "element %u prop \"%s\"", prev->element_id, prev->prop_name.data);
26533 ufbxi_fail_err_msg(&ac->error, "Duplicate override", "Duplicate override");
26534 }
26535 }
26536 }
26537
26538 if (ac->opts.transform_overrides.count > 0) {
26539 anim->transform_overrides.count = ac->opts.transform_overrides.count;
26540 anim->transform_overrides.data = ufbxi_push_copy(&ac->result, ufbx_transform_override, anim->transform_overrides.count, ac->opts.transform_overrides.data);
26541 ufbxi_check_err(&ac->error, anim->transform_overrides.data);
26542 ufbxi_unstable_sort(anim->transform_overrides.data, anim->transform_overrides.count, sizeof(ufbx_transform_override), &ufbxi_transform_override_less, NULL);
26543 }
26544
26545 ac->imp = ufbxi_push(&ac->result, ufbxi_anim_imp, 1);
26546 ufbxi_check_err(&ac->error, ac->imp);
26547
26548 ufbxi_init_ref(&ac->imp->refcount, UFBXI_ANIM_IMP_MAGIC, &(ufbxi_get_imp(ufbxi_scene_imp, scene))->refcount);
26549
26550 ac->imp->magic = UFBXI_ANIM_IMP_MAGIC;
26551 ac->imp->anim = ac->anim;
26552 ac->imp->refcount.ator = ac->ator_result;
26553 ac->imp->refcount.buf = ac->result;
26554
26555 return 1;
26556 }
26557
26558 // -- Animation baking
26559
26560 typedef struct {
26561 ufbxi_refcount refcount;
26562 ufbx_baked_anim bake;
26563 uint32_t magic;
26564 } ufbxi_baked_anim_imp;
26565
26566 #if UFBXI_FEATURE_ANIMATION_BAKING
26567
26568 typedef struct {
26569 double time;
26570 uint32_t flags;
26571 } ufbxi_bake_time;
26572
26573 UFBX_LIST_TYPE(ufbxi_bake_time_list, ufbxi_bake_time);
26574
26575 typedef struct {
26576 ufbx_error error;
26577 ufbxi_allocator ator_tmp;
26578 ufbxi_allocator ator_result;
26579
26580 ufbxi_buf result;
26581 ufbxi_buf tmp;
26582 ufbxi_buf tmp_prop;
26583 ufbxi_buf tmp_times;
26584 ufbxi_buf tmp_bake_props;
26585 ufbxi_buf tmp_nodes;
26586 ufbxi_buf tmp_elements;
26587 ufbxi_buf tmp_props;
26588 ufbxi_buf tmp_bake_stack;
26589
26590 ufbxi_bake_time_list layer_weight_times;
26591
26592 ufbx_baked_node **baked_nodes;
26593 bool *nodes_to_bake;
26594
26595 char *tmp_arr;
26596 size_t tmp_arr_size;
26597
26598 const ufbx_scene *scene;
26599 const ufbx_anim *anim;
26600 ufbx_bake_opts opts;
26601
26602 double ktime_offset;
26603
26604 double time_begin;
26605 double time_end;
26606 double time_min;
26607 double time_max;
26608
26609 ufbx_baked_anim bake;
26610 ufbxi_baked_anim_imp *imp;
26611 } ufbxi_bake_context;
26612
26613 typedef struct {
26614 uint32_t sort_id;
26615 uint32_t element_id;
26616 const char *prop_name;
26617 ufbx_anim_value *anim_value;
26618 } ufbxi_bake_prop;
26619
26620 static bool ufbxi_bake_prop_less(void *user, const void *va, const void *vb)
26621 {
26622 (void)user;
26623 const ufbxi_bake_prop *a = (const ufbxi_bake_prop*)va;
26624 const ufbxi_bake_prop *b = (const ufbxi_bake_prop*)vb;
26625 if (a->sort_id != b->sort_id) return a->sort_id < b->sort_id;
26626 if (a->element_id != b->element_id) return a->element_id < b->element_id;
26627 if (a->prop_name != b->prop_name) return strcmp(a->prop_name, b->prop_name) < 0;
26628 return false;
26629 }
26630
26631 ufbx_static_assert(bake_step_left, UFBX_BAKED_KEY_STEP_LEFT == 0x1);
26632 ufbx_static_assert(bake_step_right, UFBX_BAKED_KEY_STEP_RIGHT == 0x2);
26633 ufbx_static_assert(bake_step_key, UFBX_BAKED_KEY_STEP_KEY == 0x4);
26634 static ufbxi_forceinline int ufbxi_cmp_bake_time(ufbxi_bake_time a, ufbxi_bake_time b)
26635 {
26636 if (a.time != b.time) return a.time < b.time ? -1 : 1;
26637 // Bit twiddling for a fast sorting of `0x1 (LEFT) < 0x0 < 0x2 (RIGHT)`
26638 // by `step ^ 1`: `0x0 (LEFT) < 0x1 < 0x3 (RIGHT)`
26639 uint32_t a_step = a.flags & 0x3, b_step = b.flags & 0x3;
26640 if (a_step != b_step) return (a_step ^ 0x1) < (b_step ^ 0x1) ? -1 : 1;
26641 return 0;
26642 }
26643
26644 ufbxi_nodiscard static ufbxi_forceinline int ufbxi_bake_push_time(ufbxi_bake_context *bc, double time, uint32_t flags)
26645 {
26646 ufbxi_bake_time *p_key = ufbxi_push_fast(&bc->tmp_times, ufbxi_bake_time, 1);
26647 if (!p_key) return 0;
26648 p_key->time = time;
26649 p_key->flags = flags;
26650 return 1;
26651 }
26652
26653 ufbxi_nodiscard static ufbxi_noinline int ufbxi_bake_times(ufbxi_bake_context *bc, const ufbx_anim_value *anim_value, bool resample_linear, uint32_t key_flag)
26654 {
26655 double sample_rate = bc->opts.resample_rate;
26656 double min_duration = bc->opts.minimum_sample_rate > 0.0 ? 1.0 / bc->opts.minimum_sample_rate : 0.0;
26657
26658 for (size_t curve_ix = 0; curve_ix < 3; curve_ix++) {
26659 ufbx_anim_curve *curve = anim_value->curves[curve_ix];
26660 if (!curve) continue;
26661
26662 const ufbx_keyframe *keys = curve->keyframes.data;
26663 size_t num_keys = curve->keyframes.count;
26664 for (size_t key_ix = 0; key_ix < num_keys; key_ix++) {
26665 ufbx_keyframe a = keys[key_ix];
26666 double a_time = a.time;
26667 ufbxi_check_err(&bc->error, ufbxi_bake_push_time(bc, a_time, key_flag));
26668 if (key_ix + 1 >= num_keys) break;
26669 ufbx_keyframe b = keys[key_ix + 1];
26670 double b_time = b.time;
26671
26672 // Skip fully flat sections
26673 if (a.value == b.value && a.right.dy == 0.0f && b.left.dy == 0.0f) continue;
26674
26675 if (a.interpolation == UFBX_INTERPOLATION_CONSTANT_PREV) {
26676 ufbxi_check_err(&bc->error, ufbxi_bake_push_time(bc, b_time, UFBX_BAKED_KEY_STEP_LEFT));
26677 } else if (a.interpolation == UFBX_INTERPOLATION_CONSTANT_NEXT) {
26678 ufbxi_check_err(&bc->error, ufbxi_bake_push_time(bc, a_time, UFBX_BAKED_KEY_STEP_RIGHT));
26679 } else if ((resample_linear || a.interpolation == UFBX_INTERPOLATION_CUBIC) && sample_rate > 0.0) {
26680 double duration = b_time - a_time;
26681 if (duration <= min_duration) continue;
26682
26683 double factor = 1.0;
26684 while (duration * sample_rate / factor >= (double)bc->opts.max_keyframe_segments) {
26685 factor *= 2.0;
26686 }
26687
26688 double padding = 0.5 / sample_rate;
26689 double start = ufbx_ceil((a_time + padding) * sample_rate / factor) * factor;
26690 double stop = b_time - padding;
26691 for (size_t i = 0; i < bc->opts.max_keyframe_segments; i++) {
26692 double time = (start + (double)i * factor) / sample_rate;
26693 if (time >= stop) break;
26694 ufbxi_check_err(&bc->error, ufbxi_bake_push_time(bc, time, 0));
26695 }
26696 }
26697 }
26698 }
26699
26700 return 1;
26701 }
26702
26703 static const char *const ufbxi_transform_props[] = {
26704 ufbxi_Lcl_Translation, ufbxi_Lcl_Rotation, ufbxi_Lcl_Scaling, ufbxi_PreRotation, ufbxi_PostRotation,
26705 ufbxi_RotationOffset, ufbxi_ScalingOffset, ufbxi_RotationPivot, ufbxi_ScalingPivot, ufbxi_RotationOrder,
26706 };
26707
26708 static const char *const ufbxi_complex_translation_props[] = {
26709 ufbxi_ScalingPivot, ufbxi_RotationPivot, ufbxi_RotationOffset, ufbxi_ScalingOffset,
26710 };
26711
26712 static const char *const ufbxi_complex_rotation_props[] = {
26713 ufbxi_PreRotation, ufbxi_PostRotation, ufbxi_RotationOrder,
26714 };
26715
26716 static const char *const ufbxi_complex_rotation_sources[] = {
26717 ufbxi_Lcl_Rotation, ufbxi_PreRotation, ufbxi_PostRotation, ufbxi_RotationOrder,
26718 };
26719
26720 ufbxi_nodiscard static ufbxi_noinline bool ufbxi_in_list(const char *const *items, size_t count, const char *item)
26721 {
26722 for (size_t i = 0; i < count; i++) {
26723 if (items[i] == item) return true;
26724 }
26725 return false;
26726 }
26727
26728 ufbxi_nodiscard static ufbxi_noinline int ufbxi_sort_bake_times(ufbxi_bake_context *bc, ufbxi_bake_time *times, size_t count)
26729 {
26730 ufbxi_check_err(&bc->error, ufbxi_grow_array(&bc->ator_tmp, &bc->tmp_arr, &bc->tmp_arr_size, count * sizeof(ufbxi_bake_time)));
26731 ufbxi_macro_stable_sort(ufbxi_bake_time, 32, times, bc->tmp_arr, count, ( ufbxi_cmp_bake_time(*a, *b) < 0 ));
26732 return 1;
26733 }
26734
26735 ufbxi_nodiscard static ufbxi_noinline int ufbxi_finalize_bake_times(ufbxi_bake_context *bc, ufbxi_bake_time_list *p_dst)
26736 {
26737 if (bc->layer_weight_times.count > 0) {
26738 ufbxi_check_err(&bc->error, ufbxi_push_copy(&bc->tmp_times, ufbxi_bake_time, bc->layer_weight_times.count, bc->layer_weight_times.data));
26739 }
26740
26741 if (bc->tmp_times.num_items == 0) {
26742 ufbxi_check_err(&bc->error, ufbxi_bake_push_time(bc, bc->time_begin, 0));
26743 ufbxi_check_err(&bc->error, ufbxi_bake_push_time(bc, bc->time_end, 0));
26744 }
26745
26746 size_t num_times = bc->tmp_times.num_items;
26747 ufbxi_bake_time *times = ufbxi_push_pop(&bc->tmp_prop, &bc->tmp_times, ufbxi_bake_time, num_times);
26748 ufbxi_check_err(&bc->error, times);
26749
26750 ufbxi_check_err(&bc->error, ufbxi_sort_bake_times(bc, times, num_times));
26751
26752 // Deduplicate times
26753 if (num_times > 0) {
26754 size_t dst = 0;
26755 ufbxi_bake_time prev = times[0];
26756 for (size_t src = 1; src < num_times; src++) {
26757 ufbxi_bake_time next = times[src];
26758 // Merge keys with the same time and step flags `(0x1, 0x2)`
26759 if (next.time == prev.time) {
26760 if (((next.flags ^ prev.flags) & 0x3) == 0) {
26761 prev.flags |= next.flags;
26762 continue;
26763 } else if (prev.flags & UFBX_BAKED_KEY_STEP_LEFT) {
26764 next.flags |= UFBX_BAKED_KEY_STEP_KEY;
26765 } else if (next.flags & UFBX_BAKED_KEY_STEP_RIGHT) {
26766 prev.flags |= UFBX_BAKED_KEY_STEP_KEY;
26767 }
26768 }
26769
26770 times[dst++] = prev;
26771 prev = next;
26772 }
26773 times[dst++] = prev;
26774 num_times = dst;
26775 }
26776
26777 // Cull too close resampled keys, these may arise during merging multiple times
26778 if (num_times > 0) {
26779 double min_dist = 0.25 / bc->opts.resample_rate;
26780 uint32_t keep_flags = UFBX_BAKED_KEY_STEP_LEFT|UFBX_BAKED_KEY_STEP_RIGHT|UFBX_BAKED_KEY_STEP_KEY|UFBX_BAKED_KEY_KEYFRAME;
26781
26782 size_t dst = 0;
26783 for (size_t src = 0; src < num_times; src++) {
26784 ufbxi_bake_time cur = times[src];
26785 double delta = UFBX_INFINITY;
26786
26787 bool keep = true;
26788 if ((cur.flags & keep_flags) == 0) {
26789 if (dst > 0) delta = cur.time - times[dst - 1].time;
26790 if (src + 1 < num_times) delta = ufbx_fmin(delta, times[src + 1].time - cur.time);
26791 if (delta < min_dist) keep = false;
26792 }
26793 if (keep) {
26794 times[dst++] = cur;
26795 }
26796 }
26797 num_times = dst;
26798 }
26799
26800 // Enforce maximum sample rate
26801 if (bc->opts.maximum_sample_rate > 0.0) {
26802 const double epsilon = 0.0078125 / bc->opts.maximum_sample_rate;
26803 double sample_rate = bc->opts.maximum_sample_rate;
26804 double max_interval = 1.0 / bc->opts.maximum_sample_rate;
26805 double min_interval = 1.0 / bc->opts.maximum_sample_rate - epsilon;
26806 size_t dst = 0, src = 0;
26807
26808 // Pre-expand constant keyframes
26809 for (size_t i = 0; i < num_times; i++) {
26810 if ((times[i].flags & (UFBX_BAKED_KEY_STEP_LEFT|UFBX_BAKED_KEY_STEP_RIGHT)) != 0) {
26811 double sign = (times[i].flags & UFBX_BAKED_KEY_STEP_LEFT) != 0 ? -1.0 : 1.0;
26812 double time = times[i].time + sign * max_interval;
26813 if (i > 0) time = ufbx_fmax(time, times[i - 1].time);
26814 if (i + 1 < num_times) time = ufbx_fmin(time, times[i + 1].time);
26815 times[i].time = time;
26816 times[i].flags = UFBX_BAKED_KEY_REDUCED;
26817 }
26818 }
26819
26820 ufbxi_bake_time prev_time = { -UFBX_INFINITY };
26821 while (src < num_times) {
26822 ufbxi_bake_time src_time = times[src];
26823 src++;
26824
26825 size_t start_src = src;
26826 ufbxi_bake_time next_time;
26827 next_time.time = ufbx_ceil(src_time.time * sample_rate - epsilon) / sample_rate;
26828 next_time.flags = UFBX_BAKED_KEY_REDUCED;
26829 while (src < num_times && times[src].time <= next_time.time + epsilon) {
26830 src++;
26831 }
26832
26833 if (src != start_src || src_time.time - prev_time.time <= min_interval) {
26834 prev_time = next_time;
26835 } else {
26836 prev_time = src_time;
26837 }
26838
26839 if (dst == 0 || prev_time.time > times[dst - 1].time) {
26840 times[dst++] = prev_time;
26841 }
26842 }
26843
26844 num_times = dst;
26845 }
26846
26847 if (num_times > 0) {
26848 if (times[0].time < bc->time_min) bc->time_min = times[0].time;
26849 if (times[num_times - 1].time > bc->time_max) bc->time_max = times[num_times - 1].time;
26850 }
26851
26852 p_dst->data = times;
26853 p_dst->count = num_times;
26854
26855 return 1;
26856 }
26857
26858 #define ufbxi_add_epsilon(a, epsilon) ((a)>0 ? (a)*(epsilon) : (a)/(epsilon))
26859 #define ufbxi_sub_epsilon(a, epsilon) ((a)>0 ? (a)/(epsilon) : (a)*(epsilon))
26860
26861 static ufbxi_noinline bool ufbxi_postprocess_step(ufbxi_bake_context *bc, double prev_time, double next_time, double *p_time, ufbx_baked_key_flags flags)
26862 {
26863 ufbxi_dev_assert((flags & (UFBX_BAKED_KEY_STEP_LEFT|UFBX_BAKED_KEY_STEP_RIGHT)) != 0);
26864 bool left = (flags & UFBX_BAKED_KEY_STEP_LEFT) != 0;
26865
26866 double step = 0.001;
26867 double epsilon = 1.0 + UFBX_FLT_EPSILON * 4.0f;
26868
26869 double time = *p_time;
26870 switch (bc->opts.step_handling) {
26871 case UFBX_BAKE_STEP_HANDLING_DEFAULT:
26872 break;
26873 case UFBX_BAKE_STEP_HANDLING_CUSTOM_DURATION:
26874 step = bc->opts.step_custom_duration;
26875 epsilon = 1.0 + bc->opts.step_custom_epsilon;
26876 break;
26877 case UFBX_BAKE_STEP_HANDLING_IDENTICAL_TIME:
26878 return true;
26879 case UFBX_BAKE_STEP_HANDLING_ADJACENT_DOUBLE:
26880 if (left) {
26881 *p_time = time = ufbx_nextafter(time, -UFBX_INFINITY);
26882 return time > prev_time;
26883 } else {
26884 *p_time = time = ufbx_nextafter(time, UFBX_INFINITY);
26885 return time < next_time;
26886 }
26887 case UFBX_BAKE_STEP_HANDLING_IGNORE:
26888 return false;
26889 default:
26890 ufbxi_unreachable("Unhandled bake step handling");
26891 return false;
26892 }
26893
26894 if (left) {
26895 double min_time = ufbx_fmax(prev_time + step, ufbxi_add_epsilon(prev_time, epsilon));
26896 *p_time = time = ufbx_fmin(time - step, ufbxi_sub_epsilon(time, epsilon));
26897 return time > min_time;
26898 } else {
26899 double max_time = ufbx_fmin(next_time - step, ufbxi_sub_epsilon(next_time, epsilon));
26900 *p_time = time = ufbx_fmax(time + step, ufbxi_add_epsilon(time, epsilon));
26901 return time < max_time;
26902 }
26903 }
26904
26905 ufbxi_nodiscard static ufbxi_noinline int ufbxi_bake_postprocess_vec3(ufbxi_bake_context *bc, ufbx_baked_vec3_list *p_dst, bool *p_constant, ufbx_baked_vec3_list src)
26906 {
26907 if (src.count == 0) return 1;
26908
26909 // Offset times
26910 if (bc->ktime_offset != 0.0) {
26911 double scale = (double)bc->scene->metadata.ktime_second;
26912 double offset = bc->ktime_offset;
26913 for (size_t i = 0; i < src.count; i++) {
26914 src.data[i].time = ufbx_rint(src.data[i].time * scale + offset) / scale;
26915 }
26916 }
26917
26918 // Postprocess stepped tangents
26919 {
26920 size_t dst = 0;
26921 double prev_time = src.data[0].time;
26922 for (size_t i = 0; i < src.count; i++) {
26923 ufbx_baked_vec3 cur = src.data[i];
26924 double next_time = i + 1 < src.count ? src.data[i + 1].time : UFBX_INFINITY;
26925 bool keep = true;
26926 if ((cur.flags & (UFBX_BAKED_KEY_STEP_LEFT|UFBX_BAKED_KEY_STEP_RIGHT)) != 0) {
26927 keep = ufbxi_postprocess_step(bc, prev_time, next_time, &cur.time, cur.flags);
26928 }
26929 if (keep) {
26930 src.data[dst] = cur;
26931 dst++;
26932 prev_time = cur.time;
26933 }
26934 }
26935 src.count = dst;
26936 }
26937
26938 if (bc->opts.key_reduction_enabled) {
26939 double threshold = bc->opts.key_reduction_threshold * bc->opts.key_reduction_threshold;
26940 for (size_t pass = 0; pass < bc->opts.key_reduction_passes; pass++) {
26941 size_t dst = 1;
26942 for (size_t i = 1; i < src.count; i++) {
26943 ufbx_baked_vec3 prev = src.data[i - 1];
26944 ufbx_baked_vec3 cur = src.data[i];
26945 if (i + 1 < src.count) {
26946 ufbx_baked_vec3 next = src.data[i + 1];
26947 double delta = (cur.time - prev.time) / (next.time - prev.time);
26948 ufbx_vec3 tmp = ufbxi_lerp3(prev.value, next.value, (ufbx_real)delta);
26949 double error = 0.0;
26950 error += ((double)tmp.x - (double)cur.value.x) * ((double)tmp.x - (double)cur.value.x);
26951 error += ((double)tmp.y - (double)cur.value.y) * ((double)tmp.y - (double)cur.value.y);
26952 error += ((double)tmp.z - (double)cur.value.z) * ((double)tmp.z - (double)cur.value.z);
26953 if (error <= threshold) {
26954 src.data[dst] = src.data[i + 1];
26955 i += 1;
26956 dst += 1;
26957 continue;
26958 }
26959 }
26960
26961 src.data[dst] = src.data[i];
26962 dst += 1;
26963 }
26964 if (dst == src.count) break;
26965 src.count = dst;
26966 }
26967 }
26968
26969 bool constant = true;
26970 ufbx_vec3 ref = src.data[0].value;
26971 for (size_t i = 1; i < src.count; i++) {
26972 ufbx_vec3 v = src.data[i].value;
26973 if (v.x != ref.x || v.y != ref.y || v.z != ref.z) {
26974 constant = false;
26975 break;
26976 }
26977 }
26978 *p_constant = constant;
26979
26980 p_dst->count = src.count;
26981 p_dst->data = ufbxi_push_copy(&bc->result, ufbx_baked_vec3, src.count, src.data);
26982 ufbxi_check_err(&bc->error, p_dst->data);
26983
26984 return 1;
26985 }
26986
26987 ufbxi_nodiscard static ufbxi_noinline int ufbxi_bake_postprocess_quat(ufbxi_bake_context *bc, ufbx_baked_quat_list *p_dst, bool *p_constant, ufbx_baked_quat_list src)
26988 {
26989 if (src.count == 0) return 1;
26990
26991 // Offset times
26992 if (bc->ktime_offset != 0.0) {
26993 double scale = (double)bc->scene->metadata.ktime_second;
26994 double offset = bc->ktime_offset;
26995 for (size_t i = 0; i < src.count; i++) {
26996 src.data[i].time = ufbx_rint(src.data[i].time * scale + offset) / scale;
26997 }
26998 }
26999
27000 // Postprocess stepped tangents
27001 {
27002 size_t dst = 0;
27003 double prev_time = src.data[0].time;
27004 for (size_t i = 0; i < src.count; i++) {
27005 ufbx_baked_quat cur = src.data[i];
27006 double next_time = i + 1 < src.count ? src.data[i + 1].time : UFBX_INFINITY;
27007 bool keep = true;
27008 if ((cur.flags & (UFBX_BAKED_KEY_STEP_LEFT|UFBX_BAKED_KEY_STEP_RIGHT)) != 0) {
27009 keep = ufbxi_postprocess_step(bc, prev_time, next_time, &cur.time, cur.flags);
27010 }
27011 if (keep) {
27012 prev_time = cur.time;
27013 src.data[dst] = cur;
27014 dst++;
27015 }
27016 }
27017 src.count = dst;
27018 }
27019
27020 // Fix quaternion antipodality
27021 for (size_t i = 1; i < src.count; i++) {
27022 src.data[i].value = ufbx_quat_fix_antipodal(src.data[i].value, src.data[i - 1].value);
27023 }
27024
27025 if (bc->opts.key_reduction_enabled) {
27026 double threshold = bc->opts.key_reduction_threshold * bc->opts.key_reduction_threshold;
27027 for (size_t pass = 0; pass < bc->opts.key_reduction_passes; pass++) {
27028 size_t dst = 1;
27029 for (size_t i = 1; i < src.count; i++) {
27030 ufbx_baked_quat prev = src.data[i - 1];
27031 ufbx_baked_quat cur = src.data[i];
27032 if (i + 1 < src.count) {
27033 ufbx_baked_quat next = src.data[i + 1];
27034 double delta = (cur.time - prev.time) / (next.time - prev.time);
27035 double error = 0.0;
27036
27037 if (bc->opts.key_reduction_rotation) {
27038 ufbx_quat tmp = ufbx_quat_slerp(prev.value, next.value, (ufbx_real)delta);
27039 error += ((double)tmp.x - (double)cur.value.x) * ((double)tmp.x - (double)cur.value.x);
27040 error += ((double)tmp.y - (double)cur.value.y) * ((double)tmp.y - (double)cur.value.y);
27041 error += ((double)tmp.z - (double)cur.value.z) * ((double)tmp.z - (double)cur.value.z);
27042 error += ((double)tmp.w - (double)cur.value.w) * ((double)tmp.w - (double)cur.value.w);
27043 } else {
27044 error += ((double)prev.value.x - (double)cur.value.x) * ((double)prev.value.x - (double)cur.value.x);
27045 error += ((double)prev.value.y - (double)cur.value.y) * ((double)prev.value.y - (double)cur.value.y);
27046 error += ((double)prev.value.z - (double)cur.value.z) * ((double)prev.value.z - (double)cur.value.z);
27047 error += ((double)prev.value.w - (double)cur.value.w) * ((double)prev.value.w - (double)cur.value.w);
27048 error += ((double)next.value.x - (double)cur.value.x) * ((double)next.value.x - (double)cur.value.x);
27049 error += ((double)next.value.y - (double)cur.value.y) * ((double)next.value.y - (double)cur.value.y);
27050 error += ((double)next.value.z - (double)cur.value.z) * ((double)next.value.z - (double)cur.value.z);
27051 error += ((double)next.value.w - (double)cur.value.w) * ((double)next.value.w - (double)cur.value.w);
27052 error *= 0.5;
27053 }
27054
27055 if (error <= threshold) {
27056 src.data[dst] = src.data[i + 1];
27057 i += 1;
27058 dst += 1;
27059 continue;
27060 }
27061 }
27062
27063 src.data[dst] = src.data[i];
27064 dst += 1;
27065 }
27066 if (dst == src.count) break;
27067 src.count = dst;
27068 }
27069 }
27070
27071 bool constant = true;
27072 ufbx_quat ref = src.data[0].value;
27073 for (size_t i = 1; i < src.count; i++) {
27074 ufbx_quat v = src.data[i].value;
27075 if (v.x != ref.x || v.y != ref.y || v.z != ref.z || v.y != ref.w) {
27076 constant = false;
27077 break;
27078 }
27079 }
27080 *p_constant = constant;
27081
27082 p_dst->count = src.count;
27083 p_dst->data = ufbxi_push_copy(&bc->result, ufbx_baked_quat, src.count, src.data);
27084 ufbxi_check_err(&bc->error, p_dst->data);
27085
27086 return 1;
27087 }
27088
27089 static ufbxi_forceinline double ufbxi_bake_time_sample_time(ufbxi_bake_time time)
27090 {
27091 // Move an infinitesimal step for stepped tangents
27092 if ((time.flags & (UFBX_BAKED_KEY_STEP_LEFT|UFBX_BAKED_KEY_STEP_RIGHT)) != 0) {
27093 double dir = (time.flags & UFBX_BAKED_KEY_STEP_LEFT) != 0 ? -UFBX_INFINITY : UFBX_INFINITY;
27094 return ufbx_nextafter(time.time, dir);
27095 } else {
27096 return time.time;
27097 }
27098 }
27099
27100 ufbxi_nodiscard static ufbxi_noinline int ufbxi_push_resampled_times(ufbxi_bake_context *bc, const ufbx_baked_vec3_list *p_keys)
27101 {
27102 ufbx_baked_vec3_list keys = *p_keys;
27103
27104 ufbxi_bake_time *times = ufbxi_push(&bc->tmp_times, ufbxi_bake_time, keys.count);
27105 ufbxi_check_err(&bc->error, times);
27106 for (size_t i = 0; i < keys.count; i++) {
27107 ufbx_baked_key_flags flags = keys.data[i].flags;
27108 double time = keys.data[i].time;
27109 if ((flags & UFBX_BAKED_KEY_STEP_LEFT) != 0 && i + 1 < keys.count && (keys.data[i + 1].flags & UFBX_BAKED_KEY_STEP_KEY) != 0) {
27110 time = keys.data[i + 1].time;
27111 } else if ((flags & UFBX_BAKED_KEY_STEP_RIGHT) != 0 && i > 0 && (keys.data[i - 1].flags & UFBX_BAKED_KEY_STEP_KEY) != 0) {
27112 time = keys.data[i - 1].time;
27113 }
27114 times[i].time = time;
27115 times[i].flags = flags & 0x7;
27116 }
27117
27118 return 1;
27119 }
27120
27121 ufbxi_nodiscard static ufbxi_noinline int ufbxi_bake_node_imp(ufbxi_bake_context *bc, uint32_t element_id, ufbxi_bake_prop *props, size_t count)
27122 {
27123 ufbx_assert(bc->baked_nodes && bc->nodes_to_bake);
27124
27125 ufbx_node *node = (ufbx_node*)bc->scene->elements.data[element_id];
27126 ufbxi_dev_assert(node->element.type == UFBX_ELEMENT_NODE);
27127
27128 bool complex_translation = false;
27129 bool complex_rotation = false;
27130
27131 for (size_t i = 0; i < ufbxi_arraycount(ufbxi_complex_translation_props); i++) {
27132 const char *name = ufbxi_complex_translation_props[i];
27133 ufbx_prop *prop = ufbxi_find_prop(&node->props, name);
27134 if (prop && !ufbxi_is_vec3_zero(prop->value_vec3)) {
27135 complex_translation = true;
27136 }
27137 ufbxi_for(ufbxi_bake_prop, bprop, props, count) {
27138 if (bprop->prop_name == name) {
27139 complex_translation = true;
27140 }
27141 }
27142 }
27143
27144 for (size_t i = 0; i < ufbxi_arraycount(ufbxi_complex_rotation_props); i++) {
27145 const char *name = ufbxi_complex_rotation_props[i];
27146 ufbxi_for(ufbxi_bake_prop, bprop, props, count) {
27147 if (bprop->prop_name == name) {
27148 complex_rotation = true;
27149 }
27150 }
27151 }
27152
27153 ufbxi_bake_time_list times_t, times_r, times_s;
27154
27155 // Translation
27156 bool resample_translation = false;
27157
27158 // Account for the _resampled_ scale helper scale animation to keep the
27159 // translation scale consistent with the parent scaling.
27160 ufbx_baked_node *scale_helper_t = NULL;
27161 ufbx_vec3 constant_scale_t = { 1.0f, 1.0f, 1.0f };
27162 if (!node->is_scale_helper && node->parent && node->parent->scale_helper) {
27163 scale_helper_t = bc->baked_nodes[node->parent->scale_helper->typed_id];
27164 if (scale_helper_t) {
27165 if (!scale_helper_t->constant_scale) {
27166 resample_translation = true;
27167 }
27168 ufbxi_check_err(&bc->error, ufbxi_push_resampled_times(bc, &scale_helper_t->scale_keys));
27169 } else {
27170 constant_scale_t = node->parent->scale_helper->inherit_scale;
27171 }
27172 }
27173
27174 if (complex_translation) {
27175 ufbxi_for(ufbxi_bake_prop, prop, props, count) {
27176 // Literally any transform related property can affect complex translation
27177 if (ufbxi_in_list(ufbxi_transform_props, ufbxi_arraycount(ufbxi_transform_props), prop->prop_name)) {
27178 bool resample_linear = resample_translation || prop->prop_name != ufbxi_Lcl_Translation;
27179 uint32_t key_flag = prop->prop_name == ufbxi_Lcl_Translation ? UFBX_BAKED_KEY_KEYFRAME : 0;
27180 ufbxi_check_err(&bc->error, ufbxi_bake_times(bc, prop->anim_value, resample_linear, key_flag));
27181 }
27182 }
27183 } else {
27184 ufbxi_for(ufbxi_bake_prop, prop, props, count) {
27185 if (prop->prop_name == ufbxi_Lcl_Translation) {
27186 ufbxi_check_err(&bc->error, ufbxi_bake_times(bc, prop->anim_value, resample_translation, UFBX_BAKED_KEY_KEYFRAME));
27187 }
27188 }
27189 }
27190
27191 ufbxi_check_err(&bc->error, ufbxi_finalize_bake_times(bc, &times_t));
27192
27193 // Rotation
27194 if (complex_rotation) {
27195 ufbxi_for(ufbxi_bake_prop, prop, props, count) {
27196 if (ufbxi_in_list(ufbxi_complex_rotation_sources, ufbxi_arraycount(ufbxi_complex_rotation_sources), prop->prop_name)) {
27197 bool resample_linear = !bc->opts.no_resample_rotation || prop->prop_name != ufbxi_Lcl_Rotation;
27198 uint32_t key_flag = prop->prop_name == ufbxi_Lcl_Rotation ? UFBX_BAKED_KEY_KEYFRAME : 0;
27199 ufbxi_check_err(&bc->error, ufbxi_bake_times(bc, prop->anim_value, resample_linear, key_flag));
27200 }
27201 }
27202 } else {
27203 ufbxi_for(ufbxi_bake_prop, prop, props, count) {
27204 if (prop->prop_name == ufbxi_Lcl_Rotation) {
27205 ufbxi_check_err(&bc->error, ufbxi_bake_times(bc, prop->anim_value, !bc->opts.no_resample_rotation, UFBX_BAKED_KEY_KEYFRAME));
27206 }
27207 }
27208 }
27209 ufbxi_check_err(&bc->error, ufbxi_finalize_bake_times(bc, &times_r));
27210
27211 // Scaling
27212 bool resample_scale = false;
27213
27214 // Account for the resampled scale
27215 ufbx_baked_node *scale_helper_s = NULL;
27216 ufbx_vec3 constant_scale_s = { 1.0f, 1.0f, 1.0f };
27217 if (node->is_scale_helper && node->parent && node->parent->inherit_scale_node && node->parent->inherit_scale_node->scale_helper) {
27218 ufbx_node *inherit_helper = node->parent->inherit_scale_node->scale_helper;
27219 scale_helper_s = bc->baked_nodes[inherit_helper->typed_id];
27220 if (scale_helper_s) {
27221 if (!scale_helper_s->constant_scale) {
27222 resample_scale = true;
27223 }
27224 ufbxi_check_err(&bc->error, ufbxi_push_resampled_times(bc, &scale_helper_s->scale_keys));
27225 } else {
27226 constant_scale_s = inherit_helper->local_transform.scale;
27227 }
27228 }
27229
27230 ufbxi_for(ufbxi_bake_prop, prop, props, count) {
27231 if (prop->prop_name == ufbxi_Lcl_Scaling) {
27232 ufbxi_check_err(&bc->error, ufbxi_bake_times(bc, prop->anim_value, resample_scale, UFBX_BAKED_KEY_KEYFRAME));
27233 }
27234 }
27235 ufbxi_check_err(&bc->error, ufbxi_finalize_bake_times(bc, &times_s));
27236
27237 ufbx_baked_vec3_list keys_t;
27238 ufbx_baked_quat_list keys_r;
27239 ufbx_baked_vec3_list keys_s;
27240
27241 keys_t.count = times_t.count;
27242 keys_t.data = ufbxi_push(&bc->tmp_prop, ufbx_baked_vec3, keys_t.count);
27243 ufbxi_check_err(&bc->error, keys_t.data);
27244
27245 keys_r.count = times_r.count;
27246 keys_r.data = ufbxi_push(&bc->tmp_prop, ufbx_baked_quat, keys_r.count);
27247 ufbxi_check_err(&bc->error, keys_r.data);
27248
27249 keys_s.count = times_s.count;
27250 keys_s.data = ufbxi_push(&bc->tmp_prop, ufbx_baked_vec3, keys_s.count);
27251 ufbxi_check_err(&bc->error, keys_s.data);
27252
27253 size_t ix_t = 0, ix_r = 0, ix_s = 0;
27254 while (ix_t < times_t.count || ix_r < times_r.count || ix_s < times_s.count) {
27255 ufbxi_bake_time bake_time = { UFBX_INFINITY };
27256 uint32_t flags_r = 0, flags_t = 0, flags_s = 0;
27257
27258 uint32_t flags = 0;
27259 if (ix_r < times_r.count) {
27260 bake_time = times_r.data[ix_r];
27261 flags_r = bake_time.flags;
27262 bake_time.flags &= 0x7;
27263 flags |= UFBX_TRANSFORM_FLAG_INCLUDE_ROTATION;
27264 }
27265 if (ix_t < times_t.count) {
27266 ufbxi_bake_time t = times_t.data[ix_t];
27267 int cmp = ufbxi_cmp_bake_time(t, bake_time);
27268 if (cmp <= 0) {
27269 if (cmp < 0) {
27270 bake_time = t;
27271 flags = 0;
27272 }
27273 bake_time.flags |= t.flags & 0x7;
27274 flags_t = t.flags;
27275 flags |= UFBX_TRANSFORM_FLAG_INCLUDE_TRANSLATION;
27276 }
27277 }
27278 if (ix_s < times_s.count) {
27279 ufbxi_bake_time t = times_s.data[ix_s];
27280 int cmp = ufbxi_cmp_bake_time(t, bake_time);
27281 if (cmp <= 0) {
27282 if (cmp < 0) {
27283 bake_time = t;
27284 flags = 0;
27285 }
27286 bake_time.flags |= t.flags & 0x7;
27287 flags_s = t.flags;
27288 flags |= UFBX_TRANSFORM_FLAG_INCLUDE_SCALE;
27289 }
27290 }
27291
27292 flags |= UFBX_TRANSFORM_FLAG_IGNORE_SCALE_HELPER|UFBX_TRANSFORM_FLAG_IGNORE_COMPONENTWISE_SCALE|UFBX_TRANSFORM_FLAG_EXPLICIT_INCLUDES;
27293 if (bc->opts.evaluate_flags & UFBX_EVALUATE_FLAG_NO_EXTRAPOLATION) {
27294 flags |= UFBX_TRANSFORM_FLAG_NO_EXTRAPOLATION;
27295 }
27296
27297 double eval_time = ufbxi_bake_time_sample_time(bake_time);
27298 ufbx_transform transform = ufbx_evaluate_transform_flags(bc->anim, node, eval_time, flags);
27299
27300 if (flags & UFBX_TRANSFORM_FLAG_INCLUDE_TRANSLATION) {
27301 if (scale_helper_t) {
27302 ufbx_vec3 scale = ufbx_evaluate_baked_vec3(scale_helper_t->scale_keys, eval_time);
27303 transform.translation.x *= scale.x;
27304 transform.translation.y *= scale.y;
27305 transform.translation.z *= scale.z;
27306 }
27307
27308 transform.translation.x *= constant_scale_t.x;
27309 transform.translation.y *= constant_scale_t.y;
27310 transform.translation.z *= constant_scale_t.z;
27311
27312 keys_t.data[ix_t].time = bake_time.time;
27313 keys_t.data[ix_t].value = transform.translation;
27314 keys_t.data[ix_t].flags = (ufbx_baked_key_flags)(bake_time.flags | flags_t);
27315 ix_t++;
27316 }
27317 if (flags & UFBX_TRANSFORM_FLAG_INCLUDE_ROTATION) {
27318 keys_r.data[ix_r].time = bake_time.time;
27319 keys_r.data[ix_r].value = transform.rotation;
27320 keys_r.data[ix_r].flags = (ufbx_baked_key_flags)(bake_time.flags | flags_r);
27321 ix_r++;
27322 }
27323 if (flags & UFBX_TRANSFORM_FLAG_INCLUDE_SCALE) {
27324 if (scale_helper_s) {
27325 ufbx_vec3 scale = ufbx_evaluate_baked_vec3(scale_helper_s->scale_keys, eval_time);
27326 transform.scale.x *= scale.x;
27327 transform.scale.y *= scale.y;
27328 transform.scale.z *= scale.z;
27329 }
27330
27331 transform.scale.x *= constant_scale_s.x;
27332 transform.scale.y *= constant_scale_s.y;
27333 transform.scale.z *= constant_scale_s.z;
27334
27335 keys_s.data[ix_s].time = bake_time.time;
27336 keys_s.data[ix_s].value = transform.scale;
27337 keys_s.data[ix_s].flags = (ufbx_baked_key_flags)(bake_time.flags | flags_s);
27338 ix_s++;
27339 }
27340 }
27341
27342 ufbx_baked_node *baked_node = ufbxi_push_zero(&bc->tmp_nodes, ufbx_baked_node, 1);
27343 ufbxi_check_err(&bc->error, baked_node);
27344
27345 baked_node->element_id = node->element_id;
27346 baked_node->typed_id = node->typed_id;
27347 ufbxi_check_err(&bc->error, ufbxi_bake_postprocess_vec3(bc, &baked_node->translation_keys, &baked_node->constant_translation, keys_t));
27348 ufbxi_check_err(&bc->error, ufbxi_bake_postprocess_quat(bc, &baked_node->rotation_keys, &baked_node->constant_rotation, keys_r));
27349 ufbxi_check_err(&bc->error, ufbxi_bake_postprocess_vec3(bc, &baked_node->scale_keys, &baked_node->constant_scale, keys_s));
27350
27351 bc->baked_nodes[node->typed_id] = baked_node;
27352
27353 ufbxi_buf_clear(&bc->tmp_prop);
27354
27355 // If this node is a scale helper, make sure to bake its siblings and
27356 // potentially their scale helpers if they are not a part of the animation.
27357 if (node->is_scale_helper) {
27358 ufbx_assert(node->parent);
27359 ufbxi_for_ptr_list(ufbx_node, p_child, node->parent->children) {
27360 ufbx_node *child = *p_child;
27361 if (child == node) continue;
27362 if (!bc->nodes_to_bake[child->typed_id]) {
27363 bc->nodes_to_bake[child->typed_id] = true;
27364 ufbxi_check_err(&bc->error, ufbxi_push_copy(&bc->tmp_bake_stack, uint32_t, 1, &child->element_id));
27365 }
27366 if (child->inherit_scale_node && child->inherit_scale_node->scale_helper && child->scale_helper
27367 && bc->nodes_to_bake[child->inherit_scale_node->scale_helper->typed_id]) {
27368 ufbx_assert(bc->baked_nodes[child->inherit_scale_node->scale_helper->typed_id]);
27369 if (!bc->nodes_to_bake[child->scale_helper->typed_id]) {
27370 bc->nodes_to_bake[child->scale_helper->typed_id] = true;
27371 ufbxi_check_err(&bc->error, ufbxi_push_copy(&bc->tmp_bake_stack, uint32_t, 1, &child->scale_helper->element_id));
27372 }
27373 }
27374 }
27375 }
27376
27377 return 1;
27378 }
27379
27380 ufbxi_nodiscard static ufbxi_noinline int ufbxi_bake_node(ufbxi_bake_context *bc, uint32_t element_id, ufbxi_bake_prop *props, size_t count)
27381 {
27382 ufbxi_check_err(&bc->error, ufbxi_bake_node_imp(bc, element_id, props, count));
27383
27384 // Baking a node may cause further nodes to be baked, so keep going
27385 // until all dependencies are baked.
27386 while (bc->tmp_bake_stack.num_items > 0) {
27387 uint32_t child_id = 0;
27388 ufbxi_pop(&bc->tmp_bake_stack, uint32_t, 1, &child_id);
27389 ufbxi_check_err(&bc->error, ufbxi_bake_node_imp(bc, child_id, NULL, 0));
27390 }
27391
27392 return 1;
27393 }
27394
27395 ufbxi_nodiscard static ufbxi_noinline int ufbxi_bake_anim_prop(ufbxi_bake_context *bc, ufbx_element *element, const char *prop_name, ufbxi_bake_prop *props, size_t count)
27396 {
27397 ufbxi_for(ufbxi_bake_prop, prop, props, count) {
27398 ufbxi_check_err(&bc->error, ufbxi_bake_times(bc, prop->anim_value, false, UFBX_BAKED_KEY_KEYFRAME));
27399 }
27400
27401 ufbxi_bake_time_list times;
27402 ufbxi_check_err(&bc->error, ufbxi_finalize_bake_times(bc, &times));
27403
27404 ufbx_baked_vec3_list keys;
27405 keys.count = times.count;
27406 keys.data = ufbxi_push(&bc->tmp_prop, ufbx_baked_vec3, keys.count);
27407 ufbxi_check_err(&bc->error, keys.data);
27408
27409 ufbx_string name;
27410 name.data = prop_name;
27411 name.length = strlen(prop_name);
27412
27413 for (size_t i = 0; i < times.count; i++) {
27414 ufbxi_bake_time bake_time = times.data[i];
27415 double eval_time = ufbxi_bake_time_sample_time(bake_time);
27416 ufbx_prop prop = ufbx_evaluate_prop_len_flags(bc->anim, element, name.data, name.length, eval_time, bc->opts.evaluate_flags);
27417 keys.data[i].time = bake_time.time;
27418 keys.data[i].value = prop.value_vec3;
27419 keys.data[i].flags = (ufbx_baked_key_flags)bake_time.flags;
27420 }
27421
27422 ufbx_baked_prop *baked_prop = ufbxi_push_zero(&bc->tmp_props, ufbx_baked_prop, 1);
27423 ufbxi_check_err(&bc->error, baked_prop);
27424
27425 baked_prop->name.length = strlen(prop_name);
27426 baked_prop->name.data = ufbxi_push_copy(&bc->result, char, baked_prop->name.length + 1, prop_name);
27427 ufbxi_check_err(&bc->error, baked_prop->name.data);
27428
27429 ufbxi_check_err(&bc->error, ufbxi_bake_postprocess_vec3(bc, &baked_prop->keys, &baked_prop->constant_value, keys));
27430
27431 ufbxi_buf_clear(&bc->tmp_prop);
27432
27433 return 1;
27434 }
27435
27436 ufbxi_nodiscard static ufbxi_noinline int ufbxi_bake_element(ufbxi_bake_context *bc, uint32_t element_id, ufbxi_bake_prop *props, size_t count)
27437 {
27438 ufbx_element *element = bc->scene->elements.data[element_id];
27439 if (element->type == UFBX_ELEMENT_NODE && !bc->opts.skip_node_transforms) {
27440 ufbxi_check_err(&bc->error, ufbxi_bake_node(bc, element_id, props, count));
27441 }
27442
27443 size_t begin = 0;
27444 while (begin < count) {
27445 const char *prop_name = props[begin].prop_name;
27446 size_t end = begin + 1;
27447 while (end < count && props[end].prop_name == prop_name) {
27448 end++;
27449 }
27450
27451 // Don't bake transform related props for nodes unless specifically requested
27452 if (element->type == UFBX_ELEMENT_NODE && !bc->opts.bake_transform_props && ufbxi_in_list(ufbxi_transform_props, ufbxi_arraycount(ufbxi_transform_props), prop_name)) {
27453 begin = end;
27454 continue;
27455 }
27456
27457 ufbxi_check_err(&bc->error, ufbxi_bake_anim_prop(bc, element, prop_name, props + begin, end - begin));
27458 begin = end;
27459 }
27460
27461 size_t num_props = bc->tmp_props.num_items;
27462 if (num_props > 0) {
27463 ufbx_baked_element *baked_elem = ufbxi_push_zero(&bc->tmp_elements, ufbx_baked_element, 1);
27464 ufbxi_check_err(&bc->error, baked_elem);
27465
27466 baked_elem->element_id = element->element_id;
27467 baked_elem->props.count = num_props;
27468 baked_elem->props.data = ufbxi_push_pop(&bc->result, &bc->tmp_props, ufbx_baked_prop, num_props);
27469 ufbxi_check_err(&bc->error, baked_elem->props.data);
27470 }
27471
27472 return 1;
27473 }
27474
27475 static ufbxi_noinline bool ufbxi_baked_node_less(void *user, const void *va, const void *vb)
27476 {
27477 (void)user;
27478 const ufbx_baked_node *a = (const ufbx_baked_node*)va, *b = (const ufbx_baked_node*)vb;
27479 return a->typed_id < b->typed_id;
27480 }
27481
27482 static ufbxi_noinline bool ufbxi_baked_element_less(void *user, const void *va, const void *vb)
27483 {
27484 (void)user;
27485 const ufbx_baked_element *a = (const ufbx_baked_element*)va, *b = (const ufbx_baked_element*)vb;
27486 return a->element_id < b->element_id;
27487 }
27488
27489 ufbxi_nodiscard static ufbxi_noinline int ufbxi_bake_anim(ufbxi_bake_context *bc)
27490 {
27491 const ufbx_anim *anim = bc->anim;
27492 const ufbx_scene *scene = bc->scene;
27493
27494 if (!bc->opts.skip_node_transforms) {
27495 bc->baked_nodes = ufbxi_push_zero(&bc->result, ufbx_baked_node*, scene->nodes.count);
27496 ufbxi_check_err(&bc->error, bc->baked_nodes);
27497 bc->nodes_to_bake = ufbxi_push_zero(&bc->result, bool, scene->nodes.count);
27498 ufbxi_check_err(&bc->error, bc->nodes_to_bake);
27499 }
27500
27501 ufbxi_for_ptr_list(ufbx_anim_layer, p_layer, anim->layers) {
27502 ufbx_anim_layer *layer = *p_layer;
27503
27504 ufbxi_for_list(ufbx_anim_prop, anim_prop, layer->anim_props) {
27505 ufbxi_bake_prop *prop = ufbxi_push(&bc->tmp_bake_props, ufbxi_bake_prop, 1);
27506 ufbxi_check_err(&bc->error, prop);
27507
27508 ufbx_element *element = anim_prop->element;
27509
27510 // Sort nodes by `typed_id` to make sure we process them in order.
27511 if (element->type == UFBX_ELEMENT_NODE) {
27512 if (bc->nodes_to_bake) {
27513 bc->nodes_to_bake[element->typed_id] = true;
27514 }
27515 prop->sort_id = element->typed_id;
27516 } else {
27517 prop->sort_id = UINT32_MAX;
27518 }
27519
27520 prop->element_id = element->element_id;
27521 prop->prop_name = anim_prop->prop_name.data;
27522 prop->anim_value = anim_prop->anim_value;
27523 }
27524 }
27525
27526 size_t num_props = bc->tmp_bake_props.num_items;
27527 ufbxi_bake_prop *props = ufbxi_push_pop(&bc->tmp, &bc->tmp_bake_props, ufbxi_bake_prop, num_props);
27528 ufbxi_check_err(&bc->error, props);
27529
27530 ufbxi_unstable_sort(props, num_props, sizeof(ufbxi_bake_prop), &ufbxi_bake_prop_less, NULL);
27531
27532 // Pre-bake layer weight times
27533 if (!bc->opts.ignore_layer_weight_animation) {
27534 bool has_weight_times = false;
27535 ufbxi_for(ufbxi_bake_prop, prop, props, num_props) {
27536 if (prop->prop_name != ufbxi_Weight) continue;
27537 ufbx_element *element = scene->elements.data[prop->element_id];
27538 if (element->type == UFBX_ELEMENT_ANIM_LAYER) {
27539 ufbxi_check_err(&bc->error, ufbxi_bake_times(bc, prop->anim_value, true, 0));
27540 has_weight_times = true;
27541 }
27542 }
27543
27544 if (has_weight_times) {
27545 ufbxi_bake_time_list weight_times = { 0 };
27546 ufbxi_check_err(&bc->error, ufbxi_finalize_bake_times(bc, &weight_times));
27547
27548 bc->layer_weight_times.count = weight_times.count;
27549 bc->layer_weight_times.data = ufbxi_push_copy(&bc->tmp, ufbxi_bake_time, weight_times.count, weight_times.data);
27550 ufbxi_check_err(&bc->error, bc->layer_weight_times.data);
27551
27552 ufbxi_buf_clear(&bc->tmp_prop);
27553 }
27554 }
27555
27556 size_t begin = 0;
27557 while (begin < num_props) {
27558 uint32_t element_id = props[begin].element_id;
27559 size_t end = begin + 1;
27560 while (end < num_props && props[end].element_id == element_id) {
27561 end++;
27562 }
27563 ufbxi_check_err(&bc->error, ufbxi_bake_element(bc, element_id, props + begin, end - begin));
27564 begin = end;
27565 }
27566
27567 size_t num_nodes = bc->tmp_nodes.num_items;
27568 size_t num_elements = bc->tmp_elements.num_items;
27569
27570 bc->bake.nodes.count = num_nodes;
27571 bc->bake.nodes.data = ufbxi_push_pop(&bc->result, &bc->tmp_nodes, ufbx_baked_node, num_nodes);
27572 ufbxi_check_err(&bc->error, bc->bake.nodes.data);
27573
27574 bc->bake.elements.count = num_elements;
27575 bc->bake.elements.data = ufbxi_push_pop(&bc->result, &bc->tmp_elements, ufbx_baked_element, num_elements);
27576 ufbxi_check_err(&bc->error, bc->bake.elements.data);
27577
27578 ufbxi_unstable_sort(bc->bake.nodes.data, bc->bake.nodes.count, sizeof(ufbx_baked_node), &ufbxi_baked_node_less, NULL);
27579 ufbxi_unstable_sort(bc->bake.elements.data, bc->bake.elements.count, sizeof(ufbx_baked_element), &ufbxi_baked_element_less, NULL);
27580
27581 if (bc->time_min < bc->time_max) {
27582 bc->bake.key_time_min = bc->time_min;
27583 bc->bake.key_time_max = bc->time_max;
27584 }
27585
27586 if (bc->time_begin < bc->time_end) {
27587 bc->bake.playback_time_begin = bc->time_begin;
27588 bc->bake.playback_time_end = bc->time_end;
27589 bc->bake.playback_duration = bc->time_end - bc->time_begin;
27590 }
27591
27592 return 1;
27593 }
27594
27595 ufbxi_nodiscard static ufbxi_noinline int ufbxi_bake_anim_imp(ufbxi_bake_context *bc, const ufbx_anim *anim)
27596 {
27597 if (bc->opts.resample_rate <= 0.0) bc->opts.resample_rate = 30.0;
27598 if (bc->opts.minimum_sample_rate <= 0.0) bc->opts.minimum_sample_rate = 19.5;
27599 if (bc->opts.max_keyframe_segments == 0) bc->opts.max_keyframe_segments = 32;
27600 if (bc->opts.key_reduction_threshold == 0) bc->opts.key_reduction_threshold = 0.000001;
27601 if (bc->opts.key_reduction_passes == 0) bc->opts.key_reduction_passes = 4;
27602
27603 if (bc->opts.trim_start_time && anim->time_begin > 0.0) {
27604 bc->ktime_offset = -anim->time_begin * (double)bc->scene->metadata.ktime_second;
27605 }
27606
27607 ufbxi_init_ator(&bc->error, &bc->ator_tmp, &bc->opts.temp_allocator, "temp");
27608 ufbxi_init_ator(&bc->error, &bc->ator_result, &bc->opts.result_allocator, "result");
27609
27610 bc->result.unordered = true;
27611 bc->result.ator = &bc->ator_result;
27612
27613 bc->tmp.unordered = true;
27614 bc->tmp.ator = &bc->ator_tmp;
27615
27616 bc->tmp_prop.ator = &bc->ator_tmp;
27617 bc->tmp_prop.unordered = true;
27618 bc->tmp_prop.clearable = true;
27619
27620 bc->tmp_times.ator = &bc->ator_tmp;
27621 bc->tmp_bake_props.ator = &bc->ator_tmp;
27622 bc->tmp_nodes.ator = &bc->ator_tmp;
27623 bc->tmp_elements.ator = &bc->ator_tmp;
27624 bc->tmp_props.ator = &bc->ator_tmp;
27625 bc->tmp_bake_stack.ator = &bc->ator_tmp;
27626
27627 bc->anim = anim;
27628 if (anim->time_begin < anim->time_end) {
27629 bc->time_begin = anim->time_begin;
27630 bc->time_end = anim->time_end;
27631 }
27632 bc->time_min = UFBX_INFINITY;
27633 bc->time_max = -UFBX_INFINITY;
27634
27635 bc->imp = ufbxi_push(&bc->result, ufbxi_baked_anim_imp, 1);
27636 ufbxi_check_err(&bc->error, bc->imp);
27637
27638 ufbxi_check_err(&bc->error, ufbxi_bake_anim(bc));
27639
27640 ufbxi_init_ref(&bc->imp->refcount, UFBXI_BAKED_ANIM_IMP_MAGIC, NULL);
27641
27642 bc->bake.metadata.result_memory_used = bc->ator_result.current_size;
27643 bc->bake.metadata.temp_memory_used = bc->ator_tmp.current_size;
27644 bc->bake.metadata.result_allocs = bc->ator_result.num_allocs;
27645 bc->bake.metadata.temp_allocs = bc->ator_tmp.num_allocs;
27646
27647 bc->imp->magic = UFBXI_BAKED_ANIM_IMP_MAGIC;
27648 bc->imp->bake = bc->bake;
27649 bc->imp->refcount.ator = bc->ator_result;
27650 bc->imp->refcount.buf = bc->result;
27651
27652 return 1;
27653 }
27654
27655 #endif
27656
27657 // -- NURBS
27658
27659 static ufbxi_forceinline ufbx_real ufbxi_nurbs_weight(const ufbx_real_list *knots, size_t knot, size_t degree, ufbx_real u)
27660 {
27661 if (knot >= knots->count) return 0.0f;
27662 if (knots->count - knot < degree) return 0.0f;
27663 ufbx_real prev_u = knots->data[knot], next_u = knots->data[knot + degree];
27664 if (prev_u >= next_u) return 0.0f;
27665 if (u <= prev_u) return 0.0f;
27666 if (u >= next_u) return 1.0f;
27667 return (u - prev_u) / (next_u - prev_u);
27668 }
27669
27670 static ufbxi_forceinline ufbx_real ufbxi_nurbs_deriv(const ufbx_real_list *knots, size_t knot, size_t degree)
27671 {
27672 if (knot >= knots->count) return 0.0f;
27673 if (knots->count - knot < degree) return 0.0f;
27674 ufbx_real prev_u = knots->data[knot], next_u = knots->data[knot + degree];
27675 if (prev_u >= next_u) return 0.0f;
27676 return (ufbx_real)degree / (next_u - prev_u);
27677 }
27678
27679 typedef struct {
27680 ufbxi_refcount refcount;
27681 ufbx_line_curve curve;
27682 uint32_t magic;
27683 } ufbxi_line_curve_imp;
27684
27685 ufbx_static_assert(line_curve_imp_offset, offsetof(ufbxi_line_curve_imp, curve) == sizeof(ufbxi_refcount));
27686
27687 #if UFBXI_FEATURE_TESSELLATION
27688
27689 typedef struct {
27690 ufbx_error error;
27691
27692 ufbx_tessellate_curve_opts opts;
27693
27694 const ufbx_nurbs_curve *curve;
27695
27696 ufbxi_allocator ator_tmp;
27697 ufbxi_allocator ator_result;
27698
27699 ufbxi_buf result;
27700
27701 ufbx_line_curve line;
27702
27703 ufbxi_line_curve_imp *imp;
27704
27705 } ufbxi_tessellate_curve_context;
27706
27707 typedef struct {
27708 ufbx_error error;
27709
27710 ufbx_tessellate_surface_opts opts;
27711
27712 const ufbx_nurbs_surface *surface;
27713
27714 ufbxi_allocator ator_tmp;
27715 ufbxi_allocator ator_result;
27716
27717 ufbxi_buf tmp;
27718 ufbxi_buf result;
27719
27720 ufbxi_map position_map;
27721
27722 ufbx_mesh mesh;
27723
27724 ufbxi_mesh_imp *imp;
27725
27726 } ufbxi_tessellate_surface_context;
27727
27728 ufbxi_nodiscard static ufbxi_noinline int ufbxi_tessellate_nurbs_curve_imp(ufbxi_tessellate_curve_context *tc)
27729 {
27730 if (tc->opts.span_subdivision <= 0) {
27731 tc->opts.span_subdivision = 4;
27732 }
27733 size_t num_sub = tc->opts.span_subdivision;
27734
27735 const ufbx_nurbs_curve *curve = tc->curve;
27736 ufbx_line_curve *line = &tc->line;
27737 ufbxi_check_err_msg(&tc->error, curve->basis.valid && curve->control_points.count > 0, "Bad NURBS geometry");
27738
27739 ufbxi_init_ator(&tc->error, &tc->ator_tmp, &tc->opts.temp_allocator, "temp");
27740 ufbxi_init_ator(&tc->error, &tc->ator_result, &tc->opts.result_allocator, "result");
27741
27742 tc->result.unordered = true;
27743 tc->result.ator = &tc->ator_result;
27744
27745 size_t num_spans = curve->basis.spans.count;
27746
27747 // Check conservatively that we don't overflow anything
27748 {
27749 size_t over_spans = num_spans * 2 * sizeof(ufbx_real);
27750 size_t over = over_spans * num_sub;
27751 ufbxi_check_err(&tc->error, !ufbxi_does_overflow(over, over_spans, num_sub));
27752 }
27753
27754 bool is_open = curve->basis.topology == UFBX_NURBS_TOPOLOGY_OPEN;
27755
27756 size_t num_indices = num_spans + (num_spans - 1) * (num_sub - 1);
27757 size_t num_vertices = num_indices - (is_open ? 0u : 1u);
27758 ufbxi_check_err(&tc->error, num_indices <= INT32_MAX);
27759
27760 uint32_t *indices = ufbxi_push(&tc->result, uint32_t, num_indices);
27761 ufbx_vec3 *vertices = ufbxi_push(&tc->result, ufbx_vec3, num_vertices);
27762 ufbx_line_segment *segments = ufbxi_push(&tc->result, ufbx_line_segment, 1);
27763 ufbxi_check_err(&tc->error, indices && vertices && segments);
27764
27765 for (size_t span_ix = 0; span_ix < num_spans; span_ix++) {
27766 size_t num_splits = span_ix + 1 == num_spans ? 1 : num_sub;
27767
27768 for (size_t sub_ix = 0; sub_ix < num_splits; sub_ix++) {
27769 size_t ix = span_ix * num_sub + sub_ix;
27770
27771 if (ix < num_vertices) {
27772 ufbx_real u = curve->basis.spans.data[span_ix];
27773 if (sub_ix > 0) {
27774 ufbx_real t = (ufbx_real)sub_ix / (ufbx_real)num_sub;
27775 u = u * (1.0f - t) + t * curve->basis.spans.data[span_ix + 1];
27776 }
27777
27778 ufbx_curve_point point = ufbx_evaluate_nurbs_curve(curve, u);
27779 vertices[ix] = point.position;
27780 indices[ix] = (uint32_t)ix;
27781 } else {
27782 indices[ix] = 0;
27783 }
27784 }
27785 }
27786
27787 segments[0].index_begin = 0;
27788 segments[0].num_indices = (uint32_t)num_indices;
27789
27790 line->element.name.data = ufbxi_empty_char;
27791 line->element.type = UFBX_ELEMENT_LINE_CURVE;
27792 line->element.typed_id = UINT32_MAX;
27793 line->element.element_id = UINT32_MAX;
27794
27795 line->color.x = 1.0f;
27796 line->color.y = 1.0f;
27797 line->color.z = 1.0f;
27798
27799 line->control_points.data = vertices;
27800 line->control_points.count = num_vertices;
27801 line->point_indices.data = indices;
27802 line->point_indices.count = num_indices;
27803 line->segments.data = segments;
27804 line->segments.count = 1;
27805
27806 line->from_tessellated_nurbs = true;
27807
27808 tc->imp = ufbxi_push(&tc->result, ufbxi_line_curve_imp, 1);
27809 ufbxi_check_err(&tc->error, tc->imp);
27810
27811 ufbxi_init_ref(&tc->imp->refcount, UFBXI_LINE_CURVE_IMP_MAGIC, &(ufbxi_get_imp(ufbxi_scene_imp, curve->element.scene))->refcount);
27812
27813 tc->imp->magic = UFBXI_LINE_CURVE_IMP_MAGIC;
27814 tc->imp->curve = tc->line;
27815 tc->imp->refcount.ator = tc->ator_result;
27816 tc->imp->refcount.buf = tc->result;
27817
27818 return 1;
27819 }
27820
27821 ufbxi_nodiscard static ufbxi_noinline int ufbxi_tessellate_nurbs_surface_imp(ufbxi_tessellate_surface_context *tc)
27822 {
27823 if (tc->opts.span_subdivision_u <= 0) {
27824 tc->opts.span_subdivision_u = 4;
27825 }
27826 if (tc->opts.span_subdivision_v <= 0) {
27827 tc->opts.span_subdivision_v = 4;
27828 }
27829
27830 size_t sub_u = tc->opts.span_subdivision_u;
27831 size_t sub_v = tc->opts.span_subdivision_v;
27832
27833 const ufbx_nurbs_surface *surface = tc->surface;
27834 ufbx_mesh *mesh = &tc->mesh;
27835 ufbxi_check_err_msg(&tc->error, surface->basis_u.valid && surface->basis_v.valid
27836 && surface->num_control_points_u > 0 && surface->num_control_points_v > 0, "Bad NURBS geometry");
27837
27838 ufbxi_init_ator(&tc->error, &tc->ator_tmp, &tc->opts.temp_allocator, "temp");
27839 ufbxi_init_ator(&tc->error, &tc->ator_result, &tc->opts.result_allocator, "result");
27840
27841 tc->result.unordered = true;
27842 tc->tmp.unordered = true;
27843
27844 tc->result.ator = &tc->ator_result;
27845 tc->tmp.ator = &tc->ator_tmp;
27846
27847 bool open_u = surface->basis_u.topology == UFBX_NURBS_TOPOLOGY_OPEN;
27848 bool open_v = surface->basis_v.topology == UFBX_NURBS_TOPOLOGY_OPEN;
27849
27850 size_t spans_u = surface->basis_u.spans.count;
27851 size_t spans_v = surface->basis_v.spans.count;
27852
27853 // Check conservatively that we don't overflow anything
27854 {
27855 size_t over_spans_u = spans_u * 2 * sizeof(ufbx_real);
27856 size_t over_spans_v = spans_v * 2 * sizeof(ufbx_real);
27857 size_t over_u = over_spans_u * sub_u;
27858 size_t over_v = over_spans_v * sub_v;
27859 size_t over_uv = over_u * over_v;
27860 ufbxi_check_err(&tc->error, !ufbxi_does_overflow(over_u, over_spans_u, sub_u));
27861 ufbxi_check_err(&tc->error, !ufbxi_does_overflow(over_v, over_spans_v, sub_v));
27862 ufbxi_check_err(&tc->error, !ufbxi_does_overflow(over_uv, over_u, over_v));
27863 }
27864
27865 size_t faces_u = (spans_u - 1) * sub_u;
27866 size_t faces_v = (spans_v - 1) * sub_v;
27867
27868 size_t indices_u = spans_u + (spans_u - 1) * (sub_u - 1);
27869 size_t indices_v = spans_v + (spans_v - 1) * (sub_v - 1);
27870
27871 size_t num_faces = faces_u * faces_v;
27872 size_t num_indices = indices_u * indices_v;
27873 ufbxi_check_err(&tc->error, num_indices <= INT32_MAX);
27874
27875 uint32_t *position_ix = ufbxi_push(&tc->tmp, uint32_t, num_indices);
27876 ufbx_vec3 *positions = ufbxi_push(&tc->result, ufbx_vec3, num_indices + 1);
27877 ufbx_vec3 *normals = ufbxi_push(&tc->result, ufbx_vec3, num_indices + 1);
27878 ufbx_vec2 *uvs = ufbxi_push(&tc->result, ufbx_vec2, num_indices + 1);
27879 ufbx_vec3 *tangents = ufbxi_push(&tc->result, ufbx_vec3, num_indices + 1);
27880 ufbx_vec3 *bitangents = ufbxi_push(&tc->result, ufbx_vec3, num_indices + 1);
27881 ufbxi_check_err(&tc->error, position_ix && uvs && tangents && bitangents);
27882
27883 *positions++ = ufbx_zero_vec3;
27884 *normals++ = ufbx_zero_vec3;
27885 *uvs++ = ufbx_zero_vec2;
27886 *tangents++ = ufbx_zero_vec3;
27887 *bitangents++ = ufbx_zero_vec3;
27888
27889 uint32_t num_positions = 0;
27890
27891 for (size_t span_v = 0; span_v < spans_v; span_v++) {
27892 size_t splits_v = span_v + 1 == spans_v ? 1 : sub_v;
27893
27894 for (size_t split_v = 0; split_v < splits_v; split_v++) {
27895 size_t ix_v = span_v * sub_v + split_v;
27896 ufbx_assert(ix_v < indices_v);
27897
27898 ufbx_real v = surface->basis_v.spans.data[span_v];
27899 if (split_v > 0) {
27900 ufbx_real t = (ufbx_real)split_v / (ufbx_real)splits_v;
27901 v = v * (1.0f - t) + t * surface->basis_v.spans.data[span_v + 1];
27902 }
27903 ufbx_real original_v = v;
27904 if (span_v + 1 == spans_v && !open_v) {
27905 v = surface->basis_v.spans.data[0];
27906 }
27907
27908 for (size_t span_u = 0; span_u < spans_u; span_u++) {
27909 size_t splits_u = span_u + 1 == spans_u ? 1 : sub_u;
27910 for (size_t split_u = 0; split_u < splits_u; split_u++) {
27911 size_t ix_u = span_u * sub_u + split_u;
27912 ufbx_assert(ix_u < indices_u);
27913
27914 ufbx_real u = surface->basis_u.spans.data[span_u];
27915 if (split_u > 0) {
27916 ufbx_real t = (ufbx_real)split_u / (ufbx_real)splits_u;
27917 u = u * (1.0f - t) + t * surface->basis_u.spans.data[span_u + 1];
27918 }
27919 ufbx_real original_u = u;
27920 if (span_u + 1 == spans_u && !open_u) {
27921 u = surface->basis_u.spans.data[0];
27922 }
27923
27924 ufbx_surface_point point = ufbx_evaluate_nurbs_surface(surface, u, v);
27925 ufbx_vec3 pos = point.position;
27926
27927 ufbx_vec3 tangent_u = ufbxi_slow_normalize3(&point.derivative_u);
27928 ufbx_vec3 tangent_v = ufbxi_slow_normalize3(&point.derivative_v);
27929
27930 // Check if there's any wrapped positions that we could match
27931 size_t neighbors[5]; // ufbxi_uninit
27932 size_t num_neighbors = 0;
27933
27934 if ((span_v == 0 && (span_u > 0 || split_u > 0)) || (span_u == 0 && (span_v > 0 || split_v > 0))) {
27935 // Top/left
27936 neighbors[num_neighbors++] = 0;
27937 }
27938 if (span_v + 1 == spans_v) {
27939 // Bottom
27940 neighbors[num_neighbors++] = ix_u;
27941 if (span_u > 0 || split_u > 0) {
27942 neighbors[num_neighbors++] = ix_v * indices_u;
27943 }
27944 }
27945 if (span_u + 1 == spans_u) {
27946 // Right
27947 neighbors[num_neighbors++] = ix_v * indices_u;
27948 if (span_v > 0 || split_v > 0) {
27949 neighbors[num_neighbors++] = indices_u - 1;
27950 }
27951 }
27952
27953 size_t ix = ix_v * indices_u + ix_u;
27954
27955 uint32_t pos_ix = num_positions;
27956 for (size_t i = 0; i < num_neighbors; i++) {
27957 size_t nb_ix = neighbors[i];
27958 ufbx_assert(nb_ix < ix);
27959 uint32_t nb_pos_ix = position_ix[nb_ix];
27960 ufbx_vec3 nb_pos = positions[nb_pos_ix];
27961 ufbx_real dx = nb_pos.x - pos.x;
27962 ufbx_real dy = nb_pos.y - pos.y;
27963 ufbx_real dz = nb_pos.z - pos.z;
27964 ufbx_real delta = dx*dx + dy*dy + dz*dz;
27965 if (delta < 0.0000001f) { // TODO: Configurable / something more rigorous
27966 pos_ix = nb_pos_ix;
27967 break;
27968 }
27969 }
27970
27971 position_ix[ix] = pos_ix;
27972 if (pos_ix == num_positions) {
27973 positions[pos_ix] = pos;
27974 num_positions = pos_ix + 1;
27975 }
27976 uvs[ix].x = original_u;
27977 uvs[ix].y = original_v;
27978 tangents[ix] = tangent_u;
27979 bitangents[ix] = tangent_v;
27980 }
27981 }
27982 }
27983 }
27984
27985 ufbx_face *faces = ufbxi_push(&tc->result, ufbx_face, num_faces);
27986 uint32_t *vertex_ix = ufbxi_push(&tc->result, uint32_t, num_faces * 4);
27987 uint32_t *attrib_ix = ufbxi_push(&tc->result, uint32_t, num_faces * 4);
27988 ufbxi_check_err(&tc->error, faces && vertex_ix && attrib_ix);
27989
27990 size_t face_ix = 0;
27991 size_t dst_index = 0;
27992
27993 size_t num_triangles = 0;
27994
27995 for (size_t face_v = 0; face_v < faces_v; face_v++) {
27996 for (size_t face_u = 0; face_u < faces_u; face_u++) {
27997
27998 attrib_ix[dst_index + 0] = (uint32_t)((face_v + 0) * indices_u + (face_u + 0));
27999 attrib_ix[dst_index + 1] = (uint32_t)((face_v + 0) * indices_u + (face_u + 1));
28000 attrib_ix[dst_index + 2] = (uint32_t)((face_v + 1) * indices_u + (face_u + 1));
28001 attrib_ix[dst_index + 3] = (uint32_t)((face_v + 1) * indices_u + (face_u + 0));
28002
28003 vertex_ix[dst_index + 0] = position_ix[attrib_ix[dst_index + 0]];
28004 vertex_ix[dst_index + 1] = position_ix[attrib_ix[dst_index + 1]];
28005 vertex_ix[dst_index + 2] = position_ix[attrib_ix[dst_index + 2]];
28006 vertex_ix[dst_index + 3] = position_ix[attrib_ix[dst_index + 3]];
28007
28008 bool is_triangle = false;
28009 for (size_t prev_ix = 0; prev_ix < 4; prev_ix++) {
28010 size_t next_ix = (prev_ix + 1) % 4;
28011 if (vertex_ix[dst_index + prev_ix] == vertex_ix[dst_index + next_ix]) {
28012 for (size_t i = next_ix; i < 3; i++) {
28013 attrib_ix[dst_index + i] = attrib_ix[dst_index + i + 1];
28014 vertex_ix[dst_index + i] = vertex_ix[dst_index + i + 1];
28015 }
28016 is_triangle = true;
28017 break;
28018 }
28019 }
28020
28021 faces[face_ix].index_begin = (uint32_t)dst_index;
28022 faces[face_ix].num_indices = is_triangle ? 3 : 4;
28023 dst_index += is_triangle ? 3 : 4;
28024 num_triangles += is_triangle ? 1 : 2;
28025 face_ix++;
28026 }
28027 }
28028
28029 ufbxi_check_err(&tc->error, positions && normals);
28030
28031 mesh->element.name.data = ufbxi_empty_char;
28032 mesh->element.type = UFBX_ELEMENT_MESH;
28033 mesh->element.typed_id = UINT32_MAX;
28034 mesh->element.element_id = UINT32_MAX;
28035
28036 mesh->vertices.data = positions;
28037 mesh->vertices.count = num_positions;
28038 mesh->num_vertices = num_positions;
28039 mesh->vertex_indices.data = vertex_ix;
28040 mesh->vertex_indices.count = dst_index;
28041
28042 mesh->faces.data = faces;
28043 mesh->faces.count = num_faces;
28044
28045 mesh->vertex_position.exists = true;
28046 mesh->vertex_position.values.data = positions;
28047 mesh->vertex_position.values.count = num_positions;
28048 mesh->vertex_position.indices.data = vertex_ix;
28049 mesh->vertex_position.indices.count = dst_index;
28050 mesh->vertex_position.unique_per_vertex = true;
28051
28052 mesh->vertex_uv.exists = true;
28053 mesh->vertex_uv.values.data = uvs;
28054 mesh->vertex_uv.values.count = dst_index;
28055 mesh->vertex_uv.indices.data = attrib_ix;
28056 mesh->vertex_uv.indices.count = dst_index;
28057
28058 mesh->vertex_normal.exists = true;
28059 mesh->vertex_normal.values.data = normals;
28060 mesh->vertex_normal.values.count = num_positions;
28061 mesh->vertex_normal.indices.data = vertex_ix;
28062 mesh->vertex_normal.indices.count = dst_index;
28063
28064 mesh->vertex_tangent.exists = true;
28065 mesh->vertex_tangent.values.data = tangents;
28066 mesh->vertex_tangent.values.count = dst_index;
28067 mesh->vertex_tangent.indices.data = attrib_ix;
28068 mesh->vertex_tangent.indices.count = dst_index;
28069
28070 mesh->vertex_bitangent.exists = true;
28071 mesh->vertex_bitangent.values.data = bitangents;
28072 mesh->vertex_bitangent.values.count = dst_index;
28073 mesh->vertex_bitangent.indices.data = attrib_ix;
28074 mesh->vertex_bitangent.indices.count = dst_index;
28075
28076 mesh->num_faces = num_faces;
28077 mesh->num_triangles = num_triangles;
28078 mesh->num_indices = dst_index;
28079 mesh->max_face_triangles = 2;
28080
28081 if (surface->material) {
28082 mesh->face_material.data = ufbxi_push_zero(&tc->result, uint32_t, num_faces);
28083 ufbxi_check_err(&tc->error, mesh->face_material.data);
28084
28085 ufbx_material **mat = ufbxi_push_zero(&tc->result, ufbx_material*, 1);
28086 ufbxi_check_err(&tc->error, mat);
28087
28088 *mat = surface->material;
28089 mesh->materials.data = mat;
28090 mesh->materials.count = 1;
28091 }
28092
28093 if (!tc->opts.skip_mesh_parts) {
28094 mesh->material_parts.count = 1;
28095 mesh->material_parts.data = ufbxi_push_zero(&tc->result, ufbx_mesh_part, 1);
28096 ufbxi_check_err(&tc->error, mesh->material_parts.data);
28097 }
28098
28099 ufbxi_check_err(&tc->error, ufbxi_finalize_mesh_material(&tc->result, &tc->error, mesh));
28100 ufbxi_check_err(&tc->error, ufbxi_finalize_mesh(&tc->result, &tc->error, mesh));
28101
28102 mesh->generated_normals = true;
28103 ufbx_compute_normals(mesh, &mesh->vertex_position,
28104 mesh->vertex_normal.indices.data, mesh->vertex_normal.indices.count,
28105 mesh->vertex_normal.values.data, mesh->vertex_normal.values.count);
28106
28107 if (surface->flip_normals) {
28108 ufbxi_nounroll ufbxi_for_list(ufbx_vec3, normal, mesh->vertex_normal.values) {
28109 normal->x *= -1.0f;
28110 normal->y *= -1.0f;
28111 normal->z *= -1.0f;
28112 }
28113 }
28114
28115 tc->imp = ufbxi_push(&tc->result, ufbxi_mesh_imp, 1);
28116 ufbxi_check_err(&tc->error, tc->imp);
28117
28118 ufbxi_init_ref(&tc->imp->refcount, UFBXI_MESH_IMP_MAGIC, &(ufbxi_get_imp(ufbxi_scene_imp, surface->element.scene))->refcount);
28119
28120 tc->imp->magic = UFBXI_MESH_IMP_MAGIC;
28121 tc->imp->mesh = tc->mesh;
28122 tc->imp->refcount.ator = tc->ator_result;
28123 tc->imp->refcount.buf = tc->result;
28124 tc->imp->mesh.subdivision_evaluated = true;
28125
28126 return 1;
28127 }
28128
28129 #endif
28130
28131 // -- Topology
28132
28133 #if UFBXI_FEATURE_KD
28134
28135 typedef struct {
28136 ufbx_real split;
28137 uint32_t index_plus_one; // 0 for empty
28138 uint32_t slow_left;
28139 uint32_t slow_right;
28140 uint32_t slow_end;
28141 } ufbxi_kd_node;
28142
28143 typedef struct {
28144 ufbx_face face;
28145 ufbx_vertex_vec3 positions;
28146 ufbx_vec3 axes[3];
28147 ufbxi_kd_node kd_nodes[1 << (UFBXI_KD_FAST_DEPTH + 1)];
28148 uint32_t *kd_indices;
28149
28150 // Temporary
28151 ufbx_vec3 cur_axis_dir;
28152 ufbx_face cur_face;
28153 } ufbxi_ngon_context;
28154
28155 typedef struct {
28156 ufbx_real min_t[2];
28157 ufbx_real max_t[2];
28158 ufbx_vec2 points[3];
28159 uint32_t indices[3];
28160 } ufbxi_kd_triangle;
28161
28162 ufbxi_noinline static ufbx_vec2 ufbxi_ngon_project(ufbxi_ngon_context *nc, uint32_t index)
28163 {
28164 ufbx_vec3 point = nc->positions.values.data[nc->positions.indices.data[nc->face.index_begin + index]];
28165
28166 ufbx_vec2 p;
28167 p.x = ufbxi_dot3(nc->axes[0], point);
28168 p.y = ufbxi_dot3(nc->axes[1], point);
28169 return p;
28170 }
28171
28172 ufbxi_forceinline static ufbx_real ufbxi_orient2d(ufbx_vec2 a, ufbx_vec2 b, ufbx_vec2 c)
28173 {
28174 return (b.x - a.x)*(c.y - a.y) - (b.y - a.y)*(c.x - a.x);
28175 }
28176
28177 ufbxi_noinline static bool ufbxi_kd_check_point(ufbxi_ngon_context *nc, const ufbxi_kd_triangle *tri, uint32_t index)
28178 {
28179 if (index == tri->indices[0] || index == tri->indices[1] || index == tri->indices[2]) return false;
28180 ufbx_vec2 p = ufbxi_ngon_project(nc, index);
28181
28182 ufbx_real u = ufbxi_orient2d(p, tri->points[0], tri->points[1]);
28183 ufbx_real v = ufbxi_orient2d(p, tri->points[1], tri->points[2]);
28184 ufbx_real w = ufbxi_orient2d(p, tri->points[2], tri->points[0]);
28185
28186 if (u <= 0.0f && v <= 0.0f && w <= 0.0f) return true;
28187 if (u >= 0.0f && v >= 0.0f && w >= 0.0f) return true;
28188 return false;
28189 }
28190
28191 // Recursion limited by 32-bit indices in input, minus halvings from `ufbxi_kd_check_fast()`
28192 ufbxi_noinline static bool ufbxi_kd_check_slow(ufbxi_ngon_context *nc, const ufbxi_kd_triangle *tri, uint32_t begin, uint32_t count, uint32_t axis)
28193 ufbxi_recursive_function(bool, ufbxi_kd_check_slow, (nc, tri, begin, count, axis), 32 - UFBXI_KD_FAST_DEPTH,
28194 (ufbxi_ngon_context *nc, const ufbxi_kd_triangle *tri, uint32_t begin, uint32_t count, uint32_t axis))
28195 {
28196 ufbx_vertex_vec3 pos = nc->positions;
28197 uint32_t *kd_indices = nc->kd_indices;
28198
28199 while (count > 0) {
28200 uint32_t num_left = count / 2;
28201 uint32_t begin_right = begin + num_left + 1;
28202 uint32_t num_right = count - (num_left + 1);
28203
28204 uint32_t index = kd_indices[begin + num_left];
28205 ufbx_vec3 point = pos.values.data[pos.indices.data[nc->face.index_begin + index]];
28206 ufbx_real split = ufbxi_dot3(point, nc->axes[axis]);
28207 bool hit_left = tri->min_t[axis] <= split;
28208 bool hit_right = tri->max_t[axis] >= split;
28209
28210 if (hit_left && hit_right) {
28211 if (ufbxi_kd_check_point(nc, tri, index)) {
28212 return true;
28213 }
28214
28215 if (ufbxi_kd_check_slow(nc, tri, begin_right, num_right, axis ^ 1)) {
28216 return true;
28217 }
28218 }
28219
28220 axis ^= 1;
28221 if (hit_left) {
28222 count = num_left;
28223 } else {
28224 begin = begin_right;
28225 count = num_right;
28226 }
28227 }
28228
28229 return false;
28230 }
28231
28232 // Recursion limited by `UFBXI_KD_FAST_DEPTH`
28233 ufbxi_noinline static bool ufbxi_kd_check_fast(ufbxi_ngon_context *nc, const ufbxi_kd_triangle *tri, uint32_t kd_index, uint32_t axis, uint32_t depth)
28234 ufbxi_recursive_function(bool, ufbxi_kd_check_fast, (nc, tri, kd_index, axis, depth), UFBXI_KD_FAST_DEPTH,
28235 (ufbxi_ngon_context *nc, const ufbxi_kd_triangle *tri, uint32_t kd_index, uint32_t axis, uint32_t depth))
28236 {
28237 for (;;) {
28238 ufbxi_kd_node node = nc->kd_nodes[kd_index];
28239 if (node.index_plus_one == 0) return false;
28240
28241 bool hit_left = tri->min_t[axis] <= node.split;
28242 bool hit_right = tri->max_t[axis] >= node.split;
28243
28244 uint32_t side = hit_left ? 0 : 1;
28245 uint32_t child_kd_index = kd_index * 2 + 1 + side;
28246 if (hit_left && hit_right) {
28247
28248 // Check for the point on the split plane
28249 uint32_t index = node.index_plus_one - 1;
28250 if (ufbxi_kd_check_point(nc, tri, index)) {
28251 return true;
28252 }
28253
28254 // Recurse always to the right if we hit both sides
28255 if (depth + 1 == UFBXI_KD_FAST_DEPTH) {
28256 if (ufbxi_kd_check_slow(nc, tri, node.slow_right, node.slow_end - node.slow_right, axis ^ 1)) {
28257 return true;
28258 }
28259 } else {
28260 if (ufbxi_kd_check_fast(nc, tri, child_kd_index + 1, axis ^ 1, depth + 1)) {
28261 return true;
28262 }
28263 }
28264 }
28265
28266 depth++;
28267 axis ^= 1;
28268 kd_index = child_kd_index;
28269
28270 if (depth == UFBXI_KD_FAST_DEPTH) {
28271 if (hit_left) {
28272 return ufbxi_kd_check_slow(nc, tri, node.slow_left, node.slow_right - node.slow_left, axis);
28273 } else {
28274 return ufbxi_kd_check_slow(nc, tri, node.slow_right, node.slow_end - node.slow_right, axis);
28275 }
28276 }
28277 }
28278 }
28279
28280 ufbxi_noinline static bool ufbxi_kd_check(ufbxi_ngon_context *nc, const ufbx_vec2 *points, const uint32_t *indices)
28281 {
28282 ufbxi_kd_triangle tri; // ufbxi_uninit
28283 tri.points[0] = points[0];
28284 tri.points[1] = points[1];
28285 tri.points[2] = points[2];
28286 tri.indices[0] = indices[0];
28287 tri.indices[1] = indices[1];
28288 tri.indices[2] = indices[2];
28289 tri.min_t[0] = ufbxi_min_real(ufbxi_min_real(points[0].x, points[1].x), points[2].x);
28290 tri.min_t[1] = ufbxi_min_real(ufbxi_min_real(points[0].y, points[1].y), points[2].y);
28291 tri.max_t[0] = ufbxi_max_real(ufbxi_max_real(points[0].x, points[1].x), points[2].x);
28292 tri.max_t[1] = ufbxi_max_real(ufbxi_max_real(points[0].y, points[1].y), points[2].y);
28293 return ufbxi_kd_check_fast(nc, &tri, 0, 0, 0);
28294 }
28295
28296 ufbxi_noinline static bool ufbxi_kd_index_less(void *user, const void *va, const void *vb)
28297 {
28298 ufbxi_ngon_context *nc = (ufbxi_ngon_context*)user;
28299 ufbx_vertex_vec3 *pos = &nc->positions;
28300 const uint32_t a = *(const uint32_t*)va, b = *(const uint32_t*)vb;
28301 ufbx_real da = ufbxi_dot3(nc->cur_axis_dir, pos->values.data[pos->indices.data[nc->cur_face.index_begin + a]]);
28302 ufbx_real db = ufbxi_dot3(nc->cur_axis_dir, pos->values.data[pos->indices.data[nc->cur_face.index_begin + b]]);
28303 return da < db;
28304 }
28305
28306 // Recursion limited by 32-bit indices in input
28307 ufbxi_noinline static void ufbxi_kd_build(ufbxi_ngon_context *nc, uint32_t *indices, uint32_t *tmp, uint32_t num, uint32_t axis, uint32_t fast_index, uint32_t depth)
28308 ufbxi_recursive_function_void(ufbxi_kd_build, (nc, indices, tmp, num, axis, fast_index, depth), 32,
28309 (ufbxi_ngon_context *nc, uint32_t *indices, uint32_t *tmp, uint32_t num, uint32_t axis, uint32_t fast_index, uint32_t depth))
28310 {
28311 if (num == 0) return;
28312
28313 ufbx_vertex_vec3 pos = nc->positions;
28314 ufbx_vec3 axis_dir = nc->axes[axis];
28315 ufbx_face face = nc->face;
28316
28317 nc->cur_axis_dir = axis_dir;
28318 nc->cur_face = face;
28319
28320 // Sort the remaining indices based on the axis
28321 ufbxi_stable_sort(sizeof(uint32_t), 16, indices, tmp, num, &ufbxi_kd_index_less, nc);
28322
28323 uint32_t num_left = num / 2;
28324 uint32_t begin_right = num_left + 1;
28325 uint32_t num_right = num - begin_right;
28326 uint32_t dst_right = num_left + 1;
28327 if (depth < UFBXI_KD_FAST_DEPTH) {
28328 uint32_t skip_left = 1u << (UFBXI_KD_FAST_DEPTH - depth - 1);
28329 dst_right = dst_right > skip_left ? dst_right - skip_left : 0;
28330
28331 uint32_t index = indices[num_left];
28332 ufbxi_kd_node *kd = &nc->kd_nodes[fast_index];
28333
28334 kd->split = ufbxi_dot3(axis_dir, pos.values.data[pos.indices.data[face.index_begin + index]]);
28335 kd->index_plus_one = index + 1;
28336
28337 if (depth + 1 == UFBXI_KD_FAST_DEPTH) {
28338 kd->slow_left = (uint32_t)(indices - nc->kd_indices);
28339 kd->slow_right = kd->slow_left + num_left;
28340 kd->slow_end = kd->slow_right + num_right;
28341 } else {
28342 kd->slow_left = UINT32_MAX;
28343 kd->slow_right = UINT32_MAX;
28344 kd->slow_end = UINT32_MAX;
28345 }
28346 }
28347
28348 uint32_t child_fast = fast_index * 2 + 1;
28349 ufbxi_kd_build(nc, indices, tmp, num_left, axis ^ 1, child_fast + 0, depth + 1);
28350
28351 if (dst_right != begin_right) {
28352 memmove(indices + dst_right, indices + begin_right, num_right * sizeof(uint32_t));
28353 }
28354
28355 ufbxi_kd_build(nc, indices + dst_right, tmp, num_right, axis ^ 1, child_fast + 1, depth + 1);
28356 }
28357
28358 #endif
28359
28360 #if UFBXI_FEATURE_TRIANGULATION
28361
28362 ufbxi_noinline static ufbx_real ufbxi_ngon_tri_weight(const ufbx_vec2 *points)
28363 {
28364 ufbx_vec2 p0 = points[0], p1 = points[1], p2 = points[2];
28365 ufbx_real orient = ufbxi_orient2d(p0, p1, p2);
28366 if (orient <= 0.0f) return -1.0f;
28367
28368 ufbx_real a = ufbxi_distsq2(p0, p1);
28369 ufbx_real b = ufbxi_distsq2(p1, p2);
28370 ufbx_real c = ufbxi_distsq2(p2, p0);
28371 ufbx_real ab = (a + b - c) / (ufbx_real)ufbx_sqrt(4.0f * a * b);
28372 ufbx_real bc = (b + c - a) / (ufbx_real)ufbx_sqrt(4.0f * b * c);
28373 ufbx_real ca = (c + a - b) / (ufbx_real)ufbx_sqrt(4.0f * c * a);
28374 return (ufbx_real)ufbx_fmax(UFBX_EPSILON, 2.0f - ufbx_fmax(ufbx_fmax(ab, bc), ca));
28375 }
28376
28377 ufbxi_noinline static uint32_t ufbxi_triangulate_ngon(ufbxi_ngon_context *nc, uint32_t *indices, uint32_t num_indices)
28378 {
28379 ufbx_face face = nc->face;
28380 ufbx_assert(face.num_indices > 4);
28381
28382 // Form an orthonormal basis to project the polygon into a 2D plane
28383 ufbx_vec3 normal = ufbx_get_weighted_face_normal(&nc->positions, face);
28384 ufbx_real len = ufbxi_length3(normal);
28385 if (len > UFBX_EPSILON) {
28386 normal = ufbxi_mul3(normal, 1.0f / len);
28387 } else {
28388 normal.x = 1.0f;
28389 normal.y = 0.0f;
28390 normal.z = 0.0f;
28391 }
28392
28393 ufbx_vec3 axis; // ufbxi_uninit
28394 if (normal.x*normal.x < 0.5f) {
28395 axis.x = 1.0f;
28396 axis.y = 0.0f;
28397 axis.z = 0.0f;
28398 } else {
28399 axis.x = 0.0f;
28400 axis.y = 1.0f;
28401 axis.z = 0.0f;
28402 }
28403 nc->axes[0] = ufbxi_slow_normalized_cross3(&axis, &normal);
28404 nc->axes[1] = ufbxi_slow_normalized_cross3(&normal, &nc->axes[0]);
28405 nc->axes[2] = normal;
28406
28407 uint32_t *kd_indices = indices;
28408 nc->kd_indices = kd_indices;
28409
28410 uint32_t *kd_tmp = indices + face.num_indices;
28411
28412 // Collect all the reflex corners for intersection testing.
28413 uint32_t num_kd_indices = 0;
28414 {
28415 ufbx_vec2 a = ufbxi_ngon_project(nc, face.num_indices - 1);
28416 ufbx_vec2 b = ufbxi_ngon_project(nc, 0);
28417 for (uint32_t i = 0; i < face.num_indices; i++) {
28418 uint32_t next = i + 1 < face.num_indices ? i + 1 : 0;
28419 ufbx_vec2 c = ufbxi_ngon_project(nc, next);
28420
28421 if (ufbxi_orient2d(a, b, c) <= 0.0f) {
28422 kd_indices[num_kd_indices++] = i;
28423 }
28424
28425 a = b;
28426 b = c;
28427 }
28428 }
28429
28430 // Build a KD-tree of the vertices.
28431 uint32_t num_skip_indices = (1u << (UFBXI_KD_FAST_DEPTH + 1)) - 1;
28432 uint32_t kd_slow_indices = num_kd_indices > num_skip_indices ? num_kd_indices - num_skip_indices : 0;
28433 ufbxi_ignore(kd_slow_indices);
28434 ufbx_assert(kd_slow_indices + face.num_indices * 2 <= num_indices);
28435 ufbxi_kd_build(nc, kd_indices, kd_tmp, num_kd_indices, 0, 0, 0);
28436
28437 uint32_t *edges = indices + num_indices - face.num_indices * 2;
28438
28439 // Initialize `edges` to be a connectivity structure where:
28440 // `edges[2*i + 0]` is the previous vertex of `i`
28441 // `edges[2*i + 1]` is the next vertex of `i`
28442 // When clipped we mark indices with the high bit (0x80000000)
28443 for (uint32_t i = 0; i < face.num_indices; i++) {
28444 edges[i*2 + 0] = i > 0 ? i - 1 : face.num_indices - 1;
28445 edges[i*2 + 1] = i + 1 < face.num_indices ? i + 1 : 0;
28446 }
28447
28448 // Core of the ear clipping algorithm.
28449 // Iterate through the polygon corners looking for potential ears satisfying:
28450 // - Angle must be less than 180deg
28451 // - The triangle formed by the two edges must be contained within the polygon
28452 // As these properties change only locally between modifications we only need
28453 // to iterate the polygon once if we move backwards one step every time we clip an ear.
28454 uint32_t indices_left = face.num_indices;
28455 {
28456 uint32_t point_indices[4] = { 0, 1, 2, 3 };
28457 ufbx_real weights[2]; // ufbxi_uninit
28458 ufbx_vec2 points[4]; // ufbxi_uninit
28459
28460 uint32_t num_steps = 0;
28461 while (indices_left > 3) {
28462 points[0] = ufbxi_ngon_project(nc, point_indices[0]);
28463 points[1] = ufbxi_ngon_project(nc, point_indices[1]);
28464 points[2] = ufbxi_ngon_project(nc, point_indices[2]);
28465 points[3] = ufbxi_ngon_project(nc, point_indices[3]);
28466
28467 weights[0] = ufbxi_ngon_tri_weight(points + 0);
28468 weights[1] = ufbxi_ngon_tri_weight(points + 1);
28469
28470 uint32_t first_side = weights[1] > weights[0] ? 1 : 0;
28471 bool clipped = false;
28472 ufbxi_nounroll for (uint32_t side_ix = 0; side_ix < 2; side_ix++) {
28473 uint32_t side = side_ix ^ first_side;
28474 if (!(weights[side] >= 0.0f)) break;
28475
28476 // If there is no reflex angle contained within the triangle formed
28477 // by `{ a, b, c }` connect the vertices `a - c` (prev, next) directly.
28478 if (!ufbxi_kd_check(nc, points + side, point_indices + side)) {
28479 uint32_t ia = point_indices[side + 0];
28480 uint32_t ib = point_indices[side + 1];
28481 uint32_t ic = point_indices[side + 2];
28482
28483 // Mark as clipped
28484 edges[ib*2 + 0] |= 0x80000000;
28485 edges[ib*2 + 1] |= 0x80000000;
28486
28487 edges[ic*2 + 0] = ia;
28488 edges[ia*2 + 1] = ic;
28489
28490 indices_left -= 1;
28491
28492 // TODO: This may cause O(n^2) behavior!
28493 num_steps = 0;
28494
28495 if (side == 1) {
28496 point_indices[2] = point_indices[3];
28497 point_indices[3] = edges[point_indices[3]*2 + 1];
28498 } else {
28499 point_indices[1] = point_indices[0];
28500 point_indices[0] = edges[point_indices[0]*2 + 0];
28501 }
28502
28503 clipped = true;
28504 break;
28505 }
28506 }
28507 if (clipped) continue;
28508
28509 // Continue forward
28510 point_indices[0] = point_indices[1];
28511 point_indices[1] = point_indices[2];
28512 point_indices[2] = point_indices[3];
28513 point_indices[3] = edges[point_indices[3]*2 + 1];
28514 num_steps++;
28515
28516 // If we have walked around the entire polygon it is irregular and
28517 // ear cutting won't find any more triangles.
28518 // TODO: This could be stricter?
28519 if (num_steps >= face.num_indices*2) break;
28520 }
28521
28522 // Fallback: Cut non-ears until the polygon is completed.
28523 // TODO: Could do something better here..
28524 uint32_t ix = point_indices[1];
28525 while (indices_left > 3) {
28526 uint32_t prev = edges[ix*2 + 0];
28527 uint32_t next = edges[ix*2 + 1];
28528
28529 // Mark as clipped
28530 edges[ix*2 + 0] |= 0x80000000;
28531 edges[ix*2 + 1] |= 0x80000000;
28532
28533 edges[prev*2 + 1] = next;
28534 edges[next*2 + 0] = prev;
28535
28536 indices_left -= 1;
28537 ix = next;
28538 }
28539
28540 // Now we have a single triangle left at `ix`.
28541 edges[ix*2 + 0] |= 0x80000000;
28542 edges[ix*2 + 1] |= 0x80000000;
28543 }
28544
28545 // Expand the adjacency information `edges` into proper triangles.
28546 // Care needs to be taken here as both refer to the same memory area:
28547 // The last 4 triangles may overlap in source and destination so we write
28548 // them to a stack buffer and copy them over in the end.
28549 uint32_t max_triangles = face.num_indices - 2;
28550 uint32_t num_triangles = 0, num_last_triangles = 0;
28551 uint32_t last_triangles[4*3]; // ufbxi_uninit
28552
28553 uint32_t index_begin = face.index_begin;
28554 for (uint32_t ix = 0; ix < face.num_indices; ix++) {
28555 uint32_t prev = edges[ix*2 + 0];
28556 uint32_t next = edges[ix*2 + 1];
28557 if (!(prev & 0x80000000)) continue;
28558
28559 uint32_t *dst = indices + num_triangles * 3;
28560 if (num_triangles + 4 >= max_triangles) {
28561 dst = last_triangles + num_last_triangles * 3;
28562 num_last_triangles++;
28563 }
28564
28565 dst[0] = index_begin + (prev & 0x7fffffff);
28566 dst[1] = index_begin + ix;
28567 dst[2] = index_begin + (next & 0x7fffffff);
28568 num_triangles++;
28569 }
28570
28571 // Copy over the last triangles
28572 ufbx_assert(num_triangles == max_triangles);
28573 memcpy(indices + (max_triangles - num_last_triangles) * 3, last_triangles, num_last_triangles * 3 * sizeof(uint32_t));
28574
28575 return num_triangles;
28576 }
28577
28578 #endif
28579
28580 static bool ufbxi_topo_less_index_prev_next(void *user, const void *va, const void *vb)
28581 {
28582 (void)user;
28583 const ufbx_topo_edge *a = (const ufbx_topo_edge*)va, *b = (const ufbx_topo_edge*)vb;
28584 if ((int32_t)a->prev != (int32_t)b->prev) return (int32_t)a->prev < (int32_t)b->prev;
28585 return (int32_t)a->next < (int32_t)b->next;
28586 }
28587
28588 static bool ufbxi_topo_less_index_index(void *user, const void *va, const void *vb)
28589 {
28590 (void)user;
28591 const ufbx_topo_edge *a = (const ufbx_topo_edge*)va, *b = (const ufbx_topo_edge*)vb;
28592 return (int32_t)a->index < (int32_t)b->index;
28593 }
28594
28595 ufbxi_noinline static void ufbxi_compute_topology(const ufbx_mesh *mesh, ufbx_topo_edge *topo)
28596 {
28597 size_t num_indices = mesh->num_indices;
28598
28599 // Temporarily use `prev` and `next` for vertices
28600 for (uint32_t fi = 0; fi < mesh->num_faces; fi++) {
28601 ufbx_face face = mesh->faces.data[fi];
28602 for (uint32_t pi = 0; pi < face.num_indices; pi++) {
28603 ufbx_topo_edge *te = &topo[face.index_begin + pi];
28604 uint32_t ni = (pi + 1) % face.num_indices;
28605 uint32_t va = mesh->vertex_indices.data[face.index_begin + pi];
28606 uint32_t vb = mesh->vertex_indices.data[face.index_begin + ni];
28607
28608 if (vb < va) {
28609 uint32_t vt = va; va = vb; vb = vt;
28610 }
28611 te->index = face.index_begin + pi;
28612 te->twin = UFBX_NO_INDEX;
28613 te->edge = UFBX_NO_INDEX;
28614 te->prev = va;
28615 te->next = vb;
28616 te->face = fi;
28617 te->flags = (ufbx_topo_flags)0;
28618 }
28619 }
28620
28621 ufbxi_unstable_sort(topo, num_indices, sizeof(ufbx_topo_edge), &ufbxi_topo_less_index_prev_next, NULL);
28622
28623 if (mesh->edges.data) {
28624 for (uint32_t ei = 0; ei < mesh->num_edges; ei++) {
28625 ufbx_edge edge = mesh->edges.data[ei];
28626 uint32_t va = mesh->vertex_indices.data[edge.a];
28627 uint32_t vb = mesh->vertex_indices.data[edge.b];
28628 if (vb < va) {
28629 uint32_t vt = va; va = vb; vb = vt;
28630 }
28631
28632 size_t ix = num_indices;
28633 ufbxi_macro_lower_bound_eq(ufbx_topo_edge, 32, &ix, topo, 0, num_indices,
28634 (a->prev == va ? a->next < vb : a->prev < va), (a->prev == va && a->next == vb));
28635
28636 for (; ix < num_indices && topo[ix].prev == va && topo[ix].next == vb; ix++) {
28637 topo[ix].edge = ei;
28638 }
28639 }
28640 }
28641
28642 // Connect paired edges
28643 for (size_t i0 = 0; i0 < num_indices; ) {
28644 size_t i1 = i0;
28645
28646 uint32_t a = topo[i0].prev, b = topo[i0].next;
28647 while (i1 + 1 < num_indices && topo[i1 + 1].prev == a && topo[i1 + 1].next == b) i1++;
28648
28649 if (i1 == i0 + 1) {
28650 topo[i0].twin = topo[i1].index;
28651 topo[i1].twin = topo[i0].index;
28652 } else if (i1 > i0 + 1) {
28653 for (size_t i = i0; i <= i1; i++) {
28654 topo[i].flags = (ufbx_topo_flags)(topo[i].flags | UFBX_TOPO_NON_MANIFOLD);
28655 }
28656 }
28657
28658 i0 = i1 + 1;
28659 }
28660
28661 ufbxi_unstable_sort(topo, num_indices, sizeof(ufbx_topo_edge), &ufbxi_topo_less_index_index, NULL);
28662
28663 // Fix `prev` and `next` to the actual index values
28664 for (uint32_t fi = 0; fi < mesh->num_faces; fi++) {
28665 ufbx_face face = mesh->faces.data[fi];
28666 for (uint32_t i = 0; i < face.num_indices; i++) {
28667 ufbx_topo_edge *to = &topo[face.index_begin + i];
28668 to->prev = (uint32_t)(face.index_begin + (i + face.num_indices - 1) % face.num_indices);
28669 to->next = (uint32_t)(face.index_begin + (i + 1) % face.num_indices);
28670 }
28671 }
28672 }
28673
28674 static bool ufbxi_is_edge_smooth(const ufbx_mesh *mesh, const ufbx_topo_edge *topo, size_t num_topo, uint32_t index, bool assume_smooth)
28675 {
28676 ufbxi_ignore(num_topo);
28677 ufbx_assert((size_t)index < num_topo);
28678 if (mesh->edge_smoothing.data) {
28679 uint32_t edge = topo[index].edge;
28680 if (edge != UFBX_NO_INDEX && mesh->edge_smoothing.data[edge]) return true;
28681 }
28682
28683 if (mesh->face_smoothing.data) {
28684 if (mesh->face_smoothing.data[topo[index].face]) return true;
28685 uint32_t twin = topo[index].twin;
28686 if (twin != UFBX_NO_INDEX) {
28687 if (mesh->face_smoothing.data[topo[twin].face]) return true;
28688 }
28689 }
28690
28691 if (!mesh->edge_smoothing.data && !mesh->face_smoothing.data && mesh->vertex_normal.exists) {
28692 uint32_t twin = topo[index].twin;
28693 if (twin != UFBX_NO_INDEX && mesh->vertex_normal.exists) {
28694 ufbx_assert((size_t)twin < num_topo);
28695 ufbx_vec3 a0 = ufbx_get_vertex_vec3(&mesh->vertex_normal, index);
28696 ufbx_vec3 a1 = ufbx_get_vertex_vec3(&mesh->vertex_normal, topo[index].next);
28697 ufbx_vec3 b0 = ufbx_get_vertex_vec3(&mesh->vertex_normal, topo[twin].next);
28698 ufbx_vec3 b1 = ufbx_get_vertex_vec3(&mesh->vertex_normal, twin);
28699 if (a0.x == b0.x && a0.y == b0.y && a0.z == b0.z) return true;
28700 if (a1.x == b1.x && a1.y == b1.y && a1.z == b1.z) return true;
28701 }
28702 } else if (assume_smooth) {
28703 return true;
28704 }
28705
28706 return false;
28707 }
28708
28709 // -- Subdivision
28710
28711 #if UFBXI_FEATURE_SUBDIVISION
28712
28713 typedef struct {
28714 const void *data;
28715 ufbx_real weight;
28716 } ufbxi_subdivide_input;
28717
28718 typedef int ufbxi_subdivide_sum_fn(void *user, void *output, const ufbxi_subdivide_input *inputs, size_t num_inputs);
28719
28720 typedef struct {
28721 ufbxi_subdivide_sum_fn *sum_fn;
28722 void *sum_user;
28723
28724 const void *values;
28725 size_t stride;
28726
28727 const uint32_t *indices;
28728
28729 bool check_split_data;
28730 bool ignore_indices;
28731
28732 ufbx_subdivision_boundary boundary;
28733
28734 } ufbxi_subdivide_layer_input;
28735
28736 typedef struct {
28737 void *values;
28738 size_t num_values;
28739 uint32_t *indices;
28740 size_t num_indices;
28741 bool unique_per_vertex;
28742 } ufbxi_subdivide_layer_output;
28743
28744 typedef struct {
28745 ufbx_subdivision_weight *weights;
28746 size_t num_weights;
28747 } ufbxi_subdivision_vertex_weights;
28748
28749 typedef struct {
28750 ufbxi_mesh_imp *imp;
28751
28752 ufbx_error error;
28753
28754 ufbx_mesh *src_mesh_ptr;
28755 ufbx_mesh src_mesh;
28756 ufbx_mesh dst_mesh;
28757 ufbx_topo_edge *topo;
28758 size_t num_topo;
28759
28760 ufbx_subdivide_opts opts;
28761
28762 ufbxi_allocator ator_result;
28763 ufbxi_allocator ator_tmp;
28764
28765 ufbxi_buf result;
28766 ufbxi_buf tmp;
28767 ufbxi_buf source;
28768
28769 ufbxi_subdivide_input *inputs;
28770 size_t inputs_cap;
28771
28772 ufbx_real *tmp_vertex_weights;
28773 ufbx_subdivision_weight *tmp_weights;
28774 size_t total_weights;
28775 size_t max_vertex_weights;
28776
28777 } ufbxi_subdivide_context;
28778
28779 static int ufbxi_subdivide_sum_vec2(void *user, void *output, const ufbxi_subdivide_input *inputs, size_t num_inputs)
28780 {
28781 (void)user;
28782 ufbx_vec2 dst = { 0 };
28783 ufbxi_nounroll for (size_t i = 0; i != num_inputs; i++) {
28784 const ufbx_vec2 *src = (const ufbx_vec2*)inputs[i].data;
28785 ufbx_real weight = inputs[i].weight;
28786 dst.x += src->x * weight;
28787 dst.y += src->y * weight;
28788 }
28789 *(ufbx_vec2*)output = dst;
28790
28791 return 1;
28792 }
28793
28794 static int ufbxi_subdivide_sum_vec3(void *user, void *output, const ufbxi_subdivide_input *inputs, size_t num_inputs)
28795 {
28796 (void)user;
28797 ufbx_vec3 dst = { 0 };
28798 ufbxi_nounroll for (size_t i = 0; i != num_inputs; i++) {
28799 const ufbx_vec3 *src = (const ufbx_vec3*)inputs[i].data;
28800 ufbx_real weight = inputs[i].weight;
28801 dst.x += src->x * weight;
28802 dst.y += src->y * weight;
28803 dst.z += src->z * weight;
28804 }
28805 *(ufbx_vec3*)output = dst;
28806
28807 return 1;
28808 }
28809
28810 static int ufbxi_subdivide_sum_vec4(void *user, void *output, const ufbxi_subdivide_input *inputs, size_t num_inputs)
28811 {
28812 (void)user;
28813 ufbx_vec4 dst = { 0 };
28814 ufbxi_nounroll for (size_t i = 0; i != num_inputs; i++) {
28815 const ufbx_vec4 *src = (const ufbx_vec4*)inputs[i].data;
28816 ufbx_real weight = inputs[i].weight;
28817 dst.x += src->x * weight;
28818 dst.y += src->y * weight;
28819 dst.z += src->z * weight;
28820 dst.w += src->w * weight;
28821 }
28822 *(ufbx_vec4*)output = dst;
28823
28824 return 1;
28825 }
28826
28827 static ufbxi_noinline bool ufbxi_subdivision_weight_less(void *user, const void *va, const void *vb)
28828 {
28829 (void)user;
28830 ufbx_subdivision_weight a = *(const ufbx_subdivision_weight*)va, b = *(const ufbx_subdivision_weight*)vb;
28831 ufbxi_dev_assert(a.index != b.index);
28832 if (a.weight != b.weight) return a.weight > b.weight;
28833 return a.index < b.index;
28834 }
28835
28836 static int ufbxi_subdivide_sum_vertex_weights(void *user, void *output, const ufbxi_subdivide_input *inputs, size_t num_inputs)
28837 {
28838 ufbxi_subdivide_context *sc = (ufbxi_subdivide_context*)user;
28839
28840 ufbx_real *vertex_weights = sc->tmp_vertex_weights;
28841 ufbx_subdivision_weight *tmp_weights = sc->tmp_weights;
28842 size_t num_weights = 0;
28843
28844 ufbxi_nounroll for (size_t input_ix = 0; input_ix != num_inputs; input_ix++) {
28845 ufbxi_subdivision_vertex_weights src = *(const ufbxi_subdivision_vertex_weights*)inputs[input_ix].data;
28846 ufbx_real input_weight = inputs[input_ix].weight;
28847
28848 for (size_t weight_ix = 0; weight_ix < src.num_weights; weight_ix++) {
28849 ufbx_real weight = input_weight * src.weights[weight_ix].weight;
28850 if (weight < 1.175494351e-38f) continue;
28851
28852 uint32_t vx = src.weights[weight_ix].index;
28853 ufbxi_dev_assert(vx < sc->src_mesh.num_vertices);
28854
28855 ufbx_real prev = vertex_weights[vx];
28856 vertex_weights[vx] = prev + weight;
28857 if (prev == 0.0f) {
28858 tmp_weights[num_weights++].index = vx;
28859 }
28860 }
28861 }
28862
28863 ufbxi_nounroll for (size_t i = 0; i != num_weights; i++) {
28864 uint32_t vx = tmp_weights[i].index;
28865 tmp_weights[i].weight = vertex_weights[vx];
28866 vertex_weights[vx] = 0.0f;
28867 }
28868
28869 ufbxi_unstable_sort(tmp_weights, num_weights, sizeof(ufbx_subdivision_weight), ufbxi_subdivision_weight_less, NULL);
28870
28871 if (sc->max_vertex_weights != SIZE_MAX) {
28872 num_weights = ufbxi_min_sz(sc->max_vertex_weights, num_weights);
28873
28874 // Normalize weights
28875 ufbx_real prefix_weight = 0.0f;
28876 ufbxi_nounroll for (size_t i = 0; i != num_weights; i++) {
28877 prefix_weight += tmp_weights[i].weight;
28878 }
28879 ufbxi_nounroll for (size_t i = 0; i != num_weights; i++) {
28880 tmp_weights[i].weight /= prefix_weight;
28881 }
28882 }
28883
28884 sc->total_weights += num_weights;
28885 ufbx_subdivision_weight *weights = ufbxi_push_copy(&sc->tmp, ufbx_subdivision_weight, num_weights, tmp_weights);
28886 ufbxi_check_err(&sc->error, weights);
28887
28888 ufbxi_subdivision_vertex_weights *dst = (ufbxi_subdivision_vertex_weights*)output;
28889 dst->weights = weights;
28890 dst->num_weights = num_weights;
28891
28892 return 1;
28893 }
28894
28895 static ufbxi_subdivide_sum_fn *const ufbxi_real_sum_fns[] = {
28896 NULL,
28897 &ufbxi_subdivide_sum_vec2,
28898 &ufbxi_subdivide_sum_vec3,
28899 &ufbxi_subdivide_sum_vec4,
28900 };
28901
28902 ufbxi_noinline static bool ufbxi_is_edge_split(const ufbxi_subdivide_layer_input *input, const ufbx_topo_edge *topo, uint32_t index)
28903 {
28904 uint32_t twin = topo[index].twin;
28905 if (twin != UFBX_NO_INDEX) {
28906 uint32_t a0 = input->indices[index];
28907 uint32_t a1 = input->indices[topo[index].next];
28908 uint32_t b0 = input->indices[topo[twin].next];
28909 uint32_t b1 = input->indices[twin];
28910 if (a0 == b0 && a1 == b1) return false;
28911 if (!input->check_split_data) return true;
28912 size_t stride = input->stride;
28913 char *da0 = (char*)input->values + a0 * stride;
28914 char *da1 = (char*)input->values + a1 * stride;
28915 char *db0 = (char*)input->values + b0 * stride;
28916 char *db1 = (char*)input->values + b1 * stride;
28917 if (!memcmp(da0, db0, stride) && !memcmp(da1, db1, stride)) return false;
28918 return true;
28919 }
28920
28921 return false;
28922 }
28923
28924 static ufbx_real ufbxi_edge_crease(const ufbx_mesh *mesh, bool split, const ufbx_topo_edge *topo, uint32_t index)
28925 {
28926 if (topo[index].twin == UFBX_NO_INDEX) return 1.0f;
28927 if (split) return 1.0f;
28928 if (mesh->edge_crease.data && topo[index].edge != UFBX_NO_INDEX) return mesh->edge_crease.data[topo[index].edge] * (ufbx_real)10.0;
28929 return 0.0f;
28930 }
28931
28932 static ufbxi_noinline int ufbxi_subdivide_layer(ufbxi_subdivide_context *sc, ufbxi_subdivide_layer_output *output, const ufbxi_subdivide_layer_input *input)
28933 {
28934 ufbx_subdivision_boundary boundary = input->boundary;
28935
28936 const ufbx_mesh *mesh = &sc->src_mesh;
28937 const ufbx_topo_edge *topo = sc->topo;
28938 size_t num_topo = sc->num_topo;
28939
28940 uint32_t *edge_indices = ufbxi_push(&sc->result, uint32_t, mesh->num_indices);
28941 ufbxi_check_err(&sc->error, edge_indices);
28942
28943 size_t num_edge_values = 0;
28944 for (uint32_t ix = 0; ix < (uint32_t)mesh->num_indices; ix++) {
28945 uint32_t twin = topo[ix].twin;
28946 if (twin < ix && !ufbxi_is_edge_split(input, topo, ix)) {
28947 edge_indices[ix] = edge_indices[twin];
28948 } else {
28949 edge_indices[ix] = (uint32_t)num_edge_values++;
28950 }
28951 }
28952
28953 size_t stride = input->stride;
28954 size_t num_initial_values = (num_edge_values + mesh->num_faces + mesh->num_indices);
28955 char *values = (char*)ufbxi_push_size(&sc->tmp, stride, num_initial_values);
28956 ufbxi_check_err(&sc->error, values);
28957
28958 char *face_values = values;
28959 char *edge_values = face_values + mesh->num_faces * stride;
28960 char *vertex_values = edge_values + num_edge_values * stride;
28961
28962 size_t num_vertex_values = 0;
28963
28964 uint32_t *vertex_indices = ufbxi_push(&sc->result, uint32_t, mesh->num_indices);
28965 ufbxi_check_err(&sc->error, vertex_indices);
28966
28967 size_t min_inputs = ufbxi_max_sz(32, mesh->max_face_triangles + 2);
28968 ufbxi_check_err(&sc->error, ufbxi_grow_array(&sc->ator_tmp, &sc->inputs, &sc->inputs_cap, min_inputs));
28969 ufbxi_subdivide_input *inputs = sc->inputs;
28970
28971 // Assume initially unique per vertex, remove if not the case
28972 output->unique_per_vertex = true;
28973
28974 bool sharp_corners = false;
28975 bool sharp_splits = false;
28976 bool sharp_all = false;
28977
28978 switch (boundary) {
28979 case UFBX_SUBDIVISION_BOUNDARY_DEFAULT:
28980 case UFBX_SUBDIVISION_BOUNDARY_SHARP_NONE:
28981 case UFBX_SUBDIVISION_BOUNDARY_LEGACY:
28982 // All smooth
28983 break;
28984 case UFBX_SUBDIVISION_BOUNDARY_SHARP_CORNERS:
28985 sharp_corners = true;
28986 break;
28987 case UFBX_SUBDIVISION_BOUNDARY_SHARP_BOUNDARY:
28988 sharp_corners = true;
28989 sharp_splits = true;
28990 break;
28991 case UFBX_SUBDIVISION_BOUNDARY_SHARP_INTERIOR:
28992 sharp_all = true;
28993 break;
28994 default:
28995 ufbxi_unreachable("Bad boundary mode");
28996 }
28997
28998 ufbxi_subdivide_sum_fn *sum_fn = input->sum_fn;
28999 void *sum_user = input->sum_user;
29000
29001 // Mark unused indices as `UFBX_NO_INDEX` so we can patch non-manifold
29002 ufbxi_nounroll for (size_t i = 0; i < mesh->num_indices; i++) {
29003 vertex_indices[i] = UFBX_NO_INDEX;
29004 }
29005
29006 // Face points
29007 for (size_t fi = 0; fi < mesh->num_faces; fi++) {
29008 ufbx_face face = mesh->faces.data[fi];
29009 char *dst = face_values + fi * stride;
29010
29011 ufbx_real weight = 1.0f / (ufbx_real)face.num_indices;
29012 for (uint32_t ci = 0; ci < face.num_indices; ci++) {
29013 uint32_t ix = face.index_begin + ci;
29014 inputs[ci].data = (const char*)input->values + input->indices[ix] * stride;
29015 inputs[ci].weight = weight;
29016 }
29017
29018 ufbxi_check_err(&sc->error, sum_fn(sum_user, dst, inputs, face.num_indices));
29019 }
29020
29021 // Edge points
29022 for (uint32_t ix = 0; ix < mesh->num_indices; ix++) {
29023 char *dst = edge_values + edge_indices[ix] * stride;
29024
29025 uint32_t twin = topo[ix].twin;
29026 bool split = ufbxi_is_edge_split(input, topo, ix);
29027
29028 if (split || (topo[ix].flags & UFBX_TOPO_NON_MANIFOLD) != 0) {
29029 output->unique_per_vertex = false;
29030 }
29031
29032 ufbx_real crease = 0.0f;
29033 if (split || twin == UFBX_NO_INDEX) {
29034 crease = 1.0f;
29035 } else if (topo[ix].edge != UFBX_NO_INDEX && mesh->edge_crease.data) {
29036 crease = mesh->edge_crease.data[topo[ix].edge] * (ufbx_real)10.0;
29037 }
29038 if (sharp_all) crease = 1.0f;
29039
29040 const char *v0 = (const char*)input->values + input->indices[ix] * stride;
29041 const char *v1 = (const char*)input->values + input->indices[topo[ix].next] * stride;
29042
29043 // TODO: Unify
29044 if (twin < ix && !split) {
29045 // Already calculated
29046 } else if (crease <= 0.0f) {
29047 const char *f0 = face_values + topo[ix].face * stride;
29048 const char *f1 = face_values + topo[twin].face * stride;
29049 inputs[0].data = v0;
29050 inputs[0].weight = 0.25f;
29051 inputs[1].data = v1;
29052 inputs[1].weight = 0.25f;
29053 inputs[2].data = f0;
29054 inputs[2].weight = 0.25f;
29055 inputs[3].data = f1;
29056 inputs[3].weight = 0.25f;
29057 ufbxi_check_err(&sc->error, sum_fn(sum_user, dst, inputs, 4));
29058 } else if (crease >= 1.0f) {
29059 inputs[0].data = v0;
29060 inputs[0].weight = 0.5f;
29061 inputs[1].data = v1;
29062 inputs[1].weight = 0.5f;
29063 ufbxi_check_err(&sc->error, sum_fn(sum_user, dst, inputs, 2));
29064 } else if (crease < 1.0f) {
29065 const char *f0 = face_values + topo[ix].face * stride;
29066 const char *f1 = face_values + topo[twin].face * stride;
29067 ufbx_real w0 = 0.25f + 0.25f * crease;
29068 ufbx_real w1 = 0.25f - 0.25f * crease;
29069
29070 inputs[0].data = v0;
29071 inputs[0].weight = w0;
29072 inputs[1].data = v1;
29073 inputs[1].weight = w0;
29074 inputs[2].data = f0;
29075 inputs[2].weight = w1;
29076 inputs[3].data = f1;
29077 inputs[3].weight = w1;
29078 ufbxi_check_err(&sc->error, sum_fn(sum_user, dst, inputs, 4));
29079 }
29080 }
29081
29082 // Vertex points
29083 for (size_t vi = 0; vi < mesh->num_vertices; vi++) {
29084 uint32_t original_start = mesh->vertex_first_index.data[vi];
29085 if (original_start == UFBX_NO_INDEX) continue;
29086
29087 // Find a topological boundary, or if not found a split edge
29088 uint32_t start = original_start;
29089 for (uint32_t cur = start;;) {
29090 uint32_t prev = ufbx_topo_prev_vertex_edge(topo, num_topo, cur);
29091 if (prev == UFBX_NO_INDEX) { start = cur; break; } // Topological boundary: Stop and use as start
29092 if (ufbxi_is_edge_split(input, topo, prev)) start = cur; // Split edge: Consider as start
29093 if (prev == original_start) break; // Loop: Stop, use original start or split if found
29094 cur = prev;
29095 }
29096
29097 original_start = start;
29098 while (start != UFBX_NO_INDEX) {
29099 if (start != original_start) {
29100 output->unique_per_vertex = false;
29101 }
29102
29103 uint32_t value_index = (uint32_t)num_vertex_values++;
29104 char *dst = vertex_values + value_index * stride;
29105
29106 // We need to compute the average crease value and keep track of
29107 // two creased edges, if there's more we use the corner rule that
29108 // does not need the information.
29109 ufbx_real total_crease = 0.0f;
29110 size_t num_crease = 0;
29111 size_t num_split = 0;
29112 bool on_boundary = false;
29113 bool non_manifold = false;
29114 size_t crease_input_indices[2]; // ufbxi_uninit
29115
29116 // At start we always have two edges and a single face
29117 uint32_t start_prev = topo[start].prev;
29118 uint32_t end_edge = topo[start_prev].twin;
29119 size_t valence = 2;
29120
29121 non_manifold |= (topo[start].flags & UFBX_TOPO_NON_MANIFOLD) != 0;
29122 non_manifold |= (topo[start_prev].flags & UFBX_TOPO_NON_MANIFOLD) != 0;
29123
29124 const char *v0 = (const char*)input->values + input->indices[start] * stride;
29125
29126 size_t num_inputs = 4;
29127
29128 {
29129 const char *e0 = (const char*)input->values + input->indices[topo[start].next] * stride;
29130 const char *e1 = (const char*)input->values + input->indices[start_prev] * stride;
29131 const char *f0 = face_values + topo[start].face * stride;
29132 inputs[0].data = v0;
29133 inputs[1].data = e0;
29134 inputs[2].data = e1;
29135 inputs[3].data = f0;
29136 }
29137
29138 bool start_split = ufbxi_is_edge_split(input, topo, start);
29139 bool prev_split = end_edge != UFBX_NO_INDEX && ufbxi_is_edge_split(input, topo, end_edge);
29140
29141 // Either of the first two edges may be creased
29142 ufbx_real start_crease = ufbxi_edge_crease(mesh, start_split, topo, start);
29143 if (start_crease > 0.0f) {
29144 total_crease += start_crease;
29145 crease_input_indices[num_crease++] = 1;
29146 }
29147 ufbx_real prev_crease = ufbxi_edge_crease(mesh, prev_split, topo, start_prev);
29148 if (prev_crease > 0.0f) {
29149 total_crease += prev_crease;
29150 crease_input_indices[num_crease++] = 2;
29151 }
29152
29153 if (end_edge != UFBX_NO_INDEX) {
29154 if (prev_split) {
29155 num_split++;
29156 }
29157 } else {
29158 on_boundary = true;
29159 }
29160
29161 ufbxi_check_err(&sc->error, vertex_indices[start] == UFBX_NO_INDEX);
29162 vertex_indices[start] = value_index;
29163
29164 if (start_split) {
29165 // We need to special case if the first edge is split as we have
29166 // handled it already in the code above..
29167 start = ufbx_topo_next_vertex_edge(topo, num_topo, start);
29168 num_split++;
29169 } else {
29170 // Follow vertex edges until we either hit a topological/split boundary
29171 // or loop back to the left edge we accounted for in `start_prev`
29172 uint32_t cur = start;
29173 for (;;) {
29174 cur = ufbx_topo_next_vertex_edge(topo, num_topo, cur);
29175
29176 // Topological boundary: Finished
29177 if (cur == UFBX_NO_INDEX) {
29178 on_boundary = true;
29179 start = UFBX_NO_INDEX;
29180 break;
29181 }
29182
29183 non_manifold |= (topo[cur].flags & UFBX_TOPO_NON_MANIFOLD) != 0;
29184 ufbxi_check_err(&sc->error, vertex_indices[cur] == UFBX_NO_INDEX);
29185 vertex_indices[cur] = value_index;
29186
29187 bool split = ufbxi_is_edge_split(input, topo, cur);
29188
29189 // Looped: Add the face from the other side still if not split
29190 if (cur == end_edge && !split) {
29191 ufbxi_check_err(&sc->error, ufbxi_grow_array(&sc->ator_tmp, &sc->inputs, &sc->inputs_cap, num_inputs + 1));
29192 const char *f0 = face_values + topo[cur].face * stride;
29193 inputs[num_inputs].data = f0;
29194 start = UFBX_NO_INDEX;
29195 num_inputs += 1;
29196 break;
29197 }
29198
29199 // Add the edge crease, this also handles boundaries as they
29200 // have an implicit crease of 1.0 using `ufbxi_edge_crease()`
29201 ufbx_real cur_crease = ufbxi_edge_crease(mesh, split, topo, cur);
29202 if (cur_crease > 0.0f) {
29203 total_crease += cur_crease;
29204 if (num_crease < 2) crease_input_indices[num_crease] = num_inputs;
29205 num_crease++;
29206 }
29207
29208 // Add the new edge and face to the sum
29209 {
29210 ufbxi_check_err(&sc->error, ufbxi_grow_array(&sc->ator_tmp, &sc->inputs, &sc->inputs_cap, num_inputs + 2));
29211 inputs = sc->inputs;
29212
29213 const char *e0 = (char*)input->values + input->indices[topo[cur].next] * stride;
29214 const char *f0 = face_values + topo[cur].face * stride;
29215 inputs[num_inputs + 0].data = e0;
29216 inputs[num_inputs + 1].data = f0;
29217 num_inputs += 2;
29218 }
29219 valence++;
29220
29221 // If we landed at a split edge advance to the next one
29222 // and continue from there in the outer loop
29223 if (split) {
29224 start = ufbx_topo_next_vertex_edge(topo, num_topo, cur);
29225 num_split++;
29226 break;
29227 }
29228 }
29229 }
29230
29231 if (start == original_start) start = UFBX_NO_INDEX;
29232
29233 // Weights for various subdivision masks
29234 ufbx_real fe_weight = 1.0f / (ufbx_real)(valence*valence);
29235 ufbx_real v_weight = (ufbx_real)(valence - 2) / (ufbx_real)valence;
29236
29237 // Select the right subdivision mask depending on valence and crease
29238 if (num_crease > 2
29239 || (sharp_corners && valence == 2 && (num_split > 0 || on_boundary))
29240 || (sharp_splits && (num_split > 0 || on_boundary))
29241 || sharp_all
29242 || non_manifold) {
29243 // Corner: Copy as-is
29244 inputs[0].data = v0;
29245 inputs[0].weight = 1.0f;
29246 num_inputs = 1;
29247 } else if (num_crease == 2) {
29248 // Boundary: Interpolate edge
29249 total_crease *= 0.5f;
29250 if (total_crease < 0.0f) total_crease = 0.0f;
29251 if (total_crease > 1.0f) total_crease = 1.0f;
29252
29253 inputs[0].weight = v_weight * (1.0f - total_crease) + 0.75f * total_crease;
29254 ufbx_real few = fe_weight * (1.0f - total_crease);
29255 for (size_t i = 1; i < num_inputs; i++) {
29256 inputs[i].weight = few;
29257 }
29258
29259 // Add weight to the creased edges
29260 inputs[crease_input_indices[0]].weight += 0.125f * total_crease;
29261 inputs[crease_input_indices[1]].weight += 0.125f * total_crease;
29262 } else {
29263 // Regular: Weighted sum with the accumulated edge/face points
29264 inputs[0].weight = v_weight;
29265 for (size_t i = 1; i < num_inputs; i++) {
29266 inputs[i].weight = fe_weight;
29267 }
29268
29269 }
29270
29271 if (mesh->vertex_crease.exists) {
29272 ufbx_real v = ufbx_get_vertex_real(&mesh->vertex_crease, original_start);
29273 v *= (ufbx_real)10.0;
29274 if (v > 0.0f) {
29275 if (v > 1.0) v = 1.0f;
29276
29277 ufbx_real iv = 1.0f - v;
29278 inputs[0].weight = 1.0f * v + (inputs[0].weight) * iv;
29279 for (size_t i = 1; i < num_inputs; i++) {
29280 inputs[i].weight *= iv;
29281 }
29282 }
29283 }
29284
29285 #if defined(UFBX_REGRESSION)
29286 {
29287 ufbx_real total_weight = 0.0f;
29288 for (size_t i = 0; i < num_inputs; i++) {
29289 total_weight += inputs[i].weight;
29290 }
29291 ufbx_assert(ufbx_fabs(total_weight - 1.0f) < 0.001f);
29292 }
29293 #endif
29294
29295 ufbxi_check_err(&sc->error, sum_fn(sum_user, dst, inputs, num_inputs));
29296 }
29297 }
29298
29299 // Copy non-manifold vertex values as-is
29300 for (size_t old_ix = 0; old_ix < mesh->num_indices; old_ix++) {
29301 uint32_t ix = vertex_indices[old_ix];
29302 if (ix == UFBX_NO_INDEX) {
29303 ix = (uint32_t)num_vertex_values++;
29304 vertex_indices[old_ix] = ix;
29305 const char *src = (const char*)input->values + input->indices[old_ix] * stride;
29306 char *dst = vertex_values + ix * stride;
29307
29308 inputs[0].data = src;
29309 inputs[0].weight = 1.0f;
29310 ufbxi_check_err(&sc->error, sum_fn(sum_user, dst, inputs, 1));
29311 }
29312 }
29313
29314 ufbx_assert(num_vertex_values <= mesh->num_indices);
29315 size_t num_values = num_edge_values + mesh->num_faces + num_vertex_values;
29316 char *new_values = (char*)ufbxi_push_size(&sc->result, stride, (num_values+1));
29317 ufbxi_check_err(&sc->error, new_values);
29318
29319 memset(new_values, 0, stride);
29320 new_values += stride;
29321
29322 memcpy(new_values, values, num_values * stride);
29323
29324 output->values = new_values;
29325 output->num_values = num_values;
29326
29327 if (!input->ignore_indices) {
29328 uint32_t *new_indices = ufbxi_push(&sc->result, uint32_t, mesh->num_indices * 4);
29329 ufbxi_check_err(&sc->error, new_indices);
29330
29331 uint32_t face_start = 0;
29332 uint32_t edge_start = (uint32_t)(face_start + mesh->num_faces);
29333 uint32_t vert_start = (uint32_t)(edge_start + num_edge_values);
29334 uint32_t *p_ix = new_indices;
29335 for (size_t ix = 0; ix < mesh->num_indices; ix++) {
29336 p_ix[0] = vert_start + vertex_indices[ix];
29337 p_ix[1] = edge_start + edge_indices[ix];
29338 p_ix[2] = face_start + topo[ix].face;
29339 p_ix[3] = edge_start + edge_indices[topo[ix].prev];
29340 p_ix += 4;
29341 }
29342 output->indices = new_indices;
29343 output->num_indices = mesh->num_indices * 4;
29344 } else {
29345 output->indices = NULL;
29346 output->num_indices = 0;
29347 }
29348
29349 return 1;
29350 }
29351
29352 static ufbxi_noinline int ufbxi_subdivide_attrib(ufbxi_subdivide_context *sc, ufbx_vertex_attrib *attrib, ufbx_subdivision_boundary boundary, bool check_split_data)
29353 {
29354 if (!attrib->exists) return 1;
29355
29356 ufbx_assert(attrib->value_reals >= 2 && attrib->value_reals <= 4);
29357
29358 ufbxi_subdivide_layer_input input; // ufbxi_uninit
29359 input.sum_fn = ufbxi_real_sum_fns[attrib->value_reals - 1];
29360 input.sum_user = NULL;
29361 input.values = attrib->values.data;
29362 input.indices = attrib->indices.data;
29363 input.stride = attrib->value_reals * sizeof(ufbx_real);
29364 input.boundary = boundary;
29365 input.check_split_data = check_split_data;
29366 input.ignore_indices = false;
29367
29368 ufbxi_subdivide_layer_output output; // ufbxi_uninit
29369 ufbxi_check_err(&sc->error, ufbxi_subdivide_layer(sc, &output, &input));
29370
29371 attrib->values.data = output.values;
29372 attrib->indices.data = output.indices;
29373 attrib->values.count = output.num_values;
29374 attrib->indices.count = output.num_indices;
29375
29376 return 1;
29377 }
29378
29379 static ufbxi_noinline ufbxi_subdivision_vertex_weights *ufbxi_subdivision_copy_weights(ufbxi_subdivide_context *sc, ufbx_subdivision_weight_range_list ranges, ufbx_subdivision_weight_list weights)
29380 {
29381 ufbxi_subdivision_vertex_weights *dst = ufbxi_push(&sc->tmp, ufbxi_subdivision_vertex_weights, ranges.count);
29382 ufbxi_check_return_err(&sc->error, dst, NULL);
29383
29384 ufbxi_nounroll for (size_t i = 0; i != ranges.count; i++) {
29385 ufbx_subdivision_weight_range range = ranges.data[i];
29386 dst[i].weights = weights.data + range.weight_begin;
29387 dst[i].num_weights = range.num_weights;
29388 }
29389
29390 return dst;
29391 }
29392
29393 static ufbxi_noinline ufbxi_subdivision_vertex_weights *ufbxi_init_source_vertex_weights(ufbxi_subdivide_context *sc, size_t num_vertices)
29394 {
29395 ufbxi_subdivision_vertex_weights *dst = ufbxi_push(&sc->tmp, ufbxi_subdivision_vertex_weights, num_vertices);
29396 ufbx_subdivision_weight *weights = ufbxi_push(&sc->tmp, ufbx_subdivision_weight, num_vertices);
29397 ufbxi_check_return_err(&sc->error, dst && weights, NULL);
29398
29399 ufbxi_nounroll for (size_t i = 0; i != num_vertices; i++) {
29400 dst[i].weights = weights + i;
29401 dst[i].num_weights = 1;
29402 weights[i].index = (uint32_t)i;
29403 weights[i].weight = 1.0f;
29404 }
29405
29406 return dst;
29407 }
29408
29409 static ufbxi_noinline ufbxi_subdivision_vertex_weights *ufbxi_init_skin_weights(ufbxi_subdivide_context *sc, size_t num_vertices, const ufbx_skin_deformer *skin)
29410 {
29411 ufbxi_subdivision_vertex_weights *dst = ufbxi_push(&sc->tmp, ufbxi_subdivision_vertex_weights, num_vertices);
29412 ufbxi_check_return_err(&sc->error, dst, NULL);
29413
29414 for (size_t i = 0; i < num_vertices; i++) {
29415 ufbxi_dev_assert(i < skin->vertices.count);
29416 ufbx_skin_vertex vertex = skin->vertices.data[i];
29417 size_t num_weights = ufbxi_min_sz(sc->max_vertex_weights, vertex.num_weights);
29418
29419 ufbx_subdivision_weight *weights = ufbxi_push(&sc->tmp, ufbx_subdivision_weight, num_weights);
29420 ufbxi_check_err(&sc->error, weights);
29421
29422 const ufbx_skin_weight *skin_weights = skin->weights.data + vertex.weight_begin;
29423
29424 dst[i].weights = weights;
29425 dst[i].num_weights = num_weights;
29426 ufbxi_nounroll for (size_t wi = 0; wi != num_weights; wi++) {
29427 ufbxi_check_err(&sc->error, skin_weights[wi].cluster_index <= INT32_MAX);
29428 weights[wi].index = skin_weights[wi].cluster_index;
29429 weights[wi].weight = skin_weights[wi].weight;
29430 }
29431 }
29432
29433 return dst;
29434 }
29435
29436 static ufbxi_noinline int ufbxi_subdivide_weights(ufbxi_subdivide_context *sc, ufbx_subdivision_weight_range_list *ranges,
29437 ufbx_subdivision_weight_list *weights, const ufbxi_subdivision_vertex_weights *src)
29438 {
29439 ufbxi_check_err(&sc->error, src);
29440
29441 ufbxi_subdivide_layer_input input; // ufbxi_uninit
29442 input.sum_fn = ufbxi_subdivide_sum_vertex_weights;
29443 input.sum_user = sc;
29444 input.values = src;
29445 input.indices = sc->src_mesh.vertex_indices.data;
29446 input.stride = sizeof(ufbxi_subdivision_vertex_weights);
29447 input.boundary = sc->opts.boundary;
29448 input.check_split_data = false;
29449 input.ignore_indices = true;
29450
29451 sc->total_weights = 0;
29452
29453 ufbxi_subdivide_layer_output output; // ufbxi_uninit
29454 ufbxi_check_err(&sc->error, ufbxi_subdivide_layer(sc, &output, &input));
29455
29456 size_t num_vertices = output.num_values;
29457 ufbx_assert(num_vertices == sc->dst_mesh.vertex_position.values.count);
29458
29459 ufbx_subdivision_weight_range *dst_ranges = ufbxi_push(&sc->result, ufbx_subdivision_weight_range, num_vertices);
29460 ufbx_subdivision_weight *dst_weights = ufbxi_push(&sc->result, ufbx_subdivision_weight, sc->total_weights);
29461 ufbxi_check_err(&sc->error, ranges && weights);
29462
29463 ufbxi_subdivision_vertex_weights *src_weights = (ufbxi_subdivision_vertex_weights*)output.values;
29464
29465 size_t weight_offset = 0;
29466 for (size_t vi = 0; vi < num_vertices; vi++) {
29467 ufbxi_subdivision_vertex_weights ws = src_weights[vi];
29468 ufbxi_check_err(&sc->error, (size_t)UINT32_MAX - weight_offset >= ws.num_weights);
29469
29470 dst_ranges[vi].weight_begin = (uint32_t)weight_offset;
29471 dst_ranges[vi].num_weights = (uint32_t)ws.num_weights;
29472 memcpy(dst_weights + weight_offset, ws.weights, ws.num_weights * sizeof(ufbx_subdivision_weight));
29473 weight_offset += ws.num_weights;
29474 }
29475
29476 ranges->data = dst_ranges;
29477 ranges->count = num_vertices;
29478 weights->data = dst_weights;
29479 weights->count = sc->total_weights;
29480
29481 return 1;
29482 }
29483
29484 ufbxi_nodiscard static ufbxi_noinline int ufbxi_subdivide_vertex_crease(ufbxi_subdivide_context *sc, ufbx_vertex_real *ufbxi_restrict dst, const ufbx_vertex_real *ufbxi_restrict src)
29485 {
29486 size_t src_indices = src->indices.count;
29487 size_t src_values = src->values.count;
29488
29489 dst->values.count = src_values + 1;
29490 dst->values.data = ufbxi_push(&sc->result, ufbx_real, dst->values.count);
29491 ufbxi_check_err(&sc->error, dst->values.data);
29492 dst->values.data[src_values] = 0.0f;
29493
29494 dst->indices.count = src_indices * 4;
29495 dst->indices.data = ufbxi_push(&sc->result, uint32_t, dst->indices.count);
29496 ufbxi_check_err(&sc->error, dst->indices.data);
29497
29498 // Reduce the amount of vertex crease on each iteration
29499 ufbxi_nounroll for (size_t i = 0; i < src_values; i++) {
29500 ufbx_real crease = src->values.data[i];
29501 if (crease < 0.999f) crease -= 0.1f;
29502 if (crease < 0.0f) crease = 0.0f;
29503 dst->values.data[i] = crease;
29504 }
29505
29506 // Write the crease at the vertex corner and zero (at `src_values`) on other ones
29507 uint32_t zero_index = (uint32_t)src_values;
29508 ufbxi_nounroll for (size_t i = 0; i < src_indices; i++) {
29509 uint32_t *quad = dst->indices.data + i * 4;
29510 quad[0] = src->indices.data[i];
29511 quad[1] = zero_index;
29512 quad[2] = zero_index;
29513 quad[3] = zero_index;
29514 }
29515
29516 return 1;
29517 }
29518
29519 ufbxi_nodiscard static ufbxi_noinline int ufbxi_subdivide_mesh_level(ufbxi_subdivide_context *sc)
29520 {
29521 const ufbx_mesh *mesh = &sc->src_mesh;
29522 ufbx_mesh *result = &sc->dst_mesh;
29523
29524 *result = *mesh;
29525
29526 ufbx_topo_edge *topo = ufbxi_push(&sc->tmp, ufbx_topo_edge, mesh->num_indices);
29527 ufbxi_check_err(&sc->error, topo);
29528 ufbx_compute_topology(mesh, topo, mesh->num_indices);
29529 sc->topo = topo;
29530 sc->num_topo = mesh->num_indices;
29531
29532 ufbxi_check_err(&sc->error, ufbxi_subdivide_attrib(sc, (ufbx_vertex_attrib*)&result->vertex_position, sc->opts.boundary, false));
29533
29534 memset(&result->vertex_uv, 0, sizeof(result->vertex_uv));
29535 memset(&result->vertex_tangent, 0, sizeof(result->vertex_tangent));
29536 memset(&result->vertex_bitangent, 0, sizeof(result->vertex_bitangent));
29537 memset(&result->vertex_color, 0, sizeof(result->vertex_color));
29538
29539 result->uv_sets.data = ufbxi_push_copy(&sc->result, ufbx_uv_set, result->uv_sets.count, result->uv_sets.data);
29540 ufbxi_check_err(&sc->error, result->uv_sets.data);
29541
29542 result->color_sets.data = ufbxi_push_copy(&sc->result, ufbx_color_set, result->color_sets.count, result->color_sets.data);
29543 ufbxi_check_err(&sc->error, result->color_sets.data);
29544
29545 ufbxi_for_list(ufbx_uv_set, set, result->uv_sets) {
29546 ufbxi_check_err(&sc->error, ufbxi_subdivide_attrib(sc, (ufbx_vertex_attrib*)&set->vertex_uv, sc->opts.uv_boundary, true));
29547 if (sc->opts.interpolate_tangents) {
29548 ufbxi_check_err(&sc->error, ufbxi_subdivide_attrib(sc, (ufbx_vertex_attrib*)&set->vertex_tangent, sc->opts.uv_boundary, true));
29549 ufbxi_check_err(&sc->error, ufbxi_subdivide_attrib(sc, (ufbx_vertex_attrib*)&set->vertex_bitangent, sc->opts.uv_boundary, true));
29550 } else {
29551 memset(&set->vertex_tangent, 0, sizeof(set->vertex_tangent));
29552 memset(&set->vertex_bitangent, 0, sizeof(set->vertex_bitangent));
29553 }
29554 }
29555
29556 ufbxi_for_list(ufbx_color_set, set, result->color_sets) {
29557 ufbxi_check_err(&sc->error, ufbxi_subdivide_attrib(sc, (ufbx_vertex_attrib*)&set->vertex_color, sc->opts.uv_boundary, true));
29558 }
29559
29560 if (result->uv_sets.count > 0) {
29561 result->vertex_uv = result->uv_sets.data[0].vertex_uv;
29562 result->vertex_bitangent = result->uv_sets.data[0].vertex_bitangent;
29563 result->vertex_tangent = result->uv_sets.data[0].vertex_tangent;
29564 }
29565 if (result->color_sets.count > 0) {
29566 result->vertex_color = result->color_sets.data[0].vertex_color;
29567 }
29568
29569 if (sc->opts.interpolate_normals && !sc->opts.ignore_normals) {
29570 ufbxi_check_err(&sc->error, ufbxi_subdivide_attrib(sc, (ufbx_vertex_attrib*)&result->vertex_normal, sc->opts.boundary, true));
29571 ufbxi_for_list(ufbx_vec3, normal, result->vertex_normal.values) {
29572 *normal = ufbxi_slow_normalize3(normal);
29573 }
29574 if (mesh->skinned_normal.values.data == mesh->vertex_normal.values.data) {
29575 result->skinned_normal = result->vertex_normal;
29576 } else {
29577 ufbxi_check_err(&sc->error, ufbxi_subdivide_attrib(sc, (ufbx_vertex_attrib*)&result->skinned_normal, sc->opts.boundary, true));
29578 ufbxi_for_list(ufbx_vec3, normal, result->skinned_normal.values) {
29579 *normal = ufbxi_slow_normalize3(normal);
29580 }
29581 }
29582 }
29583
29584 if (result->vertex_crease.exists) {
29585 ufbxi_check_err(&sc->error, ufbxi_subdivide_vertex_crease(sc, &result->vertex_crease, &mesh->vertex_crease));
29586 }
29587
29588 if (mesh->skinned_position.values.data == mesh->vertex_position.values.data) {
29589 result->skinned_position = result->vertex_position;
29590 } else {
29591 ufbxi_check_err(&sc->error, ufbxi_subdivide_attrib(sc, (ufbx_vertex_attrib*)&result->skinned_position, sc->opts.boundary, false));
29592 }
29593
29594 ufbx_subdivision_result *result_sub = ufbxi_push_zero(&sc->result, ufbx_subdivision_result, 1);
29595 ufbxi_check_err(&sc->error, result_sub);
29596 result->subdivision_result = result_sub;
29597
29598 if (sc->opts.evaluate_source_vertices || sc->opts.evaluate_skin_weights) {
29599 ufbx_subdivision_result *mesh_sub = mesh->subdivision_result;
29600
29601 ufbx_skin_deformer *skin = NULL;
29602 if (sc->opts.evaluate_skin_weights) {
29603 if (mesh->skin_deformers.count > 0) {
29604 ufbxi_check_err(&sc->error, sc->opts.skin_deformer_index < mesh->skin_deformers.count);
29605 skin = mesh->skin_deformers.data[sc->opts.skin_deformer_index];
29606 }
29607 }
29608
29609 size_t max_weights = 0;
29610 if (sc->opts.evaluate_source_vertices) {
29611 max_weights = ufbxi_max_sz(max_weights, mesh->num_vertices);
29612 }
29613 if (skin) {
29614 max_weights = ufbxi_max_sz(max_weights, skin->clusters.count);
29615 }
29616
29617 sc->tmp_vertex_weights = ufbxi_push_zero(&sc->tmp, ufbx_real, mesh->num_vertices);
29618 sc->tmp_weights = ufbxi_push(&sc->tmp, ufbx_subdivision_weight, max_weights);
29619 ufbxi_check_err(&sc->error, sc->tmp_vertex_weights && sc->tmp_weights);
29620
29621 if (sc->opts.evaluate_source_vertices) {
29622 sc->max_vertex_weights = sc->opts.max_source_vertices ? sc->opts.max_source_vertices : SIZE_MAX;
29623
29624 ufbxi_subdivision_vertex_weights *weights;
29625 if (mesh_sub && mesh_sub->source_vertex_ranges.count > 0) {
29626 weights = ufbxi_subdivision_copy_weights(sc, mesh_sub->source_vertex_ranges, mesh_sub->source_vertex_weights);
29627 } else {
29628 weights = ufbxi_init_source_vertex_weights(sc, mesh->num_vertices);
29629 }
29630
29631 ufbxi_check_err(&sc->error, ufbxi_subdivide_weights(sc, &result_sub->source_vertex_ranges, &result_sub->source_vertex_weights, weights));
29632 }
29633
29634 if (skin) {
29635 sc->max_vertex_weights = sc->opts.max_skin_weights ? sc->opts.max_skin_weights : SIZE_MAX;
29636
29637 ufbxi_subdivision_vertex_weights *weights;
29638 if (mesh_sub && mesh_sub->source_vertex_ranges.count > 0) {
29639 weights = ufbxi_subdivision_copy_weights(sc, mesh_sub->skin_cluster_ranges, mesh_sub->skin_cluster_weights);
29640 } else {
29641 weights = ufbxi_init_skin_weights(sc, mesh->num_vertices, skin);
29642 }
29643
29644 ufbxi_check_err(&sc->error, ufbxi_subdivide_weights(sc, &result_sub->skin_cluster_ranges, &result_sub->skin_cluster_weights, weights));
29645 }
29646
29647 }
29648
29649 result->num_vertices = result->vertex_position.values.count;
29650 result->num_indices = mesh->num_indices * 4;
29651 result->num_faces = mesh->num_indices;
29652 result->num_triangles = mesh->num_indices * 2;
29653
29654 result->vertex_indices.data = result->vertex_position.indices.data;
29655 result->vertex_indices.count = result->num_indices;
29656 result->vertices.data = result->vertex_position.values.data;
29657 result->vertices.count = result->num_vertices;
29658
29659 result->faces.count = result->num_faces;
29660 result->faces.data = ufbxi_push(&sc->result, ufbx_face, result->num_faces);
29661 ufbxi_check_err(&sc->error, result->faces.data);
29662
29663 for (size_t i = 0; i < result->num_faces; i++) {
29664 result->faces.data[i].index_begin = (uint32_t)(i * 4);
29665 result->faces.data[i].num_indices = 4;
29666 }
29667
29668 if (mesh->edges.data) {
29669 result->num_edges = mesh->num_edges*2 + result->num_faces;
29670 result->edges.count = result->num_edges;
29671 result->edges.data = ufbxi_push(&sc->result, ufbx_edge, result->num_edges);
29672 ufbxi_check_err(&sc->error, result->edges.data);
29673
29674 if (mesh->edge_crease.data) {
29675 result->edge_crease.count = result->num_edges;
29676 result->edge_crease.data = ufbxi_push(&sc->result, ufbx_real, result->num_edges);
29677 ufbxi_check_err(&sc->error, result->edge_crease.data);
29678 }
29679 if (mesh->edge_smoothing.data) {
29680 result->edge_smoothing.count = result->num_edges;
29681 result->edge_smoothing.data = ufbxi_push(&sc->result, bool, result->num_edges);
29682 ufbxi_check_err(&sc->error, result->edge_smoothing.data);
29683 }
29684 if (mesh->edge_visibility.data) {
29685 result->edge_visibility.count = result->num_edges;
29686 result->edge_visibility.data = ufbxi_push(&sc->result, bool, result->num_edges);
29687 ufbxi_check_err(&sc->error, result->edge_visibility.data);
29688 }
29689
29690 size_t di = 0;
29691 for (size_t i = 0; i < mesh->num_edges; i++) {
29692 ufbx_edge edge = mesh->edges.data[i];
29693 uint32_t face_ix = topo[edge.a].face;
29694 ufbx_face face = mesh->faces.data[face_ix];
29695 uint32_t offset = edge.a - face.index_begin;
29696 uint32_t next = (offset + 1) % (uint32_t)face.num_indices;
29697
29698 uint32_t a = (face.index_begin + offset) * 4;
29699 uint32_t b = (face.index_begin + next) * 4;
29700
29701 result->edges.data[di + 0].a = a;
29702 result->edges.data[di + 0].b = a + 1;
29703 result->edges.data[di + 1].a = b + 3;
29704 result->edges.data[di + 1].b = b;
29705
29706 if (mesh->edge_crease.data) {
29707 ufbx_real crease = mesh->edge_crease.data[i];
29708 if (crease < 0.999f) crease -= (ufbx_real)0.1;
29709 if (crease < 0.0f) crease = 0.0f;
29710 result->edge_crease.data[di + 0] = crease;
29711 result->edge_crease.data[di + 1] = crease;
29712 }
29713
29714 if (mesh->edge_smoothing.data) {
29715 result->edge_smoothing.data[di + 0] = mesh->edge_smoothing.data[i];
29716 result->edge_smoothing.data[di + 1] = mesh->edge_smoothing.data[i];
29717 }
29718
29719 if (mesh->edge_visibility.data) {
29720 result->edge_visibility.data[di + 0] = mesh->edge_visibility.data[i];
29721 result->edge_visibility.data[di + 1] = mesh->edge_visibility.data[i];
29722 }
29723
29724 di += 2;
29725 }
29726
29727 for (size_t fi = 0; fi < result->num_faces; fi++) {
29728 result->edges.data[di].a = (uint32_t)(fi * 4 + 1);
29729 result->edges.data[di].b = (uint32_t)(fi * 4 + 2);
29730
29731 if (result->edge_crease.data) {
29732 result->edge_crease.data[di] = 0.0f;
29733 }
29734
29735 if (result->edge_smoothing.data) {
29736 result->edge_smoothing.data[di + 0] = true;
29737 }
29738
29739 if (result->edge_visibility.data) {
29740 result->edge_visibility.data[di + 0] = false;
29741 }
29742
29743 di++;
29744 }
29745 }
29746
29747 if (mesh->face_material.data) {
29748 result->face_material.count = result->num_faces;
29749 result->face_material.data = ufbxi_push(&sc->result, uint32_t, result->num_faces);
29750 ufbxi_check_err(&sc->error, result->face_material.data);
29751 }
29752 if (mesh->face_smoothing.data) {
29753 result->face_smoothing.count = result->num_faces;
29754 result->face_smoothing.data = ufbxi_push(&sc->result, bool, result->num_faces);
29755 ufbxi_check_err(&sc->error, result->face_smoothing.data);
29756 }
29757 if (mesh->face_group.data) {
29758 result->face_group.count = result->num_faces;
29759 result->face_group.data = ufbxi_push(&sc->result, uint32_t, result->num_faces);
29760 ufbxi_check_err(&sc->error, result->face_group.data);
29761 }
29762 if (mesh->face_hole.data) {
29763 result->face_hole.count = result->num_faces;
29764 result->face_hole.data = ufbxi_push(&sc->result, bool, result->num_faces);
29765 ufbxi_check_err(&sc->error, result->face_hole.data);
29766 }
29767
29768 if (result->material_parts.count > 0) {
29769 result->material_parts.data = ufbxi_push_zero(&sc->result, ufbx_mesh_part, result->material_parts.count);
29770 ufbxi_check_err(&sc->error, result->materials.data);
29771 }
29772
29773 size_t index_offset = 0;
29774 for (size_t i = 0; i < mesh->num_faces; i++) {
29775 ufbx_face face = mesh->faces.data[i];
29776
29777 uint32_t mat = 0;
29778 if (mesh->face_material.data) {
29779 mat = mesh->face_material.data[i];
29780 for (size_t ci = 0; ci < face.num_indices; ci++) {
29781 result->face_material.data[index_offset + ci] = mat;
29782 }
29783 }
29784 if (mesh->face_smoothing.data) {
29785 bool flag = mesh->face_smoothing.data[i];
29786 for (size_t ci = 0; ci < face.num_indices; ci++) {
29787 result->face_smoothing.data[index_offset + ci] = flag;
29788 }
29789 }
29790 if (mesh->face_group.data) {
29791 uint32_t group = mesh->face_group.data[i];
29792 for (size_t ci = 0; ci < face.num_indices; ci++) {
29793 result->face_group.data[index_offset + ci] = group;
29794 }
29795 }
29796 if (mesh->face_hole.data) {
29797 bool flag = mesh->face_hole.data[i];
29798 for (size_t ci = 0; ci < face.num_indices; ci++) {
29799 result->face_hole.data[index_offset + ci] = flag;
29800 }
29801 }
29802 index_offset += face.num_indices;
29803 }
29804
29805 // Will be filled in by `ufbxi_finalize_mesh()`.
29806 result->vertex_first_index.count = 0;
29807
29808 ufbxi_check_err(&sc->error, ufbxi_finalize_mesh_material(&sc->result, &sc->error, result));
29809 ufbxi_check_err(&sc->error, ufbxi_finalize_mesh(&sc->result, &sc->error, result));
29810 ufbxi_check_err(&sc->error, ufbxi_update_face_groups(&sc->result, &sc->error, result, true));
29811
29812 return 1;
29813 }
29814
29815 ufbxi_nodiscard static ufbxi_noinline int ufbxi_subdivide_mesh_imp(ufbxi_subdivide_context *sc, size_t level)
29816 {
29817 if (sc->opts.boundary == UFBX_SUBDIVISION_BOUNDARY_DEFAULT) {
29818 sc->opts.boundary = sc->src_mesh.subdivision_boundary;
29819 }
29820
29821 if (sc->opts.uv_boundary == UFBX_SUBDIVISION_BOUNDARY_DEFAULT) {
29822 sc->opts.uv_boundary = sc->src_mesh.subdivision_uv_boundary;
29823 }
29824
29825 ufbxi_init_ator(&sc->error, &sc->ator_tmp, &sc->opts.temp_allocator, "temp");
29826 ufbxi_init_ator(&sc->error, &sc->ator_result, &sc->opts.result_allocator, "result");
29827
29828 sc->result.unordered = true;
29829 sc->source.unordered = true;
29830 sc->tmp.unordered = true;
29831
29832 sc->source.ator = &sc->ator_tmp;
29833 sc->tmp.ator = &sc->ator_tmp;
29834
29835 for (size_t i = 1; i < level; i++) {
29836 sc->result.ator = &sc->ator_tmp;
29837
29838 ufbxi_check_err(&sc->error, ufbxi_subdivide_mesh_level(sc));
29839
29840 sc->src_mesh = sc->dst_mesh;
29841
29842 ufbxi_buf_free(&sc->source);
29843 ufbxi_buf_free(&sc->tmp);
29844 sc->source = sc->result;
29845 memset(&sc->result, 0, sizeof(sc->result));
29846 }
29847
29848 sc->result.ator = &sc->ator_result;
29849 ufbxi_check_err(&sc->error, ufbxi_subdivide_mesh_level(sc));
29850 ufbxi_buf_free(&sc->tmp);
29851
29852 ufbx_mesh *mesh = &sc->dst_mesh;
29853
29854 // Subdivision always results in a mesh that consists only of quads
29855 mesh->max_face_triangles = 2;
29856 mesh->num_empty_faces = 0;
29857 mesh->num_point_faces = 0;
29858 mesh->num_line_faces = 0;
29859
29860 if (!sc->opts.interpolate_normals) {
29861 memset(&mesh->vertex_normal, 0, sizeof(mesh->vertex_normal));
29862 memset(&mesh->skinned_normal, 0, sizeof(mesh->skinned_normal));
29863 }
29864
29865 if (!sc->opts.interpolate_normals && !sc->opts.ignore_normals) {
29866
29867 ufbx_topo_edge *topo = ufbxi_push(&sc->tmp, ufbx_topo_edge, mesh->num_indices);
29868 ufbxi_check_err(&sc->error, topo);
29869 ufbx_compute_topology(mesh, topo, mesh->num_indices);
29870
29871 uint32_t *normal_indices = ufbxi_push(&sc->result, uint32_t, mesh->num_indices);
29872 ufbxi_check_err(&sc->error, normal_indices);
29873
29874 size_t num_normals = ufbx_generate_normal_mapping(mesh, topo, mesh->num_indices, normal_indices, mesh->num_indices, true);
29875 if (num_normals == mesh->num_vertices) {
29876 mesh->skinned_normal.unique_per_vertex = true;
29877 }
29878
29879 ufbx_vec3 *normal_data = ufbxi_push(&sc->result, ufbx_vec3, num_normals + 1);
29880 ufbxi_check_err(&sc->error, normal_data);
29881 normal_data[0] = ufbx_zero_vec3;
29882 normal_data++;
29883
29884 ufbx_compute_normals(mesh, &mesh->skinned_position, normal_indices, mesh->num_indices, normal_data, num_normals);
29885
29886 mesh->generated_normals = true;
29887 mesh->vertex_normal.exists = true;
29888 mesh->vertex_normal.values.data = normal_data;
29889 mesh->vertex_normal.values.count = num_normals;
29890 mesh->vertex_normal.indices.data = normal_indices;
29891 mesh->vertex_normal.indices.count = mesh->num_indices;
29892
29893 mesh->skinned_normal = mesh->vertex_normal;
29894 }
29895
29896 ufbxi_refcount *parent = NULL;
29897 if (sc->src_mesh_ptr->subdivision_evaluated && sc->src_mesh_ptr->from_tessellated_nurbs) {
29898 parent = &(ufbxi_get_imp(ufbxi_mesh_imp, sc->src_mesh_ptr))->refcount;
29899 } else {
29900 parent = &(ufbxi_get_imp(ufbxi_scene_imp, sc->src_mesh_ptr->element.scene))->refcount;
29901 }
29902
29903 ufbxi_patch_mesh_reals(mesh);
29904
29905 sc->imp = ufbxi_push(&sc->result, ufbxi_mesh_imp, 1);
29906 ufbxi_check_err(&sc->error, sc->imp);
29907
29908 sc->dst_mesh.subdivision_result->result_memory_used = sc->ator_result.current_size;
29909 sc->dst_mesh.subdivision_result->temp_memory_used = sc->ator_tmp.current_size;
29910 sc->dst_mesh.subdivision_result->result_allocs = sc->ator_result.num_allocs;
29911 sc->dst_mesh.subdivision_result->temp_allocs = sc->ator_tmp.num_allocs;
29912
29913 ufbxi_init_ref(&sc->imp->refcount, UFBXI_MESH_IMP_MAGIC, parent);
29914
29915 sc->imp->magic = UFBXI_MESH_IMP_MAGIC;
29916 sc->imp->mesh = sc->dst_mesh;
29917 sc->imp->refcount.ator = sc->ator_result;
29918 sc->imp->refcount.buf = sc->result;
29919 sc->imp->mesh.subdivision_evaluated = true;
29920
29921 return 1;
29922 }
29923
29924 ufbxi_noinline static ufbx_mesh *ufbxi_subdivide_mesh(const ufbx_mesh *mesh, size_t level, const ufbx_subdivide_opts *user_opts, ufbx_error *p_error)
29925 {
29926 ufbxi_subdivide_context sc = { 0 };
29927 if (user_opts) {
29928 sc.opts = *user_opts;
29929 }
29930
29931 sc.src_mesh_ptr = (ufbx_mesh*)mesh;
29932 sc.src_mesh = *mesh;
29933
29934 int ok = ufbxi_subdivide_mesh_imp(&sc, level);
29935
29936 ufbxi_free(&sc.ator_tmp, ufbxi_subdivide_input, sc.inputs, sc.inputs_cap);
29937 ufbxi_buf_free(&sc.tmp);
29938 ufbxi_buf_free(&sc.source);
29939
29940 if (ok) {
29941 ufbxi_free_ator(&sc.ator_tmp);
29942 if (p_error) {
29943 ufbxi_clear_error(p_error);
29944 }
29945
29946 ufbxi_mesh_imp *imp = sc.imp;
29947 return &imp->mesh;
29948 } else {
29949 ufbxi_fix_error_type(&sc.error, "Failed to subdivide", p_error);
29950 ufbxi_buf_free(&sc.result);
29951 ufbxi_free_ator(&sc.ator_tmp);
29952 ufbxi_free_ator(&sc.ator_result);
29953 return NULL;
29954 }
29955 }
29956
29957 #else
29958
29959 ufbxi_noinline static ufbx_mesh *ufbxi_subdivide_mesh(const ufbx_mesh *mesh, size_t level, const ufbx_subdivide_opts *user_opts, ufbx_error *p_error)
29960 {
29961 if (p_error) {
29962 memset(p_error, 0, sizeof(ufbx_error));
29963 ufbxi_fmt_err_info(p_error, "UFBX_ENABLE_SUBDIVISION");
29964 ufbxi_report_err_msg(p_error, "UFBXI_FEATURE_SUBDIVISION", "Feature disabled");
29965 }
29966 return NULL;
29967 }
29968
29969 #endif
29970
29971 // -- Utility
29972
29973 #if UFBXI_FEATURE_INDEX_GENERATION
29974
29975 static int ufbxi_map_cmp_vertex(void *user, const void *va, const void *vb)
29976 {
29977 size_t size = *(size_t*)user;
29978 #if defined(UFBX_REGRESSION)
29979 ufbx_assert(size % 8 == 0);
29980 #endif
29981 for (size_t i = 0; i < size; i += 8) {
29982 uint64_t a = *(const uint64_t*)((const char*)va + i);
29983 uint64_t b = *(const uint64_t*)((const char*)vb + i);
29984 if (a != b) return a < b ? -1 : +1;
29985 }
29986 return 0;
29987 }
29988
29989 typedef struct {
29990 char *begin, *ptr;
29991 size_t vertex_size;
29992 size_t packed_offset;
29993 } ufbxi_vertex_stream;
29994
29995 static ufbxi_noinline size_t ufbxi_generate_indices(const ufbx_vertex_stream *user_streams, size_t num_streams, uint32_t *indices, size_t num_indices, const ufbx_allocator_opts *allocator, ufbx_error *error)
29996 {
29997 bool fail = false;
29998
29999 ufbxi_allocator ator = { 0 };
30000 ufbxi_init_ator(error, &ator, allocator, "allocator");
30001
30002 ufbxi_vertex_stream local_streams[16]; // ufbxi_uninit
30003 uint64_t local_packed_vertex[64]; // ufbxi_uninit
30004
30005 ufbxi_vertex_stream *streams = NULL;
30006 if (num_streams > ufbxi_arraycount(local_streams)) {
30007 streams = ufbxi_alloc(&ator, ufbxi_vertex_stream, num_streams);
30008 if (!streams) fail = true;
30009 } else {
30010 streams = local_streams;
30011 }
30012
30013 size_t packed_size = 0;
30014 if (!fail) {
30015 for (size_t i = 0; i < num_streams; i++) {
30016 if (user_streams[i].vertex_count < num_indices) {
30017 ufbxi_fmt_err_info(error, "%zu", i);
30018 ufbxi_report_err_msg(error, "user_streams[i].vertex_count < num_indices", "Truncated vertex stream");
30019 fail = true;
30020 break;
30021 }
30022
30023 size_t vertex_size = user_streams[i].vertex_size;
30024 size_t align = ufbxi_size_align_mask(vertex_size);
30025 packed_size = ufbxi_align_to_mask(packed_size, align);
30026 streams[i].ptr = streams[i].begin = (char*)user_streams[i].data;
30027 streams[i].vertex_size = vertex_size;
30028 streams[i].packed_offset = packed_size;
30029 packed_size += vertex_size;
30030 }
30031 packed_size = ufbxi_align_to_mask(packed_size, 7);
30032 }
30033
30034 if (!fail && packed_size == 0) {
30035 ufbxi_report_err_msg(error, "packed_size != 0", "Zero vertex size");
30036 fail = true;
30037 }
30038
30039 char *packed_vertex = NULL;
30040 if (!fail) {
30041 if (packed_size > sizeof(local_packed_vertex)) {
30042 ufbx_assert(packed_size % 8 == 0);
30043 packed_vertex = (char*)ufbxi_alloc(&ator, uint64_t, packed_size / 8);
30044 if (!packed_vertex) fail = true;
30045 } else {
30046 packed_vertex = (char*)local_packed_vertex;
30047 }
30048 }
30049
30050 ufbxi_map map = { 0 };
30051 ufbxi_map_init(&map, &ator, &ufbxi_map_cmp_vertex, &packed_size);
30052
30053 if (num_indices > 0 && !ufbxi_map_grow_size(&map, packed_size, num_indices)) {
30054 fail = true;
30055 }
30056
30057 if (!fail) {
30058 ufbx_assert(packed_vertex != NULL);
30059 memset(packed_vertex, 0, packed_size);
30060
30061 for (size_t i = 0; i < num_indices; i++) {
30062 for (size_t si = 0; si < num_streams; si++) {
30063 size_t size = streams[si].vertex_size, offset = streams[si].packed_offset;
30064 char *ptr = streams[si].ptr;
30065 memcpy(packed_vertex + offset, ptr, size);
30066 streams[si].ptr = ptr + size;
30067 }
30068
30069 uint32_t hash = ufbxi_hash_string(packed_vertex, packed_size);
30070 void *entry = ufbxi_map_find_size(&map, packed_size, hash, packed_vertex);
30071 if (!entry) {
30072 entry = ufbxi_map_insert_size(&map, packed_size, hash, packed_vertex);
30073 if (!entry) {
30074 fail = true;
30075 break;
30076 }
30077 memcpy(entry, packed_vertex, packed_size);
30078 }
30079 uint32_t index = (uint32_t)(ufbxi_to_size((char*)entry - (char*)map.items) / packed_size);
30080 indices[i] = index;
30081 }
30082 }
30083
30084 size_t result_vertices = 0;
30085 if (!fail) {
30086 result_vertices = map.size;
30087
30088 for (size_t si = 0; si < num_streams; si++) {
30089 size_t vertex_size = streams[si].vertex_size;
30090 char *dst = streams[si].begin;
30091 char *src = ufbxi_add_ptr((char*)map.items, streams[si].packed_offset);
30092 for (size_t i = 0; i < result_vertices; i++) {
30093 memcpy(dst, src, vertex_size);
30094 dst += vertex_size;
30095 src += packed_size;
30096 }
30097 }
30098
30099 ufbxi_clear_error(error);
30100 } else {
30101 ufbxi_fix_error_type(error, "Failed to generate indices", NULL);
30102 }
30103
30104 if (streams && streams != local_streams) {
30105 ufbxi_free(&ator, ufbxi_vertex_stream, streams, num_streams);
30106 }
30107 if (packed_vertex && packed_vertex != (char*)local_packed_vertex) {
30108 ufbxi_free(&ator, uint64_t, packed_vertex, packed_size / 8);
30109 }
30110
30111 ufbxi_map_free(&map);
30112 ufbxi_free_ator(&ator);
30113
30114 return result_vertices;
30115 }
30116
30117 #else
30118
30119 static ufbxi_noinline size_t ufbxi_generate_indices(const ufbx_vertex_stream *user_streams, size_t num_streams, uint32_t *indices, size_t num_indices, const ufbx_allocator_opts *allocator, ufbx_error *error)
30120 {
30121 if (error) {
30122 memset(error, 0, sizeof(ufbx_error));
30123 ufbxi_fmt_err_info(error, "UFBX_ENABLE_INDEX_GENERATION");
30124 ufbxi_report_err_msg(error, "UFBXI_FEATURE_INDEX_GENERATION", "Feature disabled");
30125 }
30126 return 0;
30127 }
30128
30129 #endif
30130
30131 static ufbxi_noinline void ufbxi_free_scene_imp(ufbxi_scene_imp *imp)
30132 {
30133 ufbx_assert(imp->magic == UFBXI_SCENE_IMP_MAGIC);
30134 ufbxi_buf_free(&imp->string_buf);
30135 }
30136
30137 static ufbxi_noinline void ufbxi_init_ref(ufbxi_refcount *refcount, uint32_t magic, ufbxi_refcount *parent)
30138 {
30139 if (parent) {
30140 ufbxi_retain_ref(parent);
30141 }
30142
30143 ufbxi_atomic_counter_init(&refcount->refcount);
30144 refcount->self_magic = UFBXI_REFCOUNT_IMP_MAGIC;
30145 refcount->type_magic = magic;
30146 refcount->parent = parent;
30147 }
30148
30149 static ufbxi_noinline void ufbxi_retain_ref(ufbxi_refcount *refcount)
30150 {
30151 ufbx_assert(refcount->self_magic == UFBXI_REFCOUNT_IMP_MAGIC);
30152 size_t count = ufbxi_atomic_counter_inc(&refcount->refcount);
30153 ufbxi_ignore(count);
30154 ufbx_assert(count < SIZE_MAX / 2);
30155 }
30156
30157 static ufbxi_noinline void ufbxi_release_ref(ufbxi_refcount *refcount)
30158 {
30159 while (refcount) {
30160 ufbx_assert(refcount->self_magic == UFBXI_REFCOUNT_IMP_MAGIC);
30161 if (ufbxi_atomic_counter_dec(&refcount->refcount) > 0) return;
30162 ufbxi_atomic_counter_free(&refcount->refcount);
30163
30164 ufbxi_refcount *parent = refcount->parent;
30165 uint32_t type_magic = refcount->type_magic;
30166
30167 refcount->self_magic = 0;
30168 refcount->type_magic = 0;
30169
30170 // Type-specific cleanup
30171 switch (type_magic) {
30172 case UFBXI_SCENE_IMP_MAGIC: ufbxi_free_scene_imp((ufbxi_scene_imp*)refcount); break;
30173 case UFBXI_CACHE_IMP_MAGIC: ufbxi_free_geometry_cache_imp((ufbxi_geometry_cache_imp*)refcount); break;
30174 default: break;
30175 }
30176
30177 // We need to free `data_buf` last and be careful to copy it to
30178 // the stack since the `ufbxi_refcount` that contains it is allocated
30179 // from the same result buffer!
30180 ufbxi_allocator ator = refcount->ator;
30181 ufbxi_buf buf = refcount->buf;
30182 buf.ator = &ator;
30183 ufbxi_buf_free(&buf);
30184 ufbxi_free_ator(&ator);
30185
30186 refcount = parent;
30187 }
30188 }
30189
30190 static ufbxi_noinline void *ufbxi_uninitialized_options(ufbx_error *p_error)
30191 {
30192 if (p_error) {
30193 memset(p_error, 0, sizeof(ufbx_error));
30194 p_error->type = UFBX_ERROR_UNINITIALIZED_OPTIONS;
30195 p_error->description.data = "Uninitialized options";
30196 p_error->description.length = strlen("Uninitialized options");
30197 }
30198 return NULL;
30199 }
30200
30201 #define ufbxi_check_opts_ptr(m_type, m_opts, m_error) do { if (m_opts) { \
30202 uint32_t opts_cleared_to_zero = m_opts->_begin_zero | m_opts->_end_zero; \
30203 ufbx_assert(opts_cleared_to_zero == 0); \
30204 if (opts_cleared_to_zero != 0) return (m_type*)ufbxi_uninitialized_options(m_error); \
30205 } } while (0)
30206
30207 #define ufbxi_check_opts_return(m_value, m_opts, m_error) do { if (m_opts) { \
30208 uint32_t opts_cleared_to_zero = m_opts->_begin_zero | m_opts->_end_zero; \
30209 ufbx_assert(opts_cleared_to_zero == 0); \
30210 if (opts_cleared_to_zero != 0) { \
30211 ufbxi_uninitialized_options(m_error); \
30212 return m_value; \
30213 } \
30214 } } while (0)
30215
30216 #define ufbxi_check_opts_return_no_error(m_value, m_opts) do { if (m_opts) { \
30217 uint32_t opts_cleared_to_zero = m_opts->_begin_zero | m_opts->_end_zero; \
30218 if (opts_cleared_to_zero != 0) return m_value; \
30219 } } while (0)
30220
30221 // -- API
30222
30223 #ifdef __cplusplus
30224 extern "C" {
30225 #endif
30226
30227 ufbx_abi_data_def const ufbx_string ufbx_empty_string = { ufbxi_empty_char, 0 };
30228 ufbx_abi_data_def const ufbx_blob ufbx_empty_blob = { NULL, 0 };
30229 ufbx_abi_data_def const ufbx_matrix ufbx_identity_matrix = { 1,0,0, 0,1,0, 0,0,1, 0,0,0 };
30230 ufbx_abi_data_def const ufbx_transform ufbx_identity_transform = { {0,0,0}, {0,0,0,1}, {1,1,1} };
30231 ufbx_abi_data_def const ufbx_vec2 ufbx_zero_vec2 = { 0,0 };
30232 ufbx_abi_data_def const ufbx_vec3 ufbx_zero_vec3 = { 0,0,0 };
30233 ufbx_abi_data_def const ufbx_vec4 ufbx_zero_vec4 = { 0,0,0,0 };
30234 ufbx_abi_data_def const ufbx_quat ufbx_identity_quat = { 0,0,0,1 };
30235
30236 ufbx_abi_data_def const ufbx_coordinate_axes ufbx_axes_right_handed_y_up = {
30237 UFBX_COORDINATE_AXIS_POSITIVE_X, UFBX_COORDINATE_AXIS_POSITIVE_Y, UFBX_COORDINATE_AXIS_POSITIVE_Z,
30238 };
30239 ufbx_abi_data_def const ufbx_coordinate_axes ufbx_axes_right_handed_z_up = {
30240 UFBX_COORDINATE_AXIS_POSITIVE_X, UFBX_COORDINATE_AXIS_POSITIVE_Z, UFBX_COORDINATE_AXIS_NEGATIVE_Y,
30241 };
30242 ufbx_abi_data_def const ufbx_coordinate_axes ufbx_axes_left_handed_y_up = {
30243 UFBX_COORDINATE_AXIS_POSITIVE_X, UFBX_COORDINATE_AXIS_POSITIVE_Y, UFBX_COORDINATE_AXIS_NEGATIVE_Z,
30244 };
30245 ufbx_abi_data_def const ufbx_coordinate_axes ufbx_axes_left_handed_z_up = {
30246 UFBX_COORDINATE_AXIS_POSITIVE_X, UFBX_COORDINATE_AXIS_POSITIVE_Z, UFBX_COORDINATE_AXIS_POSITIVE_Y,
30247 };
30248
30249 ufbx_abi_data_def const size_t ufbx_element_type_size[UFBX_ELEMENT_TYPE_COUNT] = {
30250 sizeof(ufbx_unknown),
30251 sizeof(ufbx_node),
30252 sizeof(ufbx_mesh),
30253 sizeof(ufbx_light),
30254 sizeof(ufbx_camera),
30255 sizeof(ufbx_bone),
30256 sizeof(ufbx_empty),
30257 sizeof(ufbx_line_curve),
30258 sizeof(ufbx_nurbs_curve),
30259 sizeof(ufbx_nurbs_surface),
30260 sizeof(ufbx_nurbs_trim_surface),
30261 sizeof(ufbx_nurbs_trim_boundary),
30262 sizeof(ufbx_procedural_geometry),
30263 sizeof(ufbx_stereo_camera),
30264 sizeof(ufbx_camera_switcher),
30265 sizeof(ufbx_marker),
30266 sizeof(ufbx_lod_group),
30267 sizeof(ufbx_skin_deformer),
30268 sizeof(ufbx_skin_cluster),
30269 sizeof(ufbx_blend_deformer),
30270 sizeof(ufbx_blend_channel),
30271 sizeof(ufbx_blend_shape),
30272 sizeof(ufbx_cache_deformer),
30273 sizeof(ufbx_cache_file),
30274 sizeof(ufbx_material),
30275 sizeof(ufbx_texture),
30276 sizeof(ufbx_video),
30277 sizeof(ufbx_shader),
30278 sizeof(ufbx_shader_binding),
30279 sizeof(ufbx_anim_stack),
30280 sizeof(ufbx_anim_layer),
30281 sizeof(ufbx_anim_value),
30282 sizeof(ufbx_anim_curve),
30283 sizeof(ufbx_display_layer),
30284 sizeof(ufbx_selection_set),
30285 sizeof(ufbx_selection_node),
30286 sizeof(ufbx_character),
30287 sizeof(ufbx_constraint),
30288 sizeof(ufbx_audio_layer),
30289 sizeof(ufbx_audio_clip),
30290 sizeof(ufbx_pose),
30291 sizeof(ufbx_metadata_object),
30292 };
30293
30294 ufbx_abi bool ufbx_default_open_file(void *user, ufbx_stream *stream, const char *path, size_t path_len, const ufbx_open_file_info *info)
30295 {
30296 (void)user;
30297 return ufbx_open_file_ctx(stream, info->context, path, path_len, NULL, NULL);
30298 }
30299
30300 ufbx_abi bool ufbx_open_file(ufbx_stream *stream, const char *path, size_t path_len, const ufbx_open_file_opts *opts, ufbx_error *error)
30301 {
30302 return ufbx_open_file_ctx(stream, (ufbx_open_file_context)NULL, path, path_len, opts, error);
30303 }
30304
30305 ufbx_abi bool ufbx_open_file_ctx(ufbx_stream *stream, ufbx_open_file_context ctx, const char *path, size_t path_len, const ufbx_open_file_opts *opts, ufbx_error *error)
30306 {
30307 bool ok = false;
30308 ufbxi_file_context fc; // ufbxi_uninit
30309 ufbxi_begin_file_context(&fc, ctx, NULL);
30310 if (path_len == SIZE_MAX) path_len = strlen(path);
30311 #if !defined(UFBX_NO_STDIO)
30312 ok = ufbxi_stdio_open(&fc, stream, path, path_len, opts ? opts->filename_null_terminated : false);
30313 #else
30314 (void)stream;
30315 (void)path;
30316 (void)path_len;
30317 (void)opts;
30318 ufbxi_fmt_err_info(&fc.error, "UFBX_NO_STDIO");
30319 ufbxi_report_err_msg(&fc.error, "UFBX_NO_STDIO", "Feature disabled");
30320 #endif
30321 ufbxi_end_file_context(&fc, error, ok);
30322 return ok;
30323 }
30324
30325 ufbx_abi bool ufbx_open_memory(ufbx_stream *stream, const void *data, size_t data_size, const ufbx_open_memory_opts *opts, ufbx_error *error)
30326 {
30327 return ufbx_open_memory_ctx(stream, (ufbx_open_file_context)NULL, data, data_size, opts, error);
30328 }
30329
30330 ufbx_abi bool ufbx_open_memory_ctx(ufbx_stream *stream, ufbx_open_file_context ctx, const void *data, size_t data_size, const ufbx_open_memory_opts *opts, ufbx_error *error)
30331 {
30332 ufbx_open_memory_opts local_opts; // ufbxi_uninit
30333 if (!opts) {
30334 memset(&local_opts, 0, sizeof(local_opts));
30335 opts = &local_opts;
30336 }
30337 ufbx_assert(opts->_begin_zero == 0 && opts->_end_zero == 0);
30338
30339 ufbxi_file_context fc; // ufbxi_uninit
30340 ufbxi_begin_file_context(&fc, ctx, &opts->allocator);
30341
30342 size_t copy_size = opts->no_copy ? 0 : data_size;
30343
30344 // Align the allocation size to 8 bytes to make sure the header is aligned.
30345 size_t self_size = ufbxi_align_to_mask(sizeof(ufbxi_memory_stream) + copy_size, 7);
30346
30347 void *memory = ufbxi_alloc(&fc.ator, char, self_size);
30348 if (!memory) {
30349 ufbxi_end_file_context(&fc, error, false);
30350 return false;
30351 }
30352
30353 ufbxi_memory_stream *mem = (ufbxi_memory_stream*)memory;
30354 memset(mem, 0, sizeof(ufbxi_memory_stream));
30355
30356 mem->size = data_size;
30357 mem->self_size = self_size;
30358 mem->close_cb = opts->close_cb;
30359
30360 if (opts->no_copy) {
30361 mem->data = data;
30362 } else {
30363 memcpy(mem->data_copy, data, data_size);
30364 mem->data = mem->data_copy;
30365 }
30366
30367 // Transplant the allocator in the result blob
30368 if (fc.parent_ator) {
30369 mem->parent_ator = fc.parent_ator;
30370 } else {
30371 fc.parent_ator = &mem->local_ator;
30372 }
30373
30374 stream->read_fn = ufbxi_memory_read;
30375 stream->skip_fn = ufbxi_memory_skip;
30376 stream->size_fn = ufbxi_memory_size;
30377 stream->close_fn = ufbxi_memory_close;
30378 stream->user = mem;
30379
30380 ufbxi_end_file_context(&fc, error, true);
30381
30382 return true;
30383 }
30384
30385 ufbx_abi bool ufbx_is_thread_safe(void)
30386 {
30387 return UFBXI_THREAD_SAFE != 0;
30388 }
30389
30390 ufbx_abi ufbx_scene *ufbx_load_memory(const void *data, size_t size, const ufbx_load_opts *opts, ufbx_error *error)
30391 {
30392 ufbxi_check_opts_ptr(ufbx_scene, opts, error);
30393 ufbxi_context uc; // ufbxi_uninit
30394 memset(&uc, 0, sizeof(ufbxi_context));
30395 uc.data_begin = uc.data = (const char *)data;
30396 uc.data_size = size;
30397 uc.progress_bytes_total = size;
30398 return ufbxi_load(&uc, opts, error);
30399 }
30400
30401 ufbx_abi ufbx_scene *ufbx_load_file(const char *filename, const ufbx_load_opts *opts, ufbx_error *error)
30402 {
30403 return ufbx_load_file_len(filename, SIZE_MAX, opts, error);
30404 }
30405
30406 ufbx_abi ufbx_scene *ufbx_load_file_len(const char *filename, size_t filename_len, const ufbx_load_opts *opts, ufbx_error *error)
30407 {
30408 ufbxi_check_opts_ptr(ufbx_scene, opts, error);
30409 ufbxi_context uc; // ufbxi_uninit
30410 memset(&uc, 0, sizeof(ufbxi_context));
30411 uc.deferred_load = true;
30412 uc.load_filename = filename;
30413 uc.load_filename_len = filename_len;
30414 return ufbxi_load(&uc, opts, error);
30415 }
30416
30417 ufbx_abi ufbx_scene *ufbx_load_stdio(void *file_void, const ufbx_load_opts *opts, ufbx_error *error)
30418 {
30419 return ufbx_load_stdio_prefix(file_void, NULL, 0, opts, error);
30420 }
30421
30422 ufbx_abi ufbx_scene *ufbx_load_stdio_prefix(void *file_void, const void *prefix, size_t prefix_size, const ufbx_load_opts *opts, ufbx_error *error)
30423 {
30424 #if !defined(UFBX_NO_STDIO)
30425 if (!file_void) return NULL;
30426 ufbx_stream stream = { 0 };
30427 ufbxi_stdio_init(&stream, file_void, false);
30428 return ufbx_load_stream_prefix(&stream, prefix, prefix_size, opts, error);
30429 #else
30430 (void)file_void;
30431 (void)prefix;
30432 (void)prefix_size;
30433 (void)opts;
30434
30435 ufbxi_context uc; // ufbxi_uninit
30436 memset(&uc, 0, sizeof(ufbxi_context));
30437 ufbxi_fmt_err_info(&uc.error, "UFBX_NO_STDIO");
30438 ufbxi_report_err_msg(&uc.error, "UFBX_NO_STDIO", "Feature disabled");
30439 uc.deferred_failure = true;
30440 return ufbxi_load(&uc, NULL, error);
30441 #endif
30442 }
30443
30444 ufbx_abi ufbx_scene *ufbx_load_stream(const ufbx_stream *stream, const ufbx_load_opts *opts, ufbx_error *error)
30445 {
30446 return ufbx_load_stream_prefix(stream, NULL, 0, opts, error);
30447 }
30448
30449 ufbx_abi ufbx_scene *ufbx_load_stream_prefix(const ufbx_stream *stream, const void *prefix, size_t prefix_size, const ufbx_load_opts *opts, ufbx_error *error)
30450 {
30451 ufbxi_check_opts_ptr(ufbx_scene, opts, error);
30452 ufbxi_context uc; // ufbxi_uninit
30453 memset(&uc, 0, sizeof(ufbxi_context));
30454 uc.data_begin = uc.data = (const char *)prefix;
30455 uc.data_size = prefix_size;
30456 uc.read_fn = stream->read_fn;
30457 uc.skip_fn = stream->skip_fn;
30458 uc.size_fn = stream->size_fn;
30459 uc.close_fn = stream->close_fn;
30460 uc.read_user = stream->user;
30461
30462 ufbx_scene *scene = ufbxi_load(&uc, opts, error);
30463 return scene;
30464 }
30465
30466 ufbx_abi void ufbx_free_scene(ufbx_scene *scene)
30467 {
30468 if (!scene) return;
30469
30470 ufbxi_scene_imp *imp = ufbxi_get_imp(ufbxi_scene_imp, scene);
30471 ufbx_assert(imp->magic == UFBXI_SCENE_IMP_MAGIC);
30472 if (imp->magic != UFBXI_SCENE_IMP_MAGIC) return;
30473 ufbxi_release_ref(&imp->refcount);
30474 }
30475
30476 ufbx_abi void ufbx_retain_scene(ufbx_scene *scene)
30477 {
30478 if (!scene) return;
30479
30480 ufbxi_scene_imp *imp = ufbxi_get_imp(ufbxi_scene_imp, scene);
30481 ufbx_assert(imp->magic == UFBXI_SCENE_IMP_MAGIC);
30482 if (imp->magic != UFBXI_SCENE_IMP_MAGIC) return;
30483 ufbxi_retain_ref(&imp->refcount);
30484 }
30485
30486 ufbx_abi ufbxi_noinline size_t ufbx_format_error(char *dst, size_t dst_size, const ufbx_error *error)
30487 {
30488 if (!dst || !dst_size) return 0;
30489 if (!error) {
30490 *dst = '\0';
30491 return 0;
30492 }
30493
30494 size_t offset = 0;
30495
30496 {
30497 int num;
30498 if (error->info_length > 0 && error->info_length < UFBX_ERROR_INFO_LENGTH) {
30499 num = ufbxi_snprintf(dst + offset, dst_size - offset, "ufbx v%u.%u.%u error: %s (%.*s)\n",
30500 UFBX_SOURCE_VERSION/1000000, UFBX_SOURCE_VERSION/1000%1000, UFBX_SOURCE_VERSION%1000,
30501 error->description.data ? error->description.data : "Unknown error",
30502 (int)error->info_length, error->info);
30503 } else {
30504 num = ufbxi_snprintf(dst + offset, dst_size - offset, "ufbx v%u.%u.%u error: %s\n",
30505 UFBX_SOURCE_VERSION/1000000, UFBX_SOURCE_VERSION/1000%1000, UFBX_SOURCE_VERSION%1000,
30506 error->description.data ? error->description.data : "Unknown error");
30507 }
30508
30509 if (num > 0) offset = ufbxi_min_sz(offset + (size_t)num, dst_size - 1);
30510 }
30511
30512 size_t stack_size = ufbxi_min_sz(error->stack_size, UFBX_ERROR_STACK_MAX_DEPTH);
30513 int line_width = 6;
30514 for (size_t i = 0; i < stack_size; i++) {
30515 const ufbx_error_frame *frame = &error->stack[i];
30516 int num = ufbxi_snprintf(dst + offset, dst_size - offset, "%*u:%s: %s\n", line_width, frame->source_line, frame->function.data, frame->description.data);
30517 if (num > 0) offset = ufbxi_min_sz(offset + (size_t)num, dst_size - 1);
30518 }
30519
30520 return offset;
30521 }
30522
30523 ufbx_abi ufbx_prop *ufbx_find_prop_len(const ufbx_props *props, const char *name, size_t name_len)
30524 {
30525 uint32_t key = ufbxi_get_name_key(name, name_len);
30526 ufbx_string name_str = ufbxi_safe_string(name, name_len);
30527
30528 while (props) {
30529 size_t index = SIZE_MAX;
30530 ufbxi_macro_lower_bound_eq(ufbx_prop, 4, &index, props->props.data, 0, props->props.count,
30531 ( ufbxi_cmp_prop_less_ref(a, name_str, key) ), ( a->_internal_key == key && ufbxi_str_equal(a->name, name_str) ));
30532 if (index != SIZE_MAX) return &props->props.data[index];
30533
30534 props = props->defaults;
30535 }
30536
30537 return NULL;
30538 }
30539
30540 ufbx_abi ufbx_real ufbx_find_real_len(const ufbx_props *props, const char *name, size_t name_len, ufbx_real def)
30541 {
30542 ufbx_prop *prop = ufbx_find_prop_len(props, name, name_len);
30543 if (prop) {
30544 return prop->value_real;
30545 } else {
30546 return def;
30547 }
30548 }
30549
30550 ufbx_abi ufbxi_noinline ufbx_vec3 ufbx_find_vec3_len(const ufbx_props *props, const char *name, size_t name_len, ufbx_vec3 def)
30551 {
30552 ufbx_prop *prop = ufbx_find_prop_len(props, name, name_len);
30553 if (prop) {
30554 return prop->value_vec3;
30555 } else {
30556 return def;
30557 }
30558 }
30559
30560 ufbx_abi ufbxi_noinline int64_t ufbx_find_int_len(const ufbx_props *props, const char *name, size_t name_len, int64_t def)
30561 {
30562 ufbx_prop *prop = ufbx_find_prop_len(props, name, name_len);
30563 if (prop) {
30564 return prop->value_int;
30565 } else {
30566 return def;
30567 }
30568 }
30569
30570 ufbx_abi bool ufbx_find_bool_len(const ufbx_props *props, const char *name, size_t name_len, bool def)
30571 {
30572 ufbx_prop *prop = ufbx_find_prop_len(props, name, name_len);
30573 if (prop) {
30574 return prop->value_int != 0;
30575 } else {
30576 return def;
30577 }
30578 }
30579
30580 ufbx_abi ufbxi_noinline ufbx_string ufbx_find_string_len(const ufbx_props *props, const char *name, size_t name_len, ufbx_string def)
30581 {
30582 ufbx_prop *prop = ufbx_find_prop_len(props, name, name_len);
30583 if (prop) {
30584 return prop->value_str;
30585 } else {
30586 return def;
30587 }
30588 }
30589
30590 ufbx_abi ufbx_blob ufbx_find_blob_len(const ufbx_props *props, const char *name, size_t name_len, ufbx_blob def)
30591 {
30592 ufbx_prop *prop = ufbx_find_prop_len(props, name, name_len);
30593 if (prop) {
30594 return prop->value_blob;
30595 } else {
30596 return def;
30597 }
30598 }
30599
30600 ufbx_abi ufbx_prop *ufbx_find_prop_concat(const ufbx_props *props, const ufbx_string *parts, size_t num_parts)
30601 {
30602 uint32_t key = ufbxi_get_concat_key(parts, num_parts);
30603
30604 while (props) {
30605 size_t index = SIZE_MAX;
30606
30607 ufbxi_macro_lower_bound_eq(ufbx_prop, 2, &index, props->props.data, 0, props->props.count,
30608 ( ufbxi_cmp_prop_less_concat(a, parts, num_parts, key) ),
30609 ( a->_internal_key == key && ufbxi_concat_str_cmp(&a->name, parts, num_parts) == 0 ));
30610 if (index != SIZE_MAX) return &props->props.data[index];
30611
30612 props = props->defaults;
30613 }
30614
30615 return NULL;
30616 }
30617
30618 ufbx_abi ufbx_element *ufbx_find_element_len(const ufbx_scene *scene, ufbx_element_type type, const char *name, size_t name_len)
30619 {
30620 if (!scene) return NULL;
30621 ufbx_string name_str = ufbxi_safe_string(name, name_len);
30622 uint32_t key = ufbxi_get_name_key(name, name_len);
30623
30624 size_t index = SIZE_MAX;
30625 ufbxi_macro_lower_bound_eq(ufbx_name_element, 16, &index, scene->elements_by_name.data, 0, scene->elements_by_name.count,
30626 ( ufbxi_cmp_name_element_less_ref(a, name_str, type, key) ), ( ufbxi_str_equal(a->name, name_str) && a->type == type ));
30627
30628 return index < SIZE_MAX ? scene->elements_by_name.data[index].element : NULL;
30629 }
30630
30631 ufbx_abi ufbx_element *ufbx_get_prop_element(const ufbx_element *element, const ufbx_prop *prop, ufbx_element_type type)
30632 {
30633 ufbx_assert(element && prop);
30634 if (!element || !prop) return NULL;
30635 return ufbxi_fetch_dst_element((ufbx_element*)element, false, prop->name.data, type);
30636 }
30637
30638 ufbx_abi ufbx_element *ufbx_find_prop_element_len(const ufbx_element *element, const char *name, size_t name_len, ufbx_element_type type)
30639 {
30640 const ufbx_prop *prop = ufbx_find_prop_len(&element->props, name, name_len);
30641 if (prop) {
30642 return ufbx_get_prop_element(element, prop, type);
30643 } else {
30644 return NULL;
30645 }
30646 }
30647
30648 ufbx_abi ufbx_node *ufbx_find_node_len(const ufbx_scene *scene, const char *name, size_t name_len)
30649 {
30650 return (ufbx_node*)ufbx_find_element_len(scene, UFBX_ELEMENT_NODE, name, name_len);
30651 }
30652
30653 ufbx_abi ufbx_anim_stack *ufbx_find_anim_stack_len(const ufbx_scene *scene, const char *name, size_t name_len)
30654 {
30655 return (ufbx_anim_stack*)ufbx_find_element_len(scene, UFBX_ELEMENT_ANIM_STACK, name, name_len);
30656 }
30657
30658 ufbx_abi ufbx_material *ufbx_find_material_len(const ufbx_scene *scene, const char *name, size_t name_len)
30659 {
30660 return (ufbx_material*)ufbx_find_element_len(scene, UFBX_ELEMENT_MATERIAL, name, name_len);
30661 }
30662
30663 ufbx_abi ufbx_anim_prop *ufbx_find_anim_prop_len(const ufbx_anim_layer *layer, const ufbx_element *element, const char *prop, size_t prop_len)
30664 {
30665 ufbx_assert(layer);
30666 ufbx_assert(element);
30667 if (!layer || !element) return NULL;
30668
30669 ufbx_string prop_str = ufbxi_safe_string(prop, prop_len);
30670
30671 size_t index = SIZE_MAX;
30672 ufbxi_macro_lower_bound_eq(ufbx_anim_prop, 16, &index, layer->anim_props.data, 0, layer->anim_props.count,
30673 ( a->element != element ? a->element < element : ufbxi_str_less(a->prop_name, prop_str) ),
30674 ( a->element == element && ufbxi_str_equal(a->prop_name, prop_str) ));
30675
30676 if (index == SIZE_MAX) return NULL;
30677 return &layer->anim_props.data[index];
30678 }
30679
30680 ufbx_abi ufbxi_noinline ufbx_anim_prop_list ufbx_find_anim_props(const ufbx_anim_layer *layer, const ufbx_element *element)
30681 {
30682 ufbx_anim_prop_list result = { 0 };
30683 ufbx_assert(layer);
30684 ufbx_assert(element);
30685 if (!layer || !element) return result;
30686
30687 size_t begin = layer->anim_props.count, end = begin;
30688 ufbxi_macro_lower_bound_eq(ufbx_anim_prop, 16, &begin, layer->anim_props.data, 0, layer->anim_props.count,
30689 ( a->element < element ), ( a->element == element ));
30690
30691 ufbxi_macro_upper_bound_eq(ufbx_anim_prop, 16, &end, layer->anim_props.data, begin, layer->anim_props.count,
30692 ( a->element == element ));
30693
30694 if (begin != end) {
30695 result.data = layer->anim_props.data + begin;
30696 result.count = end - begin;
30697 }
30698
30699 return result;
30700 }
30701
30702 ufbx_abi ufbxi_noinline ufbx_matrix ufbx_get_compatible_matrix_for_normals(const ufbx_node *node)
30703 {
30704 if (!node) return ufbx_identity_matrix;
30705
30706 ufbx_transform geom_rot = ufbx_identity_transform;
30707 geom_rot.rotation = node->geometry_transform.rotation;
30708 ufbx_matrix geom_rot_mat = ufbx_transform_to_matrix(&geom_rot);
30709
30710 ufbx_matrix norm_mat = ufbx_matrix_mul(&node->node_to_world, &geom_rot_mat);
30711 norm_mat = ufbx_matrix_for_normals(&norm_mat);
30712 return norm_mat;
30713 }
30714
30715 ufbx_abi ufbx_real ufbx_evaluate_curve(const ufbx_anim_curve *curve, double time, ufbx_real default_value)
30716 {
30717 return ufbx_evaluate_curve_flags(curve, time, default_value, 0);
30718 }
30719
30720 ufbx_abi ufbx_real ufbx_evaluate_curve_flags(const ufbx_anim_curve *curve, double time, ufbx_real default_value, uint32_t flags)
30721 {
30722 if (!curve) return default_value;
30723 if (curve->keyframes.count <= 1) {
30724 if (curve->keyframes.count == 1) {
30725 return curve->keyframes.data[0].value;
30726 } else {
30727 return default_value;
30728 }
30729 }
30730
30731 if ((flags & UFBX_EVALUATE_FLAG_NO_EXTRAPOLATION) == 0) {
30732 if (time < curve->min_time || time > curve->max_time) {
30733 return ufbxi_extrapolate_curve(curve, time, flags);
30734 }
30735 }
30736
30737 size_t begin = 0;
30738 size_t end = curve->keyframes.count;
30739 const ufbx_keyframe *keys = curve->keyframes.data;
30740 while (end - begin >= 8) {
30741 size_t mid = (begin + end) >> 1;
30742 if (keys[mid].time <= time) {
30743 begin = mid + 1;
30744 } else {
30745 end = mid;
30746 }
30747 }
30748
30749 end = curve->keyframes.count;
30750 for (; begin < end; begin++) {
30751 const ufbx_keyframe *next = &keys[begin];
30752 if (next->time <= time) continue;
30753
30754 // First keyframe
30755 if (begin == 0) return next->value;
30756
30757 const ufbx_keyframe *prev = next - 1;
30758
30759 // Exact keyframe
30760 if (prev->time == time) return prev->value;
30761
30762 double rcp_delta = 1.0 / (next->time - prev->time);
30763 double t = (time - prev->time) * rcp_delta;
30764
30765 switch (prev->interpolation) {
30766
30767 case UFBX_INTERPOLATION_CONSTANT_PREV:
30768 return prev->value;
30769
30770 case UFBX_INTERPOLATION_CONSTANT_NEXT:
30771 return next->value;
30772
30773 case UFBX_INTERPOLATION_LINEAR:
30774 return (ufbx_real)(prev->value*(1.0 - t) + next->value*t);
30775
30776 case UFBX_INTERPOLATION_CUBIC:
30777 {
30778 double x1 = prev->right.dx * rcp_delta;
30779 double x2 = 1.0 - next->left.dx * rcp_delta;
30780 t = ufbxi_find_cubic_bezier_t(x1, x2, t);
30781
30782 double t2 = t*t, t3 = t2*t;
30783 double u = 1.0 - t, u2 = u*u, u3 = u2*u;
30784
30785 double y0 = prev->value;
30786 double y3 = next->value;
30787 double y1 = y0 + prev->right.dy;
30788 double y2 = y3 - next->left.dy;
30789
30790 return (ufbx_real)(u3*y0 + 3.0 * (u2*t*y1 + u*t2*y2) + t3*y3);
30791 }
30792
30793 default:
30794 ufbxi_unreachable("Bad interpolation mode");
30795 return 0.0f;
30796
30797 }
30798 }
30799
30800 // Last keyframe
30801 return curve->keyframes.data[curve->keyframes.count - 1].value;
30802 }
30803
30804 ufbx_abi ufbxi_noinline ufbx_real ufbx_evaluate_anim_value_real(const ufbx_anim_value *anim_value, double time)
30805 {
30806 return ufbx_evaluate_anim_value_real_flags(anim_value, time, 0);
30807 }
30808
30809 ufbx_abi ufbxi_noinline ufbx_vec3 ufbx_evaluate_anim_value_vec3(const ufbx_anim_value *anim_value, double time)
30810 {
30811 return ufbx_evaluate_anim_value_vec3_flags(anim_value, time, 0);
30812 }
30813
30814 ufbx_abi ufbxi_noinline ufbx_real ufbx_evaluate_anim_value_real_flags(const ufbx_anim_value *anim_value, double time, uint32_t flags)
30815 {
30816 if (!anim_value) {
30817 return 0.0f;
30818 }
30819
30820 ufbx_real res = anim_value->default_value.x;
30821 if (anim_value->curves[0]) res = ufbx_evaluate_curve_flags(anim_value->curves[0], time, res, flags);
30822 return res;
30823 }
30824
30825 ufbx_abi ufbxi_noinline ufbx_vec3 ufbx_evaluate_anim_value_vec3_flags(const ufbx_anim_value *anim_value, double time, uint32_t flags)
30826 {
30827 if (!anim_value) {
30828 ufbx_vec3 zero = { 0.0f };
30829 return zero;
30830 }
30831
30832 ufbx_vec3 res = anim_value->default_value;
30833 if (anim_value->curves[0]) res.x = ufbx_evaluate_curve_flags(anim_value->curves[0], time, res.x, flags);
30834 if (anim_value->curves[1]) res.y = ufbx_evaluate_curve_flags(anim_value->curves[1], time, res.y, flags);
30835 if (anim_value->curves[2]) res.z = ufbx_evaluate_curve_flags(anim_value->curves[2], time, res.z, flags);
30836 return res;
30837 }
30838
30839 ufbx_abi ufbxi_noinline ufbx_prop ufbx_evaluate_prop_len(const ufbx_anim *anim, const ufbx_element *element, const char *name, size_t name_len, double time)
30840 {
30841 return ufbx_evaluate_prop_len_flags(anim, element, name, name_len, time, 0);
30842 }
30843
30844 ufbx_abi ufbxi_noinline ufbx_prop ufbx_evaluate_prop_len_flags(const ufbx_anim *anim, const ufbx_element *element, const char *name, size_t name_len, double time, uint32_t flags)
30845 {
30846 ufbx_prop result;
30847
30848 ufbx_prop *prop = ufbx_find_prop_len(&element->props, name, name_len);
30849 if (prop) {
30850 result = *prop;
30851 } else {
30852 memset(&result, 0, sizeof(result));
30853 result.name.data = name;
30854 result.name.length = name_len;
30855 result._internal_key = ufbxi_get_name_key(name, name_len);
30856 result.flags = UFBX_PROP_FLAG_NOT_FOUND;
30857 result.value_str.data = ufbxi_empty_char;
30858 result.value_str.length = 0;
30859 result.value_blob.data = NULL;
30860 result.value_blob.size = 0;
30861 }
30862
30863 if (anim->prop_overrides.count > 0) {
30864 ufbxi_find_prop_override(&anim->prop_overrides, element->element_id, &result);
30865 return result;
30866 }
30867
30868 if ((result.flags & (UFBX_PROP_FLAG_ANIMATED|UFBX_PROP_FLAG_CONNECTED)) == 0) return result;
30869
30870 if ((prop->flags & UFBX_PROP_FLAG_CONNECTED) != 0 && !anim->ignore_connections) {
30871 ufbxi_evaluate_connected_prop(&result, anim, element, prop->name.data, time, flags);
30872 }
30873
30874 ufbxi_evaluate_props(anim, element, time, &result, 1, flags);
30875
30876 return result;
30877 }
30878
30879 ufbx_abi ufbxi_noinline ufbx_props ufbx_evaluate_props(const ufbx_anim *anim, const ufbx_element *element, double time, ufbx_prop *buffer, size_t buffer_size)
30880 {
30881 return ufbx_evaluate_props_flags(anim, element, time, buffer, buffer_size, 0);
30882 }
30883
30884 ufbx_abi ufbxi_noinline ufbx_props ufbx_evaluate_props_flags(const ufbx_anim *anim, const ufbx_element *element, double time, ufbx_prop *buffer, size_t buffer_size, uint32_t flags)
30885 {
30886 ufbx_props ret = { NULL };
30887 if (!element) return ret;
30888
30889 size_t num_anim = 0;
30890 ufbxi_prop_iter iter; // ufbxi_uninit
30891 ufbxi_init_prop_iter(&iter, anim, element);
30892 const ufbx_prop *prop = NULL;
30893 while ((prop = ufbxi_next_prop(&iter)) != NULL) {
30894 if (!(prop->flags & (UFBX_PROP_FLAG_ANIMATED|UFBX_PROP_FLAG_OVERRIDDEN|UFBX_PROP_FLAG_CONNECTED))) continue;
30895 if (num_anim >= buffer_size) break;
30896
30897 ufbx_prop *dst = &buffer[num_anim++];
30898 *dst = *prop;
30899
30900 if ((prop->flags & UFBX_PROP_FLAG_CONNECTED) != 0 && !anim->ignore_connections) {
30901 ufbxi_evaluate_connected_prop(dst, anim, element, prop->name.data, time, flags);
30902 }
30903 }
30904
30905 ufbxi_evaluate_props(anim, element, time, buffer, num_anim, flags);
30906
30907 ret.props.data = buffer;
30908 ret.props.count = ret.num_animated = num_anim;
30909 ret.defaults = (ufbx_props*)&element->props;
30910 return ret;
30911 }
30912
30913 ufbx_abi ufbxi_noinline ufbx_transform ufbx_evaluate_transform(const ufbx_anim *anim, const ufbx_node *node, double time)
30914 {
30915 return ufbx_evaluate_transform_flags(anim, node, time, 0);
30916 }
30917
30918 static const char *const ufbxi_transform_props_all[] = {
30919 ufbxi_Lcl_Rotation,
30920 ufbxi_Lcl_Scaling,
30921 ufbxi_Lcl_Translation,
30922 ufbxi_PostRotation,
30923 ufbxi_PreRotation,
30924 ufbxi_RotationOffset,
30925 ufbxi_RotationOrder,
30926 ufbxi_RotationPivot,
30927 ufbxi_ScalingOffset,
30928 ufbxi_ScalingPivot,
30929 };
30930
30931 static const char *const ufbxi_transform_props_rotation[] = {
30932 ufbxi_Lcl_Rotation,
30933 ufbxi_PostRotation,
30934 ufbxi_PreRotation,
30935 ufbxi_RotationOrder,
30936 };
30937
30938 static const char *const ufbxi_transform_props_scale[] = {
30939 ufbxi_Lcl_Scaling,
30940 };
30941
30942 static const char *const ufbxi_transform_props_rotation_scale[] = {
30943 ufbxi_Lcl_Rotation,
30944 ufbxi_Lcl_Scaling,
30945 ufbxi_PostRotation,
30946 ufbxi_PreRotation,
30947 ufbxi_RotationOrder,
30948 };
30949
30950 ufbx_abi ufbxi_noinline ufbx_transform ufbx_evaluate_transform_flags(const ufbx_anim *anim, const ufbx_node *node, double time, uint32_t flags)
30951 {
30952 ufbx_assert(anim);
30953 ufbx_assert(node);
30954 if (!node) return ufbx_identity_transform;
30955 if (!anim) return node->local_transform;
30956 if (node->is_root) return node->local_transform;
30957
30958 if ((flags & UFBX_TRANSFORM_FLAG_EXPLICIT_INCLUDES) == 0) {
30959 flags |= UFBX_TRANSFORM_FLAG_INCLUDE_ROTATION|UFBX_TRANSFORM_FLAG_INCLUDE_SCALE|UFBX_TRANSFORM_FLAG_INCLUDE_TRANSLATION;
30960 }
30961
30962 const char *const *prop_names = ufbxi_transform_props_all;
30963 size_t num_prop_names = ufbxi_arraycount(ufbxi_transform_props_all);
30964 uint32_t components = flags & (UFBX_TRANSFORM_FLAG_INCLUDE_ROTATION|UFBX_TRANSFORM_FLAG_INCLUDE_SCALE|UFBX_TRANSFORM_FLAG_INCLUDE_TRANSLATION);
30965 if (components == (UFBX_TRANSFORM_FLAG_INCLUDE_ROTATION|UFBX_TRANSFORM_FLAG_INCLUDE_SCALE)) {
30966 prop_names = ufbxi_transform_props_rotation_scale;
30967 num_prop_names = ufbxi_arraycount(ufbxi_transform_props_rotation_scale);
30968 } else if (components == UFBX_TRANSFORM_FLAG_INCLUDE_ROTATION) {
30969 prop_names = ufbxi_transform_props_rotation;
30970 num_prop_names = ufbxi_arraycount(ufbxi_transform_props_rotation);
30971 } else if (components == UFBX_TRANSFORM_FLAG_INCLUDE_SCALE) {
30972 prop_names = ufbxi_transform_props_scale;
30973 num_prop_names = ufbxi_arraycount(ufbxi_transform_props_scale);
30974 } else if (components == 0) {
30975 return ufbx_identity_transform;
30976 }
30977
30978 const ufbx_vec3 *translation_scale = NULL;
30979 ufbx_prop helper_scale; // ufbxi_uninit
30980 ufbx_vec3 scale_factor = ufbxi_one_vec3;
30981 bool use_scale_factor = false;
30982
30983 if (node->parent && (flags & (UFBX_TRANSFORM_FLAG_INCLUDE_SCALE|UFBX_TRANSFORM_FLAG_INCLUDE_TRANSLATION)) != 0) {
30984 ufbx_node *parent = node->parent;
30985
30986 if ((flags & UFBX_TRANSFORM_FLAG_IGNORE_COMPONENTWISE_SCALE) == 0 && parent->inherit_scale_node) {
30987 ufbx_node *p = parent->inherit_scale_node;
30988
30989 if (node->is_scale_helper) {
30990 use_scale_factor = true;
30991 }
30992
30993 while (p && p->scale_helper) {
30994 ufbx_prop scale = ufbx_evaluate_prop(anim, &p->scale_helper->element, ufbxi_Lcl_Scaling, time);
30995 scale_factor.x *= scale.value_vec3.x;
30996 scale_factor.y *= scale.value_vec3.y;
30997 scale_factor.z *= scale.value_vec3.z;
30998 p = p->inherit_scale_node;
30999 }
31000 }
31001
31002 if (parent->scale_helper && (flags & UFBX_TRANSFORM_FLAG_IGNORE_SCALE_HELPER) == 0) {
31003 helper_scale = ufbx_evaluate_prop(anim, &parent->scale_helper->element, ufbxi_Lcl_Scaling, time);
31004 if (helper_scale.flags & UFBX_PROP_FLAG_NOT_FOUND) {
31005 helper_scale.value_vec3.x = 1.0f;
31006 helper_scale.value_vec3.y = 1.0f;
31007 helper_scale.value_vec3.z = 1.0f;
31008 }
31009 helper_scale.value_vec3.x *= scale_factor.x;
31010 helper_scale.value_vec3.y *= scale_factor.y;
31011 helper_scale.value_vec3.z *= scale_factor.z;
31012 translation_scale = &helper_scale.value_vec3;
31013 }
31014 }
31015
31016 uint32_t eval_flags = 0;
31017 if (flags & UFBX_TRANSFORM_FLAG_NO_EXTRAPOLATION) {
31018 eval_flags |= UFBX_EVALUATE_FLAG_NO_EXTRAPOLATION;
31019 }
31020
31021 ufbx_prop buf[ufbxi_arraycount(ufbxi_transform_props_all)]; // ufbxi_uninit
31022 ufbx_props props = ufbxi_evaluate_selected_props(anim, &node->element, time, buf, prop_names, num_prop_names, eval_flags);
31023 ufbx_rotation_order order = (ufbx_rotation_order)ufbxi_find_enum(&props, ufbxi_RotationOrder, UFBX_ROTATION_ORDER_XYZ, UFBX_ROTATION_ORDER_SPHERIC);
31024
31025 ufbx_transform transform; // ufbxi_uninit
31026 if ((components & UFBX_TRANSFORM_FLAG_INCLUDE_TRANSLATION) != 0) {
31027 transform = ufbxi_get_transform(&props, order, node, translation_scale);
31028 } else {
31029 transform.translation = ufbx_zero_vec3;
31030 if ((components & UFBX_TRANSFORM_FLAG_INCLUDE_ROTATION) != 0) {
31031 transform.rotation = ufbxi_get_rotation(&props, order, node);
31032 } else {
31033 transform.rotation = ufbx_identity_quat;
31034 }
31035 if ((components & UFBX_TRANSFORM_FLAG_INCLUDE_SCALE) != 0) {
31036 transform.scale = ufbxi_get_scale(&props, node);
31037 } else {
31038 transform.scale = ufbxi_one_vec3;
31039 }
31040 }
31041
31042 if (use_scale_factor) {
31043 transform.scale.x *= scale_factor.x;
31044 transform.scale.y *= scale_factor.y;
31045 transform.scale.z *= scale_factor.z;
31046 }
31047 return transform;
31048 }
31049
31050 ufbx_abi ufbx_real ufbx_evaluate_blend_weight(const ufbx_anim *anim, const ufbx_blend_channel *channel, double time)
31051 {
31052 return ufbx_evaluate_blend_weight_flags(anim, channel, time, 0);
31053 }
31054
31055 ufbx_abi ufbx_real ufbx_evaluate_blend_weight_flags(const ufbx_anim *anim, const ufbx_blend_channel *channel, double time, uint32_t flags)
31056 {
31057 const char *prop_names[] = {
31058 ufbxi_DeformPercent,
31059 };
31060
31061 ufbx_prop buf[ufbxi_arraycount(prop_names)]; // ufbxi_uninit
31062 ufbx_props props = ufbxi_evaluate_selected_props(anim, &channel->element, time, buf, prop_names, ufbxi_arraycount(prop_names), flags);
31063 return ufbxi_find_real(&props, ufbxi_DeformPercent, channel->weight * (ufbx_real)100.0) * (ufbx_real)0.01;
31064 }
31065
31066 ufbx_abi ufbx_scene *ufbx_evaluate_scene(const ufbx_scene *scene, const ufbx_anim *anim, double time, const ufbx_evaluate_opts *opts, ufbx_error *error)
31067 {
31068 ufbxi_check_opts_ptr(ufbx_scene, opts, error);
31069 #if UFBXI_FEATURE_SCENE_EVALUATION
31070 ufbxi_eval_context ec = { 0 };
31071 return ufbxi_evaluate_scene(&ec, (ufbx_scene*)scene, anim, time, opts, error);
31072 #else
31073 if (error) {
31074 memset(error, 0, sizeof(ufbx_error));
31075 ufbxi_fmt_err_info(error, "UFBX_ENABLE_SCENE_EVALUATION");
31076 ufbxi_report_err_msg(error, "UFBXI_FEATURE_SCENE_EVALUATION", "Feature disabled");
31077 }
31078 return NULL;
31079 #endif
31080 }
31081
31082 ufbx_abi ufbx_anim *ufbx_create_anim(const ufbx_scene *scene, const ufbx_anim_opts *opts, ufbx_error *error)
31083 {
31084 ufbxi_check_opts_ptr(ufbx_anim, opts, error);
31085 ufbx_assert(scene);
31086
31087 ufbxi_create_anim_context ac = { UFBX_ERROR_NONE };
31088 if (opts) {
31089 ac.opts = *opts;
31090 }
31091
31092 ac.scene = scene;
31093
31094 int ok = ufbxi_create_anim_imp(&ac);
31095
31096 if (ok) {
31097 ufbxi_clear_error(error);
31098 ufbxi_anim_imp *imp = ac.imp;
31099 return &imp->anim;
31100 } else {
31101 ufbxi_fix_error_type(&ac.error, "Failed to create anim", error);
31102 ufbxi_buf_free(&ac.result);
31103 ufbxi_free_ator(&ac.ator_result);
31104 return NULL;
31105 }
31106 }
31107
31108 ufbx_abi void ufbx_free_anim(ufbx_anim *anim)
31109 {
31110 if (!anim) return;
31111 if (!anim->custom) return;
31112
31113 ufbxi_anim_imp *imp = ufbxi_get_imp(ufbxi_anim_imp, anim);
31114 ufbx_assert(imp->magic == UFBXI_ANIM_IMP_MAGIC);
31115 if (imp->magic != UFBXI_ANIM_IMP_MAGIC) return;
31116 ufbxi_release_ref(&imp->refcount);
31117 }
31118
31119 ufbx_abi void ufbx_retain_anim(ufbx_anim *anim)
31120 {
31121 if (!anim) return;
31122 if (!anim->custom) return;
31123
31124 ufbxi_anim_imp *imp = ufbxi_get_imp(ufbxi_anim_imp, anim);
31125 ufbx_assert(imp->magic == UFBXI_ANIM_IMP_MAGIC);
31126 if (imp->magic != UFBXI_ANIM_IMP_MAGIC) return;
31127 ufbxi_retain_ref(&imp->refcount);
31128 }
31129
31130 ufbx_abi ufbx_baked_anim *ufbx_bake_anim(const ufbx_scene *scene, const ufbx_anim *anim, const ufbx_bake_opts *opts, ufbx_error *error)
31131 {
31132 ufbx_assert(scene);
31133 #if UFBXI_FEATURE_ANIMATION_BAKING
31134 ufbxi_check_opts_ptr(ufbx_baked_anim, opts, error);
31135 if (!anim) {
31136 anim = scene->anim;
31137 }
31138
31139 ufbxi_bake_context bc = { UFBX_ERROR_NONE };
31140 if (opts) {
31141 bc.opts = *opts;
31142 }
31143
31144 bc.scene = scene;
31145
31146 int ok = ufbxi_bake_anim_imp(&bc, anim);
31147
31148 ufbxi_buf_free(&bc.tmp);
31149 ufbxi_buf_free(&bc.tmp_prop);
31150 ufbxi_buf_free(&bc.tmp_times);
31151 ufbxi_buf_free(&bc.tmp_bake_props);
31152 ufbxi_buf_free(&bc.tmp_nodes);
31153 ufbxi_buf_free(&bc.tmp_elements);
31154 ufbxi_buf_free(&bc.tmp_props);
31155 ufbxi_buf_free(&bc.tmp_bake_stack);
31156 ufbxi_free(&bc.ator_tmp, char, bc.tmp_arr, bc.tmp_arr_size);
31157 ufbxi_free_ator(&bc.ator_tmp);
31158
31159 if (ok) {
31160 ufbxi_clear_error(error);
31161 ufbxi_baked_anim_imp *imp = bc.imp;
31162 return &imp->bake;
31163 } else {
31164 ufbxi_fix_error_type(&bc.error, "Failed to bake anim", error);
31165 ufbxi_buf_free(&bc.result);
31166 ufbxi_free_ator(&bc.ator_result);
31167 return NULL;
31168 }
31169 #else
31170 if (error) {
31171 memset(error, 0, sizeof(ufbx_error));
31172 ufbxi_fmt_err_info(error, "UFBX_ENABLE_ANIMATION_BAKING");
31173 ufbxi_report_err_msg(error, "UFBXI_FEATURE_ANIMATION_BAKING", "Feature disabled");
31174 }
31175 return NULL;
31176 #endif
31177 }
31178
31179 ufbx_abi void ufbx_retain_baked_anim(ufbx_baked_anim *bake)
31180 {
31181 if (!bake) return;
31182
31183 ufbxi_baked_anim_imp *imp = ufbxi_get_imp(ufbxi_baked_anim_imp, bake);
31184 ufbx_assert(imp->magic == UFBXI_BAKED_ANIM_IMP_MAGIC);
31185 if (imp->magic != UFBXI_BAKED_ANIM_IMP_MAGIC) return;
31186 ufbxi_retain_ref(&imp->refcount);
31187 }
31188
31189 ufbx_abi void ufbx_free_baked_anim(ufbx_baked_anim *bake)
31190 {
31191 if (!bake) return;
31192
31193 ufbxi_baked_anim_imp *imp = ufbxi_get_imp(ufbxi_baked_anim_imp, bake);
31194 ufbx_assert(imp->magic == UFBXI_BAKED_ANIM_IMP_MAGIC);
31195 if (imp->magic != UFBXI_BAKED_ANIM_IMP_MAGIC) return;
31196 ufbxi_release_ref(&imp->refcount);
31197 }
31198
31199
31200 ufbx_abi ufbx_baked_node *ufbx_find_baked_node_by_typed_id(ufbx_baked_anim *bake, uint32_t typed_id)
31201 {
31202 size_t index = SIZE_MAX;
31203 ufbxi_macro_lower_bound_eq(ufbx_baked_node, 8, &index, bake->nodes.data, 0, bake->nodes.count,
31204 ( a->typed_id < typed_id ), ( a->typed_id == typed_id) );
31205 return index < SIZE_MAX ? &bake->nodes.data[index] : NULL;
31206 }
31207
31208 ufbx_abi ufbx_baked_node *ufbx_find_baked_node(ufbx_baked_anim *bake, ufbx_node *node)
31209 {
31210 if (!bake || !node) return NULL;
31211 return ufbx_find_baked_node_by_typed_id(bake, node->typed_id);
31212 }
31213
31214 ufbx_abi ufbx_baked_element *ufbx_find_baked_element_by_element_id(ufbx_baked_anim *bake, uint32_t element_id)
31215 {
31216 size_t index = SIZE_MAX;
31217 ufbxi_macro_lower_bound_eq(ufbx_baked_element, 8, &index, bake->elements.data, 0, bake->elements.count,
31218 ( a->element_id < element_id ), ( a->element_id == element_id) );
31219 return index < SIZE_MAX ? &bake->elements.data[index] : NULL;
31220 }
31221
31222 ufbx_abi ufbx_baked_element *ufbx_find_baked_element(ufbx_baked_anim *bake, ufbx_element *element)
31223 {
31224 if (!bake || !element) return NULL;
31225 return ufbx_find_baked_element_by_element_id(bake, element->element_id);
31226 }
31227
31228 ufbx_abi ufbx_vec3 ufbx_evaluate_baked_vec3(ufbx_baked_vec3_list keyframes, double time)
31229 {
31230 size_t begin = 0;
31231 size_t end = keyframes.count;
31232 const ufbx_baked_vec3 *keys = keyframes.data;
31233 while (end - begin >= 8) {
31234 size_t mid = (begin + end) >> 1;
31235 if (keys[mid].time <= time) {
31236 begin = mid + 1;
31237 } else {
31238 end = mid;
31239 }
31240 }
31241
31242 end = keyframes.count;
31243 for (; begin < end; begin++) {
31244 const ufbx_baked_vec3 *next = &keys[begin];
31245 if (next->time <= time) continue;
31246 if (begin == 0) return next->value;
31247
31248 const ufbx_baked_vec3 *prev = next - 1;
31249 if (prev > keys && (prev->flags & UFBX_BAKED_KEY_STEP_RIGHT) != 0 && prev[-1].time == time) prev--;
31250 if (time == prev->time) return prev->value;
31251 double t = (time - prev->time) / (next->time - prev->time);
31252 if (prev->flags & UFBX_BAKED_KEY_STEP_LEFT) t = 0.0;
31253 if (next->flags & UFBX_BAKED_KEY_STEP_RIGHT) t = 1.0;
31254 return ufbxi_lerp3(prev->value, next->value, (ufbx_real)t);
31255 }
31256
31257 return keyframes.data[keyframes.count - 1].value;
31258 }
31259
31260 ufbx_abi ufbx_quat ufbx_evaluate_baked_quat(ufbx_baked_quat_list keyframes, double time)
31261 {
31262 size_t begin = 0;
31263 size_t end = keyframes.count;
31264 const ufbx_baked_quat *keys = keyframes.data;
31265 while (end - begin >= 8) {
31266 size_t mid = (begin + end) >> 1;
31267 if (keys[mid].time <= time) {
31268 begin = mid + 1;
31269 } else {
31270 end = mid;
31271 }
31272 }
31273
31274 end = keyframes.count;
31275 for (; begin < end; begin++) {
31276 const ufbx_baked_quat *next = &keys[begin];
31277 if (next->time <= time) continue;
31278 if (begin == 0) return next->value;
31279
31280 const ufbx_baked_quat *prev = next - 1;
31281 if (prev > keys && prev[-1].time == time) prev--;
31282 if (time == prev->time) return prev->value;
31283 double t = (time - prev->time) / (next->time - prev->time);
31284 if (prev > keys && (prev->flags & UFBX_BAKED_KEY_STEP_RIGHT) != 0 && prev[-1].time == time) prev--;
31285 if (prev->flags & UFBX_BAKED_KEY_STEP_LEFT) t = 0.0;
31286 if (next->flags & UFBX_BAKED_KEY_STEP_RIGHT) t = 1.0;
31287 return ufbx_quat_slerp(prev->value, next->value, (ufbx_real)t);
31288 }
31289
31290 return keyframes.data[keyframes.count - 1].value;
31291 }
31292
31293 ufbx_abi ufbx_bone_pose *ufbx_get_bone_pose(const ufbx_pose *pose, const ufbx_node *node)
31294 {
31295 if (!pose || !node) return NULL;
31296 size_t index = SIZE_MAX;
31297 ufbxi_macro_lower_bound_eq(ufbx_bone_pose, 8, &index, pose->bone_poses.data, 0, pose->bone_poses.count,
31298 ( a->bone_node->typed_id < node->typed_id ), ( a->bone_node == node ));
31299 return index < SIZE_MAX ? &pose->bone_poses.data[index] : NULL;
31300 }
31301
31302 ufbx_abi ufbx_texture *ufbx_find_prop_texture_len(const ufbx_material *material, const char *name, size_t name_len)
31303 {
31304 ufbx_string name_str = ufbxi_safe_string(name, name_len);
31305 if (!material) return NULL;
31306
31307 size_t index = SIZE_MAX;
31308 ufbxi_macro_lower_bound_eq(ufbx_material_texture, 4, &index, material->textures.data, 0, material->textures.count,
31309 ( ufbxi_str_less(a->material_prop, name_str) ), ( ufbxi_str_equal(a->material_prop, name_str) ));
31310 return index < SIZE_MAX ? material->textures.data[index].texture : NULL;
31311 }
31312
31313 ufbx_abi ufbx_string ufbx_find_shader_prop_len(const ufbx_shader *shader, const char *name, size_t name_len)
31314 {
31315 ufbx_shader_prop_binding_list bindings = ufbx_find_shader_prop_bindings_len(shader, name, name_len);
31316 if (bindings.count > 0) {
31317 return bindings.data[0].material_prop;
31318 }
31319 return ufbx_empty_string;
31320 }
31321
31322 ufbx_abi ufbx_shader_prop_binding_list ufbx_find_shader_prop_bindings_len(const ufbx_shader *shader, const char *name, size_t name_len)
31323 {
31324 ufbx_shader_prop_binding_list bindings = { NULL, 0 };
31325
31326 ufbx_string name_str = ufbxi_safe_string(name, name_len);
31327 if (!shader) return bindings;
31328
31329 ufbxi_for_ptr_list(ufbx_shader_binding, p_bind, shader->bindings) {
31330 ufbx_shader_binding *bind = *p_bind;
31331
31332 size_t begin = SIZE_MAX;
31333 ufbxi_macro_lower_bound_eq(ufbx_shader_prop_binding, 4, &begin, bind->prop_bindings.data, 0, bind->prop_bindings.count,
31334 ( ufbxi_str_less(a->shader_prop, name_str) ), ( ufbxi_str_equal(a->shader_prop, name_str) ));
31335
31336 if (begin != SIZE_MAX) {
31337
31338 size_t end = begin;
31339 ufbxi_macro_upper_bound_eq(ufbx_shader_prop_binding, 4, &end, bind->prop_bindings.data, begin, bind->prop_bindings.count,
31340 ( ufbxi_str_equal(a->shader_prop, name_str) ));
31341
31342 bindings.data = bind->prop_bindings.data + begin;
31343 bindings.count = end - begin;
31344 break;
31345 }
31346 }
31347
31348 return bindings;
31349 }
31350
31351 ufbx_abi ufbx_shader_texture_input *ufbx_find_shader_texture_input_len(const ufbx_shader_texture *shader, const char *name, size_t name_len)
31352 {
31353 ufbx_string name_str = ufbxi_safe_string(name, name_len);
31354
31355 size_t index = SIZE_MAX;
31356 ufbxi_macro_lower_bound_eq(ufbx_shader_texture_input, 4, &index, shader->inputs.data, 0, shader->inputs.count,
31357 ( ufbxi_str_less(a->name, name_str) ), ( ufbxi_str_equal(a->name, name_str) ));
31358
31359 if (index != SIZE_MAX) {
31360 return &shader->inputs.data[index];
31361 }
31362
31363 return NULL;
31364 }
31365
31366 ufbx_abi bool ufbx_coordinate_axes_valid(ufbx_coordinate_axes axes)
31367 {
31368 if (axes.right < UFBX_COORDINATE_AXIS_POSITIVE_X || axes.right > UFBX_COORDINATE_AXIS_NEGATIVE_Z) return false;
31369 if (axes.up < UFBX_COORDINATE_AXIS_POSITIVE_X || axes.up > UFBX_COORDINATE_AXIS_NEGATIVE_Z) return false;
31370 if (axes.front < UFBX_COORDINATE_AXIS_POSITIVE_X || axes.front > UFBX_COORDINATE_AXIS_NEGATIVE_Z) return false;
31371
31372 // Check that all the positive/negative axes are used
31373 uint32_t mask = 0;
31374 mask |= 1u << ((uint32_t)axes.right >> 1);
31375 mask |= 1u << ((uint32_t)axes.up >> 1);
31376 mask |= 1u << ((uint32_t)axes.front >> 1);
31377 return (mask & 0x7u) == 0x7u;
31378 }
31379
31380 ufbx_abi ufbx_quat ufbx_quat_mul(ufbx_quat a, ufbx_quat b)
31381 {
31382 return ufbxi_mul_quat(a, b);
31383 }
31384
31385 ufbx_abi ufbx_vec3 ufbx_vec3_normalize(ufbx_vec3 v)
31386 {
31387 return ufbxi_normalize3(v);
31388 }
31389
31390 ufbx_abi ufbxi_noinline ufbx_real ufbx_quat_dot(ufbx_quat a, ufbx_quat b)
31391 {
31392 return a.x*b.x + a.y*b.y + a.z*b.z + a.w*b.w;
31393 }
31394
31395 ufbx_abi ufbxi_noinline ufbx_quat ufbx_quat_normalize(ufbx_quat q)
31396 {
31397 ufbx_real norm = ufbx_quat_dot(q, q);
31398 if (norm == 0.0) return ufbx_identity_quat;
31399 norm = (ufbx_real)ufbx_sqrt(norm);
31400 q.x /= norm;
31401 q.y /= norm;
31402 q.z /= norm;
31403 q.w /= norm;
31404 return q;
31405 }
31406
31407 ufbx_abi ufbxi_noinline ufbx_quat ufbx_quat_fix_antipodal(ufbx_quat q, ufbx_quat reference)
31408 {
31409 if (ufbx_quat_dot(q, reference) < 0.0f) {
31410 q.x = -q.x; q.y = -q.y; q.z = -q.z; q.w = -q.w;
31411 }
31412 return q;
31413 }
31414
31415 ufbx_abi ufbxi_noinline ufbx_quat ufbx_quat_slerp(ufbx_quat a, ufbx_quat b, ufbx_real t)
31416 {
31417 double dot = a.x*b.x + a.y*b.y + a.z*b.z + a.w*b.w;
31418 if (dot < 0.0) {
31419 dot = -dot;
31420 b.x = -b.x; b.y = -b.y; b.z = -b.z; b.w = -b.w;
31421 }
31422 double omega = ufbx_acos(ufbx_fmin(ufbx_fmax(dot, 0.0), 1.0));
31423 if (omega <= 1.175494351e-38f) return a;
31424 double rcp_so = 1.0 / ufbx_sin(omega);
31425 double af = ufbx_sin((1.0 - t) * omega) * rcp_so;
31426 double bf = ufbx_sin(t * omega) * rcp_so;
31427
31428 double x = af*a.x + bf*b.x;
31429 double y = af*a.y + bf*b.y;
31430 double z = af*a.z + bf*b.z;
31431 double w = af*a.w + bf*b.w;
31432 double rcp_len = 1.0 / ufbx_sqrt(x*x + y*y + z*z + w*w);
31433
31434 ufbx_quat ret;
31435 ret.x = (ufbx_real)(x * rcp_len);
31436 ret.y = (ufbx_real)(y * rcp_len);
31437 ret.z = (ufbx_real)(z * rcp_len);
31438 ret.w = (ufbx_real)(w * rcp_len);
31439 return ret;
31440 }
31441
31442 ufbx_abi ufbxi_noinline ufbx_vec3 ufbx_quat_rotate_vec3(ufbx_quat q, ufbx_vec3 v)
31443 {
31444 ufbx_real xy = q.x*v.y - q.y*v.x;
31445 ufbx_real xz = q.x*v.z - q.z*v.x;
31446 ufbx_real yz = q.y*v.z - q.z*v.y;
31447 ufbx_vec3 r;
31448 r.x = 2.0f * (+ q.w*yz + q.y*xy + q.z*xz) + v.x;
31449 r.y = 2.0f * (- q.x*xy - q.w*xz + q.z*yz) + v.y;
31450 r.z = 2.0f * (- q.x*xz - q.y*yz + q.w*xy) + v.z;
31451 return r;
31452 }
31453
31454 ufbx_abi ufbxi_noinline ufbx_quat ufbx_euler_to_quat(ufbx_vec3 v, ufbx_rotation_order order)
31455 {
31456 double vx = v.x * (UFBXI_DEG_TO_RAD_DOUBLE * 0.5);
31457 double vy = v.y * (UFBXI_DEG_TO_RAD_DOUBLE * 0.5);
31458 double vz = v.z * (UFBXI_DEG_TO_RAD_DOUBLE * 0.5);
31459 double cx = ufbx_cos(vx), sx = ufbx_sin(vx);
31460 double cy = ufbx_cos(vy), sy = ufbx_sin(vy);
31461 double cz = ufbx_cos(vz), sz = ufbx_sin(vz);
31462 ufbx_quat q;
31463
31464 // Generated by `misc/gen_rotation_order.py`
31465 switch (order) {
31466 case UFBX_ROTATION_ORDER_XYZ:
31467 q.x = (ufbx_real)(-cx*sy*sz + cy*cz*sx);
31468 q.y = (ufbx_real)(cx*cz*sy + cy*sx*sz);
31469 q.z = (ufbx_real)(cx*cy*sz - cz*sx*sy);
31470 q.w = (ufbx_real)(cx*cy*cz + sx*sy*sz);
31471 break;
31472 case UFBX_ROTATION_ORDER_XZY:
31473 q.x = (ufbx_real)(cx*sy*sz + cy*cz*sx);
31474 q.y = (ufbx_real)(cx*cz*sy + cy*sx*sz);
31475 q.z = (ufbx_real)(cx*cy*sz - cz*sx*sy);
31476 q.w = (ufbx_real)(cx*cy*cz - sx*sy*sz);
31477 break;
31478 case UFBX_ROTATION_ORDER_YZX:
31479 q.x = (ufbx_real)(-cx*sy*sz + cy*cz*sx);
31480 q.y = (ufbx_real)(cx*cz*sy - cy*sx*sz);
31481 q.z = (ufbx_real)(cx*cy*sz + cz*sx*sy);
31482 q.w = (ufbx_real)(cx*cy*cz + sx*sy*sz);
31483 break;
31484 case UFBX_ROTATION_ORDER_YXZ:
31485 q.x = (ufbx_real)(-cx*sy*sz + cy*cz*sx);
31486 q.y = (ufbx_real)(cx*cz*sy + cy*sx*sz);
31487 q.z = (ufbx_real)(cx*cy*sz + cz*sx*sy);
31488 q.w = (ufbx_real)(cx*cy*cz - sx*sy*sz);
31489 break;
31490 case UFBX_ROTATION_ORDER_ZXY:
31491 q.x = (ufbx_real)(cx*sy*sz + cy*cz*sx);
31492 q.y = (ufbx_real)(cx*cz*sy - cy*sx*sz);
31493 q.z = (ufbx_real)(cx*cy*sz - cz*sx*sy);
31494 q.w = (ufbx_real)(cx*cy*cz + sx*sy*sz);
31495 break;
31496 case UFBX_ROTATION_ORDER_ZYX:
31497 q.x = (ufbx_real)(cx*sy*sz + cy*cz*sx);
31498 q.y = (ufbx_real)(cx*cz*sy - cy*sx*sz);
31499 q.z = (ufbx_real)(cx*cy*sz + cz*sx*sy);
31500 q.w = (ufbx_real)(cx*cy*cz - sx*sy*sz);
31501 break;
31502 default:
31503 q.x = q.y = q.z = 0.0f; q.w = 1.0f;
31504 break;
31505 }
31506
31507 return q;
31508 }
31509
31510 ufbx_abi ufbxi_noinline ufbx_vec3 ufbx_quat_to_euler(ufbx_quat q, ufbx_rotation_order order)
31511 {
31512 // TODO: Derive these rigorously
31513 #if defined(UFBX_REAL_IS_FLOAT)
31514 const double eps = 0.9999999;
31515 #else
31516 const double eps = 0.999999999;
31517 #endif
31518
31519 double vx, vy, vz;
31520 double t;
31521
31522 double qx = q.x, qy = q.y, qz = q.z, qw = q.w;
31523
31524 // Generated by `misc/gen_quat_to_euler.py`
31525 switch (order) {
31526 case UFBX_ROTATION_ORDER_XYZ:
31527 t = 2.0f*(qw*qy - qx*qz);
31528 if (ufbx_fabs(t) < eps) {
31529 vy = ufbx_asin(t);
31530 vz = ufbx_atan2(2.0f*(qw*qz + qx*qy), 2.0f*(qw*qw + qx*qx) - 1.0f);
31531 vx = -ufbx_atan2(-2.0f*(qw*qx + qy*qz), 2.0f*(qw*qw + qz*qz) - 1.0f);
31532 } else {
31533 vy = ufbx_copysign(UFBXI_DPI*0.5, t);
31534 vz = ufbx_atan2(-2.0f*t*(qw*qx - qy*qz), t*(2.0f*qw*qy + 2.0f*qx*qz));
31535 vx = 0.0f;
31536 }
31537 break;
31538 case UFBX_ROTATION_ORDER_XZY:
31539 t = 2.0f*(qw*qz + qx*qy);
31540 if (ufbx_fabs(t) < eps) {
31541 vz = ufbx_asin(t);
31542 vy = ufbx_atan2(2.0f*(qw*qy - qx*qz), 2.0f*(qw*qw + qx*qx) - 1.0f);
31543 vx = -ufbx_atan2(-2.0f*(qw*qx - qy*qz), 2.0f*(qw*qw + qy*qy) - 1.0f);
31544 } else {
31545 vz = ufbx_copysign(UFBXI_DPI*0.5, t);
31546 vy = ufbx_atan2(2.0f*t*(qw*qx + qy*qz), -t*(2.0f*qx*qy - 2.0f*qw*qz));
31547 vx = 0.0f;
31548 }
31549 break;
31550 case UFBX_ROTATION_ORDER_YZX:
31551 t = 2.0f*(qw*qz - qx*qy);
31552 if (ufbx_fabs(t) < eps) {
31553 vz = ufbx_asin(t);
31554 vx = ufbx_atan2(2.0f*(qw*qx + qy*qz), 2.0f*(qw*qw + qy*qy) - 1.0f);
31555 vy = -ufbx_atan2(-2.0f*(qw*qy + qx*qz), 2.0f*(qw*qw + qx*qx) - 1.0f);
31556 } else {
31557 vz = ufbx_copysign(UFBXI_DPI*0.5, t);
31558 vx = ufbx_atan2(-2.0f*t*(qw*qy - qx*qz), t*(2.0f*qw*qz + 2.0f*qx*qy));
31559 vy = 0.0f;
31560 }
31561 break;
31562 case UFBX_ROTATION_ORDER_YXZ:
31563 t = 2.0f*(qw*qx + qy*qz);
31564 if (ufbx_fabs(t) < eps) {
31565 vx = ufbx_asin(t);
31566 vz = ufbx_atan2(2.0f*(qw*qz - qx*qy), 2.0f*(qw*qw + qy*qy) - 1.0f);
31567 vy = -ufbx_atan2(-2.0f*(qw*qy - qx*qz), 2.0f*(qw*qw + qz*qz) - 1.0f);
31568 } else {
31569 vx = ufbx_copysign(UFBXI_DPI*0.5, t);
31570 vz = ufbx_atan2(2.0f*t*(qw*qy + qx*qz), -t*(2.0f*qy*qz - 2.0f*qw*qx));
31571 vy = 0.0f;
31572 }
31573 break;
31574 case UFBX_ROTATION_ORDER_ZXY:
31575 t = 2.0f*(qw*qx - qy*qz);
31576 if (ufbx_fabs(t) < eps) {
31577 vx = ufbx_asin(t);
31578 vy = ufbx_atan2(2.0f*(qw*qy + qx*qz), 2.0f*(qw*qw + qz*qz) - 1.0f);
31579 vz = -ufbx_atan2(-2.0f*(qw*qz + qx*qy), 2.0f*(qw*qw + qy*qy) - 1.0f);
31580 } else {
31581 vx = ufbx_copysign(UFBXI_DPI*0.5, t);
31582 vy = ufbx_atan2(-2.0f*t*(qw*qz - qx*qy), t*(2.0f*qw*qx + 2.0f*qy*qz));
31583 vz = 0.0f;
31584 }
31585 break;
31586 case UFBX_ROTATION_ORDER_ZYX:
31587 t = 2.0f*(qw*qy + qx*qz);
31588 if (ufbx_fabs(t) < eps) {
31589 vy = ufbx_asin(t);
31590 vx = ufbx_atan2(2.0f*(qw*qx - qy*qz), 2.0f*(qw*qw + qz*qz) - 1.0f);
31591 vz = -ufbx_atan2(-2.0f*(qw*qz - qx*qy), 2.0f*(qw*qw + qx*qx) - 1.0f);
31592 } else {
31593 vy = ufbx_copysign(UFBXI_DPI*0.5, t);
31594 vx = ufbx_atan2(2.0f*t*(qw*qz + qx*qy), -t*(2.0f*qx*qz - 2.0f*qw*qy));
31595 vz = 0.0f;
31596 }
31597 break;
31598 default:
31599 vx = vy = vz = 0.0;
31600 break;
31601 }
31602
31603 vx *= UFBXI_RAD_TO_DEG_DOUBLE;
31604 vy *= UFBXI_RAD_TO_DEG_DOUBLE;
31605 vz *= UFBXI_RAD_TO_DEG_DOUBLE;
31606
31607 ufbx_vec3 v = { (ufbx_real)vx, (ufbx_real)vy, (ufbx_real)vz };
31608 return v;
31609 }
31610
31611 ufbx_abi ufbxi_noinline ufbx_matrix ufbx_matrix_mul(const ufbx_matrix *a, const ufbx_matrix *b)
31612 {
31613 ufbx_assert(a && b);
31614 if (!a || !b) return ufbx_identity_matrix;
31615
31616 ufbx_matrix dst;
31617
31618 dst.m03 = a->m00*b->m03 + a->m01*b->m13 + a->m02*b->m23 + a->m03;
31619 dst.m13 = a->m10*b->m03 + a->m11*b->m13 + a->m12*b->m23 + a->m13;
31620 dst.m23 = a->m20*b->m03 + a->m21*b->m13 + a->m22*b->m23 + a->m23;
31621
31622 dst.m00 = a->m00*b->m00 + a->m01*b->m10 + a->m02*b->m20;
31623 dst.m10 = a->m10*b->m00 + a->m11*b->m10 + a->m12*b->m20;
31624 dst.m20 = a->m20*b->m00 + a->m21*b->m10 + a->m22*b->m20;
31625
31626 dst.m01 = a->m00*b->m01 + a->m01*b->m11 + a->m02*b->m21;
31627 dst.m11 = a->m10*b->m01 + a->m11*b->m11 + a->m12*b->m21;
31628 dst.m21 = a->m20*b->m01 + a->m21*b->m11 + a->m22*b->m21;
31629
31630 dst.m02 = a->m00*b->m02 + a->m01*b->m12 + a->m02*b->m22;
31631 dst.m12 = a->m10*b->m02 + a->m11*b->m12 + a->m12*b->m22;
31632 dst.m22 = a->m20*b->m02 + a->m21*b->m12 + a->m22*b->m22;
31633
31634 return dst;
31635 }
31636
31637 ufbx_abi ufbx_real ufbx_matrix_determinant(const ufbx_matrix *m)
31638 {
31639 return
31640 - m->m02*m->m11*m->m20 + m->m01*m->m12*m->m20 + m->m02*m->m10*m->m21
31641 - m->m00*m->m12*m->m21 - m->m01*m->m10*m->m22 + m->m00*m->m11*m->m22;
31642 }
31643
31644 ufbx_abi ufbx_matrix ufbx_matrix_invert(const ufbx_matrix *m)
31645 {
31646 ufbx_real det = ufbx_matrix_determinant(m);
31647
31648 ufbx_matrix r;
31649 if (ufbx_fabs(det) <= UFBX_EPSILON) {
31650 memset(&r, 0, sizeof(r));
31651 return r;
31652 }
31653
31654 ufbx_real rcp_det = 1.0f / det;
31655
31656 r.m00 = ( - m->m12*m->m21 + m->m11*m->m22) * rcp_det;
31657 r.m10 = ( + m->m12*m->m20 - m->m10*m->m22) * rcp_det;
31658 r.m20 = ( - m->m11*m->m20 + m->m10*m->m21) * rcp_det;
31659 r.m01 = ( + m->m02*m->m21 - m->m01*m->m22) * rcp_det;
31660 r.m11 = ( - m->m02*m->m20 + m->m00*m->m22) * rcp_det;
31661 r.m21 = ( + m->m01*m->m20 - m->m00*m->m21) * rcp_det;
31662 r.m02 = ( - m->m02*m->m11 + m->m01*m->m12) * rcp_det;
31663 r.m12 = ( + m->m02*m->m10 - m->m00*m->m12) * rcp_det;
31664 r.m22 = ( - m->m01*m->m10 + m->m00*m->m11) * rcp_det;
31665 r.m03 = (m->m03*m->m12*m->m21 - m->m02*m->m13*m->m21 - m->m03*m->m11*m->m22 + m->m01*m->m13*m->m22 + m->m02*m->m11*m->m23 - m->m01*m->m12*m->m23) * rcp_det;
31666 r.m13 = (m->m02*m->m13*m->m20 - m->m03*m->m12*m->m20 + m->m03*m->m10*m->m22 - m->m00*m->m13*m->m22 - m->m02*m->m10*m->m23 + m->m00*m->m12*m->m23) * rcp_det;
31667 r.m23 = (m->m03*m->m11*m->m20 - m->m01*m->m13*m->m20 - m->m03*m->m10*m->m21 + m->m00*m->m13*m->m21 + m->m01*m->m10*m->m23 - m->m00*m->m11*m->m23) * rcp_det;
31668
31669 return r;
31670 }
31671
31672 ufbx_abi ufbxi_noinline ufbx_matrix ufbx_matrix_for_normals(const ufbx_matrix *m)
31673 {
31674 ufbx_real det = ufbx_matrix_determinant(m);
31675 ufbx_real det_sign = det >= 0.0f ? 1.0f : -1.0f;
31676
31677 ufbx_matrix r;
31678 r.m00 = ( - m->m12*m->m21 + m->m11*m->m22) * det_sign;
31679 r.m01 = ( + m->m12*m->m20 - m->m10*m->m22) * det_sign;
31680 r.m02 = ( - m->m11*m->m20 + m->m10*m->m21) * det_sign;
31681 r.m10 = ( + m->m02*m->m21 - m->m01*m->m22) * det_sign;
31682 r.m11 = ( - m->m02*m->m20 + m->m00*m->m22) * det_sign;
31683 r.m12 = ( + m->m01*m->m20 - m->m00*m->m21) * det_sign;
31684 r.m20 = ( - m->m02*m->m11 + m->m01*m->m12) * det_sign;
31685 r.m21 = ( + m->m02*m->m10 - m->m00*m->m12) * det_sign;
31686 r.m22 = ( - m->m01*m->m10 + m->m00*m->m11) * det_sign;
31687 r.m03 = r.m13 = r.m23 = 0.0f;
31688
31689 return r;
31690 }
31691
31692 ufbx_abi ufbxi_noinline ufbx_vec3 ufbx_transform_position(const ufbx_matrix *m, ufbx_vec3 v)
31693 {
31694 ufbx_assert(m);
31695 if (!m) return ufbx_zero_vec3;
31696
31697 ufbx_vec3 r;
31698 r.x = m->m00*v.x + m->m01*v.y + m->m02*v.z + m->m03;
31699 r.y = m->m10*v.x + m->m11*v.y + m->m12*v.z + m->m13;
31700 r.z = m->m20*v.x + m->m21*v.y + m->m22*v.z + m->m23;
31701 return r;
31702 }
31703
31704 ufbx_abi ufbxi_noinline ufbx_vec3 ufbx_transform_direction(const ufbx_matrix *m, ufbx_vec3 v)
31705 {
31706 ufbx_assert(m);
31707 if (!m) return ufbx_zero_vec3;
31708
31709 ufbx_vec3 r;
31710 r.x = m->m00*v.x + m->m01*v.y + m->m02*v.z;
31711 r.y = m->m10*v.x + m->m11*v.y + m->m12*v.z;
31712 r.z = m->m20*v.x + m->m21*v.y + m->m22*v.z;
31713 return r;
31714 }
31715
31716 ufbx_abi ufbxi_noinline ufbx_matrix ufbx_transform_to_matrix(const ufbx_transform *t)
31717 {
31718 ufbx_assert(t);
31719 if (!t) return ufbx_identity_matrix;
31720
31721 ufbx_quat q = t->rotation;
31722 ufbx_real sx = 2.0f * t->scale.x, sy = 2.0f * t->scale.y, sz = 2.0f * t->scale.z;
31723 ufbx_real xx = q.x*q.x, xy = q.x*q.y, xz = q.x*q.z, xw = q.x*q.w;
31724 ufbx_real yy = q.y*q.y, yz = q.y*q.z, yw = q.y*q.w;
31725 ufbx_real zz = q.z*q.z, zw = q.z*q.w;
31726 ufbx_matrix m;
31727 m.m00 = sx * (- yy - zz + 0.5f);
31728 m.m10 = sx * (+ xy + zw);
31729 m.m20 = sx * (- yw + xz);
31730 m.m01 = sy * (- zw + xy);
31731 m.m11 = sy * (- xx - zz + 0.5f);
31732 m.m21 = sy * (+ xw + yz);
31733 m.m02 = sz * (+ xz + yw);
31734 m.m12 = sz * (- xw + yz);
31735 m.m22 = sz * (- xx - yy + 0.5f);
31736 m.m03 = t->translation.x;
31737 m.m13 = t->translation.y;
31738 m.m23 = t->translation.z;
31739 return m;
31740 }
31741
31742 ufbx_abi ufbxi_noinline ufbx_transform ufbx_matrix_to_transform(const ufbx_matrix *m)
31743 {
31744 ufbx_assert(m);
31745 if (!m) return ufbx_identity_transform;
31746
31747 ufbx_real det = ufbx_matrix_determinant(m);
31748
31749 ufbx_transform t;
31750 t.translation = m->cols[3];
31751 t.scale.x = ufbxi_length3(m->cols[0]);
31752 t.scale.y = ufbxi_length3(m->cols[1]);
31753 t.scale.z = ufbxi_length3(m->cols[2]);
31754
31755 // Flip a single non-zero axis if negative determinant
31756 ufbx_real sign_x = 1.0f;
31757 ufbx_real sign_y = 1.0f;
31758 ufbx_real sign_z = 1.0f;
31759 if (det < 0.0f) {
31760 if (t.scale.x > 0.0f) sign_x = -1.0f;
31761 else if (t.scale.y > 0.0f) sign_y = -1.0f;
31762 else if (t.scale.z > 0.0f) sign_z = -1.0f;
31763 }
31764
31765 ufbx_vec3 x = ufbxi_mul3(m->cols[0], t.scale.x > 0.0f ? sign_x / t.scale.x : 0.0f);
31766 ufbx_vec3 y = ufbxi_mul3(m->cols[1], t.scale.y > 0.0f ? sign_y / t.scale.y : 0.0f);
31767 ufbx_vec3 z = ufbxi_mul3(m->cols[2], t.scale.z > 0.0f ? sign_z / t.scale.z : 0.0f);
31768 ufbx_real trace = x.x + y.y + z.z;
31769 if (trace > 0.0f) {
31770 ufbx_real a = (ufbx_real)ufbx_sqrt(ufbx_fmax(0.0, trace + 1.0)), b = (a != 0.0f) ? 0.5f / a : 0.0f;
31771 t.rotation.x = (y.z - z.y) * b;
31772 t.rotation.y = (z.x - x.z) * b;
31773 t.rotation.z = (x.y - y.x) * b;
31774 t.rotation.w = 0.5f * a;
31775 } else if (x.x > y.y && x.x > z.z) {
31776 ufbx_real a = (ufbx_real)ufbx_sqrt(ufbx_fmax(0.0, 1.0 + x.x - y.y - z.z)), b = (a != 0.0f) ? 0.5f / a : 0.0f;
31777 t.rotation.x = 0.5f * a;
31778 t.rotation.y = (y.x + x.y) * b;
31779 t.rotation.z = (z.x + x.z) * b;
31780 t.rotation.w = (y.z - z.y) * b;
31781 }
31782 else if (y.y > z.z) {
31783 ufbx_real a = (ufbx_real)ufbx_sqrt(ufbx_fmax(0.0, 1.0 - x.x + y.y - z.z)), b = (a != 0.0f) ? 0.5f / a : 0.0f;
31784 t.rotation.x = (y.x + x.y) * b;
31785 t.rotation.y = 0.5f * a;
31786 t.rotation.z = (z.y + y.z) * b;
31787 t.rotation.w = (z.x - x.z) * b;
31788 }
31789 else {
31790 ufbx_real a = (ufbx_real)ufbx_sqrt(ufbx_fmax(0.0, 1.0 - x.x - y.y + z.z)), b = (a != 0.0f) ? 0.5f / a : 0.0f;
31791 t.rotation.x = (z.x + x.z) * b;
31792 t.rotation.y = (z.y + y.z) * b;
31793 t.rotation.z = 0.5f * a;
31794 t.rotation.w = (x.y - y.x) * b;
31795 }
31796
31797 ufbx_real len = t.rotation.x*t.rotation.x + t.rotation.y*t.rotation.y + t.rotation.z*t.rotation.z + t.rotation.w*t.rotation.w;
31798 if (ufbx_fabs(len - 1.0f) > UFBX_EPSILON) {
31799 if (ufbx_fabs(len) <= UFBX_EPSILON) {
31800 t.rotation = ufbx_identity_quat;
31801 } else {
31802 t.rotation.x /= len;
31803 t.rotation.y /= len;
31804 t.rotation.z /= len;
31805 t.rotation.w /= len;
31806 }
31807 }
31808
31809 t.scale.x *= sign_x;
31810 t.scale.y *= sign_y;
31811 t.scale.z *= sign_z;
31812
31813 return t;
31814 }
31815
31816 ufbx_abi ufbxi_noinline ufbx_matrix ufbx_catch_get_skin_vertex_matrix(ufbx_panic *panic, const ufbx_skin_deformer *skin, size_t vertex, const ufbx_matrix *fallback)
31817 {
31818 ufbx_assert(skin);
31819 if (ufbxi_panicf(panic, vertex < skin->vertices.count, "vertex (%zu) out of bounds (%zu)", vertex, skin->vertices.count)) return ufbx_identity_matrix;
31820
31821 if (!skin || vertex >= skin->vertices.count) return ufbx_identity_matrix;
31822 ufbx_skin_vertex skin_vertex = skin->vertices.data[vertex];
31823
31824 ufbx_matrix mat = { 0.0f };
31825 ufbx_quat q0 = { 0.0f }, qe = { 0.0f };
31826 ufbx_quat first_q0 = { 0.0f };
31827 ufbx_vec3 qs = { 0.0f, 0.0f, 0.0f };
31828 ufbx_real total_weight = 0.0f;
31829
31830 for (uint32_t i = 0; i < skin_vertex.num_weights; i++) {
31831 ufbx_skin_weight weight = skin->weights.data[skin_vertex.weight_begin + i];
31832 ufbx_skin_cluster *cluster = skin->clusters.data[weight.cluster_index];
31833 const ufbx_node *node = cluster->bone_node;
31834 if (!node) continue;
31835
31836 total_weight += weight.weight;
31837 if (skin_vertex.dq_weight > 0.0f) {
31838 ufbx_transform t = cluster->geometry_to_world_transform;
31839 ufbx_quat vq0 = t.rotation;
31840 if (i == 0) first_q0 = vq0;
31841
31842 if (ufbx_quat_dot(first_q0, vq0) < 0.0f) {
31843 vq0.x = -vq0.x;
31844 vq0.y = -vq0.y;
31845 vq0.z = -vq0.z;
31846 vq0.w = -vq0.w;
31847 }
31848
31849 ufbx_quat vqt = { 0.5f * t.translation.x, 0.5f * t.translation.y, 0.5f * t.translation.z };
31850 ufbx_quat vqe = ufbxi_mul_quat(vqt, vq0);
31851 ufbxi_add_weighted_quat(&q0, vq0, weight.weight);
31852 ufbxi_add_weighted_quat(&qe, vqe, weight.weight);
31853 ufbxi_add_weighted_vec3(&qs, t.scale, weight.weight);
31854 }
31855
31856 if (skin_vertex.dq_weight < 1.0f) {
31857 ufbxi_add_weighted_mat(&mat, &cluster->geometry_to_world, (1.0f-skin_vertex.dq_weight) * weight.weight);
31858 }
31859 }
31860
31861 if (total_weight <= 0.0f) {
31862 if (fallback) {
31863 return *fallback;
31864 } else {
31865 return ufbx_identity_matrix;
31866 }
31867 }
31868
31869 if (ufbx_fabs(total_weight - 1.0f) > UFBX_EPSILON) {
31870 ufbx_real rcp_weight = ufbx_fabs(total_weight) > UFBX_EPSILON ? 1.0f / total_weight : 0.0f;
31871 if (skin_vertex.dq_weight > 0.0f) {
31872 q0.x *= rcp_weight; q0.y *= rcp_weight; q0.z *= rcp_weight; q0.w *= rcp_weight;
31873 qe.x *= rcp_weight; qe.y *= rcp_weight; qe.z *= rcp_weight; qe.w *= rcp_weight;
31874 qs.x *= rcp_weight; qs.y *= rcp_weight; qs.z *= rcp_weight;
31875 }
31876 if (skin_vertex.dq_weight < 1.0f) {
31877 mat.m00 *= rcp_weight; mat.m01 *= rcp_weight; mat.m02 *= rcp_weight; mat.m03 *= rcp_weight;
31878 mat.m10 *= rcp_weight; mat.m11 *= rcp_weight; mat.m12 *= rcp_weight; mat.m13 *= rcp_weight;
31879 mat.m20 *= rcp_weight; mat.m21 *= rcp_weight; mat.m22 *= rcp_weight; mat.m23 *= rcp_weight;
31880 }
31881 }
31882
31883 if (skin_vertex.dq_weight > 0.0f) {
31884 ufbx_transform dqt; // ufbxi_uninit
31885 ufbx_real rcp_len = (ufbx_real)(1.0 / ufbx_sqrt(q0.x*q0.x + q0.y*q0.y + q0.z*q0.z + q0.w*q0.w));
31886 ufbx_real rcp_len2x2 = 2.0f * rcp_len * rcp_len;
31887 dqt.rotation.x = q0.x * rcp_len;
31888 dqt.rotation.y = q0.y * rcp_len;
31889 dqt.rotation.z = q0.z * rcp_len;
31890 dqt.rotation.w = q0.w * rcp_len;
31891 dqt.scale.x = qs.x;
31892 dqt.scale.y = qs.y;
31893 dqt.scale.z = qs.z;
31894 dqt.translation.x = rcp_len2x2 * (- qe.w*q0.x + qe.x*q0.w - qe.y*q0.z + qe.z*q0.y);
31895 dqt.translation.y = rcp_len2x2 * (- qe.w*q0.y + qe.x*q0.z + qe.y*q0.w - qe.z*q0.x);
31896 dqt.translation.z = rcp_len2x2 * (- qe.w*q0.z - qe.x*q0.y + qe.y*q0.x + qe.z*q0.w);
31897 ufbx_matrix dqm = ufbx_transform_to_matrix(&dqt);
31898 if (skin_vertex.dq_weight < 1.0f) {
31899 ufbxi_add_weighted_mat(&mat, &dqm, skin_vertex.dq_weight);
31900 } else {
31901 mat = dqm;
31902 }
31903 }
31904
31905 return mat;
31906 }
31907
31908 ufbx_abi ufbxi_noinline uint32_t ufbx_get_blend_shape_offset_index(const ufbx_blend_shape *shape, size_t vertex)
31909 {
31910 ufbx_assert(shape);
31911 if (!shape) return UFBX_NO_INDEX;
31912
31913 size_t index = SIZE_MAX;
31914 uint32_t vertex_ix = (uint32_t)vertex;
31915
31916 ufbxi_macro_lower_bound_eq(uint32_t, 16, &index, shape->offset_vertices.data, 0, shape->num_offsets,
31917 ( *a < vertex_ix ), ( *a == vertex_ix ));
31918 if (index >= UINT32_MAX) return UFBX_NO_INDEX;
31919
31920 return (uint32_t)index;
31921 }
31922
31923 ufbx_abi ufbxi_noinline ufbx_vec3 ufbx_get_blend_shape_vertex_offset(const ufbx_blend_shape *shape, size_t vertex)
31924 {
31925 uint32_t index = ufbx_get_blend_shape_offset_index(shape, vertex);
31926 if (index == UFBX_NO_INDEX) return ufbx_zero_vec3;
31927 return shape->position_offsets.data[index];
31928 }
31929
31930 ufbx_abi ufbxi_noinline ufbx_vec3 ufbx_get_blend_vertex_offset(const ufbx_blend_deformer *blend, size_t vertex)
31931 {
31932 ufbx_assert(blend);
31933 if (!blend) return ufbx_zero_vec3;
31934
31935 ufbx_vec3 offset = ufbx_zero_vec3;
31936
31937 ufbxi_for_ptr_list(ufbx_blend_channel, p_chan, blend->channels) {
31938 ufbx_blend_channel *chan = *p_chan;
31939 ufbxi_for_list(ufbx_blend_keyframe, key, chan->keyframes) {
31940 if (key->effective_weight == 0.0f) continue;
31941
31942 ufbx_vec3 key_offset = ufbx_get_blend_shape_vertex_offset(key->shape, vertex);
31943 ufbxi_add_weighted_vec3(&offset, key_offset, key->effective_weight);
31944 }
31945 }
31946
31947 return offset;
31948 }
31949
31950 ufbx_abi void ufbx_add_blend_shape_vertex_offsets(const ufbx_blend_shape *shape, ufbx_vec3 *vertices, size_t num_vertices, ufbx_real weight)
31951 {
31952 if (weight == 0.0f) return;
31953 if (!vertices) return;
31954
31955 size_t num_offsets = shape->num_offsets;
31956 uint32_t *vertex_indices = shape->offset_vertices.data;
31957 ufbx_vec3 *offsets = shape->position_offsets.data;
31958 ufbx_real_list weights = shape->offset_weights;
31959 for (size_t i = 0; i < num_offsets; i++) {
31960 uint32_t index = vertex_indices[i];
31961 if (index < num_vertices) {
31962 ufbx_real vertex_weight = weight;
31963 if (i < weights.count) {
31964 vertex_weight *= weights.data[i];
31965 }
31966 ufbxi_add_weighted_vec3(&vertices[index], offsets[i], vertex_weight);
31967 }
31968 }
31969 }
31970
31971 ufbx_abi void ufbx_add_blend_vertex_offsets(const ufbx_blend_deformer *blend, ufbx_vec3 *vertices, size_t num_vertices, ufbx_real weight)
31972 {
31973 ufbx_assert(blend);
31974 if (!blend) return;
31975
31976 ufbxi_for_ptr_list(ufbx_blend_channel, p_chan, blend->channels) {
31977 ufbx_blend_channel *chan = *p_chan;
31978 ufbxi_for_list(ufbx_blend_keyframe, key, chan->keyframes) {
31979 if (key->effective_weight == 0.0f) continue;
31980 ufbx_add_blend_shape_vertex_offsets(key->shape, vertices, num_vertices, weight * key->effective_weight);
31981 }
31982 }
31983 }
31984
31985 ufbx_abi size_t ufbx_evaluate_nurbs_basis(const ufbx_nurbs_basis *basis, ufbx_real u, ufbx_real *weights, size_t num_weights, ufbx_real *derivatives, size_t num_derivatives)
31986 {
31987 ufbx_assert(basis);
31988 if (!basis) return SIZE_MAX;
31989 if (basis->order == 0) return SIZE_MAX;
31990 if (!basis->valid) return SIZE_MAX;
31991
31992 size_t degree = basis->order - 1;
31993 ufbx_assert(degree >= 1);
31994
31995 // Binary search for the knot span `[min_u, max_u]` where `min_u <= u < max_u`
31996 ufbx_real_list knots = basis->knot_vector;
31997 size_t knot = SIZE_MAX;
31998
31999 if (u <= basis->t_min) {
32000 knot = degree;
32001 u = basis->t_min;
32002 } else if (u >= basis->t_max) {
32003 knot = basis->knot_vector.count - degree - 2;
32004 u = basis->t_max;
32005 } else {
32006 ufbxi_macro_lower_bound_eq(ufbx_real, 8, &knot, knots.data, 0, knots.count - 1,
32007 ( a[1] <= u ), ( a[0] <= u && u < a[1] ));
32008 }
32009
32010 // The found effective control points are found left from `knot`, locally
32011 // we use `knot - ix` here as it's more convenient for the following algorithm
32012 // but we return it as `knot - degree` so that users can find the control points
32013 // at `points[knot], points[knot+1], ..., points[knot+degree]`
32014 if (knot < degree) return SIZE_MAX;
32015
32016 if (num_derivatives == 0) derivatives = NULL;
32017 if (num_weights < basis->order) return knot - degree;
32018 if (!weights) return knot - degree;
32019
32020 weights[0] = 1.0f;
32021 for (size_t p = 1; p <= degree; p++) {
32022
32023 ufbx_real prev = 0.0f;
32024 ufbx_real g = 1.0f - ufbxi_nurbs_weight(&knots, knot - p + 1, p, u);
32025 ufbx_real dg = 0.0f;
32026 if (derivatives && p == degree) {
32027 dg = ufbxi_nurbs_deriv(&knots, knot - p + 1, p);
32028 }
32029
32030 for (size_t i = p; i > 0; i--) {
32031 ufbx_real f = ufbxi_nurbs_weight(&knots, knot - p + i, p, u);
32032 ufbx_real weight = weights[i - 1];
32033 weights[i] = f*weight + g*prev;
32034
32035 if (derivatives && p == degree) {
32036 ufbx_real df = ufbxi_nurbs_deriv(&knots, knot - p + i, p);
32037 if (i < num_derivatives) {
32038 derivatives[i] = df*weight - dg*prev;
32039 }
32040 dg = df;
32041 }
32042
32043 prev = weight;
32044 g = 1.0f - f;
32045 }
32046
32047 weights[0] = g*prev;
32048 if (derivatives && p == degree) {
32049 derivatives[0] = -dg*prev;
32050 }
32051 }
32052
32053 return knot - degree;
32054 }
32055
32056 ufbx_abi ufbxi_noinline ufbx_curve_point ufbx_evaluate_nurbs_curve(const ufbx_nurbs_curve *curve, ufbx_real u)
32057 {
32058 ufbx_curve_point result = { false };
32059
32060 ufbx_assert(curve);
32061 if (!curve) return result;
32062
32063 ufbx_real weights[UFBXI_MAX_NURBS_ORDER]; // ufbxi_uninit
32064 ufbx_real derivs[UFBXI_MAX_NURBS_ORDER]; // ufbxi_uninit
32065 size_t base = ufbx_evaluate_nurbs_basis(&curve->basis, u, weights, UFBXI_MAX_NURBS_ORDER, derivs, UFBXI_MAX_NURBS_ORDER);
32066 if (base == SIZE_MAX) return result;
32067
32068 ufbx_vec4 p = { 0 };
32069 ufbx_vec4 d = { 0 };
32070
32071 size_t order = curve->basis.order;
32072 if (order > UFBXI_MAX_NURBS_ORDER) return result;
32073 if (curve->control_points.count == 0) return result;
32074
32075 for (size_t i = 0; i < order; i++) {
32076 size_t ix = (base + i) % curve->control_points.count;
32077 ufbx_vec4 cp = curve->control_points.data[ix];
32078 ufbx_real weight = weights[i] * cp.w, deriv = derivs[i] * cp.w;
32079
32080 p.x += cp.x * weight;
32081 p.y += cp.y * weight;
32082 p.z += cp.z * weight;
32083 p.w += weight;
32084
32085 d.x += cp.x * deriv;
32086 d.y += cp.y * deriv;
32087 d.z += cp.z * deriv;
32088 d.w += deriv;
32089 }
32090
32091 ufbx_real rcp_w = 1.0f / p.w;
32092 result.valid = true;
32093 result.position.x = p.x * rcp_w;
32094 result.position.y = p.y * rcp_w;
32095 result.position.z = p.z * rcp_w;
32096 result.derivative.x = (d.x - d.w*result.position.x) * rcp_w;
32097 result.derivative.y = (d.y - d.w*result.position.y) * rcp_w;
32098 result.derivative.z = (d.z - d.w*result.position.z) * rcp_w;
32099 return result;
32100 }
32101
32102 ufbx_abi ufbxi_noinline ufbx_surface_point ufbx_evaluate_nurbs_surface(const ufbx_nurbs_surface *surface, ufbx_real u, ufbx_real v)
32103 {
32104 ufbx_surface_point result = { false };
32105
32106 ufbx_assert(surface);
32107 if (!surface) return result;
32108
32109 ufbx_real weights_u[UFBXI_MAX_NURBS_ORDER], weights_v[UFBXI_MAX_NURBS_ORDER]; // ufbxi_uninit
32110 ufbx_real derivs_u[UFBXI_MAX_NURBS_ORDER], derivs_v[UFBXI_MAX_NURBS_ORDER]; // ufbxi_uninit
32111 size_t base_u = ufbx_evaluate_nurbs_basis(&surface->basis_u, u, weights_u, UFBXI_MAX_NURBS_ORDER, derivs_u, UFBXI_MAX_NURBS_ORDER);
32112 size_t base_v = ufbx_evaluate_nurbs_basis(&surface->basis_v, v, weights_v, UFBXI_MAX_NURBS_ORDER, derivs_v, UFBXI_MAX_NURBS_ORDER);
32113 if (base_u == SIZE_MAX || base_v == SIZE_MAX) return result;
32114
32115 ufbx_vec4 p = { 0 };
32116 ufbx_vec4 du = { 0 };
32117 ufbx_vec4 dv = { 0 };
32118
32119 size_t num_u = surface->num_control_points_u;
32120 size_t num_v = surface->num_control_points_v;
32121 size_t order_u = surface->basis_u.order;
32122 size_t order_v = surface->basis_v.order;
32123 if (order_u > UFBXI_MAX_NURBS_ORDER || order_v > UFBXI_MAX_NURBS_ORDER) return result;
32124 if (num_u == 0 || num_v == 0) return result;
32125
32126 for (size_t vi = 0; vi < order_v; vi++) {
32127 size_t vix = (base_v + vi) % num_v;
32128 ufbx_real weight_v = weights_v[vi], deriv_v = derivs_v[vi];
32129
32130 for (size_t ui = 0; ui < order_u; ui++) {
32131 size_t uix = (base_u + ui) % num_u;
32132 ufbx_real weight_u = weights_u[ui], deriv_u = derivs_u[ui];
32133 ufbx_vec4 cp = surface->control_points.data[vix * num_u + uix];
32134
32135 ufbx_real weight = weight_u * weight_v * cp.w;
32136 ufbx_real wderiv_u = deriv_u * weight_v * cp.w;
32137 ufbx_real wderiv_v = deriv_v * weight_u * cp.w;
32138
32139 p.x += cp.x * weight;
32140 p.y += cp.y * weight;
32141 p.z += cp.z * weight;
32142 p.w += weight;
32143
32144 du.x += cp.x * wderiv_u;
32145 du.y += cp.y * wderiv_u;
32146 du.z += cp.z * wderiv_u;
32147 du.w += wderiv_u;
32148
32149 dv.x += cp.x * wderiv_v;
32150 dv.y += cp.y * wderiv_v;
32151 dv.z += cp.z * wderiv_v;
32152 dv.w += wderiv_v;
32153 }
32154 }
32155
32156 ufbx_real rcp_w = 1.0f / p.w;
32157 result.valid = true;
32158 result.position.x = p.x * rcp_w;
32159 result.position.y = p.y * rcp_w;
32160 result.position.z = p.z * rcp_w;
32161 result.derivative_u.x = (du.x - du.w*result.position.x) * rcp_w;
32162 result.derivative_u.y = (du.y - du.w*result.position.y) * rcp_w;
32163 result.derivative_u.z = (du.z - du.w*result.position.z) * rcp_w;
32164 result.derivative_v.x = (dv.x - dv.w*result.position.x) * rcp_w;
32165 result.derivative_v.y = (dv.y - dv.w*result.position.y) * rcp_w;
32166 result.derivative_v.z = (dv.z - dv.w*result.position.z) * rcp_w;
32167 return result;
32168 }
32169
32170 ufbx_abi ufbx_line_curve *ufbx_tessellate_nurbs_curve(const ufbx_nurbs_curve *curve, const ufbx_tessellate_curve_opts *opts, ufbx_error *error)
32171 {
32172 #if UFBXI_FEATURE_TESSELLATION
32173 ufbxi_check_opts_ptr(ufbx_line_curve, opts, error);
32174 ufbx_assert(curve);
32175 if (!curve) return NULL;
32176
32177 ufbxi_tessellate_curve_context tc = { UFBX_ERROR_NONE };
32178 if (opts) {
32179 tc.opts = *opts;
32180 }
32181
32182 tc.curve = curve;
32183
32184 int ok = ufbxi_tessellate_nurbs_curve_imp(&tc);
32185
32186 ufbxi_free_ator(&tc.ator_tmp);
32187
32188 if (ok) {
32189 ufbxi_clear_error(error);
32190 ufbxi_line_curve_imp *imp = tc.imp;
32191 return &imp->curve;
32192 } else {
32193 ufbxi_fix_error_type(&tc.error, "Failed to tessellate", error);
32194 ufbxi_buf_free(&tc.result);
32195 ufbxi_free_ator(&tc.ator_result);
32196 return NULL;
32197 }
32198 #else
32199 if (error) {
32200 memset(error, 0, sizeof(ufbx_error));
32201 ufbxi_fmt_err_info(error, "UFBX_ENABLE_TESSELLATION");
32202 ufbxi_report_err_msg(error, "UFBXI_FEATURE_TESSELLATION", "Feature disabled");
32203 }
32204 return NULL;
32205 #endif
32206 }
32207
32208 ufbx_abi ufbx_mesh *ufbx_tessellate_nurbs_surface(const ufbx_nurbs_surface *surface, const ufbx_tessellate_surface_opts *opts, ufbx_error *error)
32209 {
32210 #if UFBXI_FEATURE_TESSELLATION
32211 ufbx_assert(surface);
32212 ufbxi_check_opts_ptr(ufbx_mesh, opts, error);
32213 if (!surface) return NULL;
32214
32215 ufbxi_tessellate_surface_context tc = { UFBX_ERROR_NONE };
32216 if (opts) {
32217 tc.opts = *opts;
32218 }
32219
32220 tc.surface = surface;
32221
32222 int ok = ufbxi_tessellate_nurbs_surface_imp(&tc);
32223
32224 ufbxi_buf_free(&tc.tmp);
32225 ufbxi_map_free(&tc.position_map);
32226 ufbxi_free_ator(&tc.ator_tmp);
32227
32228 if (ok) {
32229 ufbxi_clear_error(error);
32230 ufbxi_mesh_imp *imp = tc.imp;
32231 return &imp->mesh;
32232 } else {
32233 ufbxi_fix_error_type(&tc.error, "Failed to tessellate", error);
32234 ufbxi_buf_free(&tc.result);
32235 ufbxi_free_ator(&tc.ator_result);
32236 return NULL;
32237 }
32238 #else
32239 if (error) {
32240 memset(error, 0, sizeof(ufbx_error));
32241 ufbxi_report_err_msg(error, "UFBXI_FEATURE_TESSELLATION", "Feature disabled");
32242 }
32243 return NULL;
32244 #endif
32245 }
32246
32247 ufbx_abi void ufbx_free_line_curve(ufbx_line_curve *line_curve)
32248 {
32249 if (!line_curve) return;
32250 if (!line_curve->from_tessellated_nurbs) return;
32251
32252 ufbxi_line_curve_imp *imp = ufbxi_get_imp(ufbxi_line_curve_imp, line_curve);
32253 ufbx_assert(imp->magic == UFBXI_LINE_CURVE_IMP_MAGIC);
32254 if (imp->magic != UFBXI_LINE_CURVE_IMP_MAGIC) return;
32255 ufbxi_release_ref(&imp->refcount);
32256 }
32257
32258 ufbx_abi void ufbx_retain_line_curve(ufbx_line_curve *line_curve)
32259 {
32260 if (!line_curve) return;
32261 if (!line_curve->from_tessellated_nurbs) return;
32262
32263 ufbxi_line_curve_imp *imp = ufbxi_get_imp(ufbxi_line_curve_imp, line_curve);
32264 ufbx_assert(imp->magic == UFBXI_LINE_CURVE_IMP_MAGIC);
32265 if (imp->magic != UFBXI_LINE_CURVE_IMP_MAGIC) return;
32266 ufbxi_retain_ref(&imp->refcount);
32267 }
32268
32269 ufbx_abi uint32_t ufbx_find_face_index(ufbx_mesh *mesh, size_t index)
32270 {
32271 if (!mesh || index > UINT32_MAX) return UFBX_NO_INDEX;
32272 uint32_t ix = (uint32_t)index;
32273
32274 size_t face_ix = SIZE_MAX;
32275 ufbxi_macro_lower_bound_eq(ufbx_face, 4, &face_ix, mesh->faces.data, 0, mesh->faces.count,
32276 ( a->index_begin + a->num_indices <= ix ), ( ix >= a->index_begin && ix < a->index_begin + a->num_indices ));
32277 return (uint32_t)face_ix;
32278 }
32279
32280 ufbx_abi ufbxi_noinline uint32_t ufbx_catch_triangulate_face(ufbx_panic *panic, uint32_t *indices, size_t num_indices, const ufbx_mesh *mesh, ufbx_face face)
32281 {
32282 #if UFBXI_FEATURE_TRIANGULATION
32283 if (face.num_indices < 3) return 0;
32284
32285 size_t required_indices = ((size_t)face.num_indices - 2) * 3;
32286 if (ufbxi_panicf(panic, num_indices >= required_indices, "Face needs at least %zu indices for triangles, got space for %zu", required_indices, num_indices)) return 0;
32287 if (ufbxi_panicf(panic, face.index_begin < mesh->num_indices, "Face index begin (%u) out of bounds (%zu)", face.index_begin, mesh->num_indices)) return 0;
32288 if (ufbxi_panicf(panic, mesh->num_indices - face.index_begin >= face.num_indices, "Face index end (%u + %u) out of bounds (%zu)", face.index_begin, face.num_indices, mesh->num_indices)) return 0;
32289
32290 if (face.num_indices == 3) {
32291 // Fast case: Already a triangle
32292 indices[0] = face.index_begin + 0;
32293 indices[1] = face.index_begin + 1;
32294 indices[2] = face.index_begin + 2;
32295 return 1;
32296 } else if (face.num_indices == 4) {
32297 // Quad: Split along the shortest axis unless a vertex crosses the axis
32298 uint32_t i0 = face.index_begin + 0;
32299 uint32_t i1 = face.index_begin + 1;
32300 uint32_t i2 = face.index_begin + 2;
32301 uint32_t i3 = face.index_begin + 3;
32302 ufbx_vec3 v0 = mesh->vertex_position.values.data[mesh->vertex_position.indices.data[i0]];
32303 ufbx_vec3 v1 = mesh->vertex_position.values.data[mesh->vertex_position.indices.data[i1]];
32304 ufbx_vec3 v2 = mesh->vertex_position.values.data[mesh->vertex_position.indices.data[i2]];
32305 ufbx_vec3 v3 = mesh->vertex_position.values.data[mesh->vertex_position.indices.data[i3]];
32306
32307 ufbx_vec3 a = ufbxi_sub3(v2, v0);
32308 ufbx_vec3 b = ufbxi_sub3(v3, v1);
32309
32310 ufbx_vec3 na1 = ufbxi_normalize3(ufbxi_cross3(a, ufbxi_sub3(v1, v0)));
32311 ufbx_vec3 na3 = ufbxi_normalize3(ufbxi_cross3(a, ufbxi_sub3(v0, v3)));
32312 ufbx_vec3 nb0 = ufbxi_normalize3(ufbxi_cross3(b, ufbxi_sub3(v1, v0)));
32313 ufbx_vec3 nb2 = ufbxi_normalize3(ufbxi_cross3(b, ufbxi_sub3(v2, v1)));
32314
32315 ufbx_real dot_aa = ufbxi_dot3(a, a);
32316 ufbx_real dot_bb = ufbxi_dot3(b, b);
32317 ufbx_real dot_na = ufbxi_dot3(na1, na3);
32318 ufbx_real dot_nb = ufbxi_dot3(nb0, nb2);
32319
32320 bool split_a = dot_aa <= dot_bb;
32321
32322 if (dot_na < 0.0f || dot_nb < 0.0f) {
32323 split_a = dot_na >= dot_nb;
32324 }
32325
32326 if (split_a) {
32327 indices[0] = i0;
32328 indices[1] = i1;
32329 indices[2] = i2;
32330 indices[3] = i2;
32331 indices[4] = i3;
32332 indices[5] = i0;
32333 } else {
32334 indices[0] = i1;
32335 indices[1] = i2;
32336 indices[2] = i3;
32337 indices[3] = i3;
32338 indices[4] = i0;
32339 indices[5] = i1;
32340 }
32341
32342 return 2;
32343 } else {
32344 ufbxi_ngon_context nc = { 0 };
32345 nc.positions = mesh->vertex_position;
32346 nc.face = face;
32347
32348 uint32_t num_indices_u32 = num_indices < UINT32_MAX ? (uint32_t)num_indices : UINT32_MAX;
32349
32350 uint32_t local_indices[12]; // ufbxi_uninit
32351 if (num_indices_u32 < 12) {
32352 uint32_t num_tris = ufbxi_triangulate_ngon(&nc, local_indices, 12);
32353 memcpy(indices, local_indices, num_tris * 3 * sizeof(uint32_t));
32354 return num_tris;
32355 } else {
32356 return ufbxi_triangulate_ngon(&nc, indices, num_indices_u32);
32357 }
32358 }
32359 #else
32360 ufbxi_panicf_imp(panic, "Triangulation disabled");
32361 return 0;
32362 #endif
32363 }
32364
32365 ufbx_abi void ufbx_catch_compute_topology(ufbx_panic *panic, const ufbx_mesh *mesh, ufbx_topo_edge *indices, size_t num_indices)
32366 {
32367 if (ufbxi_panicf(panic, num_indices >= mesh->num_indices, "Required mesh.num_indices (%zu) indices, got %zu", mesh->num_indices, num_indices)) return;
32368
32369 ufbxi_compute_topology(mesh, indices);
32370 }
32371
32372 ufbx_abi uint32_t ufbx_catch_topo_next_vertex_edge(ufbx_panic *panic, const ufbx_topo_edge *topo, size_t num_topo, uint32_t index)
32373 {
32374 if (index == UFBX_NO_INDEX) return UFBX_NO_INDEX;
32375 if (ufbxi_panicf(panic, (size_t)index < num_topo, "index (%u) out of bounds (%zu)", index, num_topo)) return UFBX_NO_INDEX;
32376 uint32_t twin = topo[index].twin;
32377 if (twin == UFBX_NO_INDEX) return UFBX_NO_INDEX;
32378 if (ufbxi_panicf(panic, (size_t)twin < num_topo, "Corrupted topology structure")) return UFBX_NO_INDEX;
32379 return topo[twin].next;
32380 }
32381
32382 ufbx_abi uint32_t ufbx_catch_topo_prev_vertex_edge(ufbx_panic *panic, const ufbx_topo_edge *topo, size_t num_topo, uint32_t index)
32383 {
32384 if (index == UFBX_NO_INDEX) return UFBX_NO_INDEX;
32385 if (ufbxi_panicf(panic, (size_t)index < num_topo, "index (%u) out of bounds (%zu)", index, num_topo)) return UFBX_NO_INDEX;
32386 return topo[topo[index].prev].twin;
32387 }
32388
32389 ufbx_abi ufbxi_noinline ufbx_vec3 ufbx_catch_get_weighted_face_normal(ufbx_panic *panic, const ufbx_vertex_vec3 *positions, ufbx_face face)
32390 {
32391 if (ufbxi_panicf(panic, face.index_begin <= positions->indices.count, "Face index begin (%u) out of bounds (%zu)", face.index_begin, positions->indices.count)) return ufbx_zero_vec3;
32392 if (ufbxi_panicf(panic, positions->indices.count - face.index_begin >= face.num_indices, "Face index end (%u + %u) out of bounds (%zu)", face.index_begin, face.num_indices, positions->indices.count)) return ufbx_zero_vec3;
32393
32394 if (face.num_indices < 3) {
32395 return ufbx_zero_vec3;
32396 } else if (face.num_indices == 3) {
32397 ufbx_vec3 a = ufbx_get_vertex_vec3(positions, face.index_begin + 0);
32398 ufbx_vec3 b = ufbx_get_vertex_vec3(positions, face.index_begin + 1);
32399 ufbx_vec3 c = ufbx_get_vertex_vec3(positions, face.index_begin + 2);
32400 return ufbxi_cross3(ufbxi_sub3(b, a), ufbxi_sub3(c, a));
32401 } else if (face.num_indices == 4) {
32402 ufbx_vec3 a = ufbx_get_vertex_vec3(positions, face.index_begin + 0);
32403 ufbx_vec3 b = ufbx_get_vertex_vec3(positions, face.index_begin + 1);
32404 ufbx_vec3 c = ufbx_get_vertex_vec3(positions, face.index_begin + 2);
32405 ufbx_vec3 d = ufbx_get_vertex_vec3(positions, face.index_begin + 3);
32406 return ufbxi_cross3(ufbxi_sub3(c, a), ufbxi_sub3(d, b));
32407 } else {
32408 // Newell's Method
32409 ufbx_vec3 result = ufbx_zero_vec3;
32410 for (size_t i = 0; i < face.num_indices; i++) {
32411 size_t next = i + 1 < face.num_indices ? i + 1 : 0;
32412 ufbx_vec3 a = ufbx_get_vertex_vec3(positions, face.index_begin + i);
32413 ufbx_vec3 b = ufbx_get_vertex_vec3(positions, face.index_begin + next);
32414 result.x += (a.y - b.y) * (a.z + b.z);
32415 result.y += (a.z - b.z) * (a.x + b.x);
32416 result.z += (a.x - b.x) * (a.y + b.y);
32417 }
32418 return result;
32419 }
32420 }
32421
32422 size_t ufbx_catch_generate_normal_mapping(ufbx_panic *panic, const ufbx_mesh *mesh, const ufbx_topo_edge *topo, size_t num_topo, uint32_t *normal_indices, size_t num_normal_indices, bool assume_smooth)
32423 {
32424 uint32_t next_index = 0;
32425 if (ufbxi_panicf(panic, num_normal_indices >= mesh->num_indices, "Expected at least mesh.num_indices (%zu), got %zu", mesh->num_indices, num_normal_indices)) return 0;
32426
32427 for (size_t i = 0; i < mesh->num_indices; i++) {
32428 normal_indices[i] = UFBX_NO_INDEX;
32429 }
32430
32431 // Walk around vertices and merge around smooth edges
32432 for (size_t vi = 0; vi < mesh->num_vertices; vi++) {
32433 uint32_t original_start = mesh->vertex_first_index.data[vi];
32434 if (original_start == UFBX_NO_INDEX) continue;
32435 uint32_t start = original_start, cur = start;
32436
32437 for (;;) {
32438 uint32_t prev = ufbx_topo_next_vertex_edge(topo, num_topo, cur);
32439 if (!ufbxi_is_edge_smooth(mesh, topo, num_topo, cur, assume_smooth)) start = cur;
32440 if (prev == UFBX_NO_INDEX) { start = cur; break; }
32441 if (prev == original_start) break;
32442 cur = prev;
32443 }
32444
32445 normal_indices[start] = next_index++;
32446 uint32_t next = start;
32447 for (;;) {
32448 next = ufbx_topo_prev_vertex_edge(topo, num_topo, next);
32449 if (next == UFBX_NO_INDEX || next == start) break;
32450
32451 if (!ufbxi_is_edge_smooth(mesh, topo, num_topo, next, assume_smooth)) {
32452 ++next_index;
32453 }
32454 normal_indices[next] = next_index - 1;
32455 }
32456 }
32457
32458 // Assign non-manifold indices
32459 for (size_t i = 0; i < mesh->num_indices; i++) {
32460 if (normal_indices[i] == UFBX_NO_INDEX) {
32461 normal_indices[i] = next_index++;
32462 }
32463 }
32464
32465 return (size_t)next_index;
32466 }
32467
32468 ufbx_abi size_t ufbx_generate_normal_mapping(const ufbx_mesh *mesh, const ufbx_topo_edge *topo, size_t num_topo, uint32_t *normal_indices, size_t num_normal_indices, bool assume_smooth)
32469 {
32470 return ufbx_catch_generate_normal_mapping(NULL, mesh, topo, num_topo, normal_indices, num_normal_indices, assume_smooth);
32471 }
32472
32473 ufbx_abi void ufbx_catch_compute_normals(ufbx_panic *panic, const ufbx_mesh *mesh, const ufbx_vertex_vec3 *positions, const uint32_t *normal_indices, size_t num_normal_indices, ufbx_vec3 *normals, size_t num_normals)
32474 {
32475 if (ufbxi_panicf(panic, num_normal_indices >= mesh->num_indices, "Expected at least mesh.num_indices (%zu), got %zu", mesh->num_indices, num_normal_indices)) return;
32476
32477 memset(normals, 0, sizeof(ufbx_vec3)*num_normals);
32478
32479 for (size_t fi = 0; fi < mesh->num_faces; fi++) {
32480 ufbx_face face = mesh->faces.data[fi];
32481 ufbx_vec3 normal = ufbx_get_weighted_face_normal(positions, face);
32482 for (size_t ix = 0; ix < face.num_indices; ix++) {
32483 uint32_t index = normal_indices[face.index_begin + ix];
32484
32485 if (ufbxi_panicf(panic, index < num_normals, "Normal index (%u) out of bounds (%zu) at %zu", index, num_normals, ix)) return;
32486
32487 ufbx_vec3 *n = &normals[index];
32488 *n = ufbxi_add3(*n, normal);
32489 }
32490 }
32491
32492 for (size_t i = 0; i < num_normals; i++) {
32493 ufbx_real len = ufbxi_length3(normals[i]);
32494 if (len > 0.0f) {
32495 normals[i].x /= len;
32496 normals[i].y /= len;
32497 normals[i].z /= len;
32498 }
32499 }
32500 }
32501
32502 ufbx_abi void ufbx_compute_normals(const ufbx_mesh *mesh, const ufbx_vertex_vec3 *positions, const uint32_t *normal_indices, size_t num_normal_indices, ufbx_vec3 *normals, size_t num_normals)
32503 {
32504 ufbx_catch_compute_normals(NULL, mesh, positions, normal_indices, num_normal_indices, normals, num_normals);
32505 }
32506
32507 ufbx_abi ufbx_mesh *ufbx_subdivide_mesh(const ufbx_mesh *mesh, size_t level, const ufbx_subdivide_opts *opts, ufbx_error *error)
32508 {
32509 ufbxi_check_opts_ptr(ufbx_mesh, opts, error);
32510 if (!mesh) return NULL;
32511 if (level == 0) return (ufbx_mesh*)mesh;
32512 return ufbxi_subdivide_mesh(mesh, level, opts, error);
32513 }
32514
32515 ufbx_abi void ufbx_free_mesh(ufbx_mesh *mesh)
32516 {
32517 if (!mesh) return;
32518 if (!mesh->subdivision_evaluated && !mesh->from_tessellated_nurbs) return;
32519
32520 ufbxi_mesh_imp *imp = ufbxi_get_imp(ufbxi_mesh_imp, mesh);
32521 ufbx_assert(imp->magic == UFBXI_MESH_IMP_MAGIC);
32522 if (imp->magic != UFBXI_MESH_IMP_MAGIC) return;
32523 ufbxi_release_ref(&imp->refcount);
32524 }
32525
32526 ufbx_abi void ufbx_retain_mesh(ufbx_mesh *mesh)
32527 {
32528 if (!mesh) return;
32529 if (!mesh->subdivision_evaluated && !mesh->from_tessellated_nurbs) return;
32530
32531 ufbxi_mesh_imp *imp = ufbxi_get_imp(ufbxi_mesh_imp, mesh);
32532 ufbx_assert(imp->magic == UFBXI_MESH_IMP_MAGIC);
32533 if (imp->magic != UFBXI_MESH_IMP_MAGIC) return;
32534 ufbxi_retain_ref(&imp->refcount);
32535 }
32536
32537 ufbx_abi ufbx_geometry_cache *ufbx_load_geometry_cache(
32538 const char *filename,
32539 const ufbx_geometry_cache_opts *opts, ufbx_error *error)
32540 {
32541 return ufbx_load_geometry_cache_len(filename, strlen(filename),
32542 opts, error);
32543 }
32544
32545 ufbx_abi ufbx_geometry_cache *ufbx_load_geometry_cache_len(
32546 const char *filename, size_t filename_len,
32547 const ufbx_geometry_cache_opts *opts, ufbx_error *error)
32548 {
32549 ufbxi_check_opts_ptr(ufbx_geometry_cache, opts, error);
32550 ufbx_string str = ufbxi_safe_string(filename, filename_len);
32551 return ufbxi_load_geometry_cache(str, opts, error);
32552 }
32553
32554 ufbx_abi void ufbx_free_geometry_cache(ufbx_geometry_cache *cache)
32555 {
32556 if (!cache) return;
32557
32558 ufbxi_geometry_cache_imp *imp = ufbxi_get_imp(ufbxi_geometry_cache_imp, cache);
32559 ufbx_assert(imp->magic == UFBXI_CACHE_IMP_MAGIC);
32560 if (imp->magic != UFBXI_CACHE_IMP_MAGIC) return;
32561 if (imp->owned_by_scene) return;
32562 ufbxi_release_ref(&imp->refcount);
32563 }
32564
32565 ufbx_abi void ufbx_retain_geometry_cache(ufbx_geometry_cache *cache)
32566 {
32567 if (!cache) return;
32568
32569 ufbxi_geometry_cache_imp *imp = ufbxi_get_imp(ufbxi_geometry_cache_imp, cache);
32570 ufbx_assert(imp->magic == UFBXI_CACHE_IMP_MAGIC);
32571 if (imp->magic != UFBXI_CACHE_IMP_MAGIC) return;
32572 if (imp->owned_by_scene) return;
32573 ufbxi_retain_ref(&imp->refcount);
32574 }
32575
32576 typedef struct {
32577 union {
32578 double f64[UFBXI_GEOMETRY_CACHE_BUFFER_SIZE];
32579 float f32[UFBXI_GEOMETRY_CACHE_BUFFER_SIZE];
32580 } src;
32581 ufbx_real dst[UFBXI_GEOMETRY_CACHE_BUFFER_SIZE];
32582 } ufbxi_geometry_cache_buffer;
32583
32584 ufbx_abi ufbxi_noinline size_t ufbx_read_geometry_cache_real(const ufbx_cache_frame *frame, ufbx_real *data, size_t count, const ufbx_geometry_cache_data_opts *user_opts)
32585 {
32586 #if UFBXI_FEATURE_GEOMETRY_CACHE
32587 ufbxi_check_opts_return_no_error(0, user_opts);
32588 if (!frame || count == 0) return 0;
32589 ufbx_assert(data);
32590 if (!data) return 0;
32591
32592 ufbx_geometry_cache_data_opts opts; // ufbxi_uninit
32593 if (user_opts) {
32594 opts = *user_opts;
32595 } else {
32596 memset(&opts, 0, sizeof(opts));
32597 }
32598
32599 if (!opts.open_file_cb.fn) {
32600 opts.open_file_cb.fn = ufbx_default_open_file;
32601 }
32602
32603 bool use_double = false;
32604
32605 size_t src_count = 0;
32606
32607 switch (frame->data_format) {
32608 case UFBX_CACHE_DATA_FORMAT_UNKNOWN: src_count = 0; break;
32609 case UFBX_CACHE_DATA_FORMAT_REAL_FLOAT: src_count = frame->data_count; break;
32610 case UFBX_CACHE_DATA_FORMAT_VEC3_FLOAT: src_count = frame->data_count * 3; break;
32611 case UFBX_CACHE_DATA_FORMAT_REAL_DOUBLE: src_count = frame->data_count; use_double = true; break;
32612 case UFBX_CACHE_DATA_FORMAT_VEC3_DOUBLE: src_count = frame->data_count * 3; use_double = true; break;
32613 default: ufbxi_unreachable("Bad data_format"); break;
32614 }
32615
32616 bool src_big_endian = false;
32617 switch (frame->data_encoding) {
32618 case UFBX_CACHE_DATA_ENCODING_UNKNOWN: return 0;
32619 case UFBX_CACHE_DATA_ENCODING_LITTLE_ENDIAN: src_big_endian = false; break;
32620 case UFBX_CACHE_DATA_ENCODING_BIG_ENDIAN: src_big_endian = true; break;
32621 default: ufbxi_unreachable("Bad data_encoding"); break;
32622 }
32623
32624 // Test endianness
32625 bool dst_big_endian;
32626 {
32627 uint8_t buf[2];
32628 uint16_t val = 0xbbaa;
32629 memcpy(buf, &val, 2);
32630 dst_big_endian = buf[0] == 0xbb;
32631 }
32632
32633 if (src_count == 0) return 0;
32634 src_count = ufbxi_min_sz(src_count, count);
32635
32636 ufbx_stream stream = { 0 };
32637 if (!ufbxi_open_file(&opts.open_file_cb, &stream, frame->filename.data, frame->filename.length, NULL, NULL, UFBX_OPEN_FILE_GEOMETRY_CACHE)) {
32638 return 0;
32639 }
32640
32641 // Skip to the correct point in the file
32642 uint64_t offset = frame->data_offset;
32643 if (stream.skip_fn) {
32644 while (offset > 0) {
32645 size_t to_skip = (size_t)ufbxi_min64(offset, UFBXI_MAX_SKIP_SIZE);
32646 if (!stream.skip_fn(stream.user, to_skip)) break;
32647 offset -= to_skip;
32648 }
32649 } else {
32650 char buffer[4096]; // ufbxi_uninit
32651 while (offset > 0) {
32652 size_t to_skip = (size_t)ufbxi_min64(offset, sizeof(buffer));
32653 size_t num_read = stream.read_fn(stream.user, buffer, to_skip);
32654 if (num_read != to_skip) break;
32655 offset -= to_skip;
32656 }
32657 }
32658
32659 // Failed to skip all the way
32660 if (offset > 0) {
32661 if (stream.close_fn) {
32662 stream.close_fn(stream.user);
32663 }
32664 return 0;
32665 }
32666
32667 ufbx_real *dst = data;
32668 size_t mirror_ix = (size_t)frame->mirror_axis - 1;
32669 ufbxi_geometry_cache_buffer buffer; // ufbxi_uninit
32670 while (src_count > 0) {
32671 size_t to_read = ufbxi_min_sz(src_count, UFBXI_GEOMETRY_CACHE_BUFFER_SIZE);
32672 src_count -= to_read;
32673 size_t num_read = 0;
32674 if (use_double) {
32675 size_t bytes_read = stream.read_fn(stream.user, buffer.src.f64, to_read * sizeof(double));
32676 if (bytes_read == SIZE_MAX) bytes_read = 0;
32677 num_read = bytes_read / sizeof(double);
32678 if (src_big_endian != dst_big_endian) {
32679 for (size_t i = 0; i < num_read; i++) {
32680 char t, *v = (char*)&buffer.src.f64[i];
32681 t = v[0]; v[0] = v[7]; v[7] = t;
32682 t = v[1]; v[1] = v[6]; v[6] = t;
32683 t = v[2]; v[2] = v[5]; v[5] = t;
32684 t = v[3]; v[3] = v[4]; v[4] = t;
32685 }
32686 }
32687 ufbxi_nounroll for (size_t i = 0; i < num_read; i++) {
32688 buffer.dst[i] = (ufbx_real)buffer.src.f64[i];
32689 }
32690 } else {
32691 size_t bytes_read = stream.read_fn(stream.user, buffer.src.f32, to_read * sizeof(float));
32692 if (bytes_read == SIZE_MAX) bytes_read = 0;
32693 num_read = bytes_read / sizeof(float);
32694 if (src_big_endian != dst_big_endian) {
32695 for (size_t i = 0; i < num_read; i++) {
32696 char t, *v = (char*)&buffer.src.f32[i];
32697 t = v[0]; v[0] = v[3]; v[3] = t;
32698 t = v[1]; v[1] = v[2]; v[2] = t;
32699 }
32700 }
32701 ufbxi_nounroll for (size_t i = 0; i < num_read; i++) {
32702 buffer.dst[i] = (ufbx_real)buffer.src.f32[i];
32703 }
32704 }
32705
32706 if (!opts.ignore_transform) {
32707 ufbx_real scale = frame->scale_factor;
32708 if (scale != 1.0f) {
32709 for (size_t i = 0; i < num_read; i++) {
32710 buffer.dst[i] *= scale;
32711 }
32712 }
32713 if (frame->mirror_axis) {
32714 while (mirror_ix < num_read) {
32715 buffer.dst[mirror_ix] = -buffer.dst[mirror_ix];
32716 mirror_ix += 3;
32717 }
32718 mirror_ix -= num_read;
32719 }
32720 }
32721
32722 if (dst) {
32723 ufbx_real weight = opts.use_weight ? opts.weight : 1.0f;
32724 if (opts.additive) {
32725 ufbxi_nounroll for (size_t i = 0; i < num_read; i++) {
32726 dst[i] += buffer.dst[i] * weight;
32727 }
32728 } else {
32729 ufbxi_nounroll for (size_t i = 0; i < num_read; i++) {
32730 dst[i] = buffer.dst[i] * weight;
32731 }
32732 }
32733 dst += num_read;
32734 }
32735
32736 if (num_read != to_read) break;
32737 }
32738
32739 if (stream.close_fn) {
32740 stream.close_fn(stream.user);
32741 }
32742
32743 return ufbxi_to_size(dst - data);
32744 #else
32745 return 0;
32746 #endif
32747 }
32748
32749 ufbx_abi ufbxi_noinline size_t ufbx_sample_geometry_cache_real(const ufbx_cache_channel *channel, double time, ufbx_real *data, size_t count, const ufbx_geometry_cache_data_opts *user_opts)
32750 {
32751 #if UFBXI_FEATURE_GEOMETRY_CACHE
32752 ufbxi_check_opts_return_no_error(0, user_opts);
32753 if (!channel || count == 0) return 0;
32754 ufbx_assert(data);
32755 if (!data) return 0;
32756 if (channel->frames.count == 0) return 0;
32757
32758 ufbx_geometry_cache_data_opts opts;
32759 if (user_opts) {
32760 opts = *user_opts;
32761 } else {
32762 memset(&opts, 0, sizeof(opts));
32763 }
32764
32765 size_t begin = 0;
32766 size_t end = channel->frames.count;
32767 const ufbx_cache_frame *frames = channel->frames.data;
32768 while (end - begin >= 8) {
32769 size_t mid = (begin + end) >> 1;
32770 if (frames[mid].time < time) {
32771 begin = mid + 1;
32772 } else {
32773 end = mid;
32774 }
32775 }
32776
32777 const double eps = 0.00000001;
32778
32779 end = channel->frames.count;
32780 for (; begin < end; begin++) {
32781 const ufbx_cache_frame *next = &frames[begin];
32782 if (next->time < time) continue;
32783
32784 // First keyframe
32785 if (begin == 0) {
32786 return ufbx_read_geometry_cache_real(next, data, count, &opts);
32787 }
32788
32789 const ufbx_cache_frame *prev = next - 1;
32790
32791 // Snap to exact frames if near
32792 if (ufbx_fabs(next->time - time) < eps) {
32793 return ufbx_read_geometry_cache_real(next, data, count, &opts);
32794 }
32795 if (ufbx_fabs(prev->time - time) < eps) {
32796 return ufbx_read_geometry_cache_real(prev, data, count, &opts);
32797 }
32798
32799 double rcp_delta = 1.0 / (next->time - prev->time);
32800 double t = (time - prev->time) * rcp_delta;
32801
32802 ufbx_real original_weight = opts.use_weight ? opts.weight : 1.0f;
32803
32804 opts.use_weight = true;
32805 opts.weight = (ufbx_real)(original_weight * (1.0 - t));
32806 size_t num_prev = ufbx_read_geometry_cache_real(prev, data, count, &opts);
32807
32808 opts.additive = true;
32809 opts.weight = (ufbx_real)(original_weight * t);
32810 return ufbx_read_geometry_cache_real(next, data, num_prev, &opts);
32811 }
32812
32813 // Last frame
32814 const ufbx_cache_frame *last = &frames[end - 1];
32815 return ufbx_read_geometry_cache_real(last, data, count, &opts);
32816 #else
32817 return 0;
32818 #endif
32819 }
32820
32821 ufbx_abi ufbxi_noinline size_t ufbx_read_geometry_cache_vec3(const ufbx_cache_frame *frame, ufbx_vec3 *data, size_t count, const ufbx_geometry_cache_data_opts *opts)
32822 {
32823 #if UFBXI_FEATURE_GEOMETRY_CACHE
32824 if (!frame || count == 0) return 0;
32825 ufbx_assert(data);
32826 if (!data) return 0;
32827 return ufbx_read_geometry_cache_real(frame, (ufbx_real*)data, count * 3, opts) / 3;
32828 #else
32829 return 0;
32830 #endif
32831 }
32832
32833 ufbx_abi ufbxi_noinline size_t ufbx_sample_geometry_cache_vec3(const ufbx_cache_channel *channel, double time, ufbx_vec3 *data, size_t count, const ufbx_geometry_cache_data_opts *opts)
32834 {
32835 #if UFBXI_FEATURE_GEOMETRY_CACHE
32836 if (!channel || count == 0) return 0;
32837 ufbx_assert(data);
32838 if (!data) return 0;
32839 return ufbx_sample_geometry_cache_real(channel, time, (ufbx_real*)data, count * 3, opts) / 3;
32840 #else
32841 return 0;
32842 #endif
32843 }
32844
32845 ufbx_abi ufbx_dom_node *ufbx_dom_find_len(const ufbx_dom_node *parent, const char *name, size_t name_len)
32846 {
32847 ufbx_string ref = ufbxi_safe_string(name, name_len);
32848 ufbxi_for_ptr_list(ufbx_dom_node, p_child, parent->children) {
32849 if (ufbxi_str_equal((*p_child)->name, ref)) return (ufbx_dom_node*)*p_child;
32850 }
32851 return NULL;
32852 }
32853
32854 ufbx_abi size_t ufbx_generate_indices(const ufbx_vertex_stream *streams, size_t num_streams, uint32_t *indices, size_t num_indices, const ufbx_allocator_opts *allocator, ufbx_error *error)
32855 {
32856 ufbx_error local_error; // ufbxi_uninit
32857 if (!error) {
32858 error = &local_error;
32859 }
32860 memset(error, 0, sizeof(ufbx_error));
32861 return ufbxi_generate_indices(streams, num_streams, indices, num_indices, allocator, error);
32862 }
32863
32864 ufbx_abi void ufbx_thread_pool_run_task(ufbx_thread_pool_context ctx, uint32_t index)
32865 {
32866 ufbxi_thread_pool_execute((ufbxi_thread_pool*)ctx, index);
32867 }
32868
32869 ufbx_abi void ufbx_thread_pool_set_user_ptr(ufbx_thread_pool_context ctx, void *user)
32870 {
32871 ufbxi_thread_pool *pool = (ufbxi_thread_pool*)ctx;
32872 pool->user_ptr = user;
32873 }
32874
32875 ufbx_abi void *ufbx_thread_pool_get_user_ptr(ufbx_thread_pool_context ctx)
32876 {
32877 ufbxi_thread_pool *pool = (ufbxi_thread_pool*)ctx;
32878 return pool->user_ptr;
32879 }
32880
32881 ufbx_abi ufbxi_noinline ufbx_real ufbx_catch_get_vertex_real(ufbx_panic *panic, const ufbx_vertex_real *v, size_t index)
32882 {
32883 if (ufbxi_panicf(panic, index < v->indices.count, "index (%zu) out of range (%zu)", index, v->indices.count)) return 0.0f;
32884 uint32_t ix = v->indices.data[index];
32885 if (ufbxi_panicf(panic, (size_t)ix < v->values.count || ix == UFBX_NO_INDEX, "Corrupted or missing vertex attribute (%u) at %zu", ix, index)) return 0.0f;
32886 return v->values.data[(int32_t)ix];
32887 }
32888
32889 ufbx_abi ufbxi_noinline ufbx_vec2 ufbx_catch_get_vertex_vec2(ufbx_panic *panic, const ufbx_vertex_vec2 *v, size_t index)
32890 {
32891 if (ufbxi_panicf(panic, index < v->indices.count, "index (%zu) out of range (%zu)", index, v->indices.count)) return ufbx_zero_vec2;
32892 uint32_t ix = v->indices.data[index];
32893 if (ufbxi_panicf(panic, (size_t)ix < v->values.count || ix == UFBX_NO_INDEX, "Corrupted or missing vertex attribute (%u) at %zu", ix, index)) return ufbx_zero_vec2;
32894 return v->values.data[(int32_t)ix];
32895 }
32896
32897 ufbx_abi ufbxi_noinline ufbx_vec3 ufbx_catch_get_vertex_vec3(ufbx_panic *panic, const ufbx_vertex_vec3 *v, size_t index)
32898 {
32899 if (ufbxi_panicf(panic, index < v->indices.count, "index (%zu) out of range (%zu)", index, v->indices.count)) return ufbx_zero_vec3;
32900 uint32_t ix = v->indices.data[index];
32901 if (ufbxi_panicf(panic, (size_t)ix < v->values.count || ix == UFBX_NO_INDEX, "Corrupted or missing vertex attribute (%u) at %zu", ix, index)) return ufbx_zero_vec3;
32902 return v->values.data[(int32_t)ix];
32903 }
32904
32905 ufbx_abi ufbxi_noinline ufbx_vec4 ufbx_catch_get_vertex_vec4(ufbx_panic *panic, const ufbx_vertex_vec4 *v, size_t index)
32906 {
32907 if (ufbxi_panicf(panic, index < v->indices.count, "index (%zu) out of range (%zu)", index, v->indices.count)) return ufbx_zero_vec4;
32908 uint32_t ix = v->indices.data[index];
32909 if (ufbxi_panicf(panic, (size_t)ix < v->values.count || ix == UFBX_NO_INDEX, "Corrupted or missing vertex attribute (%u) at %zu", ix, index)) return ufbx_zero_vec4;
32910 return v->values.data[(int32_t)ix];
32911 }
32912
32913 ufbx_abi ufbx_real ufbx_catch_get_vertex_w_vec3(ufbx_panic *panic, const ufbx_vertex_vec3 *v, size_t index)
32914 {
32915 if (ufbxi_panicf(panic, index < v->indices.count, "index (%zu) out of range (%zu)", index, v->indices.count)) return 0.0f;
32916 if (v->values_w.count == 0) return 0.0f;
32917 uint32_t ix = v->indices.data[index];
32918 if (ufbxi_panicf(panic, (size_t)ix < v->values.count || ix == UFBX_NO_INDEX, "Corrupted or missing vertex attribute (%u) at %zu", ix, index)) return 0.0f;
32919 return v->values_w.data[(int32_t)ix];
32920 }
32921
32922 ufbx_abi ufbx_unknown *ufbx_as_unknown(const ufbx_element *element) { return element && element->type == UFBX_ELEMENT_UNKNOWN ? (ufbx_unknown*)element : NULL; }
32923 ufbx_abi ufbx_node *ufbx_as_node(const ufbx_element *element) { return element && element->type == UFBX_ELEMENT_NODE ? (ufbx_node*)element : NULL; }
32924 ufbx_abi ufbx_mesh *ufbx_as_mesh(const ufbx_element *element) { return element && element->type == UFBX_ELEMENT_MESH ? (ufbx_mesh*)element : NULL; }
32925 ufbx_abi ufbx_light *ufbx_as_light(const ufbx_element *element) { return element && element->type == UFBX_ELEMENT_LIGHT ? (ufbx_light*)element : NULL; }
32926 ufbx_abi ufbx_camera *ufbx_as_camera(const ufbx_element *element) { return element && element->type == UFBX_ELEMENT_CAMERA ? (ufbx_camera*)element : NULL; }
32927 ufbx_abi ufbx_bone *ufbx_as_bone(const ufbx_element *element) { return element && element->type == UFBX_ELEMENT_BONE ? (ufbx_bone*)element : NULL; }
32928 ufbx_abi ufbx_empty *ufbx_as_empty(const ufbx_element *element) { return element && element->type == UFBX_ELEMENT_EMPTY ? (ufbx_empty*)element : NULL; }
32929 ufbx_abi ufbx_line_curve *ufbx_as_line_curve(const ufbx_element *element) { return element && element->type == UFBX_ELEMENT_LINE_CURVE ? (ufbx_line_curve*)element : NULL; }
32930 ufbx_abi ufbx_nurbs_curve *ufbx_as_nurbs_curve(const ufbx_element *element) { return element && element->type == UFBX_ELEMENT_NURBS_CURVE ? (ufbx_nurbs_curve*)element : NULL; }
32931 ufbx_abi ufbx_nurbs_surface *ufbx_as_nurbs_surface(const ufbx_element *element) { return element && element->type == UFBX_ELEMENT_NURBS_SURFACE ? (ufbx_nurbs_surface*)element : NULL; }
32932 ufbx_abi ufbx_nurbs_trim_surface *ufbx_as_nurbs_trim_surface(const ufbx_element *element) { return element && element->type == UFBX_ELEMENT_NURBS_TRIM_SURFACE ? (ufbx_nurbs_trim_surface*)element : NULL; }
32933 ufbx_abi ufbx_nurbs_trim_boundary *ufbx_as_nurbs_trim_boundary(const ufbx_element *element) { return element && element->type == UFBX_ELEMENT_NURBS_TRIM_BOUNDARY ? (ufbx_nurbs_trim_boundary*)element : NULL; }
32934 ufbx_abi ufbx_procedural_geometry *ufbx_as_procedural_geometry(const ufbx_element *element) { return element && element->type == UFBX_ELEMENT_PROCEDURAL_GEOMETRY ? (ufbx_procedural_geometry*)element : NULL; }
32935 ufbx_abi ufbx_stereo_camera *ufbx_as_stereo_camera(const ufbx_element *element) { return element && element->type == UFBX_ELEMENT_STEREO_CAMERA ? (ufbx_stereo_camera*)element : NULL; }
32936 ufbx_abi ufbx_camera_switcher *ufbx_as_camera_switcher(const ufbx_element *element) { return element && element->type == UFBX_ELEMENT_CAMERA_SWITCHER ? (ufbx_camera_switcher*)element : NULL; }
32937 ufbx_abi ufbx_marker *ufbx_as_marker(const ufbx_element *element) { return element && element->type == UFBX_ELEMENT_MARKER ? (ufbx_marker*)element : NULL; }
32938 ufbx_abi ufbx_lod_group *ufbx_as_lod_group(const ufbx_element *element) { return element && element->type == UFBX_ELEMENT_LOD_GROUP ? (ufbx_lod_group*)element : NULL; }
32939 ufbx_abi ufbx_skin_deformer *ufbx_as_skin_deformer(const ufbx_element *element) { return element && element->type == UFBX_ELEMENT_SKIN_DEFORMER ? (ufbx_skin_deformer*)element : NULL; }
32940 ufbx_abi ufbx_skin_cluster *ufbx_as_skin_cluster(const ufbx_element *element) { return element && element->type == UFBX_ELEMENT_SKIN_CLUSTER ? (ufbx_skin_cluster*)element : NULL; }
32941 ufbx_abi ufbx_blend_deformer *ufbx_as_blend_deformer(const ufbx_element *element) { return element && element->type == UFBX_ELEMENT_BLEND_DEFORMER ? (ufbx_blend_deformer*)element : NULL; }
32942 ufbx_abi ufbx_blend_channel *ufbx_as_blend_channel(const ufbx_element *element) { return element && element->type == UFBX_ELEMENT_BLEND_CHANNEL ? (ufbx_blend_channel*)element : NULL; }
32943 ufbx_abi ufbx_blend_shape *ufbx_as_blend_shape(const ufbx_element *element) { return element && element->type == UFBX_ELEMENT_BLEND_SHAPE ? (ufbx_blend_shape*)element : NULL; }
32944 ufbx_abi ufbx_cache_deformer *ufbx_as_cache_deformer(const ufbx_element *element) { return element && element->type == UFBX_ELEMENT_CACHE_DEFORMER ? (ufbx_cache_deformer*)element : NULL; }
32945 ufbx_abi ufbx_cache_file *ufbx_as_cache_file(const ufbx_element *element) { return element && element->type == UFBX_ELEMENT_CACHE_FILE ? (ufbx_cache_file*)element : NULL; }
32946 ufbx_abi ufbx_material *ufbx_as_material(const ufbx_element *element) { return element && element->type == UFBX_ELEMENT_MATERIAL ? (ufbx_material*)element : NULL; }
32947 ufbx_abi ufbx_texture *ufbx_as_texture(const ufbx_element *element) { return element && element->type == UFBX_ELEMENT_TEXTURE ? (ufbx_texture*)element : NULL; }
32948 ufbx_abi ufbx_video *ufbx_as_video(const ufbx_element *element) { return element && element->type == UFBX_ELEMENT_VIDEO ? (ufbx_video*)element : NULL; }
32949 ufbx_abi ufbx_shader *ufbx_as_shader(const ufbx_element *element) { return element && element->type == UFBX_ELEMENT_SHADER ? (ufbx_shader*)element : NULL; }
32950 ufbx_abi ufbx_shader_binding *ufbx_as_shader_binding(const ufbx_element *element) { return element && element->type == UFBX_ELEMENT_SHADER_BINDING ? (ufbx_shader_binding*)element : NULL; }
32951 ufbx_abi ufbx_anim_stack *ufbx_as_anim_stack(const ufbx_element *element) { return element && element->type == UFBX_ELEMENT_ANIM_STACK ? (ufbx_anim_stack*)element : NULL; }
32952 ufbx_abi ufbx_anim_layer *ufbx_as_anim_layer(const ufbx_element *element) { return element && element->type == UFBX_ELEMENT_ANIM_LAYER ? (ufbx_anim_layer*)element : NULL; }
32953 ufbx_abi ufbx_anim_value *ufbx_as_anim_value(const ufbx_element *element) { return element && element->type == UFBX_ELEMENT_ANIM_VALUE ? (ufbx_anim_value*)element : NULL; }
32954 ufbx_abi ufbx_anim_curve *ufbx_as_anim_curve(const ufbx_element *element) { return element && element->type == UFBX_ELEMENT_ANIM_CURVE ? (ufbx_anim_curve*)element : NULL; }
32955 ufbx_abi ufbx_display_layer *ufbx_as_display_layer(const ufbx_element *element) { return element && element->type == UFBX_ELEMENT_DISPLAY_LAYER ? (ufbx_display_layer*)element : NULL; }
32956 ufbx_abi ufbx_selection_set *ufbx_as_selection_set(const ufbx_element *element) { return element && element->type == UFBX_ELEMENT_SELECTION_SET ? (ufbx_selection_set*)element : NULL; }
32957 ufbx_abi ufbx_selection_node *ufbx_as_selection_node(const ufbx_element *element) { return element && element->type == UFBX_ELEMENT_SELECTION_NODE ? (ufbx_selection_node*)element : NULL; }
32958 ufbx_abi ufbx_character *ufbx_as_character(const ufbx_element *element) { return element && element->type == UFBX_ELEMENT_CHARACTER ? (ufbx_character*)element : NULL; }
32959 ufbx_abi ufbx_constraint *ufbx_as_constraint(const ufbx_element *element) { return element && element->type == UFBX_ELEMENT_CONSTRAINT ? (ufbx_constraint*)element : NULL; }
32960 ufbx_abi ufbx_audio_layer *ufbx_as_audio_layer(const ufbx_element *element) { return element && element->type == UFBX_ELEMENT_AUDIO_LAYER ? (ufbx_audio_layer*)element : NULL; }
32961 ufbx_abi ufbx_audio_clip *ufbx_as_audio_clip(const ufbx_element *element) { return element && element->type == UFBX_ELEMENT_AUDIO_CLIP ? (ufbx_audio_clip*)element : NULL; }
32962 ufbx_abi ufbx_pose *ufbx_as_pose(const ufbx_element *element) { return element && element->type == UFBX_ELEMENT_POSE ? (ufbx_pose*)element : NULL; }
32963 ufbx_abi ufbx_metadata_object *ufbx_as_metadata_object(const ufbx_element *element) { return element && element->type == UFBX_ELEMENT_METADATA_OBJECT ? (ufbx_metadata_object*)element : NULL; }
32964
32965 ufbx_abi bool ufbx_dom_is_array(const ufbx_dom_node *node) {
32966 if (!node || node->values.count != 1) return false;
32967 ufbx_dom_value v = node->values.data[0];
32968 return v.type >= UFBX_DOM_VALUE_ARRAY_I32 && v.type <= UFBX_DOM_VALUE_ARRAY_BLOB;
32969 }
32970 ufbx_abi size_t ufbx_dom_array_size(const ufbx_dom_node *node) {
32971 return ufbx_dom_is_array(node) ? (size_t)node->values.data[0].value_int : (size_t)0;
32972 }
32973 ufbx_abi ufbx_int32_list ufbx_dom_as_int32_list(const ufbx_dom_node *node) {
32974 ufbx_int32_list list = { NULL, 0 };
32975 if (node && node->values.count == 1 && node->values.data[0].type == UFBX_DOM_VALUE_ARRAY_I32) {
32976 ufbx_dom_value value = node->values.data[0];
32977 list.data = (int32_t*)value.value_blob.data;
32978 list.count = value.value_blob.size / sizeof(int32_t);
32979 }
32980 return list;
32981 }
32982 ufbx_abi ufbx_int64_list ufbx_dom_as_int64_list(const ufbx_dom_node *node) {
32983 ufbx_int64_list list = { NULL, 0 };
32984 if (node && node->values.count == 1 && node->values.data[0].type == UFBX_DOM_VALUE_ARRAY_I64) {
32985 ufbx_dom_value value = node->values.data[0];
32986 list.data = (int64_t*)value.value_blob.data;
32987 list.count = value.value_blob.size / sizeof(int64_t);
32988 }
32989 return list;
32990 }
32991 ufbx_abi ufbx_float_list ufbx_dom_as_float_list(const ufbx_dom_node *node) {
32992 ufbx_float_list list = { NULL, 0 };
32993 if (node && node->values.count == 1 && node->values.data[0].type == UFBX_DOM_VALUE_ARRAY_F32) {
32994 ufbx_dom_value value = node->values.data[0];
32995 list.data = (float*)value.value_blob.data;
32996 list.count = value.value_blob.size / sizeof(float);
32997 }
32998 return list;
32999 }
33000 ufbx_abi ufbx_double_list ufbx_dom_as_double_list(const ufbx_dom_node *node) {
33001 ufbx_double_list list = { NULL, 0 };
33002 if (node && node->values.count == 1 && node->values.data[0].type == UFBX_DOM_VALUE_ARRAY_F64) {
33003 ufbx_dom_value value = node->values.data[0];
33004 list.data = (double*)value.value_blob.data;
33005 list.count = value.value_blob.size / sizeof(double);
33006 }
33007 return list;
33008 }
33009 ufbx_abi ufbx_real_list ufbx_dom_as_real_list(const ufbx_dom_node *node) {
33010 ufbx_real_list list = { NULL, 0 };
33011 if (node && node->values.count == 1 && node->values.data[0].type == (sizeof(ufbx_real) == sizeof(double) ? UFBX_DOM_VALUE_ARRAY_F64 : UFBX_DOM_VALUE_ARRAY_F32)) {
33012 ufbx_dom_value value = node->values.data[0];
33013 list.data = (ufbx_real*)value.value_blob.data;
33014 list.count = value.value_blob.size / sizeof(ufbx_real);
33015 }
33016 return list;
33017 }
33018 ufbx_abi ufbx_blob_list ufbx_dom_as_blob_list(const ufbx_dom_node *node) {
33019 ufbx_blob_list list = { NULL, 0 };
33020 if (node && node->values.count == 1 && node->values.data[0].type == UFBX_DOM_VALUE_ARRAY_BLOB) {
33021 ufbx_dom_value value = node->values.data[0];
33022 list.data = (ufbx_blob*)value.value_blob.data;
33023 list.count = value.value_blob.size / sizeof(ufbx_blob);
33024 }
33025 return list;
33026 }
33027
33028 // -- String API
33029
33030 ufbx_abi ufbx_prop *ufbx_find_prop(const ufbx_props *props, const char *name) { return ufbx_find_prop_len(props, name, strlen(name)); }
33031 ufbx_abi ufbx_real ufbx_find_real(const ufbx_props *props, const char *name, ufbx_real def) { return ufbx_find_real_len(props, name, strlen(name), def); }
33032 ufbx_abi ufbx_vec3 ufbx_find_vec3(const ufbx_props *props, const char *name, ufbx_vec3 def) { return ufbx_find_vec3_len(props, name, strlen(name), def); }
33033 ufbx_abi int64_t ufbx_find_int(const ufbx_props *props, const char *name, int64_t def) { return ufbx_find_int_len(props, name, strlen(name), def); }
33034 ufbx_abi bool ufbx_find_bool(const ufbx_props *props, const char *name, bool def) { return ufbx_find_bool_len(props, name, strlen(name), def); }
33035 ufbx_abi ufbx_string ufbx_find_string(const ufbx_props *props, const char *name, ufbx_string def) { return ufbx_find_string_len(props, name, strlen(name), def); }
33036 ufbx_abi ufbx_blob ufbx_find_blob(const ufbx_props *props, const char *name, ufbx_blob def) { return ufbx_find_blob_len(props, name, strlen(name), def); }
33037 ufbx_abi ufbx_element *ufbx_find_prop_element(const ufbx_element *element, const char *name, ufbx_element_type type) { return ufbx_find_prop_element_len(element, name, strlen(name), type); }
33038 ufbx_abi ufbx_element *ufbx_find_element(const ufbx_scene *scene, ufbx_element_type type, const char *name) { return ufbx_find_element_len(scene, type, name, strlen(name)); }
33039 ufbx_abi ufbx_node *ufbx_find_node(const ufbx_scene *scene, const char *name) { return ufbx_find_node_len(scene, name, strlen(name)); }
33040 ufbx_abi ufbx_anim_stack *ufbx_find_anim_stack(const ufbx_scene *scene, const char *name) { return ufbx_find_anim_stack_len(scene, name, strlen(name)); }
33041 ufbx_abi ufbx_material *ufbx_find_material(const ufbx_scene *scene, const char *name) { return ufbx_find_material_len(scene, name, strlen(name)); }
33042 ufbx_abi ufbx_anim_prop *ufbx_find_anim_prop(const ufbx_anim_layer *layer, const ufbx_element *element, const char *prop) { return ufbx_find_anim_prop_len(layer, element, prop, strlen(prop)); }
33043 ufbx_abi ufbx_prop ufbx_evaluate_prop(const ufbx_anim *anim, const ufbx_element *element, const char *name, double time) { return ufbx_evaluate_prop_len(anim, element, name, strlen(name), time); }
33044 ufbx_abi ufbx_prop ufbx_evaluate_prop_flags(const ufbx_anim *anim, const ufbx_element *element, const char *name, double time, uint32_t flags) { return ufbx_evaluate_prop_len_flags(anim, element, name, strlen(name), time, flags); }
33045 ufbx_abi ufbx_texture *ufbx_find_prop_texture(const ufbx_material *material, const char *name) { return ufbx_find_prop_texture_len(material, name, strlen(name)); }
33046 ufbx_abi ufbx_string ufbx_find_shader_prop(const ufbx_shader *shader, const char *name) { return ufbx_find_shader_prop_len(shader, name, strlen(name)); }
33047 ufbx_abi ufbx_shader_prop_binding_list ufbx_find_shader_prop_bindings(const ufbx_shader *shader, const char *name) { return ufbx_find_shader_prop_bindings_len(shader, name, strlen(name)); }
33048 ufbx_abi ufbx_shader_texture_input *ufbx_find_shader_texture_input(const ufbx_shader_texture *shader, const char *name) { return ufbx_find_shader_texture_input_len(shader, name, strlen(name)); }
33049 ufbx_abi ufbx_dom_node *ufbx_dom_find(const ufbx_dom_node *parent, const char *name) { return ufbx_dom_find_len(parent, name, strlen(name)); }
33050
33051 // -- Catch API
33052
33053 ufbx_abi uint32_t ufbx_triangulate_face(uint32_t *indices, size_t num_indices, const ufbx_mesh *mesh, ufbx_face face) {
33054 return ufbx_catch_triangulate_face(NULL, indices, num_indices, mesh, face);
33055 }
33056 ufbx_abi void ufbx_compute_topology(const ufbx_mesh *mesh, ufbx_topo_edge *topo, size_t num_topo) {
33057 ufbx_catch_compute_topology(NULL, mesh, topo, num_topo);
33058 }
33059 ufbx_abi uint32_t ufbx_topo_next_vertex_edge(const ufbx_topo_edge *topo, size_t num_topo, uint32_t index) {
33060 return ufbx_catch_topo_next_vertex_edge(NULL, topo, num_topo, index);
33061 }
33062 ufbx_abi uint32_t ufbx_topo_prev_vertex_edge(const ufbx_topo_edge *topo, size_t num_topo, uint32_t index) {
33063 return ufbx_catch_topo_prev_vertex_edge(NULL, topo, num_topo, index);
33064 }
33065 ufbx_abi ufbx_vec3 ufbx_get_weighted_face_normal(const ufbx_vertex_vec3 *positions, ufbx_face face) {
33066 return ufbx_catch_get_weighted_face_normal(NULL, positions, face);
33067 }
33068
33069 #ifdef __cplusplus
33070 }
33071 #endif
33072
33073 #endif
33074
33075 #if defined(UFBX_STRING_PREFIX)
33076 #undef strlen
33077 #undef memcpy
33078 #undef memmove
33079 #undef memset
33080 #undef memchr
33081 #undef memcmp
33082 #undef strcmp
33083 #undef strncmp
33084 #endif
33085
33086 #if defined(_MSC_VER)
33087 #pragma warning(pop)
33088 #elif defined(__clang__)
33089 #pragma clang diagnostic pop
33090 #elif defined(__GNUC__)
33091 #pragma GCC diagnostic pop
33092 #endif
33093