refactor: improve ContainerBox geometry handling and add missing signal disconnections to prevent memory leaks.

This commit is contained in:
AndreaRigoni
2026-04-21 14:06:35 +00:00
parent 503c325f9a
commit 2bf3dc0b6d
7 changed files with 154 additions and 150 deletions

View File

@@ -9,96 +9,101 @@
//////////////////////////////////////////////////////////////////////////////*/ //////////////////////////////////////////////////////////////////////////////*/
#include "Vtk/Math/vtkAssembly.h"
#include "Math/Units.h"
#include "Vtk/Math/vtkAssembly.h" #include "Vtk/Math/vtkAssembly.h"
#include "Vtk/Math/vtkContainerBox.h" #include "Vtk/Math/vtkContainerBox.h"
#include "Vtk/Math/vtkCylinder.h" #include "Vtk/Math/vtkCylinder.h"
#include "Vtk/Math/vtkAssembly.h"
#include "Vtk/vtkObjectsContext.h"
#include "Vtk/uLibVtkViewer.h" #include "Vtk/uLibVtkViewer.h"
#include "Math/Units.h" #include "Vtk/vtkObjectsContext.h"
#include <vtkActor.h> #include <vtkActor.h>
#include <vtkProperty.h>
#include <vtkPropCollection.h> #include <vtkPropCollection.h>
#include <vtkProperty.h>
#include <iostream> #include <iostream>
using namespace uLib; using namespace uLib;
int main(int argc, char **argv) { int main(int argc, char **argv) {
bool interactive = (argc > 1 && std::string(argv[1]) == "-i"); bool interactive = (argc > 1 && std::string(argv[1]) == "-i");
// ---- 1. Build model objects ---- // ---- 1. Build model objects ----
ContainerBox box1; ContainerBox box1;
box1.Scale(Vector3f(1_m, 2_m, 0.5_m)); box1.Scale(Vector3f(1_m, 2_m, 0.5_m));
box1.SetPosition(Vector3f(0, 0, 0)); box1.SetPosition(Vector3f(0, 0, 0));
ContainerBox box2; ContainerBox box2;
box2.Scale(Vector3f(0.5_m, 0.5_m, 3_m)); box2.Scale(Vector3f(0.5_m, 0.5_m, 3_m));
box2.SetPosition(Vector3f(2_m, 0, 0)); box2.SetPosition(Vector3f(2_m, 0, 0));
Cylinder cyl(0.3_m, 1.5_m, 1); Cylinder cyl(0.3_m, 1.5_m, 1);
cyl.SetPosition(Vector3f(0, 3_m, 0)); cyl.SetPosition(Vector3f(0, 3_m, 0));
// ---- 2. Create an Assembly and add objects ---- // ---- 2. Create an Assembly and add objects ----
Assembly assembly; Assembly assembly;
assembly.AddObject(&box1); assembly.AddObject(&box1);
assembly.AddObject(&box2); assembly.AddObject(&box2);
assembly.AddObject(&cyl); assembly.AddObject(&cyl);
assembly.SetShowBoundingBox(true); assembly.SetShowBoundingBox(true);
// ---- 3. Apply a group transform ---- // ---- 3. Apply a group transform ----
assembly.SetPosition(Vector3f(1_m, 1_m, 0)); assembly.SetPosition(Vector3f(1_m, 1_m, 0));
// ---- 5. Visualize (create prop3ds to set properties) ---- // ---- 5. Visualize (create prop3ds to set properties) ----
Vtk::Assembly vtkAsm(&assembly); Vtk::Assembly vtkAsm(&assembly);
Vtk::Viewer viewer; Vtk::Viewer viewer;
vtkAsm.AddToViewer(viewer); // This triggers prop3d creation via ConnectRenderer which eventually calls Prop3D::GetProp vtkAsm.AddToViewer(
viewer); // This triggers prop3d creation via ConnectRenderer which
// Explicitly update to ensure prop3ds exist and are added to assemblies // eventually calls Prop3D::GetProp
vtkAsm.Update();
// Use the child context to find child prop3ds and set colors // Explicitly update to ensure prop3ds exist and are added to assemblies
if (auto* childCtx = vtkAsm.GetChildrenContext()) { vtkAsm.Update();
auto setProps = [](Vtk::Prop3D* p, float r, float g, float b) {
if (!p) return;
vtkPropCollection* props = p->GetProps();
props->InitTraversal();
for (int i=0; i < props->GetNumberOfItems(); ++i) {
if (auto* actor = vtkActor::SafeDownCast(props->GetNextProp())) {
actor->GetProperty()->SetColor(r, g, b);
actor->GetProperty()->SetRepresentationToSurface();
actor->GetProperty()->SetOpacity(0.5);
}
}
};
setProps(childCtx->GetProp3D(&box1), 1.0, 0.0, 0.0); // Red // Use the child context to find child prop3ds and set colors
setProps(childCtx->GetProp3D(&box2), 0.0, 1.0, 0.0); // Green if (auto *childCtx = vtkAsm.GetChildrenContext()) {
setProps(childCtx->GetProp3D(&cyl), 0.0, 0.0, 1.0); // Blue auto setProps = [](Vtk::Prop3D *p, float r, float g, float b) {
} if (!p)
return;
vtkPropCollection *props = p->GetProps();
props->InitTraversal();
for (int i = 0; i < props->GetNumberOfItems(); ++i) {
if (auto *actor = vtkActor::SafeDownCast(props->GetNextProp())) {
actor->GetProperty()->SetColor(r, g, b);
actor->GetProperty()->SetRepresentationToSurface();
actor->GetProperty()->SetOpacity(0.5);
}
}
};
std::cout << "Prop3Ds in viewport: " << viewer.getProp3Ds().size() << " (Expected 4: 1 assembly + 3 children)" << std::endl; setProps(childCtx->GetProp3D(&box1), 1.0, 0.0, 0.0); // Red
setProps(childCtx->GetProp3D(&box2), 0.0, 1.0, 0.0); // Green
setProps(childCtx->GetProp3D(&cyl), 0.0, 0.0, 1.0); // Blue
}
// ---- 4. Query the bounding box for terminal output ---- std::cout << "Prop3Ds in viewport: " << viewer.getProp3Ds().size()
Vector3f bbMin, bbMax; << " (Expected 4: 1 assembly + 3 children)" << std::endl;
assembly.GetBoundingBox(bbMin, bbMax);
std::cout << "Assembly bounding box:" << std::endl;
std::cout << " min = " << bbMin.transpose() << std::endl;
std::cout << " max = " << bbMax.transpose() << std::endl;
std::cout << "==================================================\n"; // ---- 4. Query the bounding box for terminal output ----
std::cout << " vtkAssemblyTest\n"; Vector3f bbMin, bbMax;
std::cout << " 2 boxes + 1 cylinder grouped in an assembly\n"; assembly.GetBoundingBox(bbMin, bbMax);
std::cout << "==================================================" << std::endl; std::cout << "Assembly bounding box:" << std::endl;
std::cout << " min = " << bbMin.transpose() << std::endl;
std::cout << " max = " << bbMax.transpose() << std::endl;
if (interactive) { std::cout << "==================================================\n";
viewer.ZoomAuto(); std::cout << " vtkAssemblyTest\n";
viewer.Start(); std::cout << " 2 boxes + 1 cylinder grouped in an assembly\n";
} else { std::cout << "=================================================="
std::cout << "Non-interactive test passed." << std::endl; << std::endl;
}
return 0; if (interactive) {
viewer.ZoomAuto();
viewer.Start();
} else {
std::cout << "Non-interactive test passed." << std::endl;
}
return 0;
} }

