{{ message }}
Repository navigation
Expand file tree
/
Copy pathnodes_mesh_postprocess.py
More file actions
3165 lines (2829 loc) · 148 KB
/
Copy pathnodes_mesh_postprocess.py
File metadata and controls
3165 lines (2829 loc) · 148 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
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import torch
import numpy as np
import math
from typing_extensions import override
from comfy_api.latest import ComfyExtension, IO, Types
import copy
import comfy.utils
import comfy.model_management
from server import PromptServer
from comfy_extras.mesh3d.postprocess.qem_decimate import QEMConfig, qem_decimate_simplify, qem_cluster_decimate, _compute_vertex_normals
from comfy_extras.mesh3d.postprocess.remesh import remesh_narrow_band_dc, _point_tri_closest
from comfy_extras.nodes_save_3d import get_mesh_batch_item, pack_variable_mesh_batch
from comfy_extras.mesh3d.uv_unwrap import mesh as _uv_mesh
from comfy_extras.mesh3d.uv_unwrap import segment as _uv_seg
from comfy_extras.mesh3d.uv_unwrap import parameterize as _uv_param
from comfy_extras.mesh3d.uv_unwrap import pack as _uv_pack
import logging
import time
from tqdm import tqdm
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import connected_components
from scipy.spatial import cKDTree
import scipy.ndimage as ndi
def _mesh_face_count(mesh):
if mesh.face_counts is not None:
return sum(int(count) for count in mesh.face_counts)
if isinstance(mesh.faces, list):
return sum(int(faces.shape[0]) for faces in mesh.faces)
return int(mesh.faces.numel() // 3)
def _prepare_gpu_mesh_processing(device, memory_required):
comfy.model_management.free_memory(
int(memory_required) + comfy.model_management.minimum_inference_memory(),
device,
)
def paint_mesh_with_voxels(mesh, voxel_coords, voxel_colors, resolution):
"""Paint a mesh using nearest-neighbor colors from a sparse voxel field."""
device = comfy.model_management.vae_offload_device()
origin = torch.tensor([-0.5, -0.5, -0.5], device=device)
voxel_size = 1.0 / resolution
voxel_pos = voxel_coords.to(device).float() * voxel_size + origin
verts = mesh.vertices.to(device).squeeze(0)
voxel_colors = voxel_colors.to(device)
voxel_pos_np = voxel_pos.cpu().numpy()
verts_np = verts.cpu().numpy()
tree = cKDTree(voxel_pos_np)
_, nearest_idx_np = tree.query(verts_np, k=1, workers=-1)
nearest_idx = torch.from_numpy(nearest_idx_np).long().to(voxel_colors.device)
v_colors = voxel_colors[nearest_idx]
# Voxel field may carry full PBR; vertex colors use only base_color RGB.
if v_colors.shape[-1] > 3:
v_colors = v_colors[:, :3]
srgb_colors = v_colors.clamp(0, 1)
# to Linear RGB (required for GLTF)
linear_colors = torch.pow(srgb_colors, 2.2)
final_colors = linear_colors.unsqueeze(0)
out_mesh = copy.deepcopy(mesh)
out_mesh.vertex_colors = final_colors
return out_mesh
def paint_mesh_default_colors(mesh):
out_mesh = copy.copy(mesh)
vertex_count = mesh.vertices.shape[1]
out_mesh.vertex_colors = mesh.vertices.new_zeros((1, vertex_count, 3))
return out_mesh
class PaintMesh(IO.ComfyNode):
@classmethod
def define_schema(cls):
return IO.Schema(
node_id="PaintMesh",
display_name="Paint Mesh",
category="3d/mesh",
description="Paints each mesh vertex with its nearest voxel color from the input voxel field.",
inputs=[
IO.Mesh.Input("mesh"),
IO.Voxel.Input("voxel_colors")
],
outputs=[
IO.Mesh.Output("mesh"),
]
)
@classmethod
def execute(cls, mesh, voxel_colors):
voxels = voxel_colors
coords = voxels.data
colors = voxels.voxel_colors
resolution = voxels.resolution
if coords.shape[0] == 0:
return IO.NodeOutput(paint_mesh_default_colors(mesh))
mesh_batch_size = mesh.vertices.shape[0]
if coords.shape[-1] == 4 and mesh_batch_size > 1:
batch_idx = coords[:, 0].long()
voxel_coords = coords[:, 1:]
mesh_batch_size = mesh.vertices.shape[0]
out_verts, out_faces, out_colors = [], [], []
for i in range(mesh_batch_size):
sel = batch_idx == i
item_coords = voxel_coords[sel]
item_colors = colors[sel]
item_vertices, item_faces, *_ = get_mesh_batch_item(mesh, i)
item_mesh = Types.MESH(vertices=item_vertices.unsqueeze(0), faces=item_faces.unsqueeze(0))
if item_coords.shape[0] == 0:
painted = paint_mesh_default_colors(item_mesh)
else:
painted = paint_mesh_with_voxels(item_mesh, item_coords, item_colors, resolution=resolution)
out_verts.append(painted.vertices.squeeze(0))
out_faces.append(painted.faces.squeeze(0))
out_colors.append(painted.vertex_colors.squeeze(0))
out_mesh = pack_variable_mesh_batch(out_verts, out_faces, out_colors)
return IO.NodeOutput(out_mesh)
if coords.shape[-1] == 4:
coords = coords[:, 1:]
out_mesh = paint_mesh_with_voxels(mesh, coords, colors, resolution=resolution)
return IO.NodeOutput(out_mesh)
def _rasterize_uv_barycentric(faces_np, uvs_np, texture_size):
"""Rasterize the mesh in UV space (tiled point-in-triangle, pure torch). Returns per-texel
face index [H,W], barycentric coords [H,W,3] and coverage mask [H,W], on the torch device.
Interpolate any per-vertex attribute from these with _interp_vertex_attr."""
dev = comfy.model_management.get_torch_device()
H = W = int(texture_size)
face_idx = torch.zeros((H, W), dtype=torch.long, device=dev)
bary = torch.zeros((H, W, 3), device=dev)
cov = torch.zeros((H, W), dtype=torch.bool, device=dev)
if faces_np.shape[0] == 0:
return face_idx, bary, cov
uvs = torch.from_numpy(np.ascontiguousarray(uvs_np, dtype=np.float32)).to(dev)
faces = torch.from_numpy(np.ascontiguousarray(faces_np).astype(np.int64)).to(dev)
# GL convention: window coord = uv * resolution, coverage tested at texel centre.
tri_uv = (uvs * float(W))[faces] # [F,3,2]
x0, y0 = tri_uv[:, 0, 0], tri_uv[:, 0, 1]
x1, y1 = tri_uv[:, 1, 0], tri_uv[:, 1, 1]
x2, y2 = tri_uv[:, 2, 0], tri_uv[:, 2, 1]
denom = (y1 - y2) * (x0 - x2) + (x2 - x1) * (y0 - y2)
nondegen = denom.abs() > 1e-20
xmin = torch.minimum(torch.minimum(x0, x1), x2).floor().clamp_(0, W - 1).long()
xmax = torch.maximum(torch.maximum(x0, x1), x2).ceil().clamp_(0, W - 1).long()
ymin = torch.minimum(torch.minimum(y0, y1), y2).floor().clamp_(0, H - 1).long()
ymax = torch.maximum(torch.maximum(y0, y1), y2).ceil().clamp_(0, H - 1).long()
# Tile so point-in-triangle only runs over the triangles whose bbox hits the tile.
TILE = 64
eps = 1e-6
for ty in range(0, H, TILE):
ty_end = min(ty + TILE, H)
for tx in range(0, W, TILE):
tx_end = min(tx + TILE, W)
tri_mask = (nondegen & (xmin < tx_end) & (xmax >= tx)
& (ymin < ty_end) & (ymax >= ty))
if not tri_mask.any():
continue
idx = torch.nonzero(tri_mask, as_tuple=True)[0]
ys = torch.arange(ty, ty_end, dtype=torch.float32, device=dev) + 0.5
xs = torch.arange(tx, tx_end, dtype=torch.float32, device=dev) + 0.5
yy, xx = torch.meshgrid(ys, xs, indexing="ij") # [th,tw]
sx0, sy0 = x0[idx][:, None, None], y0[idx][:, None, None]
sx1, sy1 = x1[idx][:, None, None], y1[idx][:, None, None]
sx2, sy2 = x2[idx][:, None, None], y2[idx][:, None, None]
sden = denom[idx][:, None, None]
b0 = ((sy1 - sy2) * (xx - sx2) + (sx2 - sx1) * (yy - sy2)) / sden
b1 = ((sy2 - sy0) * (xx - sx2) + (sx0 - sx2) * (yy - sy2)) / sden
b2 = 1.0 - b0 - b1
inside = (b0 >= -eps) & (b1 >= -eps) & (b2 >= -eps) # [K,th,tw]
if not inside.any():
continue
hit = inside.any(dim=0) # [th,tw]
sel = inside.int().argmax(dim=0) # [th,tw] first covering local tri
bsel = torch.stack([b0.gather(0, sel[None]).squeeze(0),
b1.gather(0, sel[None]).squeeze(0),
b2.gather(0, sel[None]).squeeze(0)], dim=-1) # [th,tw,3]
face_idx[ty:ty_end, tx:tx_end][hit] = idx[sel][hit] # slice is a view → writes through
bary[ty:ty_end, tx:tx_end][hit] = bsel[hit]
cov[ty:ty_end, tx:tx_end] |= hit
return face_idx, bary, cov
def _interp_vertex_attr(attr_v, faces, face_idx, bary, mask):
"""Interpolate a per-vertex attribute [N,C] into a [H,W,C] map via a rasterized
(face_idx, bary, mask). Uncovered texels stay zero."""
H, W = mask.shape
out = torch.zeros((H, W, attr_v.shape[1]), device=attr_v.device, dtype=attr_v.dtype)
if mask.any():
vtri = attr_v[faces[face_idx[mask]]] # [K,3,C]
out[mask] = (bary[mask][:, :, None] * vtri).sum(1)
return out
def _bake_position_map(verts_np, faces_np, uvs_np, texture_size):
"""Barycentric-interpolate a per-vertex vec3 (world position, or any vec3 e.g. normals)
at each covered texel. Returns (attr_map [H,W,3] float32, mask [H,W] bool)."""
dev = comfy.model_management.get_torch_device()
H = W = int(texture_size)
if faces_np.shape[0] == 0:
return np.zeros((H, W, 3), dtype=np.float32), np.zeros((H, W), dtype=bool)
face_idx, bary, mask = _rasterize_uv_barycentric(faces_np, uvs_np, texture_size)
verts = torch.from_numpy(np.ascontiguousarray(verts_np, dtype=np.float32)).to(dev)
faces = torch.from_numpy(np.ascontiguousarray(faces_np).astype(np.int64)).to(dev)
attr = _interp_vertex_attr(verts, faces, face_idx, bary, mask)
del face_idx, bary, verts, faces
return attr.cpu().numpy(), mask.cpu().numpy()
def _trilinear_sample_sparse(positions, voxel_coords_np, color_np, resolution):
"""Normalized trilinear over a SPARSE voxel field (only occupied corners of the 8,
renormalized; matches official o_voxel.to_glb but without dense-volume zero-bleed).
Returns (vals [K,C] float64, ok [K] bool); ok=False where no corner is occupied."""
R = int(resolution)
origin = -0.5
voxel_size = 1.0 / R
# Cell-CENTER convention: coord c sits at origin+(c+0.5)*voxel_size (matches
# official grid_sample_3d); the -0.5 puts integer gc on centres so the 8 corners
# bracket the query (omitting it bleeds colour at boundaries/thin features).
gc = (positions.astype(np.float64) - origin) / voxel_size - 0.5
base = np.floor(gc).astype(np.int64)
frac = gc - base
vc = voxel_coords_np.astype(np.int64)
occ_keys = (vc[:, 0] * R + vc[:, 1]) * R + vc[:, 2]
order = np.argsort(occ_keys)
occ_sorted = occ_keys[order]
K = positions.shape[0]
C = color_np.shape[1]
acc = np.zeros((K, C), dtype=np.float64)
wsum = np.zeros((K, 1), dtype=np.float64)
for dx in (0, 1):
wx = frac[:, 0] if dx else 1.0 - frac[:, 0]
for dy in (0, 1):
wy = frac[:, 1] if dy else 1.0 - frac[:, 1]
for dz in (0, 1):
wz = frac[:, 2] if dz else 1.0 - frac[:, 2]
cx = base[:, 0] + dx
cy = base[:, 1] + dy
cz = base[:, 2] + dz
inb = (cx >= 0) & (cx < R) & (cy >= 0) & (cy < R) & (cz >= 0) & (cz < R)
key = (cx * R + cy) * R + cz
ins = np.clip(np.searchsorted(occ_sorted, key), 0, len(occ_sorted) - 1)
matched = inb & (occ_sorted[ins] == key)
idx = order[ins] # garbage where !matched
w = np.where(matched, wx * wy * wz, 0.0)[:, None]
acc += w * color_np[idx] # w=0 cancels garbage rows
wsum += w
ok = wsum[:, 0] > 1e-8
vals = np.zeros((K, C), dtype=np.float64)
vals[ok] = acc[ok] / wsum[ok]
return vals, ok
def _trilinear_sample_sparse_gpu(positions, voxel_coords_np, color_np, resolution):
"""GPU port of `_trilinear_sample_sparse`. Returns (vals [K,C] float32, ok [K] bool)."""
dev = comfy.model_management.get_torch_device()
R = int(resolution)
origin = -0.5
voxel_size = 1.0 / R
index_dtype = torch.int32 if R ** 3 <= torch.iinfo(torch.int32).max else torch.int64
P = torch.from_numpy(np.ascontiguousarray(positions)).to(dev).float()
VC = torch.from_numpy(np.ascontiguousarray(voxel_coords_np)).to(device=dev, dtype=index_dtype)
col = torch.from_numpy(np.ascontiguousarray(color_np)).to(dev).float()
K, C = P.shape[0], col.shape[1]
M = VC.shape[0]
# Cell-CENTER convention (see NumPy path): -0.5 to bracket the query.
gc = (P - origin) / voxel_size - 0.5
base = torch.floor(gc).to(index_dtype)
frac = gc - base.float()
key = (VC[:, 0] * R + VC[:, 1]) * R + VC[:, 2]
skey, order = key.sort()
acc = torch.zeros((K, C), device=dev)
wsum = torch.zeros((K, 1), device=dev)
for dx in (0, 1):
wx = frac[:, 0] if dx else 1.0 - frac[:, 0]
for dy in (0, 1):
wy = frac[:, 1] if dy else 1.0 - frac[:, 1]
for dz in (0, 1):
wz = frac[:, 2] if dz else 1.0 - frac[:, 2]
cx = base[:, 0] + dx
cy = base[:, 1] + dy
cz = base[:, 2] + dz
inb = (cx >= 0) & (cx < R) & (cy >= 0) & (cy < R) & (cz >= 0) & (cz < R)
qk = (cx * R + cy) * R + cz
ins = torch.searchsorted(skey, qk).clamp(max=M - 1)
matched = inb & (skey[ins] == qk)
idx = order[ins] # garbage where !matched
w = torch.where(matched, wx * wy * wz, torch.zeros_like(wx))[:, None]
weighted = col[idx]
weighted.mul_(w) # w=0 cancels garbage rows
acc.add_(weighted)
wsum += w
ok = wsum[:, 0] > 1e-8
vals = torch.zeros((K, C), device=dev)
vals[ok] = acc[ok] / wsum[ok].clamp_min(1e-8)
return vals.cpu().numpy(), ok.cpu().numpy()
# Above this many grid-scan stragglers, the O(N·M) GPU brute force (and its chunk loop)
# is slower than a one-off cKDTree build, so the nearest fallback defers them to cKDTree.
_BRUTE_NEAREST_MAX = 8192
def _nearest_voxel_sample_gpu(positions, voxel_coords_np, color_np, resolution):
"""GPU nearest-occupied-voxel lookup via sorted-key grid scan. Returns (vals [K,C]
float32, found [K] bool); `found` is False for stragglers left to the caller's cKDTree."""
dev = comfy.model_management.get_torch_device()
R = int(resolution)
index_dtype = torch.int32 if R ** 3 <= torch.iinfo(torch.int32).max else torch.int64
P = torch.from_numpy(np.ascontiguousarray(positions)).to(dev).float()
VC = torch.from_numpy(np.ascontiguousarray(voxel_coords_np)).to(device=dev, dtype=index_dtype)
col = torch.from_numpy(np.ascontiguousarray(color_np)).to(dev).float()
M, K = VC.shape[0], P.shape[0]
key = (VC[:, 0] * R + VC[:, 1]) * R + VC[:, 2]
skey, order = key.sort()
def _search(idx, radius):
"""Nearest occupied voxel within ±radius cells, for query subset P[idx]."""
Ps = P[idx]
# Cell-CENTER convention: nearest coord = round((p+0.5)*R-0.5) (matches official).
rc = ((Ps + 0.5) * R - 0.5).round().to(index_dtype)
n = idx.shape[0]
bd = torch.full((n,), 1e30, device=dev)
bi = torch.zeros(n, dtype=torch.long, device=dev)
fnd = torch.zeros(n, dtype=torch.bool, device=dev)
rng = range(-radius, radius + 1)
for dx in rng:
for dy in rng:
for dz in rng:
cc = rc + torch.tensor([dx, dy, dz], dtype=index_dtype, device=dev)
inb = ((cc >= 0) & (cc < R)).all(1)
qk = (cc[:, 0] * R + cc[:, 1]) * R + cc[:, 2]
ins = torch.searchsorted(skey, qk).clamp(max=M - 1)
match = inb & (skey[ins] == qk)
dd = (((cc.float() + 0.5) / R - 0.5 - Ps) ** 2).sum(1)
upd = match & (dd < bd)
bd = torch.where(upd, dd, bd)
bi = torch.where(upd, order[ins], bi)
fnd |= match
return bi, fnd
def _brute_nearest(idx):
"""Exact nearest occupied voxel for the few grid-scan stragglers, chunked GPU
brute force (avoids a seconds-long cKDTree build over all M voxels)."""
Ps = P[idx] # [N,3] world
N = Ps.shape[0]
vox_pos = (VC.float() + 0.5) / R - 0.5 # [M,3] voxel centres
best_d = torch.full((N,), 1e30, device=dev)
best_j = torch.zeros(N, dtype=torch.long, device=dev)
# Bound the N×chunk matrix to ~64M elements.
chunk = max(1, (1 << 26) // max(1, N))
for s in range(0, M, chunk):
vc = vox_pos[s:s + chunk] # [B,3]
dd = (Ps[:, None, :] - vc[None, :, :]).pow(2).sum(-1) # [N,B]
md, mj = dd.min(1)
upd = md < best_d
best_d = torch.where(upd, md, best_d)
best_j = torch.where(upd, mj + s, best_j)
return best_j
all_idx = torch.arange(K, device=dev)
best_i = torch.zeros(K, dtype=torch.long, device=dev)
found = torch.zeros(K, dtype=torch.bool, device=dev)
# Pass 1: radius 1 over everything; Pass 2: radius 4 on misses; Pass 3: brute force.
bi1, fnd1 = _search(all_idx, 1)
best_i[all_idx] = bi1
found[all_idx] = fnd1
miss = torch.nonzero(~found, as_tuple=True)[0]
if miss.numel() > 0:
bi2, fnd2 = _search(miss, 4)
best_i[miss] = bi2
found[miss] = fnd2
# Pass 3: stragglers >4 cells from any voxel. A handful → GPU brute force; many
# (coarse mesh, texels far from the voxel shell) → leave unfound for the caller's
# cKDTree, since brute force is O(N·M) and its chunk loop blows up at large N.
miss2 = torch.nonzero(~found, as_tuple=True)[0]
if 0 < miss2.numel() <= _BRUTE_NEAREST_MAX:
best_i[miss2] = _brute_nearest(miss2)
found[miss2] = True
vals = col[best_i]
return vals.cpu().numpy(), found.cpu().numpy()
def _sample_voxel_attrs_per_texel(position_map, mask, voxel_coords, voxel_colors, resolution):
"""Sample all voxel attribute channels at every masked texel. Returns (H,W,C)
float32 in [0,1] (C = feature width: 3 color, 6 PBR). Normalized trilinear over
occupied voxels (matches official), nearest fallback where all 8 corners empty."""
H, W, _ = position_map.shape
color_np = voxel_colors.detach().cpu().numpy().astype(np.float32)
C = color_np.shape[-1]
out = np.zeros((H, W, C), dtype=np.float32)
if not mask.any():
return out
coords_np = voxel_coords.detach().cpu().numpy()
valid_positions = position_map[mask]
def _nearest(query):
# Grid scan + small-N brute tail (on the compute device). Only a large count of far
# stragglers (coarse mesh, or a surface off the voxel shell) is left unfound → resolve
# those with one cKDTree, since GPU brute force is O(N·M) and blows up at large N.
vals, found = _nearest_voxel_sample_gpu(query, coords_np, color_np, resolution)
if not found.all():
origin = np.array([-0.5, -0.5, -0.5], dtype=np.float32)
voxel_size = 1.0 / float(resolution)
voxel_pos = (coords_np.astype(np.float32) + 0.5) * voxel_size + origin
tree = cKDTree(voxel_pos)
_, nearest_idx = tree.query(query[~found], k=1, workers=-1)
vals[~found] = color_np[nearest_idx]
return vals
try:
vals, ok = _trilinear_sample_sparse_gpu(valid_positions, coords_np, color_np, resolution)
except Exception as e:
comfy.model_management.raise_non_oom(e) # only fall back on OOM; surface real errors
logging.warning(f"[BakeTextureFromVoxel] GPU trilinear ran out of memory ({e}); falling back to CPU")
vals, ok = _trilinear_sample_sparse(valid_positions, coords_np, color_np, resolution)
if not ok.all():
vals[~ok] = _nearest(valid_positions[~ok]) # no occupied neighbour
np.clip(vals, 0.0, 1.0, out=vals)
out[mask] = vals
return out
def _msb_int64(x):
"""floor(log2(x)) elementwise for int64 x >= 1 (bit-search, no float)."""
r = torch.zeros_like(x)
xx = x.clone()
for s in (32, 16, 8, 4, 2, 1):
sh = xx >> s
m = sh > 0
r = torch.where(m, r + s, r)
xx = torch.where(m, sh, xx)
return r
def _morton_expand21(v):
"""Spread the low 21 bits of v across every 3rd bit (for a 63-bit Morton code)."""
v = v & 0x1fffff
v = (v | (v << 32)) & 0x1f00000000ffff
v = (v | (v << 16)) & 0x1f0000ff0000ff
v = (v | (v << 8)) & 0x100f00f00f00f00f
v = (v | (v << 4)) & 0x10c30c30c30c30c3
v = (v | (v << 2)) & 0x1249249249249249
return v
def _build_triangle_bvh(tri):
"""Linear BVH (Karras 2012) over triangle AABBs, pure torch, no external deps
(the cuMesh approach, in torch). Internal nodes 0..T-2; leaves encoded LEAF+i,
leaf i holds triangle order[i]. Returns dict(LEAF, left, right, nmin, nmax over
2T entries, order, T)."""
dev = tri.device
T = tri.shape[0]
amin = tri.amin(1)
amax = tri.amax(1)
cent = (amin + amax) * 0.5
lo = cent.amin(0)
hi = cent.amax(0)
span = (hi - lo).clamp_min(1e-12)
q = (((cent - lo) / span).clamp(0, 1) * float((1 << 21) - 1)).long()
morton = (_morton_expand21(q[:, 0]) << 2 | _morton_expand21(q[:, 1]) << 1 | _morton_expand21(q[:, 2])).long()
order_long = torch.argsort(morton)
msort = morton[order_long]
order = order_long.to(torch.int32)
# delta(i,j): common-prefix length of (morton, index) keys of leaves i,j (index
# breaks ties so duplicate codes still split); -1 if OOB.
def delta(i, j):
ok = (j >= 0) & (j < T)
jj = j.clamp(0, T - 1)
x = msort[i] ^ msort[jj]
same = x == 0
cp = torch.where(same, torch.full_like(x, 63), 62 - _msb_int64(x.clamp_min(1)))
xi = i ^ jj
cpi = torch.where(xi == 0, torch.full_like(x, 32), 31 - _msb_int64(xi.clamp_min(1)))
return torch.where(ok, cp + torch.where(same, cpi, torch.zeros_like(cp)), torch.full_like(x, -1))
I = torch.arange(T - 1, dtype=torch.int32, device=dev)
dplus = delta(I, I + 1)
dminus = delta(I, I - 1)
direction = torch.where(dplus >= dminus, torch.ones_like(I), -torch.ones_like(I))
dmin = torch.minimum(dplus, dminus)
# range length: exponential probe then binary search
lmax = torch.full_like(I, 2)
while True:
cond = delta(I, I + lmax * direction) > dmin
if not bool(cond.any()):
break
lmax = torch.where(cond, lmax * 2, lmax)
if int(lmax.max()) > 2 * T:
break
l = torch.zeros_like(I)
t = lmax.clone()
while True:
t = t // 2
if int(t.max()) == 0:
break
cond = delta(I, I + (l + t) * direction) > dmin
l = torch.where(cond, l + t, l)
j = I + l * direction
first = torch.minimum(I, j)
last = torch.maximum(I, j)
# split position: binary search on delta within [first, last]
dnode = delta(first, last)
s = torch.zeros_like(I)
div = torch.full_like(I, 2)
rng = last - first
while True:
step = (rng + div - 1) // div
cond = delta(first, (first + s + step).clamp(max=T - 1)) > dnode
s = torch.where(cond, s + step, s)
if int(step.max()) <= 1:
cond1 = delta(first, (first + s + 1).clamp(max=T - 1)) > dnode
s = torch.where(cond1, s + 1, s)
break
div = div * 2
gamma = first + s
LEAF = T
left = torch.where(gamma == first, LEAF + gamma, gamma)
right = torch.where(gamma + 1 == last, LEAF + gamma + 1, gamma + 1)
del cent, lo, hi, span, q, morton, order_long
del I, dplus, dminus, direction, dmin, lmax, cond, l, t, j
del first, last, dnode, s, div, rng, step, cond1, gamma
delta = None
msort = None
# node AABBs: leaves seeded, internal unioned bottom-up (~log2(T) passes; cap is a backstop).
nmin = torch.empty((2 * T, 3), device=dev)
nmax = torch.empty((2 * T, 3), device=dev)
nmin[LEAF:] = amin[order]
nmax[LEAF:] = amax[order]
del amin, amax
setm = torch.zeros(2 * T, dtype=torch.bool, device=dev)
setm[LEAF:] = True
for _ in range(128):
need = ~setm[:T - 1]
if not bool(need.any()):
break
idx = torch.nonzero(need, as_tuple=True)[0]
ii = idx[setm[left[idx]] & setm[right[idx]]]
if ii.numel() == 0:
break
nmin[ii] = torch.minimum(nmin[left[ii]], nmin[right[ii]])
nmax[ii] = torch.maximum(nmax[left[ii]], nmax[right[ii]])
setm[ii] = True
return dict(LEAF=LEAF, left=left, right=right, nmin=nmin, nmax=nmax, order=order, T=T)
def _closest_points_on_mesh_bvh(Q, tri, bvh, max_stack=64, return_face=False):
"""Exact closest surface point per query via per-query BVH stack traversal
(nearest-child-first), pure torch. Returns [N,3], or (points [N,3], face_idx [N])
when return_face=True (face_idx indexes `tri`). `max_stack` bounds the stack
(= tree height); overflow is counted+warned, not silently wrong."""
dev = Q.device
N = Q.shape[0]
LEAF = bvh['LEAF']
nmin = bvh['nmin']
nmax = bvh['nmax']
left = bvh['left']
right = bvh['right']
order = bvh['order']
stack = torch.full((N, max_stack), -1, dtype=torch.int32, device=dev)
sp = torch.ones(N, dtype=torch.long, device=dev)
stack[:, 0] = 0
best = torch.full((N,), 1e30, device=dev)
bestp = Q.clone()
bestf = torch.full((N,), -1, dtype=torch.long, device=dev)
active = torch.arange(N, device=dev)
overflow = 0
def aabb_d2(node, q):
d = (nmin[node] - q).clamp_min(0) + (q - nmax[node]).clamp_min(0)
return (d * d).sum(-1)
while active.numel() > 0:
a = active
qa = Q[a]
node = stack[a, sp[a] - 1]
sp[a] = sp[a] - 1
within = aabb_d2(node, qa) < best[a]
isleaf = node >= LEAF
lv = within & isleaf
if bool(lv.any()):
ga = a[lv]
fidx = order[node[lv] - LEAF] # triangle index of each leaf
tt = tri[fidx]
cp, d2 = _point_tri_closest(qa[lv], tt)
upd = d2 < best[ga]
gu = ga[upd]
best[gu] = d2[upd]
bestp[gu] = cp[upd]
bestf[gu] = fidx[upd].long()
iv = within & ~isleaf
if bool(iv.any()):
gi = a[iv]
qi = qa[iv]
lc = left[node[iv]]
rc = right[node[iv]]
dl = aabb_d2(lc, qi)
dr = aabb_d2(rc, qi)
near = torch.where(dl <= dr, lc, rc)
far = torch.where(dl <= dr, rc, lc)
s0 = sp[gi]
stack[gi, s0.clamp(max=max_stack - 1)] = far
sp[gi] = (s0 + 1).clamp(max=max_stack)
s1 = sp[gi]
overflow += int((s1 >= max_stack).sum())
stack[gi, s1.clamp(max=max_stack - 1)] = near
sp[gi] = (s1 + 1).clamp(max=max_stack)
active = a[sp[a] > 0]
if overflow:
logging.warning(f"[back-project] BVH stack overflow on {overflow} pushes "
f"(max_stack={max_stack}); a few texels may be slightly off — "
f"raise max_stack if this is large.")
if return_face:
return bestp, bestf
return bestp
def _back_project_positions(position_map, mask, ref_v, ref_f, max_query_res=1024):
"""Snap covered texels onto the reference mesh's true surface (pure-torch BVH, no
cumesh/scipy/trimesh) so the voxel field is sampled at full detail, not along flat
triangle chords. Returns a new position_map.
"""
if not mask.any():
return position_map
dev = comfy.model_management.get_torch_device()
rv = ref_v.detach().to(dev).float()
rf = ref_f.detach().to(device=dev, dtype=torch.int32)
tri = rv[rf]
bvh = _build_triangle_bvh(tri)
del rv, rf
H, W, _ = position_map.shape
stride = max(1, int(math.ceil(max(H, W) / float(max_query_res))))
if stride == 1 or not mask[::stride, ::stride].any():
out = position_map.copy()
query = torch.from_numpy(np.ascontiguousarray(position_map[mask], dtype=np.float32)).to(dev)
closest = _closest_points_on_mesh_bvh(query, tri, bvh).cpu().numpy().astype(position_map.dtype)
del query, tri, bvh
out[mask] = closest
return out
# Low-res correction, then bilinear upsample to full resolution.
pos_lo = position_map[::stride, ::stride]
mask_lo = mask[::stride, ::stride]
Hl, Wl = mask_lo.shape
corr_lo = np.zeros((Hl, Wl, 3), dtype=np.float32)
query = torch.from_numpy(np.ascontiguousarray(pos_lo[mask_lo], dtype=np.float32)).to(dev)
closest = _closest_points_on_mesh_bvh(query, tri, bvh).cpu().numpy().astype(np.float32)
del query, tri, bvh
corr_lo[mask_lo] = closest - pos_lo[mask_lo].astype(np.float32)
inds = ndi.distance_transform_edt(~mask_lo, return_distances=False, return_indices=True)
corr_lo = corr_lo[tuple(inds)] # extrapolate into gutter (nearest)
corr = torch.nn.functional.interpolate(
torch.from_numpy(np.ascontiguousarray(corr_lo)).permute(2, 0, 1)[None].to(dev),
size=(H, W), mode="bilinear", align_corners=False,
)[0].permute(1, 2, 0).cpu().numpy()
out = position_map.copy()
out[mask] = position_map[mask] + corr[mask]
return out
def _ray_tri_hit(o, d, tri, tmin, tmax):
"""Möller-Trumbore any-hit per (ray, triangle) pair, double-sided. Returns bool [N]."""
a, b, c = tri[:, 0], tri[:, 1], tri[:, 2]
e1, e2 = b - a, c - a
p = torch.cross(d, e2, dim=-1)
det = (e1 * p).sum(-1)
inv = 1.0 / torch.where(det.abs() < 1e-20, torch.full_like(det, 1e-20), det)
tvec = o - a
u = (tvec * p).sum(-1) * inv
q = torch.cross(tvec, e1, dim=-1)
v = (d * q).sum(-1) * inv
t = (e2 * q).sum(-1) * inv
return (det.abs() > 1e-20) & (u >= 0) & (v >= 0) & (u + v <= 1) & (t > tmin) & (t < tmax)
def _any_hit_rays_bvh(orig, dirs, tri, bvh, tmin=0.0, tmax=1e30, max_stack=64):
"""Any-hit ray test over the BVH (slab cull + Möller-Trumbore), pure torch. Returns bool
[N]: True if the ray hits any triangle in (tmin, tmax). Rays early-out once they hit."""
dev = orig.device
N = orig.shape[0]
LEAF = bvh['LEAF']
nmin, nmax = bvh['nmin'], bvh['nmax']
left, right, order = bvh['left'], bvh['right'], bvh['order']
inv = 1.0 / torch.where(dirs.abs() < 1e-20, torch.full_like(dirs, 1e-20), dirs)
tmaxN = tmax if torch.is_tensor(tmax) else torch.full((N,), float(tmax), device=dev) # per-ray far bound
hit = torch.zeros(N, dtype=torch.bool, device=dev)
# int32 stack: node indices fit in 31 bits and this [N, max_stack] array dominates memory.
stack = torch.full((N, max_stack), -1, dtype=torch.int32, device=dev)
sp = torch.ones(N, dtype=torch.long, device=dev)
stack[:, 0] = 0
active = torch.arange(N, device=dev)
def slab(node, o, i, tmx):
t1 = (nmin[node] - o) * i
t2 = (nmax[node] - o) * i
tnear = torch.minimum(t1, t2).amax(-1)
tfar = torch.maximum(t1, t2).amin(-1)
return (tfar >= tnear.clamp_min(tmin)) & (tnear <= tmx) & (tfar >= tmin)
while active.numel() > 0:
a = active
node = stack[a, sp[a] - 1]
sp[a] = sp[a] - 1
within = slab(node, orig[a], inv[a], tmaxN[a])
isleaf = node >= LEAF
lv = within & isleaf
if bool(lv.any()):
ga = a[lv]
tt = tri[order[node[lv] - LEAF]]
h = _ray_tri_hit(orig[ga], dirs[ga], tt, tmin, tmaxN[ga])
hit[ga[h]] = True
iv = within & ~isleaf
if bool(iv.any()):
gi = a[iv]
s0 = sp[gi]
stack[gi, s0.clamp(max=max_stack - 1)] = left[node[iv]].to(torch.int32)
sp[gi] = (s0 + 1).clamp(max=max_stack)
s1 = sp[gi]
stack[gi, s1.clamp(max=max_stack - 1)] = right[node[iv]].to(torch.int32)
sp[gi] = (s1 + 1).clamp(max=max_stack)
active = a[(sp[a] > 0) & ~hit[a]] # drop finished + already-hit rays
return hit
def _ray_tri_intersect(o, d, tri, tmin, tmax, cull_backface=False):
"""Möller-Trumbore per (ray, triangle) pair. Returns (hit [N], t [N]) where t is the ray
parameter and hit means the meeting is in (tmin, tmax). With cull_backface, drops faces whose
outward (winding) normal points along the ray — i.e. only keep surfaces facing the origin."""
a, b, c = tri[:, 0], tri[:, 1], tri[:, 2]
e1, e2 = b - a, c - a
p = torch.cross(d, e2, dim=-1)
det = (e1 * p).sum(-1)
inv = 1.0 / torch.where(det.abs() < 1e-20, torch.full_like(det, 1e-20), det)
tvec = o - a
u = (tvec * p).sum(-1) * inv
q = torch.cross(tvec, e1, dim=-1)
v = (d * q).sum(-1) * inv
t = (e2 * q).sum(-1) * inv
hit = (det.abs() > 1e-20) & (u >= 0) & (v >= 0) & (u + v <= 1) & (t > tmin) & (t < tmax)
if cull_backface:
hit = hit & ((torch.cross(e1, e2, dim=-1) * d).sum(-1) < 0) # keep only front-facing
return hit, t
def _closest_hit_rays_bvh(orig, dirs, tri, bvh, tmin=0.0, tmax=1e30, max_stack=64, cull_backface=False):
"""Nearest-hit ray cast over the BVH, pure torch. Returns (t [N], face [N] long, -1 on
miss; hit [N] bool) — the closest intersection in (tmin, tmax), pruning nodes past best_t."""
dev = orig.device
N = orig.shape[0]
LEAF = bvh['LEAF']
nmin, nmax = bvh['nmin'], bvh['nmax']
left, right, order = bvh['left'], bvh['right'], bvh['order']
inv = 1.0 / torch.where(dirs.abs() < 1e-20, torch.full_like(dirs, 1e-20), dirs)
best_t = torch.full((N,), float(tmax), device=dev)
best_f = torch.full((N,), -1, dtype=torch.long, device=dev)
stack = torch.full((N, max_stack), -1, dtype=torch.int32, device=dev)
sp = torch.ones(N, dtype=torch.long, device=dev)
stack[:, 0] = 0
active = torch.arange(N, device=dev)
while active.numel() > 0:
a = active
node = stack[a, sp[a] - 1]
sp[a] = sp[a] - 1
t1 = (nmin[node] - orig[a]) * inv[a]
t2 = (nmax[node] - orig[a]) * inv[a]
tnear = torch.minimum(t1, t2).amax(-1)
tfar = torch.maximum(t1, t2).amin(-1)
within = (tfar >= tnear.clamp_min(tmin)) & (tfar >= tmin) & (tnear < best_t[a]) # prune past best
isleaf = node >= LEAF
lv = within & isleaf
if bool(lv.any()):
ga = a[lv]
fidx = order[node[lv] - LEAF]
h, t = _ray_tri_intersect(orig[ga], dirs[ga], tri[fidx], tmin, tmax, cull_backface)
upd = h & (t < best_t[ga])
gu = ga[upd]
best_t[gu] = t[upd]
best_f[gu] = fidx[upd].long()
iv = within & ~isleaf
if bool(iv.any()):
gi = a[iv]
s0 = sp[gi]
stack[gi, s0.clamp(max=max_stack - 1)] = left[node[iv]].to(torch.int32)
sp[gi] = (s0 + 1).clamp(max=max_stack)
s1 = sp[gi]
stack[gi, s1.clamp(max=max_stack - 1)] = right[node[iv]].to(torch.int32)
sp[gi] = (s1 + 1).clamp(max=max_stack)
active = a[sp[a] > 0]
return best_t, best_f, best_f >= 0
def _onb(n):
"""Branchless orthonormal basis (t, b) around unit normals n [N,3]."""
up = torch.where(n[..., 2:3].abs() < 0.999,
torch.tensor([0.0, 0.0, 1.0], device=n.device).expand_as(n),
torch.tensor([1.0, 0.0, 0.0], device=n.device).expand_as(n))
t = torch.nn.functional.normalize(torch.cross(up, n, dim=-1), dim=-1, eps=1e-6)
return t, torch.cross(n, t, dim=-1)
def _bake_ambient_occlusion(high_v, high_f, low_v_np, low_f_np, low_uv_np, low_n, resolution,
num_samples=64, max_distance=0.5, strength=1.0, bias=0.01,
ray_chunk=None, pbar=None, pbar_range=None):
"""Bake high-poly ambient occlusion into the low-poly's UV layout: per texel, cosine-weight
a hemisphere of rays around the normal and cast them at the high-poly. AO = 1 - hit-fraction
(cosine weighting makes the hit-fraction the estimator). Returns ao_img [H,W,3] in [0,1].
ray_chunk caps rays cast at once (the per-chunk BVH stack is its dominant transient VRAM);
None auto-sizes it to a slice of free VRAM — big chunks (fast) on large GPUs, small (safe)
on small ones."""
dev = comfy.model_management.get_torch_device()
H = W = int(resolution)
S = int(num_samples)
if ray_chunk is None:
# ~376 B/ray (int32 stack max_stack*4 + a few [N,3] ray buffers); spend a quarter of free
# device memory. Speed saturates around 4M rays/chunk, so cap there (≈2 GB peak) rather than
# grow memory for no gain; floor keeps tiny GPUs from thrashing into too many chunks.
free = comfy.model_management.get_free_memory(dev)
ray_chunk = int(min(1 << 22, max(1 << 20, (free * 0.25) / (num_samples * 4 + 200))))
face_idx, bary_uv, mask = _rasterize_uv_barycentric(low_f_np, low_uv_np, resolution)
if not mask.any():
return np.ones((H, W, 3), dtype=np.float32)
lf = torch.from_numpy(np.ascontiguousarray(low_f_np).astype(np.int64)).to(dev)
lv = torch.from_numpy(np.ascontiguousarray(low_v_np, dtype=np.float32)).to(dev)
low_n = low_n.to(dev).float()
m = mask
vtri = lf[face_idx[m]] # [K,3] vertex ids
bsel = bary_uv[m] # [K,3]
P = (bsel[:, :, None] * lv[vtri]).sum(1) # [K,3]
Nl = torch.nn.functional.normalize((bsel[:, :, None] * low_n[vtri]).sum(1), dim=-1, eps=1e-6)
hv = high_v.to(dev).float()
hf = high_f.to(device=dev, dtype=torch.int32)
tri = hv[hf]
bvh = _build_triangle_bvh(tri)
diag = float((hv.amax(0) - hv.amin(0)).norm().clamp_min(1e-6))
biasw = max(1e-5, float(bias) * diag)
tmax = float(max_distance) * diag
# Back-project onto the high surface, then lift along the normal: the low-poly chord can sit
# below the high surface, and casting from below floods false self-occlusion (dark blotches).
bp = _closest_points_on_mesh_bvh(P, tri, bvh)
origins = bp + Nl * biasw
K = P.shape[0]
T, B = _onb(Nl)
occ = torch.zeros(K, device=dev)
tex_per_chunk = max(1, int(ray_chunk) // max(1, S))
n_chunks = max(1, (K + tex_per_chunk - 1) // tex_per_chunk)
for ci, s in enumerate(range(0, K, tex_per_chunk)):
e = min(s + tex_per_chunk, K)
kk = e - s
o, n, t, b = origins[s:e], Nl[s:e], T[s:e], B[s:e]
r1 = torch.rand(kk, S, device=dev)
r2 = torch.rand(kk, S, device=dev)
sr = r1.sqrt()
lz = r1.mul_(-1.0).add_(1.0).clamp_min_(0.0).sqrt_() # sqrt(1-r1) (r1 dead after sr)
ang = r2.mul_(2.0 * math.pi) # in place (r2 dead)
lx = ang.cos().mul_(sr)
ly = ang.sin().mul_(sr)
d = t[:, None, :] * lx[..., None] # cosine-weighted hemisphere,
d.addcmul_(b[:, None, :], ly[..., None]) # fused d += b*ly
d.addcmul_(n[:, None, :], lz[..., None]) # fused d += n*lz (no extra temps)
d = torch.nn.functional.normalize(d.reshape(-1, 3), dim=-1, eps=1e-6)
oo = o[:, None, :].expand(-1, S, -1).reshape(-1, 3)
hit = _any_hit_rays_bvh(oo, d, tri, bvh, tmin=biasw, tmax=tmax)
occ[s:e] = hit.reshape(kk, S).sum(1, dtype=torch.float32).div_(float(S)) # mean without a float copy
if pbar is not None and pbar_range is not None:
lo, hi = pbar_range
pbar.update_absolute(lo + ((hi - lo) * (ci + 1)) // n_chunks, 1000)
ao = occ.mul_(-float(strength)).add_(1.0).clamp_(0.0, 1.0) # 1 - occ*strength, in place (occ is dead)
out = torch.ones((H, W), device=dev)
out[m] = ao
out3 = np.repeat(out.cpu().numpy()[..., None], 3, axis=2)
return _jfa_fill_gpu(np.ascontiguousarray(out3, dtype=np.float32), mask.cpu().numpy())
def _camera_basis(eye, center, up_hint):
"""Forward/right/up for a camera at `eye` looking at `center` (each [3])."""
f = torch.nn.functional.normalize(center - eye, dim=-1, eps=1e-6)
# Fall back to +Z up when looking near-vertical (f ∥ +Y would give a degenerate right vector).
up = up_hint if float(torch.abs((f * up_hint).sum())) < 0.99 else torch.tensor([0.0, 0.0, 1.0], device=f.device)
r = torch.nn.functional.normalize(torch.cross(f, up, dim=-1), dim=-1, eps=1e-6)
return f, r, torch.cross(r, f, dim=-1)
def _apply_model_transform(values, transform, is_normal=False):
def _vec(data):
return values.new_tensor([data["x"], data["y"], data["z"]])
scale = _vec(transform["scale"])
position = _vec(transform["position"])
quaternion = transform["quaternion"]
x, y, z, w = (values.new_tensor(quaternion[key]) for key in ("x", "y", "z", "w"))
rotation = torch.stack((
torch.stack((1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w))),
torch.stack((2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w))),
torch.stack((2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y))),
))
if is_normal:
return torch.nn.functional.normalize((values / scale) @ rotation.T, dim=-1, eps=1e-6)
return (values * scale) @ rotation.T + position
def _sample_image01(img_hwc, uv01):
"""Bilinear-sample img [H,W,C] at uv01 [K,2] in [0,1] (u=x/col, v=y/row). Returns [K,C]."""
g = (uv01 * 2.0 - 1.0).view(1, 1, -1, 2)
s = torch.nn.functional.grid_sample(img_hwc.permute(2, 0, 1)[None].float(), g, mode="bilinear", align_corners=False, padding_mode="border")
return s[0, :, 0, :].t()
def _render_view(tri, bvh, uv, faces, texture_hwc, eye, f, r, u, fov, H, W, ray_chunk=1 << 22,
vertex_colors=None, vertex_normals=None, render_normal=False):
"""Ray-cast render: per pixel, nearest-hit triangle → colour it. With `render_normal`, output the
view-space normal (OpenGL: x=right, y=up, z=toward camera; smooth `vertex_normals` if given, else
the face normal). Otherwise colour source in order: `texture_hwc` (sampled via interpolated UVs),
else `vertex_colors` (barycentric), else neutral clay shaded by facing angle. Returns
(img, hit_mask, depth)."""
dev = tri.device
ys = 1.0 - (torch.arange(H, device=dev, dtype=torch.float32) + 0.5) / H * 2.0 # row 0 = +up
xs = (torch.arange(W, device=dev, dtype=torch.float32) + 0.5) / W * 2.0 - 1.0
gy, gx = torch.meshgrid(ys, xs, indexing="ij")
tn = math.tan(0.5 * fov)
aspect = W / H
d = torch.nn.functional.normalize(
(r * (gx * tn * aspect)[..., None] + u * (gy * tn)[..., None] + f).reshape(-1, 3), dim=-1, eps=1e-6)
o = eye[None, :].expand(H * W, 3)
img = torch.zeros((H * W, 3), device=dev)
depth = torch.full((H * W,), float("inf"), device=dev)
hit_all = torch.zeros(H * W, dtype=torch.bool, device=dev)
for s in range(0, H * W, ray_chunk):
e = min(s + ray_chunk, H * W)
t_hit, face, hit = _closest_hit_rays_bvh(o[s:e], d[s:e], tri, bvh, tmin=1e-5, tmax=1e30)
if bool(hit.any()):
fh = face[hit].clamp_min(0)
P = o[s:e][hit] + t_hit[hit, None] * d[s:e][hit]
bary = _barycentric(P, tri[fh])
local = torch.zeros((e - s, 3), device=dev)
if render_normal:
if vertex_normals is not None:
nrm = torch.nn.functional.normalize(
(bary[:, :, None] * vertex_normals[faces[fh]]).sum(1), dim=-1, eps=1e-6)
else: # face normal, oriented toward camera
nrm = torch.nn.functional.normalize(
torch.cross(tri[fh][:, 1] - tri[fh][:, 0], tri[fh][:, 2] - tri[fh][:, 0], dim=-1),
dim=-1, eps=1e-6)
nrm = torch.where((nrm * -d[s:e][hit]).sum(-1, keepdim=True) < 0, -nrm, nrm)
nv = torch.stack([(nrm * r).sum(-1), (nrm * u).sum(-1), (nrm * -f).sum(-1)], dim=-1)
local[hit] = (nv * 0.5 + 0.5).clamp(0.0, 1.0) # view-space OpenGL normal encode
elif texture_hwc is not None and uv is not None:
uvh = (bary[:, :, None] * uv[faces[fh]]).sum(1)
local[hit] = _sample_image01(texture_hwc, uvh)
elif vertex_colors is not None:
local[hit] = (bary[:, :, None] * vertex_colors[faces[fh]]).sum(1)
else:
# Neutral clay, headlight-shaded (|n·view|) so silhouette-plus-form reads, not a flat blob.
fn = torch.nn.functional.normalize(
torch.cross(tri[fh][:, 1] - tri[fh][:, 0], tri[fh][:, 2] - tri[fh][:, 0], dim=-1),
dim=-1, eps=1e-6)
ndl = (fn * -d[s:e][hit]).sum(-1).abs().clamp(0.15, 1.0)
local[hit] = torch.tensor([0.72, 0.72, 0.72], device=dev) * ndl[:, None]
img[s:e] = local
dloc = torch.full((e - s,), float("inf"), device=dev)
You can’t perform that action at this time.
