Repository navigation
Expand file tree
/
Copy pathpy_scene.cpp
More file actions
1983 lines (1822 loc) · 96.9 KB
/
Copy pathpy_scene.cpp
File metadata and controls
1983 lines (1822 loc) · 96.9 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
/* SPDX-FileCopyrightText: 2025 LichtFeld Studio Authors
*
* SPDX-License-Identifier: GPL-3.0-or-later */
#include "py_scene.hpp"
#include "core/camera.hpp"
#include "core/events.hpp"
#include "core/logger.hpp"
#include "core/path_utils.hpp"
#include "core/property_registry.hpp"
#include "io/loader.hpp"
#include "py_error.hpp"
#include "python/python_runtime.hpp"
#include "rendering/selection_ops.hpp"
#include "visualizer/gui/gui_manager.hpp"
#include "visualizer/gui_capabilities.hpp"
#include "visualizer/input/input_controller.hpp"
#include "visualizer/operation/undo_entry.hpp"
#include "visualizer/operation/undo_history.hpp"
#include "visualizer/post_work_utils.hpp"
#include "visualizer/rendering/vulkan_external_tensor.hpp"
#include "visualizer/scene/scene_manager.hpp"
#include "visualizer/training/training_manager.hpp"
#include "visualizer/training/training_state.hpp"
#include "visualizer/visualizer_impl.hpp"
#include <algorithm>
#include <cmath>
#include <glm/gtc/type_ptr.hpp>
#include <limits>
#include <nanobind/ndarray.h>
#include <stdexcept>
#include <type_traits>
#include <utility>
namespace lfs::python {
namespace {
template <typename F>
auto point_cloud_access(core::Scene* scene, F&& access) -> std::invoke_result_t<F> {
using T = std::invoke_result_t<F>;
auto* viewer = scene ? get_visualizer() : nullptr;
if (!viewer || viewer->isOnViewerThread())
return access();
const core::TaskContext context{
.name = "python.point_cloud.access",
.domain = lfs::ErrorDomain::Python,
.operation_id = lfs::OperationId::generate(),
.site = LFS_SOURCE_SITE_CURRENT(),
};
const auto cancelled = lfs::make_error(lfs::ErrorInit{
.code = lfs::ErrorCode::Cancelled,
.domain = lfs::ErrorDomain::Python,
.severity = lfs::Severity::Warning,
.detail = "Viewer is shutting down",
.detection = LFS_SOURCE_SITE_CURRENT(),
});
nb::gil_scoped_release release;
return unwrap(vis::post_guarded_and_wait<T>(
*viewer, context,
[&access]() -> lfs::Result<T> {
if constexpr (std::is_void_v<T>) {
access();
return {};
} else {
return access();
}
},
cancelled));
}
void register_scene_node_properties() {
using namespace lfs::core::prop;
PropertyGroupBuilder<core::SceneNode>("scene_node", "Scene Node")
.string_prop(&core::SceneNode::name, "name", "Name", "", "Node name")
.animatable_prop(&core::SceneNode::local_transform, "local_transform", "Transform",
glm::mat4(1.0f), "Local transform matrix")
.animatable_prop(&core::SceneNode::visible, "visible", "Visible", true,
"Node visibility")
.animatable_prop(&core::SceneNode::locked, "locked", "Locked", false,
"Lock node from editing")
.bool_prop(&core::SceneNode::training_enabled, "training_enabled", "Training Enabled",
true, "Include camera in training dataset")
.build();
}
void register_cropbox_properties() {
using namespace lfs::core::prop;
PropertyGroupBuilder<core::CropBoxData>("crop_box", "Crop Box")
.vec3_prop(&core::CropBoxData::min, "min", "Min", glm::vec3(-1.0f),
"Minimum corner of crop box")
.vec3_prop(&core::CropBoxData::max, "max", "Max", glm::vec3(1.0f),
"Maximum corner of crop box")
.bool_prop(&core::CropBoxData::inverse, "inverse", "Invert", false,
"Invert crop logic")
.bool_prop(&core::CropBoxData::enabled, "enabled", "Enabled", false,
"Enable crop filtering")
.color3_prop(&core::CropBoxData::color, "color", "Color", glm::vec3(1.0f, 1.0f, 0.0f),
"Visualization color")
.float_prop(&core::CropBoxData::line_width, "line_width", "Line Width", 2.0f, 0.1f,
10.0f, "Border line width")
.float_prop(&core::CropBoxData::flash_intensity, "flash_intensity", "Flash", 0.0f,
0.0f, 1.0f, "Flash effect intensity")
.build();
}
void register_ellipsoid_properties() {
using namespace lfs::core::prop;
PropertyGroupBuilder<core::EllipsoidData>("ellipsoid", "Ellipsoid")
.vec3_prop(&core::EllipsoidData::radii, "radii", "Radii", glm::vec3(1.0f),
"Ellipsoid radii")
.bool_prop(&core::EllipsoidData::inverse, "inverse", "Invert", false,
"Invert selection logic")
.bool_prop(&core::EllipsoidData::enabled, "enabled", "Enabled", false,
"Enable selection filtering")
.color3_prop(&core::EllipsoidData::color, "color", "Color", glm::vec3(1.0f, 1.0f, 0.0f),
"Visualization color")
.float_prop(&core::EllipsoidData::line_width, "line_width", "Line Width", 2.0f, 0.1f,
10.0f, "Border line width")
.float_prop(&core::EllipsoidData::flash_intensity, "flash_intensity", "Flash", 0.0f,
0.0f, 1.0f, "Flash effect intensity")
.build();
}
void register_crop_polygon_properties() {
using namespace lfs::core::prop;
PropertyGroupBuilder<core::CropPolygonData>("crop_polygon", "Crop Polygon")
.float_prop(&core::CropPolygonData::half_depth, "half_depth", "Half Depth", 1.0f,
core::crop_polygon::kMinHalfDepth, 1.0e6f,
"Half the extrusion depth along the local z axis")
.bool_prop(&core::CropPolygonData::inverse, "inverse", "Invert", false,
"Invert crop logic")
.bool_prop(&core::CropPolygonData::enabled, "enabled", "Enabled", true,
"Enable crop filtering")
.color3_prop(&core::CropPolygonData::color, "color", "Color", glm::vec3(1.0f, 1.0f, 0.0f),
"Visualization color")
.float_prop(&core::CropPolygonData::line_width, "line_width", "Line Width", 2.0f, 0.1f,
10.0f, "Border line width")
.float_prop(&core::CropPolygonData::flash_intensity, "flash_intensity", "Flash", 0.0f,
0.0f, 1.0f, "Flash effect intensity")
.build();
}
} // namespace
// Helper to convert glm::mat4 to nb::tuple (row-major for NumPy compatibility)
static nb::tuple mat4_to_tuple(const glm::mat4& m) {
nb::list rows;
for (int i = 0; i < 4; ++i) {
nb::list row;
for (int j = 0; j < 4; ++j) {
row.append(m[j][i]); // glm is column-major, so m[col][row]
}
rows.append(nb::tuple(row));
}
return nb::tuple(rows);
}
// Helper to convert ndarray to glm::mat4
static glm::mat4 ndarray_to_mat4(nb::ndarray<float, nb::device::cpu, nb::shape<4, 4>> arr) {
glm::mat4 m;
auto view = arr.view();
for (int i = 0; i < 4; ++i) {
for (int j = 0; j < 4; ++j) {
m[j][i] = view(i, j); // glm is column-major
}
}
return m;
}
void apply_node_transform_with_undo(const std::string& name,
const glm::mat4& transform,
core::Scene* scene) {
if (auto* const scene_manager = get_scene_manager()) {
if (auto result = vis::cap::setTransformMatrix(*scene_manager, {name}, transform,
"python.scene.set_node_transform");
!result) {
LOG_WARN("PyScene::set_node_transform fell back to direct update for '{}': {}",
name, result.error());
scene_manager->setNodeTransform(name, transform);
}
return;
}
if (scene)
scene->setNodeTransform(name, transform);
}
void ensure_scene_manager_content_type(vis::SceneManager& scene_manager,
const vis::SceneManager::ContentType content_type) {
if (scene_manager.getContentType() == vis::SceneManager::ContentType::Empty) {
scene_manager.changeContentType(content_type);
set_application_scene(&scene_manager.getScene());
}
}
template <typename Mutator>
void apply_selection_state_with_undo(vis::SceneManager& scene_manager,
const std::string& undo_label,
Mutator&& mutator) {
auto snapshot = std::make_unique<vis::op::SceneSnapshot>(scene_manager, undo_label);
snapshot->captureSelection();
mutator(scene_manager.getScene());
snapshot->captureAfter();
vis::op::pushSceneSnapshotIfChanged(std::move(snapshot));
}
[[nodiscard]] vis::op::SceneGraphCaptureOptions scene_graph_history_options(
const bool include_selected_nodes = false,
const bool include_scene_context = true) {
return vis::op::SceneGraphCaptureOptions{
.mode = vis::op::SceneGraphCaptureMode::FULL,
.include_selected_nodes = include_selected_nodes,
.include_scene_context = include_scene_context,
.payload_uuids = std::vector<core::Uuid>{},
};
}
void push_scene_graph_metadata_history(
vis::SceneManager& scene_manager,
std::string label,
const std::vector<vis::op::SceneGraphNodeMetadataSnapshot>& before,
const std::vector<vis::op::SceneGraphNodeMetadataSnapshot>& after) {
std::vector<vis::op::SceneGraphNodeMetadataDiff> diffs;
const size_t count = std::min(before.size(), after.size());
diffs.reserve(count);
for (size_t i = 0; i < count; ++i) {
diffs.push_back(vis::op::SceneGraphNodeMetadataDiff{
.before = before[i],
.after = after[i],
});
}
if (!diffs.empty()) {
vis::op::undoHistory().push(
std::make_unique<vis::op::SceneGraphMetadataEntry>(scene_manager, std::move(label), std::move(diffs)));
}
}
// PySceneNode implementation
void PySceneNode::set_local_transform(
nb::ndarray<float, nb::device::cpu, nb::shape<4, 4>> transform) {
apply_node_transform_with_undo(node().name, ndarray_to_mat4(transform), scene_);
}
nb::tuple PySceneNode::local_transform() const {
return mat4_to_tuple(node().local_transform.get());
}
nb::tuple PySceneNode::world_transform() const {
return mat4_to_tuple(scene_->getWorldTransform(node().id));
}
std::optional<PySplatData> PySceneNode::splat_data() {
auto& live = node();
if (live.type != core::NodeType::SPLAT || !live.model) {
return std::nullopt;
}
return PySplatData(live.model.get(), scene_);
}
std::optional<PyPointCloud> PySceneNode::point_cloud() {
return point_cloud_access(scene_, [&]() -> std::optional<PyPointCloud> {
auto& live = node();
if (live.type != core::NodeType::POINTCLOUD || !live.point_cloud)
return std::nullopt;
return PyPointCloud(&live, scene_);
});
}
std::optional<PyMeshInfo> PySceneNode::mesh() {
auto& live = node();
if (live.type != core::NodeType::MESH || !live.mesh) {
return std::nullopt;
}
return PyMeshInfo(live.mesh);
}
core::SceneNode& PyPointCloud::resolve_node() const {
// A scene-backed handle follows node UUID identity, never a freed node pointer.
if (scene_ && get_application_scene() == scene_) {
if (auto* node = scene_->getNodeByUuid(node_uuid_);
node && node->type == core::NodeType::POINTCLOUD && node->point_cloud) {
return *node;
}
}
throw std::runtime_error("PointCloud source node has been deleted or is no longer available");
}
std::shared_ptr<core::PointCloud> PyPointCloud::retain_data() const {
return point_cloud_access(scene_, [&] {
return owner_ ? owner_ : resolve_node().point_cloud;
});
}
PyTensor PyPointCloud::means() const {
return point_cloud_access(scene_, [&] {
const auto pc = retain_data();
return PyTensor(pc->means, false);
});
}
PyTensor PyPointCloud::colors() const {
return point_cloud_access(scene_, [&] {
const auto pc = retain_data();
return PyTensor(pc->colors, false);
});
}
std::optional<PyTensor> PyPointCloud::normals() const {
return point_cloud_access(scene_, [&]() -> std::optional<PyTensor> {
const auto pc = retain_data();
if (!pc->normals.is_valid())
return std::nullopt;
return PyTensor(pc->normals, false);
});
}
std::optional<PyTensor> PyPointCloud::sh0() const {
return point_cloud_access(scene_, [&]() -> std::optional<PyTensor> {
const auto pc = retain_data();
if (!pc->sh0.is_valid())
return std::nullopt;
return PyTensor(pc->sh0, false);
});
}
std::optional<PyTensor> PyPointCloud::shN() const {
return point_cloud_access(scene_, [&]() -> std::optional<PyTensor> {
const auto pc = retain_data();
if (!pc->shN.is_valid())
return std::nullopt;
return PyTensor(pc->shN, false);
});
}
std::optional<PyTensor> PyPointCloud::opacity() const {
return point_cloud_access(scene_, [&]() -> std::optional<PyTensor> {
const auto pc = retain_data();
if (!pc->opacity.is_valid())
return std::nullopt;
return PyTensor(pc->opacity, false);
});
}
std::optional<PyTensor> PyPointCloud::scaling() const {
return point_cloud_access(scene_, [&]() -> std::optional<PyTensor> {
const auto pc = retain_data();
if (!pc->scaling.is_valid())
return std::nullopt;
return PyTensor(pc->scaling, false);
});
}
std::optional<PyTensor> PyPointCloud::rotation() const {
return point_cloud_access(scene_, [&]() -> std::optional<PyTensor> {
const auto pc = retain_data();
if (!pc->rotation.is_valid())
return std::nullopt;
return PyTensor(pc->rotation, false);
});
}
int64_t PyPointCloud::size() const {
return point_cloud_access(scene_, [&] {
const auto pc = retain_data();
return pc->size();
});
}
bool PyPointCloud::is_gaussian() const {
return point_cloud_access(scene_, [&] {
const auto pc = retain_data();
return pc->is_gaussian();
});
}
std::vector<std::string> PyPointCloud::attribute_names() const {
return point_cloud_access(scene_, [&] {
const auto pc = retain_data();
return pc->attribute_names;
});
}
void PyPointCloud::normalize_colors() {
return point_cloud_access(scene_, [&] {
const auto pc = retain_data();
return pc->normalize_colors();
});
}
int64_t PyPointCloud::filter(const PyTensor& keep_mask) {
return point_cloud_access(scene_, [&] {
const auto pc = retain_data();
const auto& mask = keep_mask.tensor();
assert(mask.dtype() == core::DataType::Bool && "Mask must be boolean");
assert(mask.shape().rank() == 1 && "Mask must be 1D");
assert(static_cast<size_t>(mask.shape()[0]) == static_cast<size_t>(pc->size()) && "Mask size must match point count");
// Ensure mask is on same device as data
const auto device = pc->means.device();
const auto mask_dev = mask.device() == device ? mask : mask.to(device);
const int64_t old_size = pc->size();
pc->means = pc->means.is_valid() ? pc->means[mask_dev] : pc->means;
pc->colors = pc->colors.is_valid() ? pc->colors[mask_dev] : pc->colors;
pc->normals = pc->normals.is_valid() ? pc->normals[mask_dev] : pc->normals;
pc->sh0 = pc->sh0.is_valid() ? pc->sh0[mask_dev] : pc->sh0;
pc->shN = pc->shN.is_valid() ? pc->shN[mask_dev] : pc->shN;
pc->opacity = pc->opacity.is_valid() ? pc->opacity[mask_dev] : pc->opacity;
pc->scaling = pc->scaling.is_valid() ? pc->scaling[mask_dev] : pc->scaling;
pc->rotation = pc->rotation.is_valid() ? pc->rotation[mask_dev] : pc->rotation;
if (scene_) {
scene_->setPointCloudModified(true);
scene_->notifyMutation(core::Scene::MutationType::MODEL_CHANGED);
}
return old_size - pc->size();
});
}
int64_t PyPointCloud::filter_indices(const PyTensor& indices) {
return point_cloud_access(scene_, [&] {
const auto pc = retain_data();
const auto& idx = indices.tensor();
assert(idx.shape().rank() == 1 && "Indices must be 1D");
const auto device = pc->means.device();
const auto idx_dev = idx.device() == device ? idx : idx.to(device);
const int64_t old_size = pc->size();
pc->means = pc->means.is_valid() ? pc->means[idx_dev] : pc->means;
pc->colors = pc->colors.is_valid() ? pc->colors[idx_dev] : pc->colors;
pc->normals = pc->normals.is_valid() ? pc->normals[idx_dev] : pc->normals;
pc->sh0 = pc->sh0.is_valid() ? pc->sh0[idx_dev] : pc->sh0;
pc->shN = pc->shN.is_valid() ? pc->shN[idx_dev] : pc->shN;
pc->opacity = pc->opacity.is_valid() ? pc->opacity[idx_dev] : pc->opacity;
pc->scaling = pc->scaling.is_valid() ? pc->scaling[idx_dev] : pc->scaling;
pc->rotation = pc->rotation.is_valid() ? pc->rotation[idx_dev] : pc->rotation;
if (scene_) {
scene_->setPointCloudModified(true);
scene_->notifyMutation(core::Scene::MutationType::MODEL_CHANGED);
}
return old_size - pc->size();
});
}
void PyPointCloud::set_data(const PyTensor& points, const PyTensor& colors) {
return point_cloud_access(scene_, [&] {
const auto pc = retain_data();
auto* const node = scene_ ? &resolve_node() : nullptr;
const auto& pts = points.tensor();
const auto& cols = colors.tensor();
assert(pts.shape().rank() == 2 && pts.shape()[1] == 3);
assert(cols.shape().rank() == 2 && cols.shape()[1] == 3);
assert(pts.shape()[0] == cols.shape()[0]);
pc->means = pts.to(core::Device::CUDA);
pc->colors = cols.to(core::Device::CUDA);
const int64_t n = pc->size();
if (node) {
node->gaussian_count.store(static_cast<size_t>(n), std::memory_order_release);
if (n > 0) {
auto centroid = pc->means.mean(0).cpu();
auto acc = centroid.accessor<float, 1>();
node->centroid = glm::vec3(acc(0), acc(1), acc(2));
}
}
if (scene_) {
scene_->setPointCloudModified(true);
scene_->notifyMutation(core::Scene::MutationType::MODEL_CHANGED);
}
});
}
void PyPointCloud::set_colors(const PyTensor& colors) {
return point_cloud_access(scene_, [&] {
const auto pc = retain_data();
const auto& cols = colors.tensor();
assert(cols.shape().rank() == 2 && cols.shape()[1] == 3);
assert(cols.shape()[0] == pc->size());
pc->colors = cols.to(pc->means.device());
if (scene_) {
scene_->setPointCloudModified(true);
scene_->notifyMutation(core::Scene::MutationType::MODEL_CHANGED);
}
});
}
void PyPointCloud::set_means(const PyTensor& points) {
return point_cloud_access(scene_, [&] {
const auto pc = retain_data();
auto* const node = scene_ ? &resolve_node() : nullptr;
const auto& pts = points.tensor();
assert(pts.shape().rank() == 2 && pts.shape()[1] == 3);
assert(pts.shape()[0] == pc->size());
pc->means = pts.to(pc->colors.device());
if (node && pc->size() > 0) {
auto centroid = pc->means.mean(0).cpu();
auto acc = centroid.accessor<float, 1>();
node->centroid = glm::vec3(acc(0), acc(1), acc(2));
}
if (scene_) {
scene_->setPointCloudModified(true);
scene_->notifyMutation(core::Scene::MutationType::MODEL_CHANGED);
}
});
}
std::optional<PyCropBox> PySceneNode::cropbox() {
auto& live = node();
if (live.type != core::NodeType::CROPBOX || !live.cropbox) {
return std::nullopt;
}
return PyCropBox(live.cropbox.get());
}
std::optional<PyEllipsoid> PySceneNode::ellipsoid() {
auto& live = node();
if (live.type != core::NodeType::ELLIPSOID || !live.ellipsoid) {
return std::nullopt;
}
return PyEllipsoid(live.ellipsoid.get());
}
std::optional<PyCropPolygon> PySceneNode::crop_polygon() {
auto& live = node();
if (live.type != core::NodeType::CROP_POLYGON || !live.crop_polygon) {
return std::nullopt;
}
return PyCropPolygon(live.crop_polygon.get());
}
std::optional<PyKeyframeData> PySceneNode::keyframe_data() {
auto& live = node();
if (live.type != core::NodeType::KEYFRAME || !live.keyframe) {
return std::nullopt;
}
const auto& kf = *live.keyframe;
return PyKeyframeData{
.keyframe_index = kf.keyframe_index,
.time = kf.time,
.position = {kf.position.x, kf.position.y, kf.position.z},
.rotation = {kf.rotation.w, kf.rotation.x, kf.rotation.y, kf.rotation.z},
.focal_length_mm = kf.focal_length_mm,
.easing = static_cast<int>(kf.easing)};
}
// PyScene implementation
PyScene::PyScene(core::Scene* scene)
: scene_(scene),
generation_(get_scene_generation()) {
assert(scene_ != nullptr);
}
bool PyScene::is_valid() const {
return scene_ == get_application_scene() && generation_ == get_scene_generation();
}
uint64_t PyScene::generation() const {
return generation_;
}
uint64_t PyScene::render_generation() const {
if (!is_valid()) {
throw std::runtime_error("Scene reference is no longer valid");
}
return scene_->renderGeneration();
}
int32_t PyScene::add_group(const std::string& name, int32_t parent) {
if (auto* const scene_manager = get_scene_manager()) {
std::string parent_name;
if (parent != core::NULL_NODE) {
const auto* parent_node = scene_->getNodeById(parent);
if (!parent_node) {
return core::NULL_NODE;
}
parent_name = parent_node->name;
}
const auto created_name = scene_manager->addGroupNode(name, parent_name);
if (created_name.empty()) {
return core::NULL_NODE;
}
return scene_->getNodeIdByName(created_name);
}
return scene_->addGroup(name, parent);
}
int32_t PyScene::add_splat(const std::string& name,
const PyTensor& means,
const PyTensor& sh0,
const PyTensor& shN,
const PyTensor& scaling,
const PyTensor& rotation,
const PyTensor& opacity,
const int sh_degree,
const float scene_scale,
const int32_t parent,
const bool transient) {
const auto require_float32 = [](const char* field, const PyTensor& tensor) {
const auto dtype = tensor.tensor().dtype();
if (dtype != core::DataType::Float32) {
throw std::runtime_error(std::string("add_splat: ") + field +
" must be float32, got " + core::dtype_name(dtype));
}
};
require_float32("means", means);
require_float32("sh0", sh0);
require_float32("shN", shN);
require_float32("scaling", scaling);
require_float32("rotation", rotation);
require_float32("opacity", opacity);
// A transient node is not part of the document: it is never saved, and
// adding it leaves nothing to undo.
std::optional<vis::op::SceneGraphStateSnapshot> history_before;
if (auto* const scene_manager = get_scene_manager(); scene_manager && !transient) {
history_before = vis::op::SceneGraphPatchEntry::captureState(*scene_manager, {name});
}
auto splat = std::make_unique<core::SplatData>(
sh_degree,
means.tensor().clone(),
sh0.tensor().clone(),
shN.tensor().clone(),
scaling.tensor().clone(),
rotation.tensor().clone(),
opacity.tensor().clone(),
scene_scale);
if (auto allocator = vis::makeViewerSplatTensorAllocator()) {
if (auto migrated = io::migrateSplatTensorsToAllocator(*splat, allocator); !migrated) {
throw std::runtime_error("Failed to prepare splat tensors for rendering: " +
migrated.error().format());
}
scene_->setCombinedModelAllocator(std::move(allocator));
}
const size_t gaussian_count = splat->size();
const int32_t node_id = scene_->addSplat(name, std::move(splat), parent);
if (node_id == core::NULL_NODE) {
return core::NULL_NODE;
}
auto* const added = scene_->getNodeById(node_id);
assert(added);
const std::string added_name = added ? added->name : name;
if (added) {
added->transient = transient;
}
lfs::core::events::state::PLYAdded{
.name = added_name,
.uuid = added->uuid,
.node_gaussians = gaussian_count,
.total_gaussians = scene_->getTotalGaussianCount(),
.is_visible = true,
.parent_name = "",
.is_group = false,
.node_type = 0}
.emit();
if (auto* const scene_manager = get_scene_manager()) {
ensure_scene_manager_content_type(*scene_manager, vis::SceneManager::ContentType::SplatFiles);
if (history_before) {
vis::op::undoHistory().push(std::make_unique<vis::op::SceneGraphPatchEntry>(
*scene_manager,
"Add Splat",
std::move(*history_before),
vis::op::SceneGraphPatchEntry::captureState(*scene_manager, {added_name})));
}
}
return node_id;
}
int32_t PyScene::add_point_cloud(const std::string& name,
const PyTensor& points,
const PyTensor& colors,
const int32_t parent) {
std::optional<vis::op::SceneGraphStateSnapshot> history_before;
if (auto* const scene_manager = get_scene_manager()) {
history_before = vis::op::SceneGraphPatchEntry::captureState(*scene_manager, {name});
}
const auto& pts = points.tensor();
const auto& cols = colors.tensor();
assert(pts.shape().rank() == 2 && pts.shape()[1] == 3);
assert(cols.shape().rank() == 2 && cols.shape()[1] == 3);
assert(pts.shape()[0] == cols.shape()[0]);
if (cols.dtype() != core::DataType::UInt8 && cols.dtype() != core::DataType::Float32)
throw nb::value_error("colors must have dtype uint8 or float32");
auto pc = std::make_shared<core::PointCloud>(pts.to(core::Device::CUDA), cols.to(core::Device::CUDA));
const int32_t node_id = scene_->addPointCloud(name, std::move(pc), parent);
if (node_id == core::NULL_NODE) {
return core::NULL_NODE;
}
const auto* const added = scene_->getNodeById(node_id);
const std::string added_name = added ? added->name : name;
if (auto* const scene_manager = get_scene_manager()) {
ensure_scene_manager_content_type(*scene_manager, vis::SceneManager::ContentType::SplatFiles);
vis::op::undoHistory().push(std::make_unique<vis::op::SceneGraphPatchEntry>(
*scene_manager,
"Add Point Cloud",
std::move(*history_before),
vis::op::SceneGraphPatchEntry::captureState(*scene_manager, {added_name})));
}
return node_id;
}
int32_t PyScene::add_mesh(const std::string& name,
const PyTensor& vertices,
const PyTensor& indices,
std::optional<PyTensor> colors,
std::optional<PyTensor> normals,
const int32_t parent) {
std::optional<vis::op::SceneGraphStateSnapshot> history_before;
if (auto* const scene_manager = get_scene_manager()) {
history_before = vis::op::SceneGraphPatchEntry::captureState(*scene_manager, {name});
}
const auto& verts = vertices.tensor();
const auto& idx = indices.tensor();
assert(verts.shape().rank() == 2 && verts.shape()[1] == 3);
assert(idx.shape().rank() == 2 && idx.shape()[1] == 3);
auto mesh = std::make_shared<core::MeshData>(
verts.to(core::DataType::Float32).to(core::Device::CPU),
idx.to(core::DataType::Int32).to(core::Device::CPU));
if (colors && colors->tensor().is_valid()) {
const auto& c = colors->tensor();
if (c.ndim() != 2 || c.size(0) != verts.size(0) || c.size(1) != 4)
throw nb::value_error("colors must have shape [N, 4] matching vertices");
mesh->colors = c.to(core::DataType::Float32).to(core::Device::CPU);
}
if (normals && normals->tensor().is_valid()) {
const auto& n = normals->tensor();
assert(n.shape().rank() == 2 && n.shape()[1] == 3 && n.shape()[0] == verts.shape()[0]);
mesh->normals = n.to(core::DataType::Float32).to(core::Device::CPU);
} else {
mesh->compute_normals();
}
const int32_t node_id = scene_->addMesh(name, std::move(mesh), parent);
if (node_id == core::NULL_NODE) {
return core::NULL_NODE;
}
if (auto* const scene_manager = get_scene_manager()) {
ensure_scene_manager_content_type(*scene_manager, vis::SceneManager::ContentType::SplatFiles);
const auto* const added = scene_->getNodeById(node_id);
const std::string added_name = added ? added->name : name;
vis::op::undoHistory().push(std::make_unique<vis::op::SceneGraphPatchEntry>(
*scene_manager,
"Add Mesh",
std::move(*history_before),
vis::op::SceneGraphPatchEntry::captureState(*scene_manager, {added_name})));
}
return node_id;
}
int32_t PyScene::add_camera_group(const std::string& name, const int32_t parent, const size_t camera_count) {
std::optional<vis::op::SceneGraphStateSnapshot> history_before;
if (auto* const scene_manager = get_scene_manager()) {
history_before = vis::op::SceneGraphPatchEntry::captureState(*scene_manager, {name});
}
const int32_t node_id = scene_->addCameraGroup(name, parent, camera_count);
if (node_id == core::NULL_NODE) {
return core::NULL_NODE;
}
const auto* const added = scene_->getNodeById(node_id);
const std::string added_name = added ? added->name : name;
if (auto* const scene_manager = get_scene_manager()) {
ensure_scene_manager_content_type(*scene_manager, vis::SceneManager::ContentType::Dataset);
vis::op::undoHistory().push(std::make_unique<vis::op::SceneGraphPatchEntry>(
*scene_manager,
"Add Camera Group",
std::move(*history_before),
vis::op::SceneGraphPatchEntry::captureState(*scene_manager, {added_name})));
}
return node_id;
}
int32_t PyScene::add_camera(const std::string& name,
const int32_t parent,
const PyTensor& R,
const PyTensor& T,
float focal_x,
float focal_y,
int width,
int height,
const std::string& image_path,
int uid,
std::optional<PyTensor> mask) {
std::optional<vis::op::SceneGraphStateSnapshot> history_before;
if (auto* const scene_manager = get_scene_manager()) {
history_before = vis::op::SceneGraphPatchEntry::captureState(*scene_manager, {name});
}
const auto& R_tensor = R.tensor();
const auto& T_tensor = T.tensor();
if (!R_tensor.is_valid() || R_tensor.dtype() != core::DataType::Float32 || R_tensor.ndim() != 2 ||
R_tensor.size(0) != 3 || R_tensor.size(1) != 3)
throw nb::value_error("R must be a float32 tensor of shape [3, 3]");
if (!T_tensor.is_valid() || T_tensor.dtype() != core::DataType::Float32 || T_tensor.numel() != 3 ||
!(T_tensor.ndim() == 1 || (T_tensor.ndim() == 2 && T_tensor.size(1) == 1)))
throw nb::value_error("T must be a float32 tensor of shape [3] or [3, 1]");
const auto all_finite = [](const core::Tensor& tensor) {
const auto cpu = tensor.cpu().contiguous();
const auto* values = cpu.ptr<float>();
return std::all_of(values, values + cpu.numel(), [](const float value) { return std::isfinite(value); });
};
if (!all_finite(R_tensor))
throw nb::value_error("R must contain finite values");
if (!all_finite(T_tensor))
throw nb::value_error("T must contain finite values");
if (!std::isfinite(focal_x) || focal_x <= 0.0f || !std::isfinite(focal_y) || focal_y <= 0.0f)
throw nb::value_error("focal_x and focal_y must be finite and positive");
if (width <= 0 || height <= 0)
throw nb::value_error("width and height must be positive");
auto T_flat = T_tensor.ndim() == 2 ? T_tensor.reshape({3}) : T_tensor;
// A camera without a uid is skipped by uid-keyed features such as the frustum overlay: give it the next free one.
if (uid < 0) {
uid = 0;
for (const auto& existing : *scene_->getAllCamerasCached()) {
if (!existing)
continue;
if (existing->uid() == std::numeric_limits<int>::max())
throw nb::value_error("Cannot auto-assign a camera uid above INT_MAX");
uid = std::max(uid, existing->uid() + 1);
}
}
auto camera = std::make_shared<lfs::core::Camera>(
R_tensor.clone(),
T_flat.clone(),
focal_x, focal_y,
static_cast<float>(width) / 2.0f, static_cast<float>(height) / 2.0f,
lfs::core::Tensor{},
lfs::core::Tensor{},
lfs::core::CameraModelType::PINHOLE,
name,
lfs::core::utf8_to_path(image_path),
std::filesystem::path{},
width, height,
uid);
// Attach an in-memory mask if the caller passed one (direct-scene
// plugins use this to bypass the on-disk masks/ workflow).
if (mask.has_value() && mask->tensor().is_valid()) {
camera->set_mask_tensor(mask->tensor().clone());
}
const int32_t node_id = scene_->addCamera(name, parent, std::move(camera));
if (node_id == core::NULL_NODE) {
return core::NULL_NODE;
}
if (auto* const scene_manager = get_scene_manager()) {
const auto* added = scene_->getNodeById(node_id);
const std::string added_name = added ? added->name : name;
ensure_scene_manager_content_type(*scene_manager, vis::SceneManager::ContentType::Dataset);
vis::op::undoHistory().push(std::make_unique<vis::op::SceneGraphPatchEntry>(
*scene_manager,
"Add Camera",
std::move(*history_before),
vis::op::SceneGraphPatchEntry::captureState(*scene_manager, {added_name})));
}
return node_id;
}
void PyScene::remove_node(const std::string& name, bool keep_children) {
if (auto* const scene_manager = get_scene_manager()) {
if (auto result = scene_manager->removePLYWithResult(name, keep_children); !result) {
throw std::runtime_error(result.error());
}
return;
}
scene_->removeNode(name, keep_children);
}
bool PyScene::rename_node(const std::string& old_name, const std::string& new_name) {
if (auto* const scene_manager = get_scene_manager()) {
return scene_manager->renamePLY(old_name, new_name);
}
return scene_->renameNode(old_name, new_name);
}
void PyScene::clear() {
if (get_visualizer()) {
nb::gil_scoped_release release;
unwrap(clear_application_scene());
return;
}
if (auto* const scene_manager = get_scene_manager()) {
if (scene_manager->clear()) {
return;
}
if (auto* const trainer_manager = lfs::python::get_trainer_manager();
trainer_manager &&
scene_manager->getContentType() == lfs::vis::SceneManager::ContentType::Dataset &&
!trainer_manager->canPerform(lfs::vis::TrainingAction::ClearScene)) {
throw std::runtime_error(
std::string(trainer_manager->getActionBlockedReason(lfs::vis::TrainingAction::ClearScene)));
}
throw std::runtime_error("Scene clear request was rejected");
return;
}
scene_->clear();
}
bool PyScene::reparent(int32_t node_id, int32_t new_parent_id) {
if (auto* const scene_manager = get_scene_manager()) {
return scene_manager->reparentNode(node_id, new_parent_id);
}
return scene_->reparent(node_id, new_parent_id);
}
std::optional<PySceneNode> PyScene::get_node_by_id(int32_t id) {
auto* node = scene_->getNodeById(id);
if (!node)
return std::nullopt;
return PySceneNode(node, scene_);
}
std::optional<PySceneNode> PyScene::get_node_by_uuid(const std::string& uuid) {
const auto parsed = core::Uuid::from_string(uuid);
if (!parsed)
return std::nullopt;
auto* node = scene_->getNodeByUuid(*parsed);
if (!node)
return std::nullopt;
return PySceneNode(node, scene_);
}
std::optional<PySceneNode> PyScene::get_node(const std::string& name) {
// Use the const lookup + const_cast so we don't blow the combined-model
// cache on every read. Actual mutations go through SceneNode property
// setters whose callbacks trigger Scene::notifyMutation, which still
// invalidates the cache — same pattern as get_nodes/get_visible_nodes.
const auto* node = scene_->getNode(name);
if (!node)
return std::nullopt;
return PySceneNode(const_cast<core::SceneNode*>(node), scene_);
}
std::vector<PySceneNode> PyScene::get_nodes() {
std::vector<PySceneNode> result;
for (const auto* node : scene_->getNodes()) {
result.emplace_back(const_cast<core::SceneNode*>(node), scene_);
}
return result;
}
std::vector<PySceneNode> PyScene::get_visible_nodes() {
std::vector<PySceneNode> result;
for (const auto* node : scene_->getVisibleNodes()) {
result.emplace_back(const_cast<core::SceneNode*>(node), scene_);
}
return result;
}
std::vector<PySceneSplatSnapshot> PyScene::snapshot_visible_splats() {
std::vector<PySceneSplatSnapshot> result;
for (auto& snapshot : scene_->snapshotVisibleSplats()) {
result.emplace_back(std::move(snapshot));
}
return result;
}
std::vector<PySceneNode> PyScene::get_active_cameras() {
std::vector<PySceneNode> result;
for (const auto* node : scene_->getNodes()) {
if (node->type == core::NodeType::CAMERA && node->camera && node->training_enabled) {
result.emplace_back(const_cast<core::SceneNode*>(node), scene_);
}
}
return result;
}
namespace {
bool camera_needs_distortion_handling(const core::Camera& cam) {
return cam.radial_distortion().numel() != 0 ||
cam.tangential_distortion().numel() != 0 ||
cam.camera_model_type() != core::CameraModelType::PINHOLE;
}
} // namespace