View File

@@ -35,20 +35,17 @@ using namespace uLib;
int main() { int main() {
BEGIN_TESTING(vtk ContainerBox Test); BEGIN_TESTING(vtk ContainerBox Test);
{ ContainerBox* box = new ContainerBox();
ContainerBox* box = new ContainerBox(); box->SetSize(Vector3f(1_m, 2_m, 1_m));
box->Scale(Vector3f(1_m, 2_m, 1_m)); box->SetPosition(Vector3f(0, 0, 0));
box->SetPosition(Vector3f(0, 0, 0));
Vtk::ContainerBox v_box(box); Vtk::ContainerBox v_box(box);
v_box.Update(); v_box.Update();
v_box.SetRepresentation(Vtk::Prop3D::Surface); v_box.SetRepresentation(Vtk::Prop3D::Surface);
v_box.SetOpacity(0.5); v_box.SetOpacity(0.5);
v_box.SetSelectable(true); v_box.SetSelectable(true);
}
Vtk::ContainerBox v_box;
v_box.findOrAddSignal(&Object::Updated)->connect([&v_box]() { v_box.findOrAddSignal(&Object::Updated)->connect([&v_box]() {
std::cout << "box updated: " std::cout << "box updated: "
<< v_box.GetWrapped()->GetWorldPoint(HPoint3f(1, 1, 1)) << std::endl; << v_box.GetWrapped()->GetWorldPoint(HPoint3f(1, 1, 1)) << std::endl;

View File

@@ -59,9 +59,9 @@ int main(int argc, char **argv) {
// --- Image 1: Spherical Shell --- // --- Image 1: Spherical Shell ---
Vector3i dims1(64, 64, 64); Vector3i dims1(64, 64, 64);
VoxImage<Voxel> img1(dims1); VoxImage<Voxel>* img1 = new VoxImage<Voxel>(dims1);
img1.SetSpacing(Vector3f(1.0, 1.0, 1.0)); img1->SetSpacing(Vector3f(1.0, 1.0, 1.0));
img1.SetPosition(Vector3f(-40, -32, -32)); img1->SetPosition(Vector3f(-40, -32, -32));
for (int z = 0; z < dims1(2); ++z) { for (int z = 0; z < dims1(2); ++z) {
for (int y = 0; y < dims1(1); ++y) { for (int y = 0; y < dims1(1); ++y) {
@@ -76,16 +76,16 @@ int main(int argc, char **argv) {
} else { } else {
v.Value = 0.0f; v.Value = 0.0f;
} }
img1[Vector3i(x, y, z)] = v; img1->operator[](Vector3i(x, y, z)) = v;
} }
} }
} }
// --- Image 2: Axes Gradient --- // --- Image 2: Axes Gradient ---
Vector3i dims2(64, 64, 64); Vector3i dims2(64, 64, 64);
VoxImage<Voxel> img2(dims2); VoxImage<Voxel>* img2 = new VoxImage<Voxel>(dims2);
img2.SetSpacing(Vector3f(1.0, 1.0, 1.0)); img2->SetSpacing(Vector3f(1.0, 1.0, 1.0));
img2.SetPosition(Vector3f(40, -32, -32)); img2->SetPosition(Vector3f(40, -32, -32));
for (int z = 0; z < dims2(2); ++z) { for (int z = 0; z < dims2(2); ++z) {
for (int y = 0; y < dims2(1); ++y) { for (int y = 0; y < dims2(1); ++y) {
@@ -96,15 +96,15 @@ int main(int argc, char **argv) {
(float(x) / dims2(0) + float(y) / dims2(1) + float(z) / dims2(2)) / (float(x) / dims2(0) + float(y) / dims2(1) + float(z) / dims2(2)) /
3.0f; 3.0f;
v.Value = (40.0f * val) / factor; v.Value = (40.0f * val) / factor;
img2[Vector3i(x, y, z)] = v; img2->operator[](Vector3i(x, y, z)) = v;
} }
} }
} }
Vtk::VoxImage vtk_img1(&img1); Vtk::VoxImage vtk_img1(img1);
vtk_img1.setShadingPreset(0); vtk_img1.setShadingPreset(0);
Vtk::VoxImage vtk_img2(&img2); Vtk::VoxImage vtk_img2(img2);
vtk_img2.setShadingPreset(1); // Use Composite without MIP for variety vtk_img2.setShadingPreset(1); // Use Composite without MIP for variety
Vtk::Viewer viewer; Vtk::Viewer viewer;

View File

@@ -40,12 +40,12 @@ BOOST_AUTO_TEST_CASE(vtkVoxImageConstruction) {
TestVoxel zero = {0, 0}; TestVoxel zero = {0, 0};
TestVoxel nonzero = {5.5f * 1e-6f, 100}; TestVoxel nonzero = {5.5f * 1e-6f, 100};
VoxImage<TestVoxel> img(Vector3i(10, 10, 10)); VoxImage<TestVoxel>* img = new VoxImage<TestVoxel>(Vector3i(10, 10, 10));
img.SetSpacing(Vector3f(3, 3, 3)); img->SetSpacing(Vector3f(3, 3, 3));
img.InitVoxels(zero); img->InitVoxels(zero);
img[Vector3i(3, 3, 3)] = nonzero; (*img)[Vector3i(3, 3, 3)] = nonzero;
Vtk::VoxImage vtk_img(&img); Vtk::VoxImage vtk_img(img);
vtk_img.SaveToXMLFile("test_vtkvoximage.vti"); vtk_img.SaveToXMLFile("test_vtkvoximage.vti");
if (std::getenv("CTEST_PROJECT_NAME") == nullptr) { if (std::getenv("CTEST_PROJECT_NAME") == nullptr) {

View File

@@ -44,6 +44,10 @@ Assembly::Assembly(uLib::Assembly *content)
} }
Assembly::~Assembly() { Assembly::~Assembly() {
if (this->m_model) {
Object::disconnect(this->m_model.get(), &uLib::Assembly::Updated,
this, &Assembly::Update);
}
delete m_ChildContext; delete m_ChildContext;
if (m_BBoxActor) m_BBoxActor->Delete(); if (m_BBoxActor) m_BBoxActor->Delete();
if (m_VtkAsm) m_VtkAsm->Delete(); if (m_VtkAsm) m_VtkAsm->Delete();

View File

@@ -38,6 +38,8 @@
#include <vtkMatrix4x4.h> #include <vtkMatrix4x4.h>
#include <vtkPolyDataMapper.h> #include <vtkPolyDataMapper.h>
#include <vtkProperty.h> #include <vtkProperty.h>
#include <vtkRenderWindow.h>
#include <vtkRendererCollection.h>
#include <vtkSmartPointer.h> #include <vtkSmartPointer.h>
#include <vtkTransform.h> #include <vtkTransform.h>
@@ -50,25 +52,33 @@ struct ContainerBoxData {
vtkSmartPointer<vtkActor> m_Cube; vtkSmartPointer<vtkActor> m_Cube;
vtkSmartPointer<vtkActor> m_Axes; vtkSmartPointer<vtkActor> m_Axes;
vtkSmartPointer<vtkAssembly> m_VtkAsm; vtkSmartPointer<vtkAssembly> m_VtkAsm;
vtkSmartPointer<vtkCubeSource> m_CubeSource;
vtkSmartPointer<vtkAxes> m_AxesSource;
uLib::Connection m_UpdateSignal; uLib::Connection m_UpdateSignal;
ContainerBoxData() ContainerBoxData()
: m_Cube(vtkSmartPointer<vtkActor>::New()), : m_Cube(vtkSmartPointer<vtkActor>::New()),
m_Axes(vtkSmartPointer<vtkActor>::New()), m_Axes(vtkSmartPointer<vtkActor>::New()),
m_VtkAsm(vtkSmartPointer<vtkAssembly>::New()) {} m_VtkAsm(vtkSmartPointer<vtkAssembly>::New()),
~ContainerBoxData() {} m_CubeSource(vtkSmartPointer<vtkCubeSource>::New()),
m_AxesSource(vtkSmartPointer<vtkAxes>::New()) {}
}; };
ContainerBox::ContainerBox(ContainerBox::Content *content) ContainerBox::ContainerBox(uLib::ContainerBox *model)
: d(new ContainerBoxData()), : Prop3D(), d(new ContainerBoxData()) {
ObjectWrapper(content ? content : new Content()) { this->m_model.reset(model);
this->InstallPipe(); this->InstallPipe();
d->m_UpdateSignal = Object::connect( d->m_UpdateSignal = Object::connect(
this->m_model.get(), &uLib::Object::Updated, this, &ContainerBox::Update); this->m_model.get(), &uLib::Object::Updated, this, &ContainerBox::Update);
this->Update(); this->Update();
} }
ContainerBox::~ContainerBox() { delete d; } ContainerBox::~ContainerBox() {
uLib::Object::disconnect(this->m_model.get(), &uLib::Object::Updated, this,
&ContainerBox::Update);
delete d;
}
vtkPolyData *ContainerBox::GetPolyData() const { vtkPolyData *ContainerBox::GetPolyData() const {
// TODO // TODO
@@ -80,22 +90,35 @@ void ContainerBox::Update() {
if (!this->m_model) if (!this->m_model)
return; return;
vtkProp3D *prop = vtkProp3D::SafeDownCast(this->GetProp()); // Update the sources with the model's dimensions.
if (prop) { // This makes the "natural" bounds of the actors correct for VTK gizmos.
// Apply the TRS matrix to the assembly Vector3f size = this->m_model->GetSize();
vtkNew<vtkMatrix4x4> m; Vector3f origin = this->m_model->GetOrigin();
Matrix4fToVtk(this->m_model->GetMatrix(), m);
prop->SetUserMatrix(m);
prop->Modified();
}
// Apply the local shape transformation (Size/Origin) to the cube actor // HandlerWidget relies on vtkProp3D::GetBounds() to determine the size
vtkNew<vtkMatrix4x4> localM; // and position of its transformation gizmos. Previously, we were applying
Matrix4fToVtk(this->m_model->GetLocalMatrix(), localM); // the Size of the container using the actor's UserMatrix. While this looks
d->m_Cube->SetUserMatrix(localM); // correct visually, some VTK utilities (including certain internal paths
// of GetBounds()) may prioritize the bounding box of the input geometry
// (the PolyData) over the UserMatrix. This resulted in the gizmo defaulting
// to a 1x1x1 size because the underlying vtkCubeSource was still 1x1x1.
// Delegate rest of update (appearance, render, etc) d->m_CubeSource->SetBounds(origin.x(), origin.x() + size.x(), origin.y(),
ConnectionBlock blocker(d->m_UpdateSignal); origin.y() + size.y(), origin.z(),
origin.z() + size.z());
d->m_CubeSource->Update();
d->m_AxesSource->SetOrigin(origin.x(), origin.y(), origin.z());
d->m_AxesSource->SetScaleFactor(std::max({size.x(), size.y(), size.z()}));
d->m_AxesSource->Update();
// Ensure actors have identity UserMatrix since scaling is in the source.
d->m_Cube->SetUserMatrix(nullptr);
d->m_Axes->SetUserMatrix(nullptr);
// Delegate the rest of the update (appearance, TR, render, etc) to Prop3D.
// Prop3D::Update() applies the "outer" TRS matrix (Position/Rotation/Scaling)
// to the assembly.
this->Prop3D::Update(); this->Prop3D::Update();
} }
@@ -104,66 +127,35 @@ void ContainerBox::SyncFromVtk() {
if (!this->m_model) if (!this->m_model)
return; return;
vtkProp3D *root = this->GetProxyProp(); // Sync the "outer" TRS from the assembly's matrix
if (!root) this->Prop3D::SyncFromVtk();
return;
// VTK -> Model: Extract new world TRS from proxy, which matches the model's
// TRS center
vtkMatrix4x4 *rootMat = root->GetUserMatrix();
Matrix4f vtkWorld = VtkToMatrix4f(rootMat);
// Synchronize TRS property members from the updated local matrix
this->m_model->FromMatrix(vtkWorld);
// Since we modified the model, notify observers, but block the loop back to
// VTK ConnectionBlock blocker(d->m_UpdateSignal);
this->m_model->Updated();
} }
void ContainerBox::InstallPipe() { void ContainerBox::InstallPipe() {
if (!this->m_model) if (!this->m_model)
return; return;
Content *c = this->m_model;
// CUBE vtkSmartPointer<vtkPolyDataMapper> mapper =
vtkSmartPointer<vtkPolyDataMapper>::New();
vtkSmartPointer<vtkPolyDataMapper> mapper = vtkSmartPointer<vtkPolyDataMapper>::New(); // CUBE //
vtkSmartPointer<vtkCubeSource> cube = vtkSmartPointer<vtkCubeSource>::New(); mapper->SetInputConnection(d->m_CubeSource->GetOutputPort());
// cube->SetBounds(-0.5, 0.5, -0.5, 0.5, -0.5, 0.5);
mapper->SetInputConnection(cube->GetOutputPort());
mapper->Update();
d->m_Cube->SetMapper(mapper); d->m_Cube->SetMapper(mapper);
d->m_Cube->GetProperty()->SetRepresentationToWireframe(); d->m_Cube->GetProperty()->SetRepresentationToWireframe();
d->m_Cube->GetProperty()->SetAmbient(0.7); d->m_Cube->GetProperty()->SetAmbient(0.7);
// AXES // // AXES //
vtkSmartPointer<vtkAxes> axes = vtkSmartPointer<vtkAxes>::New();
axes->SetOrigin(0, 0, 0);
mapper = vtkSmartPointer<vtkPolyDataMapper>::New(); mapper = vtkSmartPointer<vtkPolyDataMapper>::New();
mapper->SetInputConnection(axes->GetOutputPort()); mapper->SetInputConnection(d->m_AxesSource->GetOutputPort());
mapper->Update();
d->m_Axes->SetMapper(mapper); d->m_Axes->SetMapper(mapper);
d->m_Axes->GetProperty()->SetLineWidth(3); d->m_Axes->GetProperty()->SetLineWidth(3);
d->m_Axes->GetProperty()->SetAmbient(0.4); d->m_Axes->GetProperty()->SetAmbient(0.4);
d->m_Axes->GetProperty()->SetSpecular(0); d->m_Axes->GetProperty()->SetSpecular(0);
// PIVOT //
axes = vtkSmartPointer<vtkAxes>::New();
axes->SetOrigin(0, 0, 0);
mapper = vtkSmartPointer<vtkPolyDataMapper>::New();
mapper->SetInputConnection(axes->GetOutputPort());
mapper->Update();
d->m_VtkAsm->AddPart(d->m_Cube); d->m_VtkAsm->AddPart(d->m_Cube);
d->m_VtkAsm->AddPart(d->m_Axes); d->m_VtkAsm->AddPart(d->m_Axes);
this->SetProp(d->m_VtkAsm); this->SetProp(d->m_VtkAsm);
// vtkProp3D* root = d->m_VtkAsm;
// if (root) {
// this->ApplyProp3DTransform(root);
// }
this->Update(); this->Update();
} }

View File

@@ -36,6 +36,12 @@ ObjectsContext::ObjectsContext(uLib::ObjectsContext *context)
} }
ObjectsContext::~ObjectsContext() { ObjectsContext::~ObjectsContext() {
if (m_Context) {
Object::disconnect(m_Context, &uLib::ObjectsContext::ObjectAdded, this,
&ObjectsContext::OnObjectAdded);
Object::disconnect(m_Context, &uLib::ObjectsContext::ObjectRemoved, this,
&ObjectsContext::OnObjectRemoved);
}
for (auto const &[obj, prop3d] : m_Prop3Ds) { for (auto const &[obj, prop3d] : m_Prop3Ds) {
delete prop3d; delete prop3d;
} }