refactor(selection): replaced with Selection instance

This commit is contained in:
maelstrom 2025-06-23 04:07:04 +02:00
parent 9c42209e93
commit 6800ac27f3
17 changed files with 191 additions and 119 deletions

View file

@ -15,24 +15,8 @@ Handles editorToolHandles;
std::vector<std::shared_ptr<Instance>> currentSelection; std::vector<std::shared_ptr<Instance>> currentSelection;
std::vector<SelectionUpdateHandler> selectionUpdateListeners;
std::vector<PropertyUpdateHandler> propertyUpdatelisteners; std::vector<PropertyUpdateHandler> propertyUpdatelisteners;
void setSelection(std::vector<std::shared_ptr<Instance>> newSelection, bool fromExplorer) {
for (SelectionUpdateHandler handler : selectionUpdateListeners) {
handler(currentSelection, newSelection, fromExplorer);
}
currentSelection = newSelection;
}
const std::vector<std::shared_ptr<Instance>> getSelection() {
return currentSelection;
}
void addSelectionListener(SelectionUpdateHandler handler) {
selectionUpdateListeners.push_back(handler);
}
void sendPropertyUpdatedSignal(std::shared_ptr<Instance> instance, std::string property, Variant newValue) { void sendPropertyUpdatedSignal(std::shared_ptr<Instance> instance, std::string property, Variant newValue) {
for (PropertyUpdateHandler handler : propertyUpdatelisteners) { for (PropertyUpdateHandler handler : propertyUpdatelisteners) {

View file

@ -11,7 +11,6 @@ class Instance;
// typedef std::function<void(std::shared_ptr<Instance> element, std::optional<std::shared_ptr<Instance>> newParent)> HierarchyUpdateHandler; // typedef std::function<void(std::shared_ptr<Instance> element, std::optional<std::shared_ptr<Instance>> newParent)> HierarchyUpdateHandler;
typedef std::function<void(std::shared_ptr<Instance> object, std::optional<std::shared_ptr<Instance>> oldParent, std::optional<std::shared_ptr<Instance>> newParent)> HierarchyPreUpdateHandler; typedef std::function<void(std::shared_ptr<Instance> object, std::optional<std::shared_ptr<Instance>> oldParent, std::optional<std::shared_ptr<Instance>> newParent)> HierarchyPreUpdateHandler;
typedef std::function<void(std::shared_ptr<Instance> object, std::optional<std::shared_ptr<Instance>> oldParent, std::optional<std::shared_ptr<Instance>> newParent)> HierarchyPostUpdateHandler; typedef std::function<void(std::shared_ptr<Instance> object, std::optional<std::shared_ptr<Instance>> oldParent, std::optional<std::shared_ptr<Instance>> newParent)> HierarchyPostUpdateHandler;
typedef std::function<void(std::vector<std::shared_ptr<Instance>> oldSelection, std::vector<std::shared_ptr<Instance>> newSelection, bool fromExplorer)> SelectionUpdateHandler;
typedef std::function<void(std::shared_ptr<Instance> instance, std::string property, Variant newValue)> PropertyUpdateHandler; typedef std::function<void(std::shared_ptr<Instance> instance, std::string property, Variant newValue)> PropertyUpdateHandler;
// TEMPORARY COMMON DATA FOR VARIOUS INTERNAL COMPONENTS // TEMPORARY COMMON DATA FOR VARIOUS INTERNAL COMPONENTS
@ -24,9 +23,5 @@ extern std::optional<HierarchyPreUpdateHandler> hierarchyPreUpdateHandler;
extern std::optional<HierarchyPostUpdateHandler> hierarchyPostUpdateHandler; extern std::optional<HierarchyPostUpdateHandler> hierarchyPostUpdateHandler;
extern Handles editorToolHandles; extern Handles editorToolHandles;
void setSelection(std::vector<std::shared_ptr<Instance>> newSelection, bool fromExplorer = false);
const std::vector<std::shared_ptr<Instance>> getSelection();
void addSelectionListener(SelectionUpdateHandler handler);
void sendPropertyUpdatedSignal(std::shared_ptr<Instance> instance, std::string property, Variant newValue); void sendPropertyUpdatedSignal(std::shared_ptr<Instance> instance, std::string property, Variant newValue);
void addPropertyUpdateListener(PropertyUpdateHandler handler); void addPropertyUpdateListener(PropertyUpdateHandler handler);

View file

@ -3,6 +3,7 @@
#include "datatypes/cframe.h" #include "datatypes/cframe.h"
#include "datatypes/vector.h" #include "datatypes/vector.h"
#include "math_helper.h" #include "math_helper.h"
#include "objects/service/selection.h"
#include "partassembly.h" #include "partassembly.h"
#include <glm/ext/scalar_common.hpp> #include <glm/ext/scalar_common.hpp>
#include <memory> #include <memory>
@ -27,7 +28,8 @@ static rp3d::PhysicsCommon common;
static rp3d::PhysicsWorld* world = common.createPhysicsWorld(); static rp3d::PhysicsWorld* world = common.createPhysicsWorld();
std::shared_ptr<Part> getHandleAdornee() { std::shared_ptr<Part> getHandleAdornee() {
for (std::weak_ptr<Instance> inst : getSelection()) { std::shared_ptr<Selection> selection = gDataModel->GetService<Selection>();
for (std::weak_ptr<Instance> inst : selection->Get()) {
if (!inst.expired() && inst.lock()->IsA<Part>()) if (!inst.expired() && inst.lock()->IsA<Part>())
return inst.lock()->CastTo<Part>().expect(); return inst.lock()->CastTo<Part>().expect();
} }
@ -78,7 +80,8 @@ Vector3 handleSize(HandleFace face) {
static int getAABBOfSelection(glm::vec3& pos, glm::vec3& size, glm::vec3& min, glm::vec3& max) { static int getAABBOfSelection(glm::vec3& pos, glm::vec3& size, glm::vec3& min, glm::vec3& max) {
int count = 0; int count = 0;
for (std::weak_ptr<Instance> inst : getSelection()) { std::shared_ptr<Selection> selection = gDataModel->GetService<Selection>();
for (std::weak_ptr<Instance> inst : selection->Get()) {
if (inst.expired() || !inst.lock()->IsA<Part>()) continue; if (inst.expired() || !inst.lock()->IsA<Part>()) continue;
std::shared_ptr<Part> part = inst.lock()->CastTo<Part>().expect(); std::shared_ptr<Part> part = inst.lock()->CastTo<Part>().expect();
@ -97,7 +100,8 @@ static int getAABBOfSelection(glm::vec3& pos, glm::vec3& size, glm::vec3& min, g
} }
static std::shared_ptr<Part> getFirstSelectedPart() { static std::shared_ptr<Part> getFirstSelectedPart() {
for (std::weak_ptr<Instance> inst : getSelection()) { std::shared_ptr<Selection> selection = gDataModel->GetService<Selection>();
for (std::weak_ptr<Instance> inst : selection->Get()) {
if (inst.expired() || !inst.lock()->IsA<Part>()) continue; if (inst.expired() || !inst.lock()->IsA<Part>()) continue;
return inst.lock()->CastTo<Part>().expect(); return inst.lock()->CastTo<Part>().expect();
@ -107,7 +111,7 @@ static std::shared_ptr<Part> getFirstSelectedPart() {
} }
CFrame getLocalHandleCFrame(HandleFace face) { CFrame getLocalHandleCFrame(HandleFace face) {
PartAssembly assembly = PartAssembly::FromSelection(); PartAssembly assembly = PartAssembly::FromSelection(gDataModel->GetService<Selection>());
Vector3 size; Vector3 size;
if (editorToolHandles.worldMode) if (editorToolHandles.worldMode)
@ -125,7 +129,7 @@ CFrame getLocalHandleCFrame(HandleFace face) {
} }
CFrame getHandleCFrame(HandleFace face) { CFrame getHandleCFrame(HandleFace face) {
PartAssembly assembly = PartAssembly::FromSelection(); PartAssembly assembly = PartAssembly::FromSelection(gDataModel->GetService<Selection>());
if (editorToolHandles.worldMode) { if (editorToolHandles.worldMode) {
return getLocalHandleCFrame(face) + assembly.assemblyOrigin().Position(); return getLocalHandleCFrame(face) + assembly.assemblyOrigin().Position();

View file

@ -11,6 +11,7 @@
#include "objects/script.h" #include "objects/script.h"
#include "objects/service/script/scriptcontext.h" #include "objects/service/script/scriptcontext.h"
#include "objects/service/script/serverscriptservice.h" #include "objects/service/script/serverscriptservice.h"
#include "objects/service/selection.h"
#include "objects/service/workspace.h" #include "objects/service/workspace.h"
#include "objects/datamodel.h" #include "objects/datamodel.h"
@ -34,4 +35,5 @@ std::map<std::string, const InstanceType*> INSTANCE_MAP = {
{ "JointsService", &JointsService::TYPE }, { "JointsService", &JointsService::TYPE },
{ "ScriptContext", &ScriptContext::TYPE }, { "ScriptContext", &ScriptContext::TYPE },
{ "ServerScriptService", &ServerScriptService::TYPE }, { "ServerScriptService", &ServerScriptService::TYPE },
{ "Selection", &Selection::TYPE },
}; };

View file

@ -66,7 +66,6 @@ public:
DEF_PROP_CATEGORY(APPEARANCE) DEF_PROP_CATEGORY(APPEARANCE)
DEF_PROP Color3 color; DEF_PROP Color3 color;
DEF_PROP float transparency = 0.f; DEF_PROP float transparency = 0.f;
bool selected = false;
DEF_PROP_CATEGORY(BEHAVIOR) DEF_PROP_CATEGORY(BEHAVIOR)
DEF_PROP_(on_update=onUpdated) bool anchored = false; DEF_PROP_(on_update=onUpdated) bool anchored = false;

View file

@ -0,0 +1,42 @@
#include "selection.h"
#include "objects/datamodel.h"
#include <algorithm>
#include <memory>
Selection::Selection(): Service(&TYPE) {
}
Selection::~Selection() = default;
void Selection::InitService() {
if (initialized) return;
initialized = true;
}
std::vector<std::shared_ptr<Instance>> Selection::Get() {
return selection;
}
void Selection::Set(std::vector<std::shared_ptr<Instance>> newSelection) {
selection = newSelection;
SelectionChanged->Fire();
}
void Selection::Add(std::vector<std::shared_ptr<Instance>> instances) {
for (auto inst : instances) {
if (std::find(selection.begin(), selection.end(), inst) == selection.end()) {
selection.push_back(inst);
}
}
SelectionChanged->Fire();
}
void Selection::Remove(std::vector<std::shared_ptr<Instance>> instances) {
for (auto inst : instances) {
std::vector<std::shared_ptr<Instance>>::iterator p;
if ((p = std::find(selection.begin(), selection.end(), inst)) != selection.end()) {
selection.erase(p);
}
}
SelectionChanged->Fire();
}

View file

@ -0,0 +1,28 @@
#pragma once
#include "datatypes/signal.h"
#include "objects/annotation.h"
#include "objects/base/service.h"
#include <memory>
#include <vector>
class DEF_INST_SERVICE Selection : public Service {
AUTOGEN_PREAMBLE
private:
std::vector<std::shared_ptr<Instance>> selection;
protected:
void InitService() override;
bool initialized = false;
public:
Selection();
~Selection();
static inline std::shared_ptr<Instance> Create() { return std::make_shared<Selection>(); };
std::vector<std::shared_ptr<Instance>> Get();
void Set(std::vector<std::shared_ptr<Instance>> newSelection);
void Add(std::vector<std::shared_ptr<Instance>> instances);
void Remove(std::vector<std::shared_ptr<Instance>> instances);
SignalSource SelectionChanged;
};

View file

@ -6,6 +6,7 @@
#include "math_helper.h" #include "math_helper.h"
#include "objects/base/instance.h" #include "objects/base/instance.h"
#include "objects/part.h" #include "objects/part.h"
#include "objects/service/selection.h"
#include <glm/common.hpp> #include <glm/common.hpp>
#include <memory> #include <memory>
#include <vector> #include <vector>
@ -54,6 +55,10 @@ PartAssembly PartAssembly::FromSelection(std::vector<std::shared_ptr<Instance>>
return PartAssembly(selection, editorToolHandles.worldMode); return PartAssembly(selection, editorToolHandles.worldMode);
} }
PartAssembly PartAssembly::FromSelection(std::shared_ptr<Selection> selection) {
return FromSelection(selection->Get());
}
void PartAssembly::SetCollisionsEnabled(bool enabled) { void PartAssembly::SetCollisionsEnabled(bool enabled) {
for (auto part : parts) { for (auto part : parts) {
part->rigidBody->getCollider(0)->setIsWorldQueryCollider(enabled); part->rigidBody->getCollider(0)->setIsWorldQueryCollider(enabled);

View file

@ -6,8 +6,7 @@
class Part; class Part;
class Instance; class Instance;
class Selection;
const std::vector<std::shared_ptr<Instance>> getSelection();
class PartAssembly { class PartAssembly {
CFrame _assemblyOrigin; CFrame _assemblyOrigin;
@ -18,7 +17,8 @@ class PartAssembly {
public: public:
PartAssembly(std::vector<std::shared_ptr<Part>>, bool worldMode = false); PartAssembly(std::vector<std::shared_ptr<Part>>, bool worldMode = false);
static PartAssembly FromSelection(std::vector<std::shared_ptr<Instance>> selection = getSelection()); static PartAssembly FromSelection(std::vector<std::shared_ptr<Instance>> selection);
static PartAssembly FromSelection(std::shared_ptr<Selection> selection);
inline CFrame assemblyOrigin() { return _assemblyOrigin; }; inline CFrame assemblyOrigin() { return _assemblyOrigin; };
inline Vector3 bounds() { return _bounds; }; inline Vector3 bounds() { return _bounds; };

View file

@ -19,6 +19,7 @@
#include "datatypes/vector.h" #include "datatypes/vector.h"
#include "handles.h" #include "handles.h"
#include "math_helper.h" #include "math_helper.h"
#include "objects/service/selection.h"
#include "partassembly.h" #include "partassembly.h"
#include "rendering/torus.h" #include "rendering/torus.h"
#include "shader.h" #include "shader.h"
@ -270,7 +271,7 @@ static CFrame XYZToZXY(glm::vec3(0, 0, 0), -glm::vec3(1, 0, 0), glm::vec3(0, 0,
void renderHandles() { void renderHandles() {
if (!editorToolHandles.active) return; if (!editorToolHandles.active) return;
auto assembly = PartAssembly::FromSelection(); auto assembly = PartAssembly::FromSelection(gDataModel->GetService<Selection>());
if (assembly.size() == Vector3::ZERO) return; if (assembly.size() == Vector3::ZERO) return;
glDepthMask(GL_TRUE); glDepthMask(GL_TRUE);
@ -448,15 +449,12 @@ void renderOutlines() {
glm::vec3 min, max; glm::vec3 min, max;
bool first = true; bool first = true;
int count = 0;
for (auto it = gWorkspace()->GetDescendantsStart(); it != gWorkspace()->GetDescendantsEnd(); it++) { std::shared_ptr<Selection> selection = gDataModel->GetService<Selection>();
std::shared_ptr<Instance> inst = *it; for (auto inst : selection->Get()) {
if (inst->GetClass() != &Part::TYPE) continue; if (inst->GetClass() != &Part::TYPE) continue;
std::shared_ptr<Part> part = std::dynamic_pointer_cast<Part>(inst); std::shared_ptr<Part> part = std::dynamic_pointer_cast<Part>(inst);
if (!part->selected) continue;
count++;
if (first) if (first)
min = part->position(), max = part->position(); min = part->position(), max = part->position();
first = false; first = false;
@ -475,7 +473,7 @@ void renderOutlines() {
} }
// Render AABB of selected parts // Render AABB of selected parts
PartAssembly selectionAssembly = PartAssembly::FromSelection(); PartAssembly selectionAssembly = PartAssembly::FromSelection(gDataModel->GetService<Selection>());
if (selectionAssembly.size() == Vector3()) return; if (selectionAssembly.size() == Vector3()) return;
glm::vec3 outlineSize = selectionAssembly.bounds(); glm::vec3 outlineSize = selectionAssembly.bounds();
glm::vec3 outlinePos = selectionAssembly.assemblyOrigin().Position(); glm::vec3 outlinePos = selectionAssembly.assemblyOrigin().Position();
@ -498,7 +496,7 @@ void renderSelectionAssembly() {
glEnable(GL_BLEND); glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
PartAssembly selectionAssembly = PartAssembly::FromSelection(); PartAssembly selectionAssembly = PartAssembly::FromSelection(gDataModel->GetService<Selection>());
// Use shader // Use shader
outlineShader->use(); outlineShader->use();
@ -555,7 +553,7 @@ void renderRotationArcs() {
// Pass in the camera position // Pass in the camera position
handleShader->set("viewPos", camera.cameraPos); handleShader->set("viewPos", camera.cameraPos);
PartAssembly assembly = PartAssembly::FromSelection(); PartAssembly assembly = PartAssembly::FromSelection(gDataModel->GetService<Selection>());
for (HandleFace face : HandleFace::Faces) { for (HandleFace face : HandleFace::Faces) {
if (glm::any(glm::lessThan(face.normal, glm::vec3(0)))) continue; if (glm::any(glm::lessThan(face.normal, glm::vec3(0)))) continue;

View file

@ -15,6 +15,7 @@
#include "math_helper.h" #include "math_helper.h"
#include "objects/base/instance.h" #include "objects/base/instance.h"
#include "objects/pvinstance.h" #include "objects/pvinstance.h"
#include "objects/service/selection.h"
#include "partassembly.h" #include "partassembly.h"
#include "physics/util.h" #include "physics/util.h"
#include "rendering/renderer.h" #include "rendering/renderer.h"
@ -217,7 +218,7 @@ void MainGLWidget::handleLinearTransform(QMouseEvent* evt) {
absDiff = handleCFrame.Rotation() * Vector3(0, 0, diff); absDiff = handleCFrame.Rotation() * Vector3(0, 0, diff);
} }
PartAssembly selectionAssembly = PartAssembly::FromSelection(); PartAssembly selectionAssembly = PartAssembly::FromSelection(gDataModel->GetService<Selection>());
if (editorToolHandles.handlesType == MoveHandles) { if (editorToolHandles.handlesType == MoveHandles) {
selectionAssembly.TransformBy(CFrame() + absDiff); selectionAssembly.TransformBy(CFrame() + absDiff);
@ -374,7 +375,7 @@ void MainGLWidget::mousePressEvent(QMouseEvent* evt) {
auto handle = raycastHandle(pointDir); auto handle = raycastHandle(pointDir);
if (handle.has_value()) { if (handle.has_value()) {
startPoint = glm::vec2(evt->pos().x(), evt->pos().y()); startPoint = glm::vec2(evt->pos().x(), evt->pos().y());
initialAssembly = PartAssembly::FromSelection(); initialAssembly = PartAssembly::FromSelection(gDataModel->GetService<Selection>());
initialFrame = initialAssembly.assemblyOrigin(); initialFrame = initialAssembly.assemblyOrigin();
isMouseDragging = true; isMouseDragging = true;
draggingHandle = handle; draggingHandle = handle;
@ -383,10 +384,11 @@ void MainGLWidget::mousePressEvent(QMouseEvent* evt) {
} }
// raycast part // raycast part
std::shared_ptr<Selection> selection = gDataModel->GetService<Selection>();
std::optional<const RaycastResult> rayHit = gWorkspace()->CastRayNearest(camera.cameraPos, pointDir, 50000); std::optional<const RaycastResult> rayHit = gWorkspace()->CastRayNearest(camera.cameraPos, pointDir, 50000);
if (!rayHit || !partFromBody(rayHit->body)) { setSelection({}); return; } if (!rayHit || !partFromBody(rayHit->body)) { selection->Set({}); return; }
std::shared_ptr<Part> part = partFromBody(rayHit->body); std::shared_ptr<Part> part = partFromBody(rayHit->body);
if (part->locked) { setSelection({}); return; } if (part->locked) { selection->Set({}); return; }
std::shared_ptr<PVInstance> selObject = part; std::shared_ptr<PVInstance> selObject = part;
@ -429,19 +431,14 @@ void MainGLWidget::mousePressEvent(QMouseEvent* evt) {
isMouseDragging = true; isMouseDragging = true;
draggingObject = part; draggingObject = part;
if (evt->modifiers() & (Qt::ControlModifier | Qt::ShiftModifier)) { if (evt->modifiers() & (Qt::ControlModifier | Qt::ShiftModifier)) {
std::vector<std::shared_ptr<Instance>> currentSelection = getSelection(); auto sel = selection->Get();
for (size_t i = 0; i < currentSelection.size(); i++) { if (std::find(sel.begin(), sel.end(), selObject) == sel.end())
std::shared_ptr<Instance> inst = currentSelection[i]; selection->Add({ selObject });
if (inst == selObject) { else
currentSelection.erase(currentSelection.begin() + i); selection->Remove({ selObject });
goto skipAddPart; } else {
} selection->Set({ selObject });
} }
currentSelection.push_back(selObject);
skipAddPart:
setSelection(currentSelection);
} else
setSelection({ selObject });
// Disable bit so that we can ignore the part while raycasting // Disable bit so that we can ignore the part while raycasting
// part->rigidBody->getCollider(0)->setCollisionCategoryBits(0b10); // part->rigidBody->getCollider(0)->setCollisionCategoryBits(0b10);
@ -509,19 +506,6 @@ void MainGLWidget::keyPressEvent(QKeyEvent* evt) {
gWorkspace()->SyncPartPhysics(lastPart); gWorkspace()->SyncPartPhysics(lastPart);
lastPart->name = "Part" + std::to_string(partId++); lastPart->name = "Part" + std::to_string(partId++);
} }
if (evt->key() == Qt::Key_U)
Logger::info("info message");
if (evt->key() == Qt::Key_I)
Logger::warning("warning message");
if (evt->key() == Qt::Key_O)
Logger::error("error message");
if (evt->key() == Qt::Key_C && getSelection().size() > 0)
getSelection()[0]->Clone().value()->SetParent(gWorkspace());
if (evt->key() == Qt::Key_H && getSelection().size() > 0)
Logger::infof("Object at: 0x%x\n", getSelection()[0].get());
} }
void MainGLWidget::keyReleaseEvent(QKeyEvent* evt) { void MainGLWidget::keyReleaseEvent(QKeyEvent* evt) {

View file

@ -5,6 +5,7 @@
#include "logger.h" #include "logger.h"
#include "objects/datamodel.h" #include "objects/datamodel.h"
#include "objects/model.h" #include "objects/model.h"
#include "objects/service/selection.h"
#include "placedocument.h" #include "placedocument.h"
#include "script/scriptdocument.h" #include "script/scriptdocument.h"
#include <memory> #include <memory>
@ -97,28 +98,6 @@ MainWindow::MainWindow(QWidget *parent)
connectActionHandlers(); connectActionHandlers();
// Update properties
addSelectionListener([&](auto oldSelection, auto newSelection, bool fromExplorer) {
if (newSelection.size() == 0) return;
if (newSelection.size() > 1)
ui->propertiesView->setSelected(std::nullopt);
ui->propertiesView->setSelected(newSelection[0]);
});
addSelectionListener([&](auto oldSelection, auto newSelection, bool __) {
for (std::weak_ptr<Instance> inst : oldSelection) {
if (inst.expired() || inst.lock()->GetClass() != &Part::TYPE) continue;
std::shared_ptr<Part> part = std::dynamic_pointer_cast<Part>(inst.lock());
part->selected = false;
}
for (std::weak_ptr<Instance> inst : newSelection) {
if (inst.expired() || inst.lock()->GetClass() != &Part::TYPE) continue;
std::shared_ptr<Part> part = std::dynamic_pointer_cast<Part>(inst.lock());
part->selected = true;
}
});
// ui->explorerView->Init(ui); // ui->explorerView->Init(ui);
placeDocument = new PlaceDocument(this); placeDocument = new PlaceDocument(this);
placeDocument->setAttribute(Qt::WA_DeleteOnClose, true); placeDocument->setAttribute(Qt::WA_DeleteOnClose, true);
@ -299,16 +278,18 @@ void MainWindow::connectActionHandlers() {
}); });
connect(ui->actionDelete, &QAction::triggered, this, [&]() { connect(ui->actionDelete, &QAction::triggered, this, [&]() {
for (std::weak_ptr<Instance> inst : getSelection()) { std::shared_ptr<Selection> selection = gDataModel->GetService<Selection>();
for (std::weak_ptr<Instance> inst : selection->Get()) {
if (inst.expired()) continue; if (inst.expired()) continue;
inst.lock()->SetParent(std::nullopt); inst.lock()->SetParent(std::nullopt);
} }
setSelection({}); selection->Set({});
}); });
connect(ui->actionCopy, &QAction::triggered, this, [&]() { connect(ui->actionCopy, &QAction::triggered, this, [&]() {
pugi::xml_document rootDoc; pugi::xml_document rootDoc;
for (std::weak_ptr<Instance> inst : getSelection()) { std::shared_ptr<Selection> selection = gDataModel->GetService<Selection>();
for (std::weak_ptr<Instance> inst : selection->Get()) {
if (inst.expired()) continue; if (inst.expired()) continue;
inst.lock()->Serialize(rootDoc); inst.lock()->Serialize(rootDoc);
} }
@ -322,11 +303,13 @@ void MainWindow::connectActionHandlers() {
}); });
connect(ui->actionCut, &QAction::triggered, this, [&]() { connect(ui->actionCut, &QAction::triggered, this, [&]() {
pugi::xml_document rootDoc; pugi::xml_document rootDoc;
for (std::weak_ptr<Instance> inst : getSelection()) { std::shared_ptr<Selection> selection = gDataModel->GetService<Selection>();
for (std::weak_ptr<Instance> inst : selection->Get()) {
if (inst.expired()) continue; if (inst.expired()) continue;
inst.lock()->Serialize(rootDoc); inst.lock()->Serialize(rootDoc);
inst.lock()->SetParent(std::nullopt); inst.lock()->SetParent(std::nullopt);
} }
selection->Set({});
std::ostringstream encoded; std::ostringstream encoded;
rootDoc.save(encoded); rootDoc.save(encoded);
@ -353,9 +336,10 @@ void MainWindow::connectActionHandlers() {
}); });
connect(ui->actionPasteInto, &QAction::triggered, this, [&]() { connect(ui->actionPasteInto, &QAction::triggered, this, [&]() {
if (getSelection().size() != 1) return; std::shared_ptr<Selection> selection = gDataModel->GetService<Selection>();
if (selection->Get().size() != 1) return;
std::shared_ptr<Instance> selectedParent = getSelection()[0]; std::shared_ptr<Instance> selectedParent = selection->Get()[0];
const QMimeData* mimeData = QApplication::clipboard()->mimeData(); const QMimeData* mimeData = QApplication::clipboard()->mimeData();
if (!mimeData || !mimeData->hasFormat("application/xml")) return; if (!mimeData || !mimeData->hasFormat("application/xml")) return;
@ -376,7 +360,8 @@ void MainWindow::connectActionHandlers() {
auto model = Model::New(); auto model = Model::New();
std::shared_ptr<Instance> firstParent; std::shared_ptr<Instance> firstParent;
for (auto object : getSelection()) { std::shared_ptr<Selection> selection = gDataModel->GetService<Selection>();
for (auto object : selection->Get()) {
if (firstParent == nullptr && object->GetParent().has_value()) firstParent = object->GetParent().value(); if (firstParent == nullptr && object->GetParent().has_value()) firstParent = object->GetParent().value();
object->SetParent(model); object->SetParent(model);
} }
@ -389,14 +374,15 @@ void MainWindow::connectActionHandlers() {
if (firstParent == nullptr) firstParent = gWorkspace(); if (firstParent == nullptr) firstParent = gWorkspace();
model->SetParent(firstParent); model->SetParent(firstParent);
setSelection({ model }); selection->Set({ model });
playSound("./assets/excluded/electronicpingshort.wav"); playSound("./assets/excluded/electronicpingshort.wav");
}); });
connect(ui->actionUngroupObjects, &QAction::triggered, this, [&]() { connect(ui->actionUngroupObjects, &QAction::triggered, this, [&]() {
std::vector<std::shared_ptr<Instance>> newSelection; std::vector<std::shared_ptr<Instance>> newSelection;
for (auto model : getSelection()) { std::shared_ptr<Selection> selection = gDataModel->GetService<Selection>();
for (auto model : selection->Get()) {
// Not a model, skip // Not a model, skip
if (!model->IsA<Model>()) { newSelection.push_back(model); continue; } if (!model->IsA<Model>()) { newSelection.push_back(model); continue; }
@ -408,7 +394,7 @@ void MainWindow::connectActionHandlers() {
model->Destroy(); model->Destroy();
} }
setSelection(newSelection); selection->Set(newSelection);
playSound("./assets/excluded/electronicpingshort.wav"); playSound("./assets/excluded/electronicpingshort.wav");
}); });
@ -421,7 +407,8 @@ void MainWindow::connectActionHandlers() {
pugi::xml_document modelDoc; pugi::xml_document modelDoc;
pugi::xml_node modelRoot = modelDoc.append_child("openblocks"); pugi::xml_node modelRoot = modelDoc.append_child("openblocks");
for (std::weak_ptr<Instance> inst : getSelection()) { std::shared_ptr<Selection> selection = gDataModel->GetService<Selection>();
for (std::weak_ptr<Instance> inst : selection->Get()) {
if (inst.expired()) continue; if (inst.expired()) continue;
inst.lock()->Serialize(modelRoot); inst.lock()->Serialize(modelRoot);
} }
@ -430,8 +417,9 @@ void MainWindow::connectActionHandlers() {
}); });
connect(ui->actionInsertModel, &QAction::triggered, this, [&]() { connect(ui->actionInsertModel, &QAction::triggered, this, [&]() {
if (getSelection().size() != 1) return; std::shared_ptr<Selection> selection = gDataModel->GetService<Selection>();
std::shared_ptr<Instance> selectedParent = getSelection()[0]; if (selection->Get().size() != 1) return;
std::shared_ptr<Instance> selectedParent = selection->Get()[0];
std::optional<std::string> path = openFileDialog("Openblocks Model (*.obm)", ".obm", QFileDialog::AcceptOpen); std::optional<std::string> path = openFileDialog("Openblocks Model (*.obm)", ".obm", QFileDialog::AcceptOpen);
if (!path) return; if (!path) return;

View file

@ -60,6 +60,8 @@ public:
void openFile(std::string path); void openFile(std::string path);
Ui::MainWindow *ui; Ui::MainWindow *ui;
friend PlaceDocument;
private: private:
PlaceDocument* placeDocument; PlaceDocument* placeDocument;
std::map<std::shared_ptr<Script>, ScriptDocument*> scriptDocuments; std::map<std::shared_ptr<Script>, ScriptDocument*> scriptDocuments;

View file

@ -5,6 +5,7 @@
#include "objects/base/instance.h" #include "objects/base/instance.h"
#include "objects/meta.h" #include "objects/meta.h"
#include "objects/script.h" #include "objects/script.h"
#include "objects/service/selection.h"
#include <memory> #include <memory>
#include <qaction.h> #include <qaction.h>
#include <qtreeview.h> #include <qtreeview.h>
@ -37,6 +38,10 @@ ExplorerView::ExplorerView(QWidget* parent):
}); });
connect(selectionModel(), &QItemSelectionModel::selectionChanged, this, [&](const QItemSelection &selected, const QItemSelection &deselected) { connect(selectionModel(), &QItemSelectionModel::selectionChanged, this, [&](const QItemSelection &selected, const QItemSelection &deselected) {
// Simple, good old debounce.
if (handlingSelectionUpdate)
return;
std::vector<std::shared_ptr<Instance>> selectedInstances; std::vector<std::shared_ptr<Instance>> selectedInstances;
selectedInstances.reserve(selectedIndexes().count()); // This doesn't reserve everything, but should enhance things anyway selectedInstances.reserve(selectedIndexes().count()); // This doesn't reserve everything, but should enhance things anyway
@ -44,20 +49,23 @@ ExplorerView::ExplorerView(QWidget* parent):
selectedInstances.push_back(reinterpret_cast<Instance*>(index.internalPointer())->shared_from_this()); selectedInstances.push_back(reinterpret_cast<Instance*>(index.internalPointer())->shared_from_this());
} }
::setSelection(selectedInstances, true); std::shared_ptr<Selection> selection = gDataModel->GetService<Selection>();
selection->Set(selectedInstances);
}); });
addSelectionListener([&](auto oldSelection, auto newSelection, bool fromExplorer) { }
// It's from us, ignore it.
if (fromExplorer) return;
this->clearSelection(); void ExplorerView::setSelectedObjects(std::vector<std::shared_ptr<Instance>> selection) {
for (std::weak_ptr<Instance> inst : newSelection) { handlingSelectionUpdate = true;
if (inst.expired()) continue;
QModelIndex index = this->model.ObjectToIndex(inst.lock()); this->clearSelection();
this->selectionModel()->select(index, QItemSelectionModel::SelectionFlag::Select); for (std::weak_ptr<Instance> inst : selection) {
} if (inst.expired()) continue;
}); QModelIndex index = this->model.ObjectToIndex(inst.lock());
this->selectionModel()->select(index, QItemSelectionModel::SelectionFlag::Select);
}
handlingSelectionUpdate = false;
} }
ExplorerView::~ExplorerView() { ExplorerView::~ExplorerView() {
@ -103,8 +111,9 @@ void ExplorerView::buildContextMenu() {
QAction* instAction = new QAction(model.iconOf(type), QString::fromStdString(type->className)); QAction* instAction = new QAction(model.iconOf(type), QString::fromStdString(type->className));
insertObjectMenu->addAction(instAction); insertObjectMenu->addAction(instAction);
connect(instAction, &QAction::triggered, this, [&]() { connect(instAction, &QAction::triggered, this, [&]() {
if (getSelection().size() == 0) return; std::shared_ptr<Selection> selection = gDataModel->GetService<Selection>();
std::shared_ptr<Instance> instParent = getSelection()[0]; if (selection->Get().size() == 0) return;
std::shared_ptr<Instance> instParent = selection->Get()[0];
std::shared_ptr<Instance> newInst = type->constructor(); std::shared_ptr<Instance> newInst = type->constructor();
newInst->SetParent(instParent); newInst->SetParent(instParent);
}); });

View file

@ -1,12 +1,14 @@
#pragma once #pragma once
#include "panes/explorermodel.h" #include "panes/explorermodel.h"
#include <memory>
#include <qmenu.h> #include <qmenu.h>
#include <qtreeview.h> #include <qtreeview.h>
class Ui_MainWindow; class Ui_MainWindow;
class ExplorerView : public QTreeView { class ExplorerView : public QTreeView {
bool handlingSelectionUpdate = false;
public: public:
ExplorerView(QWidget* parent = nullptr); ExplorerView(QWidget* parent = nullptr);
~ExplorerView() override; ~ExplorerView() override;
@ -17,6 +19,8 @@ public:
void buildContextMenu(); void buildContextMenu();
void updateRoot(std::shared_ptr<Instance> newRoot); void updateRoot(std::shared_ptr<Instance> newRoot);
void setSelectedObjects(std::vector<std::shared_ptr<Instance>> selection);
private: private:
ExplorerModel model; ExplorerModel model;
QMenu contextMenu; QMenu contextMenu;

View file

@ -1,5 +1,6 @@
#include "placedocument.h" #include "placedocument.h"
#include "common.h" #include "common.h"
#include "datatypes/variant.h"
#include "mainglwidget.h" #include "mainglwidget.h"
#include "mainwindow.h" #include "mainwindow.h"
#include "objects/joint/snap.h" #include "objects/joint/snap.h"
@ -15,6 +16,8 @@
#include <qmdisubwindow.h> #include <qmdisubwindow.h>
#include <qlayout.h> #include <qlayout.h>
#include <qmimedata.h> #include <qmimedata.h>
#include "../ui_mainwindow.h"
#include "objects/service/selection.h"
PlaceDocument::PlaceDocument(QWidget* parent): PlaceDocument::PlaceDocument(QWidget* parent):
QMdiSubWindow(parent) { QMdiSubWindow(parent) {
@ -24,6 +27,7 @@ PlaceDocument::PlaceDocument(QWidget* parent):
setWindowTitle("Place"); setWindowTitle("Place");
_runState = RUN_STOPPED; _runState = RUN_STOPPED;
updateSelectionListeners(gDataModel->GetService<Selection>());
} }
PlaceDocument::~PlaceDocument() { PlaceDocument::~PlaceDocument() {
@ -41,7 +45,7 @@ void PlaceDocument::setRunState(RunState newState) {
std::shared_ptr<DataModel> newModel = editModeDataModel->CloneModel(); std::shared_ptr<DataModel> newModel = editModeDataModel->CloneModel();
gDataModel = newModel; gDataModel = newModel;
gDataModel->Init(true); gDataModel->Init(true);
setSelection({}); updateSelectionListeners(gDataModel->GetService<Selection>());
} else if (newState == RUN_PAUSED && _runState == RUN_RUNNING) { } else if (newState == RUN_PAUSED && _runState == RUN_RUNNING) {
_runState = RUN_PAUSED; _runState = RUN_PAUSED;
} else if (newState == RUN_STOPPED) { } else if (newState == RUN_STOPPED) {
@ -49,10 +53,28 @@ void PlaceDocument::setRunState(RunState newState) {
// TODO: GC: Check to make sure gDataModel gets properly garbage collected prior to this // TODO: GC: Check to make sure gDataModel gets properly garbage collected prior to this
gDataModel = editModeDataModel; gDataModel = editModeDataModel;
setSelection({}); updateSelectionListeners(gDataModel->GetService<Selection>());
} }
} }
void PlaceDocument::updateSelectionListeners(std::shared_ptr<Selection> selection) {
MainWindow* mainWnd = dynamic_cast<MainWindow*>(window());
if (!selectionConnection.expired())
selectionConnection.lock()->Disconnect();
selectionConnection = selection->SelectionChanged->Connect([selection, mainWnd](std::vector<Variant> _){
// Update properties
if (selection->Get().size() != 1)
mainWnd->ui->propertiesView->setSelected(std::nullopt);
else
mainWnd->ui->propertiesView->setSelected(selection->Get()[0]);
// Update explorer
mainWnd->ui->explorerView->setSelectedObjects(selection->Get());
});
}
void PlaceDocument::closeEvent(QCloseEvent *closeEvent) { void PlaceDocument::closeEvent(QCloseEvent *closeEvent) {
// Placeholder // Placeholder
closeEvent->ignore(); closeEvent->ignore();

View file

@ -1,10 +1,13 @@
#pragma once #pragma once
#include "datatypes/signal.h"
#include "mainglwidget.h" #include "mainglwidget.h"
#include <qevent.h> #include <qevent.h>
#include <qmdisubwindow.h> #include <qmdisubwindow.h>
#include <QBasicTimer> #include <QBasicTimer>
class Selection;
enum RunState { enum RunState {
RUN_STOPPED, RUN_STOPPED,
RUN_RUNNING, RUN_RUNNING,
@ -15,7 +18,10 @@ class PlaceDocument : public QMdiSubWindow {
QBasicTimer timer; QBasicTimer timer;
RunState _runState; RunState _runState;
std::weak_ptr<SignalConnection> selectionConnection;
void timerEvent(QTimerEvent*) override; void timerEvent(QTimerEvent*) override;
void updateSelectionListeners(std::shared_ptr<Selection>);
public: public:
MainGLWidget* placeWidget; MainGLWidget* placeWidget;
PlaceDocument(QWidget* parent = nullptr); PlaceDocument(QWidget* parent = nullptr);