Repository navigation
Expand file tree
/
Copy pathgltf.py
More file actions
850 lines (775 loc) · 36.5 KB
/
Copy pathgltf.py
File metadata and controls
850 lines (775 loc) · 36.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
#!/usr/bin/env python3
"""Format-neutral glTF 2.0 binary (.glb) writer and reader.
Borrowed from the Xenosaga Episode II kit, Xenosaga2PythonExtractor/gltf.py
(same author, MIT), 2026-11-20. Changed for Episode III: `add_material`
takes `unlit=True`, which writes the KHR_materials_unlit extension (and
lists it in `extensionsUsed`) for the field-map meshes, whose batches
carry baked vertex colours and no vertex normals; `self_test()` returns 0;
`add_commands()` registers `glb-info`. Everything else is the XS2 code.
2026-11-21: the XS2 animation half (`pack_glb`, `extend_skin`,
`append_animations`, `sample_animation`, `validate`, and the `overrides`
argument of `node_world_matrices` / `skinned_positions`) taken over
unchanged from the same XS2 module, with its self-test checks, for
xap.py (Episode III motion).
Lineage: the buffer-view/accessor bookkeeping, the GLB container packing
and the matrix helpers (`matmul`, `invert_rigid`, `quat_from_matrix`) are
lifted from the Xenosaga Episode I kit, `Xenosaga1PythonExtractor/lex.py`
(`to_glb`, `_matmul`, `_invert_rigid`, `_quat_from_matrix`; same author,
MIT), 2026-11-10. There they were welded to the `.lex` structures; here
they take plain numpy arrays, so any mesh decoder can use them.
Conventions used by this module:
* Matrices given to the builder are 4x4 in **column-vector** form
(`v' = M @ v`, translation in the last column), the glTF convention.
Game files that store row-vector matrices (translation in the last
row) pass `M.T`.
* Triangles are counter-clockwise front faces.
* UV (0, 0) is the top-left texel, as in glTF and on the PS2 GS.
python gltf.py --self-test
python gltf.py FILE.glb # print a summary of a .glb
"""
import json
import math
import struct
import sys
import numpy as np
__all__ = ["GlbBuilder", "read_glb", "accessor_array", "matmul",
"invert_rigid", "quat_from_matrix", "trs_from_matrix",
"skinned_positions", "node_world_matrices", "pack_glb",
"extend_skin", "append_animations", "sample_animation",
"validate", "self_test"]
FLOAT, USHORT, UINT, UBYTE = 5126, 5123, 5125, 5121
ARRAY_BUFFER, ELEMENT_ARRAY_BUFFER = 34962, 34963
REPEAT, CLAMP_TO_EDGE, MIRRORED_REPEAT = 10497, 33071, 33648
_NCOMP = {"SCALAR": 1, "VEC2": 2, "VEC3": 3, "VEC4": 4, "MAT4": 16}
_DTYPE = {FLOAT: "<f4", USHORT: "<u2", UINT: "<u4", UBYTE: "u1"}
# ---------------------------------------------------------------- matrices
def matmul(a, b):
"""4x4 product of two nested-list matrices (lifted from lex.py)."""
return [[sum(a[i][k] * b[k][j] for k in range(4)) for j in range(4)]
for i in range(4)]
def invert_rigid(m):
"""Inverse of a column-vector rotation+translation matrix (lex.py)."""
r = [[m[j][i] for j in range(3)] for i in range(3)]
t = [m[0][3], m[1][3], m[2][3]]
nt = [-sum(r[i][k] * t[k] for k in range(3)) for i in range(3)]
return [[r[0][0], r[0][1], r[0][2], nt[0]],
[r[1][0], r[1][1], r[1][2], nt[1]],
[r[2][0], r[2][1], r[2][2], nt[2]],
[0.0, 0.0, 0.0, 1.0]]
def quat_from_matrix(m):
"""(x, y, z, w) from the 3x3 rotation of a column-vector matrix
(lifted from lex.py)."""
t = m[0][0] + m[1][1] + m[2][2]
if t > 0:
s = math.sqrt(t + 1.0) * 2
q = ((m[2][1] - m[1][2]) / s, (m[0][2] - m[2][0]) / s,
(m[1][0] - m[0][1]) / s, 0.25 * s)
elif m[0][0] > m[1][1] and m[0][0] > m[2][2]:
s = math.sqrt(1.0 + m[0][0] - m[1][1] - m[2][2]) * 2
q = (0.25 * s, (m[0][1] + m[1][0]) / s, (m[0][2] + m[2][0]) / s,
(m[2][1] - m[1][2]) / s)
elif m[1][1] > m[2][2]:
s = math.sqrt(1.0 + m[1][1] - m[0][0] - m[2][2]) * 2
q = ((m[0][1] + m[1][0]) / s, 0.25 * s, (m[1][2] + m[2][1]) / s,
(m[0][2] - m[2][0]) / s)
else:
s = math.sqrt(1.0 + m[2][2] - m[0][0] - m[1][1]) * 2
q = ((m[0][2] + m[2][0]) / s, (m[1][2] + m[2][1]) / s, 0.25 * s,
(m[1][0] - m[0][1]) / s)
n = math.sqrt(sum(c * c for c in q)) or 1.0
return tuple(c / n for c in q)
def trs_from_matrix(m):
"""(translation, quaternion xyzw, scale) of a column-vector matrix
without shear. A mirrored matrix gets a negative X scale."""
m = np.asarray(m, dtype=np.float64)
t = m[:3, 3]
s = np.linalg.norm(m[:3, :3], axis=0)
if np.linalg.det(m[:3, :3]) < 0:
s[0] = -s[0]
r = m[:3, :3] / np.where(s == 0, 1.0, s)
q = quat_from_matrix(r.tolist())
return [float(x) for x in t], [float(x) for x in q], [float(x) for x in s]
def _quat_matrix(q):
x, y, z, w = q
return np.array([
[1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w)],
[2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w)],
[2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)]])
# ----------------------------------------------------------------- builder
class GlbBuilder(object):
"""Collects buffers, meshes, materials, nodes and one optional skin,
then serialises a .glb."""
def __init__(self, generator="gltf.py"):
self.generator = generator
self.bin = bytearray()
self.views = []
self.accessors = []
self.images = []
self.samplers = []
self.textures = []
self.materials = []
self.meshes = []
self.nodes = []
self.skins = []
self.scene_nodes = []
self.extras = {}
self.extensions_used = []
# -- lifted from lex.py to_glb ------------------------------------
def add_view(self, blob, target=None, stride=None):
while len(self.bin) % 4:
self.bin.append(0)
v = {"buffer": 0, "byteOffset": len(self.bin),
"byteLength": len(blob)}
if target is not None:
v["target"] = target
if stride is not None:
v["byteStride"] = stride
self.views.append(v)
self.bin.extend(blob)
return len(self.views) - 1
def add_accessor(self, view, ctype, count, atype, mn=None, mx=None,
normalized=False):
acc = {"bufferView": view, "componentType": ctype, "count": count,
"type": atype}
if mn is not None:
acc["min"], acc["max"] = list(mn), list(mx)
if normalized:
acc["normalized"] = True
self.accessors.append(acc)
return len(self.accessors) - 1
# -- arrays ---------------------------------------------------------
def add_array(self, arr, ctype, atype, target=ARRAY_BUFFER, minmax=False,
normalized=False):
a = np.ascontiguousarray(arr, dtype=_DTYPE[ctype])
n = _NCOMP[atype]
a = a.reshape(-1, n) if n > 1 else a.reshape(-1)
view = self.add_view(a.tobytes(), target)
mn = mx = None
if minmax and len(a):
mn = [float(x) for x in np.atleast_1d(a.min(axis=0))]
mx = [float(x) for x in np.atleast_1d(a.max(axis=0))]
return self.add_accessor(view, ctype, len(a), atype, mn, mx,
normalized)
# -- textures and materials ---------------------------------------
def add_image(self, png, name=None):
img = {"bufferView": self.add_view(png), "mimeType": "image/png"}
if name:
img["name"] = name
self.images.append(img)
return len(self.images) - 1
def add_texture(self, image, wrap_s=REPEAT, wrap_t=REPEAT, nearest=False):
s = {"magFilter": 9728 if nearest else 9729,
"minFilter": 9728 if nearest else 9987,
"wrapS": wrap_s, "wrapT": wrap_t}
if s not in self.samplers:
self.samplers.append(s)
self.textures.append({"sampler": self.samplers.index(s),
"source": image})
return len(self.textures) - 1
def add_material(self, name, texture=None, alpha_mode="OPAQUE",
alpha_cutoff=0.5, double_sided=True,
base_color=(1.0, 1.0, 1.0, 1.0), extras=None,
unlit=False):
pbr = {"metallicFactor": 0.0, "roughnessFactor": 0.9}
if tuple(base_color) != (1.0, 1.0, 1.0, 1.0):
pbr["baseColorFactor"] = [float(c) for c in base_color]
if texture is not None:
pbr["baseColorTexture"] = {"index": texture}
m = {"name": name, "pbrMetallicRoughness": pbr,
"doubleSided": bool(double_sided)}
if alpha_mode != "OPAQUE":
m["alphaMode"] = alpha_mode
if alpha_mode == "MASK":
m["alphaCutoff"] = alpha_cutoff
if extras:
m["extras"] = extras
if unlit:
m["extensions"] = {"KHR_materials_unlit": {}}
if "KHR_materials_unlit" not in self.extensions_used:
self.extensions_used.append("KHR_materials_unlit")
self.materials.append(m)
return len(self.materials) - 1
# -- geometry -------------------------------------------------------
def add_mesh(self, name, primitives):
"""primitives: dicts with `positions` (n,3) and `indices` (m,)
and optionally `normals` (n,3), `uvs` (n,2), `colors` (n,4 floats
0..1), `joints` (n,4 ints), `weights` (n,4), `material`."""
out = []
for p in primitives:
pos = np.asarray(p["positions"], dtype=np.float32)
n = len(pos)
idx = np.asarray(p["indices"], dtype=np.uint32).reshape(-1)
if len(idx) % 3 or (len(idx) and int(idx.max()) >= n):
raise ValueError("bad triangle index list")
attrs = {"POSITION": self.add_array(pos, FLOAT, "VEC3",
minmax=True)}
if p.get("normals") is not None:
attrs["NORMAL"] = self.add_array(p["normals"], FLOAT, "VEC3")
if p.get("uvs") is not None:
attrs["TEXCOORD_0"] = self.add_array(p["uvs"], FLOAT, "VEC2")
if p.get("colors") is not None:
attrs["COLOR_0"] = self.add_array(p["colors"], FLOAT, "VEC4")
if p.get("joints") is not None:
attrs["JOINTS_0"] = self.add_array(p["joints"], USHORT, "VEC4")
attrs["WEIGHTS_0"] = self.add_array(p["weights"], FLOAT,
"VEC4")
if n < 65536:
ia = self.add_array(idx, USHORT, "SCALAR",
ELEMENT_ARRAY_BUFFER)
else:
ia = self.add_array(idx, UINT, "SCALAR", ELEMENT_ARRAY_BUFFER)
prim = {"attributes": attrs, "indices": ia, "mode": 4}
if p.get("material") is not None:
prim["material"] = p["material"]
out.append(prim)
self.meshes.append({"name": name, "primitives": out})
return len(self.meshes) - 1
def add_node(self, name, mesh=None, skin=None, matrix=None,
translation=None, rotation=None, scale=None, children=None,
extras=None, root=False):
nd = {"name": name}
if mesh is not None:
nd["mesh"] = mesh
if skin is not None:
nd["skin"] = skin
if matrix is not None:
m = np.asarray(matrix, dtype=np.float64)
if not np.allclose(m, np.eye(4), atol=0):
nd["matrix"] = [float(x) for x in m.T.reshape(-1)]
if translation is not None and any(translation):
nd["translation"] = [float(x) for x in translation]
if rotation is not None and tuple(rotation) != (0.0, 0.0, 0.0, 1.0):
nd["rotation"] = [float(x) for x in rotation]
if scale is not None and tuple(scale) != (1.0, 1.0, 1.0):
nd["scale"] = [float(x) for x in scale]
if children:
nd["children"] = list(children)
if extras:
nd["extras"] = extras
self.nodes.append(nd)
if root:
self.scene_nodes.append(len(self.nodes) - 1)
return len(self.nodes) - 1
def add_child(self, parent, child):
self.nodes[parent].setdefault("children", []).append(child)
def add_skin(self, name, joint_nodes, inverse_bind, skeleton=None):
"""inverse_bind: (k,4,4) column-vector matrices, one per joint."""
ibm = np.asarray(inverse_bind, dtype=np.float32).reshape(-1, 4, 4)
if len(ibm) != len(joint_nodes):
raise ValueError("one inverse bind matrix per joint")
# glTF requires the IBM bottom row to be exactly (0,0,0,1); the
# mesh tables and the inverses computed from them are affine but
# carry float noise there (-3.6e-24 ... 1.1e-16), which the
# Khronos validator rejects as ACCESSOR_INVALID_IBM.
ibm = ibm.copy()
ibm[:, 3, :] = (0, 0, 0, 1)
# glTF stores matrices column-major
acc = self.add_array(ibm.transpose(0, 2, 1).reshape(-1, 16), FLOAT,
"MAT4", target=None)
s = {"name": name, "joints": list(joint_nodes),
"inverseBindMatrices": acc}
if skeleton is not None:
s["skeleton"] = skeleton
self.skins.append(s)
return len(self.skins) - 1
# -- output (container packing lifted from lex.py to_glb) ---------
def to_bytes(self, scene_name="scene"):
g = {"asset": {"version": "2.0", "generator": self.generator},
"scene": 0,
"scenes": [{"name": scene_name, "nodes": self.scene_nodes}],
"nodes": self.nodes, "meshes": self.meshes,
"buffers": [{"byteLength": (len(self.bin) + 3) & ~3}],
"bufferViews": self.views, "accessors": self.accessors}
if self.materials:
g["materials"] = self.materials
if self.images:
g["images"], g["samplers"] = self.images, self.samplers
g["textures"] = self.textures
if self.skins:
g["skins"] = self.skins
if self.extras:
g["extras"] = self.extras
if self.extensions_used:
g["extensionsUsed"] = list(self.extensions_used)
js = json.dumps(g, separators=(",", ":")).encode()
while len(js) % 4:
js += b" "
binc = bytearray(self.bin)
while len(binc) % 4:
binc.append(0)
total = 12 + 8 + len(js) + 8 + len(binc)
return (struct.pack("<4sII", b"glTF", 2, total)
+ struct.pack("<I4s", len(js), b"JSON") + js
+ struct.pack("<I4s", len(binc), b"BIN\0") + bytes(binc))
# ------------------------------------------------------------------ reader
def read_glb(data):
"""(json dict, binary chunk) of a .glb."""
magic, ver, total = struct.unpack_from("<4sII", data, 0)
if magic != b"glTF" or ver != 2 or total != len(data):
raise ValueError("not a glTF 2 binary")
n, tag = struct.unpack_from("<I4s", data, 12)
if tag != b"JSON":
raise ValueError("first chunk is not JSON")
js = json.loads(data[20:20 + n].decode())
p = 20 + n
n2, tag2 = struct.unpack_from("<I4s", data, p)
if tag2 != b"BIN\0":
raise ValueError("second chunk is not BIN")
return js, data[p + 8:p + 8 + n2]
def accessor_array(js, binc, index):
a = js["accessors"][index]
v = js["bufferViews"][a["bufferView"]]
n = _NCOMP[a["type"]]
arr = np.frombuffer(binc, dtype=_DTYPE[a["componentType"]],
count=a["count"] * n, offset=v.get("byteOffset", 0))
return arr.reshape(-1, n) if n > 1 else arr
def node_world_matrices(js, overrides=None):
"""Column-vector world matrix of every node. `overrides`: {node:
{"translation"|"rotation"|"scale": value}} as `sample_animation`
returns, replacing those parts of the node's local TRS."""
nodes = js["nodes"]
local = []
overrides = overrides or {}
for i, nd in enumerate(nodes):
ov = overrides.get(i)
if ov:
nd = dict(nd, **ov)
nd.pop("matrix", None)
if "matrix" in nd:
m = np.array(nd["matrix"], dtype=np.float64).reshape(4, 4).T
else:
m = np.eye(4)
m[:3, :3] = _quat_matrix(nd.get("rotation", (0, 0, 0, 1))) * \
np.array(nd.get("scale", (1, 1, 1)), dtype=np.float64)
m[:3, 3] = nd.get("translation", (0, 0, 0))
local.append(m)
parent = {}
for i, nd in enumerate(nodes):
for c in nd.get("children", ()):
parent[c] = i
world = [None] * len(nodes)
def w(i):
if world[i] is None:
world[i] = local[i] if i not in parent else w(parent[i]) @ local[i]
return world[i]
for i in range(len(nodes)):
w(i)
return world
def skinned_positions(js, binc, node_index, overrides=None):
"""Positions of a skinned mesh node evaluated the glTF way:
sum_i w_i * jointWorld_i * inverseBind_i * p, in the file's rest pose
or with node `overrides` (an animation sample). Returns a list of
(static positions, skinned positions), one pair per primitive."""
nd = js["nodes"][node_index]
skin = js["skins"][nd["skin"]]
world = node_world_matrices(js, overrides)
ibm = accessor_array(js, binc, skin["inverseBindMatrices"])
ibm = ibm.reshape(-1, 4, 4).transpose(0, 2, 1).astype(np.float64)
jm = np.stack([world[j] @ ibm[k] for k, j in enumerate(skin["joints"])])
out = []
for prim in js["meshes"][nd["mesh"]]["primitives"]:
at = prim["attributes"]
p = accessor_array(js, binc, at["POSITION"]).astype(np.float64)
j = accessor_array(js, binc, at["JOINTS_0"]).astype(np.int64)
wt = accessor_array(js, binc, at["WEIGHTS_0"]).astype(np.float64)
ph = np.concatenate([p, np.ones((len(p), 1))], axis=1)
acc = np.zeros((len(p), 4))
for k in range(4):
acc += wt[:, k:k + 1] * np.einsum("nij,nj->ni", jm[j[:, k]], ph)
out.append((p, acc[:, :3]))
return out
# -------------------------------------------------------------- animation
def pack_glb(js, binc):
"""Serialise a glTF dict and its binary chunk as a .glb."""
binc = bytearray(binc)
while len(binc) % 4:
binc.append(0)
js["buffers"] = [dict(js.get("buffers", [{}])[0], byteLength=len(binc))]
blob = json.dumps(js, separators=(",", ":")).encode()
while len(blob) % 4:
blob += b" "
total = 12 + 8 + len(blob) + 8 + len(binc)
return (struct.pack("<4sII", b"glTF", 2, total)
+ struct.pack("<I4s", len(blob), b"JSON") + blob
+ struct.pack("<I4s", len(binc), b"BIN\0") + bytes(binc))
_PATH_TYPE = {"translation": "VEC3", "rotation": "VEC4", "scale": "VEC3"}
def extend_skin(glb_bytes, skin_index, nodes):
"""Add `nodes` to a skin's joint list (after the existing joints, so
vertex joint indices keep their meaning), each with the inverse of its
rest world matrix as inverse bind matrix. No vertex refers to them;
importers such as Blender then make a bone of every one. The rewritten
list has every matrix's last row exactly (0, 0, 0, 1), as glTF asks
(an inverse computed in floating point can leave 1e-17 there)."""
js, binc = read_glb(glb_bytes)
skin = js["skins"][skin_index]
nodes = [n for n in nodes if n not in skin["joints"]]
if not nodes:
return glb_bytes
world = node_world_matrices(js)
old = accessor_array(js, binc, skin["inverseBindMatrices"]).reshape(
-1, 4, 4).astype(np.float64) # column-major storage
new = np.stack([np.linalg.inv(world[n]) for n in nodes])
new[:, 3, :] = (0.0, 0.0, 0.0, 1.0) # exactly affine (glTF requires it)
new = new.transpose(0, 2, 1)
ibm = np.concatenate([old, new])
ibm[:, :3, 3] = 0.0 # stored transposed: the last
ibm[:, 3, 3] = 1.0 # row of every matrix, exactly
ibm = ibm.astype("<f4")
binc = bytearray(binc)
while len(binc) % 4:
binc.append(0)
# the skin's accessor and its buffer view now cover the longer list,
# appended to the buffer (the old bytes stay, unreferenced)
acc = js["accessors"][skin["inverseBindMatrices"]]
view = {"buffer": 0, "byteOffset": len(binc), "byteLength": ibm.nbytes}
shared = sum(a.get("bufferView") == acc["bufferView"]
for a in js["accessors"]) > 1
if shared:
js["bufferViews"].append(view)
acc["bufferView"] = len(js["bufferViews"]) - 1
else:
js["bufferViews"][acc["bufferView"]] = view
binc.extend(ibm.tobytes())
acc.pop("byteOffset", None)
acc["count"] = len(ibm)
skin["joints"] = list(skin["joints"]) + list(nodes)
return pack_glb(js, binc)
def append_animations(glb_bytes, animations):
"""Append animations to a .glb and return the new bytes.
animations: [{"name", "channels": [(node, path, times (k,), values
(k,c), interpolation)], "extras"}]. Each array gets its own buffer
view at the end of the BIN chunk; inputs carry min/max."""
js, binc = read_glb(glb_bytes)
binc = bytearray(binc)
views = js.setdefault("bufferViews", [])
accs = js.setdefault("accessors", [])
def add(arr, atype, minmax):
a = np.ascontiguousarray(arr, dtype="<f4")
while len(binc) % 4:
binc.append(0)
views.append({"buffer": 0, "byteOffset": len(binc),
"byteLength": a.nbytes})
binc.extend(a.tobytes())
acc = {"bufferView": len(views) - 1, "componentType": FLOAT,
"count": int(a.shape[0]), "type": atype}
if minmax:
acc["min"] = [float(a.min())]
acc["max"] = [float(a.max())]
accs.append(acc)
return len(accs) - 1
out = js.setdefault("animations", [])
for an in animations:
samplers, channels = [], []
for node, path, times, values, interp in an["channels"]:
atype = _PATH_TYPE[path]
t = np.asarray(times, dtype=np.float64).reshape(-1)
v = np.asarray(values, dtype=np.float64).reshape(
len(t), _NCOMP[atype])
samplers.append({"input": add(t, "SCALAR", True),
"output": add(v, atype, False),
"interpolation": interp})
channels.append({"sampler": len(samplers) - 1,
"target": {"node": int(node), "path": path}})
a = {"name": an["name"], "samplers": samplers, "channels": channels}
if an.get("extras"):
a["extras"] = an["extras"]
out.append(a)
return pack_glb(js, binc)
def _slerp(q0, q1, u):
q0 = np.asarray(q0, dtype=np.float64)
q1 = np.asarray(q1, dtype=np.float64)
d = float(np.dot(q0, q1))
if d < 0:
q1, d = -q1, -d
if d > 0.9995:
q = q0 + u * (q1 - q0)
else:
th = math.acos(d)
q = (math.sin((1 - u) * th) * q0 + math.sin(u * th) * q1) / \
math.sin(th)
return q / np.linalg.norm(q)
def sample_animation(js, binc, anim_index, t):
"""Local TRS overrides {node: {path: value}} of one animation at time
t (seconds): linear for translation / scale, slerp for rotation,
clamped at both ends (glTF LINEAR semantics)."""
an = js["animations"][anim_index]
out = {}
for ch in an["channels"]:
smp = an["samplers"][ch["sampler"]]
tm = accessor_array(js, binc, smp["input"]).astype(np.float64)
v = accessor_array(js, binc, smp["output"]).astype(np.float64)
v = v.reshape(len(tm), -1)
path = ch["target"]["path"]
if t <= tm[0]:
val = v[0]
elif t >= tm[-1]:
val = v[-1]
else:
k = int(np.searchsorted(tm, t, side="right")) - 1
u = (t - tm[k]) / (tm[k + 1] - tm[k])
if path == "rotation":
val = _slerp(v[k], v[k + 1], u)
else:
val = v[k] + u * (v[k + 1] - v[k])
out.setdefault(ch["target"]["node"], {})[path] = \
[float(c) for c in val]
return out
_CSIZE = {FLOAT: 4, USHORT: 2, UINT: 4, UBYTE: 1}
def validate(js, binc):
"""Structural problems of a glTF (buffers, accessors, animations), as
a list of strings; [] when none are found."""
probs = []
views = js.get("bufferViews", [])
accs = js.get("accessors", [])
for i, v in enumerate(views):
off, ln = v.get("byteOffset", 0), v.get("byteLength", 0)
if off % 4:
probs.append("bufferView %d offset %d not 4-aligned" % (i, off))
if off + ln > len(binc):
probs.append("bufferView %d runs past the buffer" % i)
for i, a in enumerate(accs):
if a.get("bufferView") is None or a["bufferView"] >= len(views):
probs.append("accessor %d: no buffer view" % i)
continue
v = views[a["bufferView"]]
if a.get("componentType") not in _CSIZE or a.get("type") not in _NCOMP:
probs.append("accessor %d: unknown type" % i)
continue
es = _CSIZE[a["componentType"]] * _NCOMP[a["type"]]
stride = v.get("byteStride", es)
aoff = a.get("byteOffset", 0)
need = aoff + (stride * (a["count"] - 1) + es if a["count"] else 0)
if aoff % _CSIZE[a["componentType"]]:
probs.append("accessor %d offset misaligned" % i)
if need > v.get("byteLength", 0):
probs.append("accessor %d runs past its buffer view" % i)
nn = len(js.get("nodes", []))
for ai, an in enumerate(js.get("animations", [])):
smps = an.get("samplers", [])
seen = set()
for ch in an.get("channels", []):
tg = ch.get("target", {})
node, path = tg.get("node"), tg.get("path")
where = "animation %d (%s)" % (ai, an.get("name", ""))
if node is None or not 0 <= node < nn:
probs.append("%s: channel targets missing node %r"
% (where, node))
if path not in _PATH_TYPE:
probs.append("%s: path %r" % (where, path))
continue
if (node, path) in seen:
probs.append("%s: two channels for node %r %s"
% (where, node, path))
seen.add((node, path))
if not 0 <= ch.get("sampler", -1) < len(smps):
probs.append("%s: channel without sampler" % where)
continue
smp = smps[ch["sampler"]]
try:
ia, oa = accs[smp["input"]], accs[smp["output"]]
except (KeyError, IndexError):
probs.append("%s: sampler accessors missing" % where)
continue
if ia["componentType"] != FLOAT or ia["type"] != "SCALAR":
probs.append("%s: input not a float scalar" % where)
continue
if "min" not in ia or "max" not in ia:
probs.append("%s: input without min/max" % where)
if smp.get("interpolation", "LINEAR") not in ("LINEAR", "STEP",
"CUBICSPLINE"):
probs.append("%s: interpolation %r" % (where,
smp["interpolation"]))
if oa["count"] != ia["count"]:
probs.append("%s: %d outputs for %d inputs"
% (where, oa["count"], ia["count"]))
if oa["componentType"] != FLOAT or oa["type"] != _PATH_TYPE[path]:
probs.append("%s: %s output is %s" % (where, path, oa["type"]))
continue
try:
tm = accessor_array(js, binc, smp["input"])
val = accessor_array(js, binc, smp["output"])
except ValueError:
probs.append("%s: accessor data unreadable" % where)
continue
if not np.all(np.isfinite(tm)) or not np.all(np.isfinite(val)):
probs.append("%s: NaN or Inf in %s" % (where, path))
continue
if len(tm) > 1 and not np.all(np.diff(tm) > 0):
probs.append("%s: %s times not strictly increasing"
% (where, path))
if "min" in ia and len(tm) and (
abs(ia["min"][0] - float(tm.min())) > 0 or
abs(ia["max"][0] - float(tm.max())) > 0):
probs.append("%s: input min/max do not match the data" % where)
if path == "rotation" and len(val):
dev = float(np.abs(np.linalg.norm(val.astype(np.float64),
axis=1) - 1).max())
if dev >= 1e-5:
probs.append("%s: rotation not unit (|q| off by %.3g)"
% (where, dev))
return probs
# --------------------------------------------------------------- self-test
def self_test():
b = GlbBuilder("gltf.py self-test")
png = (b"\x89PNG\r\n\x1a\n" + b"\0" * 5) # opaque blob, odd length
tex = b.add_texture(b.add_image(png, "t"))
mat = b.add_material("m", tex, alpha_mode="MASK")
pos = np.array([[0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 2, 0]], "f4")
# two joints: j0 at the origin, j1 a child translated +1 in y and
# rotated 90 degrees about z; bind matrices are their inverses
j0 = np.eye(4)
j1 = np.eye(4)
j1[:3, :3] = [[0, -1, 0], [1, 0, 0], [0, 0, 1]]
j1[:3, 3] = [0, 1, 0]
joints = np.array([[0, 0, 0, 0], [0, 0, 0, 0], [0, 1, 0, 0],
[1, 0, 0, 0]], "u2")
weights = np.array([[1, 0, 0, 0], [1, 0, 0, 0], [.5, .5, 0, 0],
[1, 0, 0, 0]], "f4")
mesh = b.add_mesh("tri", [dict(positions=pos, normals=np.tile(
[0, 0, 1.0], (4, 1)), uvs=pos[:, :2], colors=np.ones((4, 4)),
joints=joints, weights=weights, indices=[0, 1, 2, 0, 2, 3],
material=mat)])
t, q, s = trs_from_matrix(j1)
n1 = b.add_node("j1", translation=t, rotation=q, scale=s)
n0 = b.add_node("j0", children=[n1], root=True)
noisy = np.linalg.inv(j1)
noisy[3, :3] = (-3.6e-24, 1.1e-16, 0) # float noise from inverses
skin = b.add_skin("skin", [n0, n1], [np.linalg.inv(j0), noisy],
skeleton=n0)
mn = b.add_node("mesh", mesh=mesh, skin=skin, root=True)
blob = b.to_bytes("test")
js, binc = read_glb(blob)
assert len(blob) % 4 == 0 and js["buffers"][0]["byteLength"] == len(binc)
for v in js["bufferViews"]:
assert v["byteOffset"] % 4 == 0
assert v["byteOffset"] + v["byteLength"] <= len(binc)
prim = js["meshes"][0]["primitives"][0]
assert np.array_equal(accessor_array(js, binc,
prim["attributes"]["POSITION"]), pos)
assert list(accessor_array(js, binc, prim["indices"])) == [0, 1, 2, 0, 2,
3]
a = js["accessors"][prim["attributes"]["POSITION"]]
assert a["min"] == [0, 0, 0] and a["max"] == [1, 2, 0]
ibm = accessor_array(js, binc, js["skins"][0]["inverseBindMatrices"])
assert all(list(m[[3, 7, 11, 15]]) == [0, 0, 0, 1] for m in ibm), \
"IBM bottom row must be exactly 0,0,0,1"
# rest pose: skinning with inverse binds must return the static mesh
(p, sk), = skinned_positions(js, binc, mn)
assert np.abs(p - sk).max() < 1e-6, np.abs(p - sk).max()
# quaternion round trip, including a 180 degree turn
for m in (j1[:3, :3], np.diag([1.0, -1.0, -1.0]),
np.diag([-1.0, -1.0, 1.0])):
assert np.abs(_quat_matrix(quat_from_matrix(m.tolist())) - m).max() \
< 1e-9
r = [[0, -1, 0, 3], [1, 0, 0, 4], [0, 0, 1, 5], [0, 0, 0, 1]]
assert np.abs(np.array(matmul(r, invert_rigid(r))) - np.eye(4)).max() \
< 1e-12
try:
b.add_mesh("bad", [dict(positions=pos, indices=[0, 1, 9])])
except ValueError:
pass
else:
raise AssertionError("accepted an out-of-range index")
# animation: append, read back, validate, sample
times = np.array([0.0, 0.5, 1.0])
qa = np.array(quat_from_matrix(np.eye(3).tolist()))
qb = np.array(quat_from_matrix(j1[:3, :3].tolist()))
qc = np.array([0.0, 0.0, 0.0, 1.0])
rots = np.stack([qa, qb, qc])
trans = np.array([[0, 1, 0], [0, 2, 0], [0, 1, 0.0]])
blob2 = append_animations(blob, [{
"name": "a", "extras": {"k": 1},
"channels": [(n1, "rotation", times, rots, "LINEAR"),
(n1, "translation", times, trans, "LINEAR"),
(n0, "scale", times[:1], [[1.0, 1.0, 1.0]], "LINEAR")]}])
js2, binc2 = read_glb(blob2)
assert validate(js2, binc2) == [], validate(js2, binc2)
assert validate(js, binc) == []
assert js2["meshes"] == js["meshes"] and js2["animations"][0]["extras"] \
== {"k": 1}
assert np.array_equal(accessor_array(js2, binc2, prim["indices"]),
accessor_array(js, binc, prim["indices"]))
ov = sample_animation(js2, binc2, 0, 0.25)
# hand slerp halfway between identity and a 90-degree z turn: 45 deg
want = [0.0, 0.0, math.sin(math.pi / 8), math.cos(math.pi / 8)]
assert np.abs(np.array(ov[n1]["rotation"]) - want).max() < 1e-6, ov
assert np.allclose(ov[n1]["translation"], [0, 1.5, 0])
assert ov[n0]["scale"] == [1.0, 1.0, 1.0]
assert np.allclose(sample_animation(js2, binc2, 0, 9.0)[n1]["translation"],
[0, 1, 0])
w = node_world_matrices(js2, ov)
assert np.abs(w[n1][:3, :3] - _quat_matrix(want)).max() < 1e-6
sk = skinned_positions(js2, binc2, mn, ov)[0][1]
want3 = (w[n1] @ np.linalg.inv(j1) @ [0, 2, 0, 1.0])[:3] # vertex 3 on j1
assert np.abs(sk[3] - want3).max() < 1e-6
# a node added to the skin keeps every vertex where it was
n_extra = len(js2["nodes"])
js3 = json.loads(json.dumps(js2))
js3["nodes"].append({"name": "extra", "translation": [0, 0, 3.0]})
js3["nodes"][n1].setdefault("children", []).append(n_extra)
blob3 = extend_skin(pack_glb(js3, binc2), 0, [n_extra, n1])
js3, binc3 = read_glb(blob3)
assert js3["skins"][0]["joints"] == [n0, n1, n_extra]
assert validate(js3, binc3) == []
p3 = skinned_positions(js3, binc3, mn)[0]
assert np.abs(p3[0] - p3[1]).max() < 1e-6
ib = accessor_array(js3, binc3, js3["skins"][0]["inverseBindMatrices"])
w3 = node_world_matrices(js3)
assert np.abs(ib.reshape(-1, 4, 4)[2].T @ w3[n_extra] - np.eye(4)).max() \
< 1e-6
assert np.all(ib.reshape(-1, 4, 4)[2][:, 3] == (0, 0, 0, 1))
# damage is reported
bad = json.loads(json.dumps(js2))
smp = bad["animations"][0]["samplers"][0]
bb = bytearray(binc2)
ti = bad["bufferViews"][bad["accessors"][smp["input"]]["bufferView"]]
struct.pack_into("<f", bb, ti["byteOffset"] + 4, 2.0) # 0, 2, 1
qv = bad["bufferViews"][bad["accessors"][smp["output"]]["bufferView"]]
struct.pack_into("<4f", bb, qv["byteOffset"], 0.0, 0.0, 0.0, 2.0)
bad["animations"][0]["channels"].append(
dict(bad["animations"][0]["channels"][1]))
pr = validate(bad, bytes(bb))
assert any("not strictly increasing" in p for p in pr), pr
assert any("not unit" in p for p in pr), pr
assert any("two channels" in p for p in pr), pr
b2 = GlbBuilder("gltf.py self-test (unlit)")
um = b2.add_material("u", unlit=True)
b2.add_node("m", mesh=b2.add_mesh("t", [dict(positions=pos[:3],
indices=[0, 1, 2],
material=um)]), root=True)
js2, _ = read_glb(b2.to_bytes())
assert js2["extensionsUsed"] == ["KHR_materials_unlit"]
assert js2["materials"][0]["extensions"] == {"KHR_materials_unlit": {}}
assert "NORMAL" not in js2["meshes"][0]["primitives"][0]["attributes"]
assert "extensionsUsed" not in js
print("gltf self-test ok (writer, reader, skinning, quaternions, "
"index check, exact IBM bottom row, unlit extension, animations)")
return 0
def _cmd_glb_info(a):
return main([a.file])
def add_commands(subparsers):
"""Register `glb-info FILE.glb` (summary of a written model)."""
p = subparsers.add_parser("glb-info", help="Summarise a .glb file "
"(nodes, meshes, materials, triangles)")
p.add_argument("file")
p.set_defaults(func=_cmd_glb_info)
return p
def main(argv=None):
argv = sys.argv[1:] if argv is None else argv
if not argv or argv[0] == "--self-test":
return self_test()
with open(argv[0], "rb") as f:
js, binc = read_glb(f.read())
nv = nt = 0
for m in js.get("meshes", ()):
for p in m["primitives"]:
nv += js["accessors"][p["attributes"]["POSITION"]]["count"]
nt += js["accessors"][p["indices"]]["count"] // 3
print("%s: %d nodes, %d meshes, %d materials, %d images, %d skins, "
"%d vertices, %d triangles, %d bytes of buffers"
% (argv[0], len(js.get("nodes", ())), len(js.get("meshes", ())),
len(js.get("materials", ())), len(js.get("images", ())),
len(js.get("skins", ())), nv, nt, len(binc)))
return 0
if __name__ == "__main__":
sys.exit(main())