Repository navigation
Expand file tree
/
Copy pathfind_transform.py
More file actions
1992 lines (1694 loc) · 68.8 KB
/
Copy pathfind_transform.py
File metadata and controls
1992 lines (1694 loc) · 68.8 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
"""Find the transform between a fixed Zarr volume and a moving source.
Note that neuroglancer uses ZYX coordinates, so that convention is followed for neuroglancer-related bits (most of this file).
Elsewhere, for example writing to a JSON file, we use XYZ coordinates.
"""
from typing import NamedTuple, Optional
from pathlib import Path
import argparse
import http.server
import sys
import threading
import time
from urllib.parse import quote, urlparse
import webbrowser
import neuroglancer
import numpy as np
try:
from numba import njit, prange
NUMBA_AVAILABLE = True
except Exception:
NUMBA_AVAILABLE = False
def njit(*args, **kwargs):
def decorator(func):
return func
return decorator
def prange(*args):
return range(*args)
from registration import align_zarrs
from transform_utils import (
get_volume_dimensions,
read_vtk_mesh_geometry,
get_vtk_mesh_info,
invert_affine_matrix,
fit_affine_transform_from_points,
fit_constrained_transform_from_points,
MeshGeometry,
matrix_swap_output_xyz_zyx,
matrix_swap_xyz_zyx,
points_swap_xyz_zyx,
read_transform_json,
strip_vtk_url_prefix,
write_transform_json,
)
GREEN_SHADER = """
void main() {
emitRGB(vec3(0, toNormalized(getDataValue()), 0));
}
"""
MAGENTA_SHADER = """
void main() {
emitRGB(vec3(toNormalized(getDataValue()), 0, toNormalized(getDataValue())));
}
"""
MAGENTA_MESH_SHADER = """
void main() {
emitRGB(vec3(1.0, 0.0, 1.0));
}
"""
GREEN_POINTS_SHADER = """
void main() {
setColor(vec3(0, 1, 0));
setPointMarkerSize(5.0);
}
"""
MAGENTA_POINTS_SHADER = """
void main() {
setColor(vec3(1, 0, 1));
setPointMarkerSize(5.0);
}
"""
ERROR_POINTS_SHADER = """
void main() {
float e = clamp(prop_error() / prop_max_error(), 0.0, 1.0);
setColor(vec4(e, 1.0 - e, 0.0, 1.0));
setPointMarkerSize(mix(5.0, 15.0, e));
}
"""
FIXED_POINTS_LAYER_STR = "fixed_points"
MOVING_POINTS_LAYER_STR = "moving_points"
ERROR_POINTS_LAYER_STR = "landmark_errors"
MESH_SLICE_LAYER_STR = "moving_mesh_slices"
UNITLESS_DIMENSIONS = neuroglancer.CoordinateSpace(
names=["z", "y", "x"],
units="",
scales=[1, 1, 1],
)
XYZ_DIMENSIONS = neuroglancer.CoordinateSpace(
names=["x", "y", "z"],
units="",
scales=[1, 1, 1],
)
class MovingSourceDescriptor(NamedTuple):
source_type: str
layer_url: str
center_source: np.ndarray
unit_size_um: float
input_dimensions: neuroglancer.CoordinateSpace
class LocalMeshHttpServer(NamedTuple):
server: http.server.ThreadingHTTPServer
thread: threading.Thread
base_url: str
directory: Path
class MeshSliceTransformCache(NamedTuple):
transform_key: tuple
transformed_vertices_zyx: np.ndarray
face_axis_mins: np.ndarray
face_axis_maxs: np.ndarray
local_mesh_http_server: Optional[LocalMeshHttpServer] = None
moving_mesh_geometry: Optional[MeshGeometry] = None
moving_mesh_vertices_homogeneous: Optional[np.ndarray] = None
mesh_slice_transform_cache: Optional[MeshSliceTransformCache] = None
mesh_slice_max_segments = 256
numba_mesh_slice_kernels_warmed = False
slice_overlay_update_pending = False
last_mesh_slice_overlay_key = None
constrained_fit_mode = False
def infer_moving_source_type(path: str, explicit_type: str) -> str:
"""Infer the moving source type from the CLI args."""
if explicit_type != "auto":
return explicit_type
stripped = strip_vtk_url_prefix(path)
if path.startswith("vtk://") or stripped.lower().endswith(".vtk"):
return "mesh"
return "zarr"
def is_remote_mesh_path(path: str) -> bool:
"""Check whether a VTK mesh path ultimately points to HTTP(S)."""
stripped = strip_vtk_url_prefix(path)
parsed = urlparse(stripped)
return parsed.scheme in ("http", "https")
def ensure_local_mesh_http_server(directory: Path) -> LocalMeshHttpServer:
"""Serve a local mesh directory over HTTP with permissive CORS for Neuroglancer."""
global local_mesh_http_server
directory = directory.resolve()
if local_mesh_http_server is not None:
if local_mesh_http_server.directory == directory:
return local_mesh_http_server
class CORSRequestHandler(http.server.SimpleHTTPRequestHandler):
def __init__(self, *args, **kwargs):
super().__init__(*args, directory=str(directory), **kwargs)
def end_headers(self):
self.send_header("Access-Control-Allow-Origin", "*")
self.send_header("Access-Control-Allow-Methods", "GET, OPTIONS")
self.send_header("Access-Control-Allow-Headers", "*")
super().end_headers()
def log_message(self, format, *args):
return
server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), CORSRequestHandler)
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
base_url = f"http://127.0.0.1:{server.server_port}"
local_mesh_http_server = LocalMeshHttpServer(
server=server,
thread=thread,
base_url=base_url,
directory=directory,
)
print(f"Serving local mesh files from {directory} at {base_url}")
return local_mesh_http_server
def resolve_mesh_layer_url(path: str) -> str:
"""Resolve a mesh path to a Neuroglancer VTK layer URL."""
stripped = strip_vtk_url_prefix(path)
if is_remote_mesh_path(path):
return f"vtk://{stripped}"
local_path = Path(stripped).expanduser().resolve()
if not local_path.exists():
raise FileNotFoundError(f"Moving mesh file does not exist: {local_path}")
server = ensure_local_mesh_http_server(local_path.parent)
return f"vtk://{server.base_url}/{quote(local_path.name)}"
def build_moving_source_descriptor(
path: str,
source_type: str,
moving_voxel_size: Optional[float],
moving_source_unit_size: Optional[float],
) -> MovingSourceDescriptor:
"""Build the moving source descriptor used by the interactive tool."""
if source_type == "zarr":
moving_dimensions = get_volume_dimensions(path, moving_voxel_size)
return MovingSourceDescriptor(
source_type="zarr",
layer_url=f"zarr://{path}",
center_source=np.array(
[
moving_dimensions.voxels_z / 2.0,
moving_dimensions.voxels_y / 2.0,
moving_dimensions.voxels_x / 2.0,
],
dtype=np.float64,
),
unit_size_um=moving_dimensions.voxel_size_um,
input_dimensions=UNITLESS_DIMENSIONS,
)
unit_size_um = (
moving_source_unit_size
if moving_source_unit_size is not None
else moving_voxel_size
)
if unit_size_um is None:
raise ValueError(
"Mesh moving sources require --moving-source-unit-size (or --moving-voxel-size as a compatibility alias)"
)
mesh_info = get_vtk_mesh_info(path)
mesh_url = resolve_mesh_layer_url(path)
return MovingSourceDescriptor(
source_type="mesh",
layer_url=mesh_url,
center_source=np.array(mesh_info.center_xyz, dtype=np.float64),
unit_size_um=unit_size_um,
input_dimensions=XYZ_DIMENSIONS,
)
def make_initial_transform(
moving_source: MovingSourceDescriptor,
scale_factor: float,
fixed_center_zyx: np.ndarray,
) -> np.ndarray:
"""Make the initial moving-source transform in viewer coordinates."""
transform = np.eye(4, dtype=np.float64)
transform[:3, :3] *= scale_factor
if moving_source.source_type == "mesh":
transform = matrix_swap_output_xyz_zyx(transform)
transformed_center = transform @ np.append(moving_source.center_source, 1.0)
transform[:3, 3] = fixed_center_zyx - transformed_center[:3]
return transform
return transform
def init_layers(
viewer: neuroglancer.Viewer,
fixed_path: str,
fixed_dimensions,
moving_source: MovingSourceDescriptor,
scale_factor: float,
) -> None:
"""Initialize the fixed Zarr volume and the moving source layers."""
with viewer.txn() as state:
fixed_source = neuroglancer.LayerDataSource(
url=f"zarr://{fixed_path}",
transform=neuroglancer.CoordinateSpaceTransform(
output_dimensions=UNITLESS_DIMENSIONS,
),
)
state.layers.append(
name="fixed",
layer=neuroglancer.ImageLayer(
source=fixed_source,
),
shader=GREEN_SHADER,
blend="additive",
opacity=1.0,
)
fixed_center_zyx = np.array(
[
fixed_dimensions.voxels_z / 2.0,
fixed_dimensions.voxels_y / 2.0,
fixed_dimensions.voxels_x / 2.0,
],
dtype=np.float64,
)
initial_transform = make_initial_transform(
moving_source, scale_factor, fixed_center_zyx
)[:-1, :]
transform_kwargs = dict(
output_dimensions=UNITLESS_DIMENSIONS,
matrix=initial_transform,
)
if moving_source.source_type == "mesh":
transform_kwargs.update(
input_dimensions=moving_source.input_dimensions,
source_rank=3,
)
moving_layer_source = neuroglancer.LayerDataSource(
url=moving_source.layer_url,
transform=neuroglancer.CoordinateSpaceTransform(**transform_kwargs),
)
if moving_source.source_type == "mesh":
state.layers.append(
name="moving",
layer=neuroglancer.SingleMeshLayer(
source=moving_layer_source,
shader=MAGENTA_MESH_SHADER,
),
)
else:
state.layers.append(
name="moving",
layer=neuroglancer.ImageLayer(
source=moving_layer_source,
),
shader=MAGENTA_SHADER,
blend="additive",
opacity=1.0,
)
def toggle_color(_):
with viewer.txn() as state:
if "vec3" in state.layers["fixed"].shader:
state.layers["fixed"].shader = ""
state.layers["moving"].shader = ""
else:
state.layers["fixed"].shader = GREEN_SHADER
state.layers["moving"].shader = (
MAGENTA_MESH_SHADER
if moving_source.source_type == "mesh"
else MAGENTA_SHADER
)
def make_rotation_matrix(axis: str, angle_deg: float):
"""Make a rotation matrix for the given axis and angle."""
angle_rad = np.deg2rad(angle_deg)
cos_theta = np.cos(angle_rad)
sin_theta = np.sin(angle_rad)
if axis == "z":
return np.array(
[
[1, 0, 0, 0],
[0, cos_theta, -sin_theta, 0],
[0, sin_theta, cos_theta, 0],
[0, 0, 0, 1],
]
)
elif axis == "y":
return np.array(
[
[cos_theta, 0, sin_theta, 0],
[0, 1, 0, 0],
[-sin_theta, 0, cos_theta, 0],
[0, 0, 0, 1],
]
)
elif axis == "x":
return np.array(
[
[cos_theta, -sin_theta, 0, 0],
[sin_theta, cos_theta, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1],
]
)
else:
raise ValueError(f"Invalid axis: {axis}")
def make_flip_matrix(axis: str):
"""Make a flip matrix for the given axis."""
if axis == "z":
return np.array(
[
[-1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1],
]
)
elif axis == "y":
return np.array(
[
[1, 0, 0, 0],
[0, -1, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1],
]
)
elif axis == "x":
return np.array(
[
[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, -1, 0],
[0, 0, 0, 1],
]
)
else:
raise ValueError(f"Invalid axis: {axis}")
def make_translate_matrix(axis: str, amount: float):
"""Make a translation matrix for the given axis and amount."""
if axis == "z":
return np.array([[1, 0, 0, amount], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]])
elif axis == "y":
return np.array([[1, 0, 0, 0], [0, 1, 0, amount], [0, 0, 1, 0], [0, 0, 0, 1]])
elif axis == "x":
return np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, amount], [0, 0, 0, 1]])
else:
raise ValueError(f"Invalid axis: {axis}")
def apply_matrix_to_centered(
state: neuroglancer.ViewerState,
transform_matrix: np.ndarray,
moving_source: MovingSourceDescriptor,
):
"""Apply a transformation matrix to a layer, centered on the moving source.
Args:
state: The neuroglancer viewer state
transform_matrix: 4x4 homogeneous transformation matrix to apply
moving_source: Moving source descriptor in source coordinates
"""
original_matrix = get_current_transform(state)
# Current position of the moving source center in fixed space.
cz, cy, cx, _ = original_matrix @ np.append(moving_source.center_source, 1.0)
# Center volume about origin
translate_to_origin_mat = np.array(
[
[1, 0, 0, -cz],
[0, 1, 0, -cy],
[0, 0, 1, -cx],
[0, 0, 0, 1],
]
)
# Translate back to original position
translate_back_mat = np.array(
[
[1, 0, 0, cz],
[0, 1, 0, cy],
[0, 0, 1, cx],
[0, 0, 0, 1],
]
)
matrix = (
translate_back_mat
@ transform_matrix
@ translate_to_origin_mat
@ original_matrix
)
set_current_transform(state, matrix)
def _make_rotator(axis: str, angle_deg: float):
def handler(_):
with viewer.txn() as state:
rotate_mat = make_rotation_matrix(axis, angle_deg)
apply_matrix_to_centered(state, rotate_mat, moving_source)
return handler
def _make_flipper(axis: str):
def handler(_):
with viewer.txn() as state:
flip_mat = make_flip_matrix(axis)
apply_matrix_to_centered(state, flip_mat, moving_source)
return handler
def _make_translator(axis: str, amount: float):
def handler(_):
with viewer.txn() as state:
translate_mat = make_translate_matrix(axis, amount)
apply_matrix_to_centered(state, translate_mat, moving_source)
return handler
def schema_to_current_transform(matrix_xyz: np.ndarray) -> np.ndarray:
"""Convert a schema-space transform into the viewer's current transform space."""
if moving_source.source_type == "mesh":
return matrix_swap_output_xyz_zyx(matrix_xyz)
return matrix_swap_xyz_zyx(matrix_xyz)
def current_to_schema_transform(matrix: np.ndarray) -> np.ndarray:
"""Convert the viewer's current transform into schema-space XYZ coordinates."""
if moving_source.source_type == "mesh":
return matrix_swap_output_xyz_zyx(matrix)
return matrix_swap_xyz_zyx(matrix)
def schema_fixed_points_to_current(points_xyz: list) -> list:
"""Convert schema fixed landmarks to viewer fixed-space landmarks."""
return points_swap_xyz_zyx(points_xyz)
def schema_moving_points_to_current(points_xyz: list) -> list:
"""Convert schema moving landmarks to the current moving-source coordinate order."""
if moving_source.source_type == "mesh":
return points_xyz
return points_swap_xyz_zyx(points_xyz)
def current_fixed_points_to_schema(points: list) -> list:
"""Convert viewer fixed-space landmarks to schema XYZ coordinates."""
return points_swap_xyz_zyx(points)
def current_moving_points_to_schema(points: list) -> list:
"""Convert current moving-source landmarks to schema XYZ coordinates."""
if moving_source.source_type == "mesh":
return points
return points_swap_xyz_zyx(points)
def make_mesh_slice_overlay_key(
position_zyx: np.ndarray, transform: np.ndarray
) -> tuple:
"""Make a compact key for mesh slice overlay invalidation."""
return (
tuple(np.round(position_zyx, 4)),
tuple(np.round(transform.reshape(-1), 6)),
)
def make_transform_only_key(transform: np.ndarray) -> tuple:
"""Make a compact key for the moving mesh affine transform alone."""
return tuple(np.round(transform.reshape(-1), 6))
def ensure_mesh_slice_transform_cache(transform: np.ndarray) -> MeshSliceTransformCache:
"""Cache transformed mesh geometry and per-axis face bounds for slice updates."""
global mesh_slice_transform_cache
if moving_mesh_geometry is None or moving_mesh_vertices_homogeneous is None:
raise RuntimeError("Mesh slice overlay requested without loaded mesh geometry")
transform_key = make_transform_only_key(transform)
if (
mesh_slice_transform_cache is not None
and mesh_slice_transform_cache.transform_key == transform_key
):
return mesh_slice_transform_cache
transform32 = transform.astype(np.float32, copy=False)
transformed_vertices_zyx = (
transform32 @ moving_mesh_vertices_homogeneous.T
).T[:, :3].astype(np.float32, copy=False)
i0, i1, i2 = moving_mesh_geometry.faces.T
face_axis_mins = np.empty((3, moving_mesh_geometry.faces.shape[0]), dtype=np.float32)
face_axis_maxs = np.empty((3, moving_mesh_geometry.faces.shape[0]), dtype=np.float32)
for axis in range(3):
axis_values = transformed_vertices_zyx[:, axis]
v0 = axis_values[i0]
v1 = axis_values[i1]
v2 = axis_values[i2]
face_axis_mins[axis, :] = np.minimum(np.minimum(v0, v1), v2)
face_axis_maxs[axis, :] = np.maximum(np.maximum(v0, v1), v2)
mesh_slice_transform_cache = MeshSliceTransformCache(
transform_key=transform_key,
transformed_vertices_zyx=transformed_vertices_zyx,
face_axis_mins=face_axis_mins,
face_axis_maxs=face_axis_maxs,
)
return mesh_slice_transform_cache
@njit(cache=True)
def _add_unique_intersection_point(
points: np.ndarray, count: int, x: np.float32, y: np.float32, z: np.float32, eps: float
) -> int:
for i in range(count):
if (
abs(points[i, 0] - x) <= eps
and abs(points[i, 1] - y) <= eps
and abs(points[i, 2] - z) <= eps
):
return count
if count < 2:
points[count, 0] = x
points[count, 1] = y
points[count, 2] = z
return count + 1
return count
@njit(cache=True)
def _triangle_plane_segment_into(
transformed_vertices_zyx: np.ndarray,
i0: int,
i1: int,
i2: int,
axis: int,
plane_coord: float,
eps: float,
segment_points: np.ndarray,
) -> int:
d0 = transformed_vertices_zyx[i0, axis] - plane_coord
d1 = transformed_vertices_zyx[i1, axis] - plane_coord
d2 = transformed_vertices_zyx[i2, axis] - plane_coord
if abs(d0) <= eps and abs(d1) <= eps and abs(d2) <= eps:
return 0
count = 0
edges = ((i0, i1, d0, d1), (i1, i2, d1, d2), (i2, i0, d2, d0))
for edge in edges:
a = edge[0]
b = edge[1]
da = edge[2]
db = edge[3]
if abs(da) <= eps and abs(db) <= eps:
continue
if abs(da) <= eps:
count = _add_unique_intersection_point(
segment_points,
count,
transformed_vertices_zyx[a, 0],
transformed_vertices_zyx[a, 1],
transformed_vertices_zyx[a, 2],
eps,
)
continue
if abs(db) <= eps:
count = _add_unique_intersection_point(
segment_points,
count,
transformed_vertices_zyx[b, 0],
transformed_vertices_zyx[b, 1],
transformed_vertices_zyx[b, 2],
eps,
)
continue
if da * db < 0.0:
t = da / (da - db)
x = transformed_vertices_zyx[a, 0] + t * (
transformed_vertices_zyx[b, 0] - transformed_vertices_zyx[a, 0]
)
y = transformed_vertices_zyx[a, 1] + t * (
transformed_vertices_zyx[b, 1] - transformed_vertices_zyx[a, 1]
)
z = transformed_vertices_zyx[a, 2] + t * (
transformed_vertices_zyx[b, 2] - transformed_vertices_zyx[a, 2]
)
count = _add_unique_intersection_point(
segment_points,
count,
np.float32(x),
np.float32(y),
np.float32(z),
eps,
)
return count
@njit(cache=True, parallel=True)
def _count_mesh_slice_hits_numba_parallel(
transformed_vertices_zyx: np.ndarray,
faces: np.ndarray,
position_zyx: np.ndarray,
face_axis_mins: np.ndarray,
face_axis_maxs: np.ndarray,
eps: float,
) -> np.ndarray:
num_faces = faces.shape[0]
num_tasks = 3 * num_faces
counts = np.zeros(num_tasks, dtype=np.uint8)
for task_index in prange(num_tasks):
axis = task_index // num_faces
face_index = task_index - axis * num_faces
plane_coord = position_zyx[axis]
plane_lower = plane_coord - eps
plane_upper = plane_coord + eps
if (
face_axis_mins[axis, face_index] <= plane_upper
and face_axis_maxs[axis, face_index] >= plane_lower
):
segment_points = np.empty((2, 3), dtype=np.float32)
num_points = _triangle_plane_segment_into(
transformed_vertices_zyx,
faces[face_index, 0],
faces[face_index, 1],
faces[face_index, 2],
axis,
plane_coord,
eps,
segment_points,
)
if num_points == 2:
counts[task_index] = 1
return counts
@njit(cache=True, parallel=True)
def _write_mesh_slice_segments_numba_parallel(
transformed_vertices_zyx: np.ndarray,
faces: np.ndarray,
position_zyx: np.ndarray,
face_axis_mins: np.ndarray,
face_axis_maxs: np.ndarray,
task_offsets: np.ndarray,
task_counts: np.ndarray,
total_segments: int,
eps: float,
) -> np.ndarray:
num_faces = faces.shape[0]
num_tasks = task_counts.shape[0]
segments = np.empty((total_segments, 6), dtype=np.float32)
for task_index in prange(num_tasks):
if task_counts[task_index] == 0:
continue
axis = task_index // num_faces
face_index = task_index - axis * num_faces
plane_coord = position_zyx[axis]
segment_points = np.empty((2, 3), dtype=np.float32)
num_points = _triangle_plane_segment_into(
transformed_vertices_zyx,
faces[face_index, 0],
faces[face_index, 1],
faces[face_index, 2],
axis,
plane_coord,
eps,
segment_points,
)
if num_points == 2:
segment_index = task_offsets[task_index]
segments[segment_index, 0] = segment_points[0, 0]
segments[segment_index, 1] = segment_points[0, 1]
segments[segment_index, 2] = segment_points[0, 2]
segments[segment_index, 3] = segment_points[1, 0]
segments[segment_index, 4] = segment_points[1, 1]
segments[segment_index, 5] = segment_points[1, 2]
return segments
def _compute_mesh_slice_segments_numba_parallel(
transformed_vertices_zyx: np.ndarray,
faces: np.ndarray,
position_zyx: np.ndarray,
face_axis_mins: np.ndarray,
face_axis_maxs: np.ndarray,
eps: float,
) -> np.ndarray:
task_counts = _count_mesh_slice_hits_numba_parallel(
transformed_vertices_zyx,
faces,
position_zyx,
face_axis_mins,
face_axis_maxs,
eps,
)
if task_counts.size == 0:
return np.empty((0, 6), dtype=np.float32)
task_offsets = np.cumsum(task_counts, dtype=np.int32) - task_counts
total_segments = int(task_offsets[-1] + task_counts[-1])
if total_segments == 0:
return np.empty((0, 6), dtype=np.float32)
return _write_mesh_slice_segments_numba_parallel(
transformed_vertices_zyx,
faces,
position_zyx,
face_axis_mins,
face_axis_maxs,
task_offsets,
task_counts,
total_segments,
eps,
)
def warm_numba_mesh_slice_kernels() -> None:
"""Compile numba kernels once to avoid the first interactive JIT pause."""
global numba_mesh_slice_kernels_warmed
if not NUMBA_AVAILABLE or numba_mesh_slice_kernels_warmed:
return
vertices = np.array(
[[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]],
dtype=np.float32,
)
faces = np.array([[0, 1, 2]], dtype=np.int32)
position = np.array([0.0, 0.0, 0.0], dtype=np.float32)
face_axis_mins = np.zeros((3, 1), dtype=np.float32)
face_axis_maxs = np.ones((3, 1), dtype=np.float32)
_compute_mesh_slice_segments_numba_parallel(
vertices,
faces,
position,
face_axis_mins,
face_axis_maxs,
np.float32(1e-5),
)
numba_mesh_slice_kernels_warmed = True
def intersect_triangle_with_plane(
triangle: np.ndarray, axis: int, plane_coord: float, eps: float = 1e-5
) -> Optional[tuple[np.ndarray, np.ndarray]]:
"""Intersect one triangle with an axis-aligned plane in fixed ZYX space."""
distances = triangle[:, axis] - plane_coord
if np.all(np.abs(distances) <= eps):
return None
points = []
for i, j in ((0, 1), (1, 2), (2, 0)):
d0 = distances[i]
d1 = distances[j]
p0 = triangle[i]
p1 = triangle[j]
if abs(d0) <= eps and abs(d1) <= eps:
continue
if abs(d0) <= eps:
points.append(p0)
continue
if abs(d1) <= eps:
points.append(p1)
continue
if d0 * d1 < 0:
t = d0 / (d0 - d1)
points.append(p0 + t * (p1 - p0))
unique_points = []
for point in points:
if not any(np.allclose(point, other, atol=eps) for other in unique_points):
unique_points.append(point)
if len(unique_points) < 2:
return None
if len(unique_points) == 2:
return unique_points[0], unique_points[1]
farthest_pair = None
farthest_distance = -1.0
for i in range(len(unique_points)):
for j in range(i + 1, len(unique_points)):
distance = float(np.linalg.norm(unique_points[i] - unique_points[j]))
if distance > farthest_distance:
farthest_distance = distance
farthest_pair = (unique_points[i], unique_points[j])
return farthest_pair
def compute_mesh_slice_segments(
transformed_vertices_zyx: np.ndarray,
faces: np.ndarray,
position_zyx: np.ndarray,
*,
face_axis_mins: Optional[np.ndarray] = None,
face_axis_maxs: Optional[np.ndarray] = None,
eps: float = 1e-5,
) -> np.ndarray:
"""Compute contour segments for the orthogonal XY/XZ/YZ slice planes."""
if (
NUMBA_AVAILABLE
and face_axis_mins is not None
and face_axis_maxs is not None
):
return _compute_mesh_slice_segments_numba_parallel(
transformed_vertices_zyx,
faces,
position_zyx.astype(np.float32, copy=False),
face_axis_mins,
face_axis_maxs,
np.float32(eps),
)
segments = []
for axis in range(3):
plane_coord = float(position_zyx[axis])
if face_axis_mins is not None and face_axis_maxs is not None:
intersects = (face_axis_mins[axis, :] <= plane_coord + eps) & (
face_axis_maxs[axis, :] >= plane_coord - eps
)
else:
axis_values = transformed_vertices_zyx[:, axis]
triangle_axis_values = axis_values[faces]
intersects = (triangle_axis_values.min(axis=1) <= plane_coord + eps) & (
triangle_axis_values.max(axis=1) >= plane_coord - eps
)
triangles = transformed_vertices_zyx[faces[intersects]]
for triangle in triangles:
segment = intersect_triangle_with_plane(triangle, axis, plane_coord, eps)
if segment is not None:
segments.append(
(
segment[0][0],
segment[0][1],
segment[0][2],
segment[1][0],
segment[1][1],
segment[1][2],
)
)
if not segments:
return np.empty((0, 6), dtype=np.float32)
return np.asarray(segments, dtype=np.float32)
def request_mesh_slice_overlay_update() -> None:
"""Coalesce mesh slice overlay updates onto the Neuroglancer callback queue."""
global slice_overlay_update_pending
moving_source_descriptor = globals().get("moving_source")
if (
"viewer" not in globals()
or globals().get("viewer") is None
or moving_source_descriptor is None
or moving_source_descriptor.source_type != "mesh"
or moving_mesh_geometry is None
or slice_overlay_update_pending
):
return
slice_overlay_update_pending = True
viewer.defer_callback(update_mesh_slice_overlay)
def invalidate_mesh_slice_overlay_cache() -> None:
"""Clear the last rendered slice key so the next request always refreshes."""
global last_mesh_slice_overlay_key
last_mesh_slice_overlay_key = None
def update_mesh_slice_overlay() -> None:
"""Update the moving mesh slice contour overlay."""
global slice_overlay_update_pending
global last_mesh_slice_overlay_key
slice_overlay_update_pending = False
if moving_source.source_type != "mesh" or moving_mesh_geometry is None:
return
state = viewer.state
position_zyx = np.asarray(state.position, dtype=np.float64)
transform = get_current_transform(state)
overlay_key = make_mesh_slice_overlay_key(position_zyx, transform)
if overlay_key == last_mesh_slice_overlay_key:
return
transform_cache = ensure_mesh_slice_transform_cache(transform)
segments = compute_mesh_slice_segments(
transform_cache.transformed_vertices_zyx,
moving_mesh_geometry.faces,
position_zyx,
face_axis_mins=transform_cache.face_axis_mins,
face_axis_maxs=transform_cache.face_axis_maxs,