载入中...
搜索中...
未找到
Scene.cpp
浏览该文件的文档.
1#include "common/ECS.h"
3#include "scene/Scene.h"
5#include "scene/PcgGrowth.h"
6
10#include "scene/SceneBounds.h"
12#include "scene/SceneInternal.h"
13#include "scene/SceneSearch.h"
15
16#include "spatial/Octree.h"
17
18#ifdef EVENGINE_SCENE_JSON
19#include <Poco/JSON/Array.h>
20#include <Poco/JSON/Object.h>
21#include <Poco/JSON/Parser.h>
22#include <Poco/JSON/Stringifier.h>
23#endif
24
25#include <simplesquirrel/simplesquirrel.hpp>
26
27#include <glm/glm.hpp>
28#include <glm/gtc/matrix_transform.hpp>
29#include <glm/gtc/quaternion.hpp>
30
31#include <cstring>
32#include <limits>
33#include <sstream>
34#include <utility>
35#include <stdexcept>
36
37namespace eve::scene {
38namespace detail {
39// Internal module binding entry point; no cross-module callers.
40void injectSceneComponentClass(ssq::Table &eveTable);
41} // namespace detail
42
48
51 if (vm_) {
52 for (auto &item : delayedDetaches_) sq_release(vm_, &item.instance);
53 }
54 delayedDetaches_.clear();
55}
56
58
59namespace {
60
61template <class T>
62T *borrowSceneResult(eve::Result<T *> result) {
63 if (!result.ok()) return nullptr;
64 return std::move(result).takeValue();
65}
66
67SceneHost *findHostByName(const std::string &name) {
68 if (name.empty()) return nullptr;
69 if (ecs::current()->getManager<SceneHost>() == nullptr) return nullptr;
70 auto view = ecs::View<SceneHost, SceneHost::Meta>();
71 for (auto it = view.begin(); it != view.end(); ++it) {
72 auto [meta] = *it;
73 if (meta->entity && meta->name == name) return meta->entity;
74 }
75 return nullptr;
76}
77
78SceneHost *findHostByOwnerId(uint32_t ownerId) {
79 if (ownerId == 0) return nullptr;
80 if (ecs::current()->getManager<SceneHost>() == nullptr) return nullptr;
81 auto view = ecs::View<SceneHost, SceneHost::Meta>();
82 for (auto it = view.begin(); it != view.end(); ++it) {
83 auto [meta] = *it;
84 if (meta->entity && meta->ownerId == ownerId) return meta->entity;
85 }
86 return nullptr;
87}
88
90void setStringField(HSQUIRRELVM vm, HSQOBJECT inst, const char *name,
91 const std::string &value) {
92 if (!vm || inst._type != OT_INSTANCE) return;
93 const SQInteger top = sq_gettop(vm);
94 sq_pushobject(vm, inst);
95 sq_pushstring(vm, name, -1);
96 sq_pushstring(vm, value.c_str(), -1);
97 if (SQ_FAILED(sq_set(vm, -3))) {
98 sq_settop(vm, top);
99 sq_pushobject(vm, inst);
100 sq_pushstring(vm, name, -1);
101 sq_pushstring(vm, value.c_str(), -1);
102 sq_newslot(vm, -3, SQFalse);
103 }
104 sq_settop(vm, top);
105}
106
107bool sameScriptObject(const HSQOBJECT &a, const HSQOBJECT &b) {
108 return a._type == b._type &&
109 std::memcmp(&a._unVal, &b._unVal, sizeof(a._unVal)) == 0;
110}
111
112// --- JSON serialization helpers ---
113
114#ifdef EVENGINE_SCENE_JSON
115Poco::JSON::Object::Ptr nodeToJson(const SceneHost::Tree &tree, const SceneNode *n) {
116 Poco::JSON::Object::Ptr o = new Poco::JSON::Object;
117 o->set("id", n->id);
118 if (!n->persistentId.isNil()) o->set("persistentId", n->persistentId.format());
119 o->set("key", n->key);
120 o->set("name", n->name);
121 o->set("space", n->space);
122 o->set("visible", n->visible);
123 o->set("layer", n->layer);
124 o->set("x", n->x);
125 o->set("y", n->y);
126 o->set("z", n->z);
127 o->set("yaw", n->yaw);
128 o->set("pitch", n->pitch);
129 o->set("roll", n->roll);
130 o->set("sx", n->sx);
131 o->set("sy", n->sy);
132 o->set("sz", n->sz);
133 if (n->hasBounds) {
134 o->set("bminX", n->bminX);
135 o->set("bminY", n->bminY);
136 o->set("bminZ", n->bminZ);
137 o->set("bmaxX", n->bmaxX);
138 o->set("bmaxY", n->bmaxY);
139 o->set("bmaxZ", n->bmaxZ);
140 }
141 if (!n->tags.empty()) {
142 Poco::JSON::Array::Ptr arr = new Poco::JSON::Array;
143 for (const auto &t : n->tags) arr->add(t);
144 o->set("tags", arr);
145 }
146 if (n->firstChild >= 0) {
147 Poco::JSON::Array::Ptr kids = new Poco::JSON::Array;
148 for (int c = n->firstChild; c >= 0;
149 c = tree.nodes[size_t(c)].nextSibling) {
150 kids->add(nodeToJson(tree, &tree.nodes[size_t(c)]));
151 }
152 o->set("children", kids);
153 }
154 return o;
155}
156
157NodeDesc nodeFromJson(const Poco::JSON::Object::Ptr &o) {
158 NodeDesc d;
159 d.id = o->optValue<std::string>("id", "");
160 const std::string persistentId = o->optValue<std::string>("persistentId", "");
161 if (!persistentId.empty()) {
162 if (const auto parsed = eve::SceneObjectId::parse(persistentId)) d.persistentId = *parsed;
163 }
164 d.key = o->optValue<std::string>("key", d.id);
165 d.name = o->optValue<std::string>("name", d.id);
166 d.space = o->optValue<std::string>("space", "3d");
167 d.visible = o->optValue<bool>("visible", true);
168 d.layer = o->optValue<int>("layer", 0);
169 d.x = float(o->optValue<double>("x", 0.0));
170 d.y = float(o->optValue<double>("y", 0.0));
171 d.z = float(o->optValue<double>("z", 0.0));
172 d.yaw = float(o->optValue<double>("yaw", 0.0));
173 d.pitch = float(o->optValue<double>("pitch", 0.0));
174 d.roll = float(o->optValue<double>("roll", 0.0));
175 d.sx = float(o->optValue<double>("sx", 1.0));
176 d.sy = float(o->optValue<double>("sy", 1.0));
177 d.sz = float(o->optValue<double>("sz", 1.0));
178 if (o->has("bminX")) {
179 d.bminX = float(o->optValue<double>("bminX", 0.0));
180 d.bminY = float(o->optValue<double>("bminY", 0.0));
181 d.bminZ = float(o->optValue<double>("bminZ", 0.0));
182 d.bmaxX = float(o->optValue<double>("bmaxX", 0.0));
183 d.bmaxY = float(o->optValue<double>("bmaxY", 0.0));
184 d.bmaxZ = float(o->optValue<double>("bmaxZ", 0.0));
185 d.hasBounds = true;
186 }
187 if (o->has("tags")) {
188 Poco::JSON::Array::Ptr arr = o->getArray("tags");
189 for (size_t i = 0; i < arr->size(); ++i) {
190 d.tags.push_back(arr->getElement<std::string>(static_cast<unsigned int>(i)));
191 }
192 }
193 if (o->has("children")) {
194 Poco::JSON::Array::Ptr kids = o->getArray("children");
195 for (size_t i = 0; i < kids->size(); ++i) {
196 d.children.push_back(nodeFromJson(kids->getObject(static_cast<unsigned int>(i))));
197 }
198 }
199 return d;
200}
201#endif
202
203
208const char *kSceneEntityBaseScript = R"SQ(
209eve.SceneEntity <- class extends eve.Entity {
210 _scene = null
211 hostName = ""
212 nodeId = ""
213 _enabled = true
214
215 function scene() { return _scene }
216 function node() {
217 if (_scene == null) return null
218 return _scene.getNodeRefAt(hostName, nodeId)
219 }
220 function isEnabled() { return _enabled }
221 function setEnabled(enabled) {
222 local next = !!enabled
223 if (_enabled == next) return
224 _enabled = next
225 if (_enabled) onEnable()
226 else onDisable()
227 }
228 function enable() { setEnabled(true) }
229 function disable() { setEnabled(false) }
230 function onAttach() {}
231 function onDetach() {}
232 function onEnable() {}
233 function onDisable() {}
234 function update(dt) {}
235}
236)SQ";
237
242const char* kSceneEntityScript = R"SQ(
243// ---- eve.Scene: per-node entity API (script wrappers over native primitives) ----
244
245eve.Scene["getNodeRef"] <- function(nodeId, hostName = null) {
246 if (hostName == null) hostName = currentHostName()
247 return getNodeRefAt(hostName, nodeId) } eve.Scene["getNodeRefByPath"] <- function(path) {
248 return getNodeRefByPathAt(currentHostName(), path) } eve.Scene["attachEntity"] <- function(nodeId, cls) {
249 return attachEntityAt(currentHostName(), nodeId, cls) } eve.Scene["attachEntityAt"] <- function(hostName, nodeId, cls) {
250 if (typeof cls != "class") return null
251 // Must be an eve.SceneEntity, not merely an eve.Entity: the body below stores the
252 // host binding in `_scene`, `hostName` and `nodeId`, which only SceneEntity
253 // declares. Accepting a plain Entity subclass used to die mid-call with
254 // "the index '_scene' does not exist" instead of taking this rejection path.
255 if (!eve.isSubclass(cls, eve.SceneEntity)) return null
256 local old = getEntityAt(hostName, nodeId, cls)
257 if (old != null) detachEntityAt(hostName, nodeId, old)
258 local inst = cls.create()
259 inst._scene = this
260 inst.hostName = hostName
261 inst.nodeId = nodeId
262 if (!rootEntity(hostName, nodeId, inst)) {
263 inst.destroy()
264 return null
265 }
266 inst.onAttach()
267 return inst
268}
269
270eve.Scene["detachEntity"] <- function(nodeId, inst) {
271 return detachEntityAt(currentHostName(), nodeId, inst) } eve.Scene["detachEntityAt"] <- function(hostName, nodeId, inst) {
272 if (inst == null) return false
273 local idx = -1
274 forEachEntity(hostName, nodeId, function(e, index) {
275 if (idx < 0 && e == inst) idx = index
276 })
277 if (idx < 0) return false
278 inst.onDetach()
279 inst.destroy()
280 return unrootEntityAt(hostName, nodeId, idx) } eve.Scene["scheduleDetachEntity"] <- function(nodeId, inst) {
281 // Native scheduleDetachEntityAt is bound on the class; this is the selected-host helper.
282 return scheduleDetachEntityAt(currentHostName(), nodeId, inst) } eve.Scene["collectIdsWith"] <- function(cls, hostName = null) {
283 if (hostName == null) hostName = currentHostName()
284 local out = []
285 foreach (id in collectIds()) {
286 if (hasEntityAt(hostName, id, cls)) out.push(id)
287 }
288 return out
289}
290
291eve.Scene["getEntity"] <- function(nodeId, cls) {
292 return getEntityAt(currentHostName(), nodeId, cls) } eve.Scene["getEntityAt"] <- function(hostName, nodeId, cls) {
293 local out = null
294 forEachEntity(hostName, nodeId, function(e, index) {
295 if (out == null && e instanceof cls) out = e
296 })
297 return out
298}
299
300eve.Scene["hasEntity"] <- function(nodeId, cls) {
301 return getEntityAt(currentHostName(), nodeId, cls) != null
302}
303
304eve.Scene["hasEntityAt"] <- function(hostName, nodeId, cls) {
305 return getEntityAt(hostName, nodeId, cls) != null
306}
307
308eve.Scene["entitiesOf"] <- function(nodeId) {
309 return entitiesOfAt(currentHostName(), nodeId) } eve.Scene["entitiesOfAt"] <- function(hostName, nodeId) {
310 local out = []
311 forEachEntity(hostName, nodeId, function(e, index) { out.push(e) })
312 return out
313}
314
315eve.Scene["update"] <- function(dt) {
316 updateScripts(dt)
317}
318
319// ---- eve.Scene: generic link system (selected-host convenience) ----
320
321eve.Scene["linkPhysics2D"] <- function(nodeId, body, mode = "node") {
322 return linkPhysics2DAt(currentHostName(), nodeId, body, mode) } eve.Scene["linkPhysics3D"] <- function(nodeId, body, mode = "node") {
323 return linkPhysics3DAt(currentHostName(), nodeId, body, mode) } eve.Scene["linkCamera3D"] <- function(nodeId, cam) {
324 return linkCamera3DAt(currentHostName(), nodeId, cam) } eve.Scene["linkAudio3D"] <- function(nodeId, source) {
325 return linkAudio3DAt(currentHostName(), nodeId, source) } eve.Scene["unlinkNodeKind"] <- function(nodeId, kind) {
326 return unlinkNodeKindAt(currentHostName(), nodeId, kind) } eve.Scene["linkCount"] <- function(nodeId) {
327 return linkCountAt(currentHostName(), nodeId)
328}
329
330// ---- eve.SceneNodeRef: node-level entity forwarding ----
331
332eve.SceneNodeRef["attachEntity"] <- function(cls) {
333 return getScene().attachEntityAt(getHostName(), getNodeId(), cls)
334}
335eve.SceneNodeRef["detachEntity"] <- function(inst) {
336 return getScene().detachEntityAt(getHostName(), getNodeId(), inst)
337}
338eve.SceneNodeRef["getEntity"] <- function(cls) {
339 return getScene().getEntityAt(getHostName(), getNodeId(), cls)
340}
341eve.SceneNodeRef["hasEntity"] <- function(cls) {
342 return getScene().hasEntityAt(getHostName(), getNodeId(), cls)
343}
344eve.SceneNodeRef["entitiesOf"] <- function() {
345 return getScene().entitiesOfAt(getHostName(), getNodeId())
346}
347eve.SceneNodeRef["scheduleDetachEntity"] <- function(inst) {
348 return getScene().scheduleDetachEntityAt(getHostName(), getNodeId(), inst)
349}
350
351// ---- eve.SceneNodeRef: generic link system ----
352
353eve.SceneNodeRef["linkRenderable2D"] <- function(r) {
354 return getScene().linkRenderable2DAt(getHostName(), getNodeId(), r)
355}
356eve.SceneNodeRef["linkRenderable3D"] <- function(r) {
357 return getScene().linkRenderable3DAt(getHostName(), getNodeId(), r)
358}
359eve.SceneNodeRef["linkPhysics2D"] <- function(body, mode = "node") {
360 return getScene().linkPhysics2DAt(getHostName(), getNodeId(), body, mode)
361}
362eve.SceneNodeRef["linkPhysics3D"] <- function(body, mode = "node") {
363 return getScene().linkPhysics3DAt(getHostName(), getNodeId(), body, mode)
364}
365eve.SceneNodeRef["linkCamera3D"] <- function(cam) {
366 return getScene().linkCamera3DAt(getHostName(), getNodeId(), cam)
367}
368eve.SceneNodeRef["linkAudio3D"] <- function(source) {
369 return getScene().linkAudio3DAt(getHostName(), getNodeId(), source)
370}
371eve.SceneNodeRef["unlinkNode"] <- function() {
372 return getScene().unlinkNodeAt(getHostName(), getNodeId())
373}
374eve.SceneNodeRef["unlinkNodeKind"] <- function(kind) {
375 return getScene().unlinkNodeKindAt(getHostName(), getNodeId(), kind)
376}
377eve.SceneNodeRef["linkCount"] <- function() {
378 return getScene().linkCountAt(getHostName(), getNodeId())
379}
380
381// ---- eve.Scene: script-API completeness (selected-host convenience) ----
382
383eve.Scene["_requireNode"] <- function(nodeId) {
384 if (!hasNode(nodeId)) throw "scene: node '" + nodeId + "' not found"
385}
386eve.Scene["getNodePosition"] <- function(nodeId) {
387 _requireNode(nodeId)
388 return getNodePositionAt(currentHostName(), nodeId) } eve.Scene["getNodeRotation"] <- function(nodeId) {
389 _requireNode(nodeId)
390 return getNodeRotationAt(currentHostName(), nodeId) } eve.Scene["getNodeScale"] <- function(nodeId) {
391 _requireNode(nodeId)
392 return getNodeScaleAt(currentHostName(), nodeId) } eve.Scene["getNodeVisible"] <- function(nodeId) {
393 _requireNode(nodeId)
394 return getNodeVisibleAt(currentHostName(), nodeId) } eve.Scene["getNodeWorldPosition"] <- function(nodeId) {
395 _requireNode(nodeId)
396 return getNodeWorldPositionAt(currentHostName(), nodeId) } eve.Scene["getNodeWorldRotation"] <- function(nodeId) {
397 _requireNode(nodeId)
398 return getNodeWorldRotationAt(currentHostName(), nodeId) } eve.Scene["getNodeWorldScale"] <- function(nodeId) {
399 _requireNode(nodeId)
400 return getNodeWorldScaleAt(currentHostName(), nodeId) } eve.Scene["localToWorld"] <- function(nodeId, x, y, z) {
401 _requireNode(nodeId)
402 return localToWorldAt(currentHostName(), nodeId, x, y, z) } eve.Scene["worldToLocal"] <- function(nodeId, x, y, z) {
403 _requireNode(nodeId)
404 return worldToLocalAt(currentHostName(), nodeId, x, y, z) } eve.Scene["setNodeParent"] <- function(nodeId, parentId) { return setNodeParentAt(currentHostName(), nodeId, parentId) }
405eve.Scene["removeNode"] <- function(nodeId) { return removeNodeAt(currentHostName(), nodeId) }
406eve.Scene["addNodeChild"] <- function(parentId, childId) { return addChildAt(currentHostName(), parentId, childId) }
407eve.Scene["removeNodeChild"] <- function(parentId, childId) { return removeChildAt(currentHostName(), parentId, childId) }
408eve.Scene["setNodeQuaternion"] <- function(nodeId, qx, qy, qz, qw) { return setNodeQuaternionAt(currentHostName(), nodeId, qx, qy, qz, qw) }
409eve.Scene["getNodeQuaternion"] <- function(nodeId) {
410 _requireNode(nodeId)
411 return getNodeQuaternionAt(currentHostName(), nodeId) } eve.Scene["setNodeLookAt"] <- function(nodeId, tx, ty, tz) { return setNodeLookAtAt(currentHostName(), nodeId, tx, ty, tz) }
412eve.Scene["addNodeTag"] <- function(nodeId, tag) { return addNodeTagAt(currentHostName(), nodeId, tag) }
413eve.Scene["removeNodeTag"] <- function(nodeId, tag) { return removeNodeTagAt(currentHostName(), nodeId, tag) }
414eve.Scene["hasNodeTag"] <- function(nodeId, tag) { return hasNodeTagAt(currentHostName(), nodeId, tag) }
415eve.Scene["getNodeTags"] <- function(nodeId) {
416 _requireNode(nodeId)
417 return getNodeTagsAt(currentHostName(), nodeId) } eve.Scene["collectIdsByTag"] <- function(tag) { return collectIdsByTagAt(currentHostName(), tag) }
418eve.Scene["setNodeLayer"] <- function(nodeId, layer) { return setNodeLayerAt(currentHostName(), nodeId, layer) }
419eve.Scene["getNodeLayer"] <- function(nodeId) {
420 _requireNode(nodeId)
421 return getNodeLayerAt(currentHostName(), nodeId) } eve.Scene["setNodeEventHandler"] <- function(cb) {
422 return setNodeEventHandlerAt(currentHostName(), cb)
423}
424
425// ---- eve.SceneNodeRef: script-API completeness forwarding ----
426
427eve.SceneNodeRef["_requireValid"] <- function() {
428 if (!isValid()) throw "scene: node not found (" + getHostName() + "/" + getNodeId() + ")"
429}
430eve.SceneNodeRef["localToWorld"] <- function(x, y, z) {
431 _requireValid()
432 return getScene().localToWorldAt(getHostName(), getNodeId(), x, y, z)
433}
434eve.SceneNodeRef["worldToLocal"] <- function(x, y, z) {
435 _requireValid()
436 return getScene().worldToLocalAt(getHostName(), getNodeId(), x, y, z)
437}
438eve.SceneNodeRef["setParent"] <- function(parentId) { return getScene().setNodeParentAt(getHostName(), getNodeId(), parentId) }
439eve.SceneNodeRef["removeNode"] <- function() { return getScene().removeNodeAt(getHostName(), getNodeId()) }
440eve.SceneNodeRef["setQuaternion"] <- function(qx, qy, qz, qw) { return getScene().setNodeQuaternionAt(getHostName(), getNodeId(), qx, qy, qz, qw) }
441eve.SceneNodeRef["getQuaternion"] <- function() {
442 _requireValid()
443 return getScene().getNodeQuaternionAt(getHostName(), getNodeId())
444}
445eve.SceneNodeRef["lookAt"] <- function(tx, ty, tz) { return getScene().setNodeLookAtAt(getHostName(), getNodeId(), tx, ty, tz) }
446eve.SceneNodeRef["addTag"] <- function(tag) { return getScene().addNodeTagAt(getHostName(), getNodeId(), tag) }
447eve.SceneNodeRef["removeTag"] <- function(tag) { return getScene().removeNodeTagAt(getHostName(), getNodeId(), tag) }
448eve.SceneNodeRef["hasTag"] <- function(tag) { return getScene().hasNodeTagAt(getHostName(), getNodeId(), tag) }
449eve.SceneNodeRef["getTags"] <- function() {
450 _requireValid()
451 return getScene().getNodeTagsAt(getHostName(), getNodeId())
452}
453eve.SceneNodeRef["setLayer"] <- function(layer) { return getScene().setNodeLayerAt(getHostName(), getNodeId(), layer) }
454eve.SceneNodeRef["getLayer"] <- function() {
455 _requireValid()
456 return getScene().getNodeLayerAt(getHostName(), getNodeId())
457}
458
459// ---- bounds / serialization / picking / culling ----
460
461eve.Scene["setNodeBounds"] <- function(nodeId, minX, minY, minZ, maxX, maxY, maxZ) {
462 return setNodeBoundsAt(currentHostName(), nodeId, minX, minY, minZ, maxX, maxY, maxZ) } eve.Scene["hasNodeBounds"] <- function(nodeId) {
463 return hasNodeBoundsAt(currentHostName(), nodeId) } eve.Scene["getNodeBounds"] <- function(nodeId) {
464 _requireNode(nodeId)
465 return getNodeBoundsAt(currentHostName(), nodeId) } eve.Scene["serializeHost"] <- function() {
466 return serializeHostAt(currentHostName()) } eve.Scene["deserializeHost"] <- function(json) {
467 return deserializeHostAt(currentHostName(), json) } eve.Scene["pickRay"] <- function(ox, oy, oz, dx, dy, dz) {
468 return pickRayAt(currentHostName(), ox, oy, oz, dx, dy, dz) } eve.Scene["pickScreen"] <- function(cam, screenX, screenY, viewW, viewH) {
469 return pickScreenAt(currentHostName(), cam, screenX, screenY, viewW, viewH) } eve.Scene["collectFrustumIds"] <- function(cam, viewW, viewH) {
470 return collectFrustumIdsAt(currentHostName(), cam, viewW, viewH) } eve.Scene["applyPcgTerrainCulling"] <- function(cam, viewW, viewH, tag) {
471 return applyPcgTerrainCullingAt(currentHostName(), cam, viewW, viewH, tag) } eve.Scene["syncSpatialIndex"] <- function(octree) {
472 return syncSpatialIndexAt(currentHostName(), octree) } eve.Scene["nodeIdFromSpatialId"] <- function(index) {
473 return nodeIdFromSpatialIdAt(currentHostName(), index)
474}
475
476eve.SceneNodeRef["setBounds"] <- function(minX, minY, minZ, maxX, maxY, maxZ) {
477 return getScene().setNodeBoundsAt(getHostName(), getNodeId(), minX, minY, minZ, maxX, maxY, maxZ)
478}
479eve.SceneNodeRef["hasBounds"] <- function() {
480 return getScene().hasNodeBoundsAt(getHostName(), getNodeId())
481}
482eve.SceneNodeRef["getBounds"] <- function() {
483 _requireValid()
484 return getScene().getNodeBoundsAt(getHostName(), getNodeId())
485}
486)SQ";
487
488void injectSceneEntityBase(ssq::Table &eveTable) {
489 (void)script::compileAndRunChunk(eveTable.getHandle(), "SceneEntity.nut", kSceneEntityBaseScript);
490}
491
492void injectSceneEntityScript(ssq::Table &eveTable) {
493 (void)script::compileAndRunChunk(eveTable.getHandle(), "SceneEntity.nut", kSceneEntityScript);
494}
495
496[[maybe_unused]] const bool g_sceneEntityHookRegistered = []() {
497 eve::registerPostEcsHook([](ssq::Table &t) { injectSceneEntityBase(t); });
498 return true;
499}();
500
501} // namespace
502
503SceneHost *Scene::ensureSelected(const std::string &preferredName) {
504 if (selected_) return selected_;
505 if (!preferredName.empty()) {
506 selected_ = findHostByName(preferredName);
507 if (selected_) return selected_;
508 auto created = SceneHost::createHost(preferredName);
509 if (!created.ok()) return nullptr;
510 selected_ = std::move(created).takeValue();
511 return selected_;
512 }
513 auto created = SceneHost::createHost("default");
514 if (!created.ok()) return nullptr;
515 selected_ = std::move(created).takeValue();
516 return selected_;
517}
518
519eve::Result<SceneHost *> Scene::mountAs(const std::string &name, NodeDesc root) {
520 SceneHost *h = findHostByName(name);
521 if (!h) {
523 if (!created.ok()) return eve::Result<SceneHost *>::failure(created.status());
524 h = std::move(created).takeValue();
525 }
526 try {
527 h->setTree(std::move(root));
529 pruneOrphanObjects();
530 } catch (const std::exception &error) {
532 eve::DiagnosticCode::PreconditionViolation, std::string("scene mount rejected: ") + error.what(), "scene"));
533 }
534 selected_ = h;
536}
537
538eve::Result<SceneHost *> Scene::mount(NodeDesc root) { return mountAs("default", std::move(root)); }
539
541 SceneHost *h = selected_ ? selected_ : findHostByName("default");
542 if (!h) {
543 auto created = SceneHost::createHost("default");
544 if (!created.ok()) return eve::Result<SceneHost *>::failure(created.status());
545 h = std::move(created).takeValue();
546 }
547 try {
548 h->setTree(std::move(root));
550 pruneOrphanObjects();
551 } catch (const std::exception &error) {
554 std::string("scene remount rejected: ") + error.what(), "scene"));
555 }
556 selected_ = h;
558}
559
561 SceneHost *h = selected_ ? selected_ : findHostByName("default");
562 if (!h) {
563 auto created = SceneHost::createHost("default");
564 if (!created.ok()) return eve::Result<SceneHost *>::failure(created.status());
565 h = std::move(created).takeValue();
566 }
567 try {
568 const bool rebuilt = h->setTreeReconcile(std::move(root));
570 pruneOrphanObjects();
571 selected_ = h;
574 } catch (const std::exception &error) {
577 std::string("scene reconcile rejected: ") + error.what(), "scene"));
578 }
579}
580
581eve::Result<SceneHost *> Scene::remountAs(const std::string &name, NodeDesc root) {
582 return mountAs(name, std::move(root));
583}
584
585bool Scene::select(const std::string &name) {
586 SceneHost *h = findHostByName(name);
587 if (!h) return false;
588 selected_ = h;
589 return true;
590}
591
592eve::Result<SceneHost *> Scene::findHost(const std::string &name) const {
593 if (name.empty())
595 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "scene host name must not be empty", "scene"));
596 if (SceneHost *host = findHostByName(name)) return eve::Result<SceneHost *>::success(host, eve::Status::success());
598 eve::Diagnostic::error(eve::DiagnosticCode::NotFound, "scene host was not found: " + name, "scene"));
599}
600
601eve::Result<SceneHost *> Scene::findHostByOwner(uint32_t ownerId) const {
602 if (ownerId == 0)
604 eve::DiagnosticCode::InvalidArgument, "scene host owner id must not be zero", "scene"));
605 if (SceneHost *host = findHostByOwnerId(ownerId))
608 eve::DiagnosticCode::NotFound, "scene host owner id was not found: " + std::to_string(ownerId), "scene"));
609}
610
611void Scene::bindOwner(uint32_t ownerId) {
612 SceneHost *h = ensureSelected();
613 h->setOwnerId(ownerId);
614}
615
617 if (auto *h = ensureSelected()) h->setVisible(visible);
619
620void Scene::setHostLayer(int layer) {
621 if (auto *h = ensureSelected()) h->setLayer(layer);
622}
623
625 if (selected_) TransformSystem::updateHost(selected_);
627}
628
630
631
632#ifdef EVENGINE_SCENE_JSON
633std::string Scene::serializeHostAt(const std::string &hostName) const {
634 SceneHost *h = resolveHost(hostName);
635 if (!h || !h->getRoot()) return "{}";
636 Poco::JSON::Object root;
637 root.set("host", h->getName());
638 root.set("root", nodeToJson(*h->tree(), h->getRoot()));
639 std::ostringstream oss;
640 Poco::JSON::Stringifier::stringify(root, oss);
641 return oss.str();
642}
643
644bool Scene::deserializeHostAt(const std::string &hostName, const std::string &json) {
645 try {
646 Poco::JSON::Parser parser;
647 Poco::Dynamic::Var result = parser.parse(json);
648 Poco::JSON::Object::Ptr root = result.extract<Poco::JSON::Object::Ptr>();
649 if (!root) return false;
650 Poco::JSON::Object::Ptr tree = root->getObject("root");
651 if (!tree) return false;
652 NodeDesc desc = nodeFromJson(tree);
653 auto mounted = mountAs(hostName.empty() ? "default" : hostName, std::move(desc));
654 return mounted.ok();
655 } catch (...) {
656 return false;
657 }
658}
659#else
660std::string Scene::serializeHostAt(const std::string &hostName) const {
661 (void)hostName;
662 return "{}"; // Poco JSON is not available on this build (e.g. WASM trim)
664
665bool Scene::deserializeHostAt(const std::string &hostName, const std::string &json) {
666 (void)hostName;
667 (void)json;
668 return false;
669}
670#endif
671
672void Scene::beginBuild() {
673 openStack_.clear();
674 hasBuiltRoot_ = false;
675 builtRoot_ = NodeDesc{};
676 buildCursor_ = BuildCursor::None;
677}
678
679void Scene::pushOpen(NodeDesc d) { openStack_.push_back(std::move(d)); }
680
681NodeDesc &Scene::currentParent() {
682 if (openStack_.empty()) throw std::runtime_error("scene: node outside beginNode/beginGroup");
683 return openStack_.back();
684}
685
686NodeDesc& Scene::buildTarget() {
687 if (openStack_.empty()) throw std::runtime_error("scene: node outside beginNode/beginGroup");
688 if (buildCursor_ == BuildCursor::LastAddedChild && !openStack_.back().children.empty())
689 return openStack_.back().children.back();
690 return openStack_.back();
691}
692
693void Scene::beginNode(const std::string &id, const std::string &name) {
694 if (openStack_.empty() && hasBuiltRoot_) beginBuild();
695 pushOpen(node(id, {}, name));
696 buildCursor_ = BuildCursor::OpenNode;
697}
699void Scene::beginGroup(const std::string &id) {
700 if (openStack_.empty() && hasBuiltRoot_) beginBuild();
701 pushOpen(group({}, id));
702 buildCursor_ = BuildCursor::OpenNode;
703}
704
705void Scene::end() {
706 if (openStack_.empty()) throw std::runtime_error("scene: end() without begin");
707 NodeDesc finished = std::move(openStack_.back());
708 openStack_.pop_back();
709 if (openStack_.empty()) {
710 builtRoot_ = std::move(finished);
711 hasBuiltRoot_ = true;
712 buildCursor_ = BuildCursor::None;
713 } else {
714 openStack_.back().children.push_back(std::move(finished));
715 // The finished node is now the open parent's last child.
716 buildCursor_ = BuildCursor::LastAddedChild;
717 }
718}
719
720void Scene::addNode(const std::string &id, const std::string &name) {
721 currentParent().children.push_back(node(id, {}, name));
722 buildCursor_ = BuildCursor::LastAddedChild;
723}
724
725void Scene::setBuildPosition(float x, float y, float z) {
726 NodeDesc& d = buildTarget();
727 d.x = x;
728 d.y = y;
729 d.z = z;
730}
731
732void Scene::setBuildRotation(float yaw, float pitch, float roll) {
733 NodeDesc& d = buildTarget();
734 d.yaw = yaw;
735 d.pitch = pitch;
736 d.roll = roll;
737}
739void Scene::setBuildScale(float sx, float sy, float sz) {
740 NodeDesc& d = buildTarget();
741 d.sx = sx;
742 d.sy = sy;
743 d.sz = sz;
744}
745
746void Scene::setBuildSpace(const std::string& space) { buildTarget().space = space; }
747
748void Scene::setBuildVisible(bool visible) { buildTarget().visible = visible; }
749
750bool Scene::buildComplete() const { return openStack_.empty() && hasBuiltRoot_; }
751
752bool Scene::mountBuild() {
753 if (!buildComplete()) return false;
754 auto mounted = remount(std::move(builtRoot_));
755 if (!mounted.ok()) return false;
756 hasBuiltRoot_ = false;
757 builtRoot_ = NodeDesc{};
758 return true;
759}
760
761bool Scene::mountBuildAs(const std::string &name) {
762 if (!buildComplete()) return false;
763 auto mounted = mountAs(name, std::move(builtRoot_));
764 if (!mounted.ok()) return false;
765 hasBuiltRoot_ = false;
766 builtRoot_ = NodeDesc{};
767 return true;
768}
769
770bool Scene::remountBuildAs(const std::string &name) {
771 if (!buildComplete()) return false;
772 SceneHost *h = findHostByName(name);
773 if (!h) {
775 if (!created.ok()) return false;
776 h = std::move(created).takeValue();
778 h->setTreeReconcile(std::move(builtRoot_));
780 pruneOrphanObjects();
781 selected_ = h;
782 hasBuiltRoot_ = false;
783 builtRoot_ = NodeDesc{};
784 return true;
785}
786
787// ---------------------------------------------------------------------------
788// Per-node script entities (native primitives; script wrappers see expose())
789// ---------------------------------------------------------------------------
790
791SceneHost *Scene::resolveHost(const std::string &hostName) const {
792 if (hostName.empty()) return selected_;
793 return findHostByName(hostName);
794}
795
796SceneObject *Scene::findSceneObjectById(uint32_t id) const {
797 if (id == 0) return nullptr;
798 if (ecs::current()->getManager<SceneObject>() == nullptr) return nullptr;
799 auto view = ecs::View<SceneObject, SceneObject::Meta>();
800 for (auto it = view.begin(); it != view.end(); ++it) {
801 auto [meta] = *it;
802 if (meta->entity && uint32_t(meta->entity->id) == id - 1u) return meta->entity;
804 return nullptr;
805}
806
807SceneObject *Scene::findSceneObjectByPersistentId(eve::SceneObjectId id) const {
808 if (id.isNil() || ecs::current()->getManager<SceneObject>() == nullptr) return nullptr;
809 auto view = ecs::View<SceneObject, SceneObject::Meta>();
810 for (auto it = view.begin(); it != view.end(); ++it) {
811 auto [meta] = *it;
812 if (meta->entity && meta->persistentId == id) return meta->entity;
813 }
814 return nullptr;
815}
816
817SceneObject *Scene::ensureSceneObject(SceneHost *host, SceneNode *node,
818 const std::string &hostName) {
819 if (node->objectId != 0) {
820 if (SceneObject *o = findSceneObjectById(node->objectId)) {
821 if (!node->persistentId.isNil()) o->meta()->persistentId = node->persistentId;
822 return o;
823 }
824 node->objectId = 0; // stale id (entity was released)
825 }
826 if (!node->persistentId.isNil()) {
827 if (SceneObject *o = findSceneObjectByPersistentId(node->persistentId)) {
828 node->objectId = uint32_t(o->id) + 1u;
829 o->meta()->hostName = hostName;
830 o->meta()->nodeId = node->id;
831 return o;
832 }
833 }
834 auto created = SceneObject::createObject(hostName, node->id, node->persistentId);
835 if (!created.ok()) return nullptr;
836 SceneObject *o = std::move(created).takeValue();
837 node->objectId = uint32_t(o->id) + 1u;
838 return o;
840
841bool Scene::rootEntity(const std::string &hostName, const std::string &nodeId,
842 ssq::Object instance) {
843 if (!vm_) return false;
844 SceneHost *h = resolveHost(hostName);
845 if (!h) return false;
846 SceneNode *n = borrowSceneResult(h->findById(nodeId));
847 if (!n) return false;
848 HSQOBJECT raw = instance.getRaw();
849 if (raw._type != OT_INSTANCE) return false;
850 const std::string hName = hostName.empty() ? h->getName() : hostName;
851 SceneObject *obj = ensureSceneObject(h, n, hName);
852 if (!obj) return false;
853 for (const auto &b : obj->scriptBindings()->instances) {
854 if (sameScriptObject(b, raw)) return false; // already rooted
855 }
856 sq_addref(vm_, &raw);
857 obj->scriptBindings()->instances.push_back(raw);
858 return true;
859}
860
861bool Scene::unrootEntityAt(const std::string &hostName, const std::string &nodeId,
862 int index) {
863 if (!vm_) return false;
864 SceneHost *h = resolveHost(hostName);
865 if (!h) return false;
866 SceneNode *n = borrowSceneResult(h->findById(nodeId));
867 if (!n) return false;
868 SceneObject* obj = n->objectId != 0 ? findSceneObjectById(n->objectId) : nullptr;
869 if (!obj) return false;
870 auto &vec = obj->scriptBindings()->instances;
871 if (index < 0 || index >= int(vec.size())) return false;
872 HSQOBJECT raw = vec[size_t(index)];
873 vec.erase(vec.begin() + index);
874 sq_release(vm_, &raw);
875 if (vec.empty()) {
876 n->objectId = 0;
877 obj->release();
878 }
879 return true;
880}
881
882int Scene::forEachEntity(const std::string &hostName, const std::string &nodeId,
883 ssq::Object cb) {
884 if (!vm_) return 0;
885 SceneHost *h = resolveHost(hostName);
886 if (!h) return 0;
887 SceneNode *n = borrowSceneResult(h->findById(nodeId));
888 if (!n) return 0;
889 SceneObject* obj = n->objectId != 0 ? findSceneObjectById(n->objectId) : nullptr;
890 if (!obj) return 0;
891 // Copy + addref: the callback may attach/detach and mutate the live list.
892 auto vec = obj->scriptBindings()->instances;
893 for (auto &b : vec) sq_addref(vm_, &b);
894 HSQOBJECT fn = cb.getRaw();
895 sq_addref(vm_, &fn);
896 int count = 0;
897 for (size_t i = 0; i < vec.size(); ++i) {
898 if (callCallback(fn, vec[i], int(i))) ++count;
899 }
900 sq_release(vm_, &fn);
901 for (auto& b : vec) sq_release(vm_, &b);
902 return count;
903}
904
905std::vector<ssq::Object> Scene::scriptEntitiesAt(const std::string& hostName, const std::string& nodeId) const {
906 std::vector<ssq::Object> out;
907 if (!vm_) return out;
908 SceneHost* h = resolveHost(hostName);
909 if (!h) return out;
910 SceneNode* n = borrowSceneResult(h->findById(nodeId));
911 if (!n) return out;
912 SceneObject* obj = n->objectId != 0 ? findSceneObjectById(n->objectId) : nullptr;
913 if (!obj) return out;
914
915 // 与 `forEachEntity` 同样的"拷贝 + addref":交给调用方的每个 `ssq::Object` 都持有一次引用。
916 // 这里不用防回调改表(原生调用方不重入脚本),但 addref 是必须的——`instances` 里那一份引用
917 // 归场景所有,直接借出去会在 `ssq::Object` 析构时多释放一次(方案文档 §9.64.3 的坑)。
918 for (const auto& bound : obj->scriptBindings()->instances) {
919 HSQOBJECT handle = bound;
920 sq_addref(vm_, &handle);
921 ssq::Object instance(vm_);
922 instance.getRaw() = handle;
923 out.push_back(std::move(instance));
924 }
925 return out;
926}
927
928std::vector<ScriptComponentInstanceState> Scene::scriptComponentStatesAt(const std::string& hostName,
929 const std::string& nodeId) const {
930 // The VM-side lookup stays here (EVPlatform already links Squirrel): handing `ssq::Object`
931 // values to the editor group would drag the Squirrel C API into EVEditors.dll, which then
932 // collides with the statically linked Squirrel of the domain test executables (LNK2005).
933 std::vector<ScriptComponentInstanceState> out;
934 for (const ssq::Object& instance : scriptEntitiesAt(hostName, nodeId)) {
935 auto states = scriptComponentInstancesOf(instance);
936 if (!states.ok()) continue;
937 for (ScriptComponentInstanceState& state : states.value()) out.push_back(std::move(state));
938 }
939 return out;
940}
941
942void Scene::updateScripts(float dt) {
944 if (!vm_) return;
945 if (ecs::current()->getManager<SceneObject>() == nullptr) return;
946 // Snapshot + addref so script update(dt) may attach/detach safely.
947 std::vector<HSQOBJECT> snapshot;
948 {
949 auto view = ecs::View<SceneObject, SceneObject::Meta, SceneObject::ScriptBindings>();
950 for (auto it = view.begin(); it != view.end(); ++it) {
951 auto [meta, sb] = *it;
952 if (!meta->entity) continue;
953 for (auto &inst : sb->instances) snapshot.push_back(inst);
954 }
955 }
956 for (auto &h : snapshot) sq_addref(vm_, &h);
957 for (auto &h : snapshot) {
958 // Skip disabled entities; enable/disable is a script-side flag on SceneEntity.
959 const SQInteger top = sq_gettop(vm_);
960 sq_pushobject(vm_, h);
961 sq_pushstring(vm_, "_enabled", -1);
962 bool enabled = true;
963 if (SQ_SUCCEEDED(sq_get(vm_, -2))) {
964 SQBool flag = SQTrue;
965 if (SQ_SUCCEEDED(sq_getbool(vm_, -1, &flag))) enabled = flag != SQFalse;
966 }
967 sq_settop(vm_, top);
968 if (enabled) callMethod(h, "update", dt);
969 }
970 for (auto &h : snapshot) sq_release(vm_, &h);
971 // Scripts moved nodes during update(dt), so world matrices are stale: recompute
972 // them before returning. updateHost() early-outs on a clean tree, so the cost is
973 // proportional to what the scripts actually touched. Without this, getWorldPosition()
974 // right after update(dt) reported pre-move values.
975 // Delayed detaches run first, so the transform pass sees the post-detach tree.
978}
979
980eve::Result<void> Scene::scheduleDetachEntityAt(const std::string &hostName,
981 const std::string &nodeId,
982 ssq::Object instance) {
983 if (!vm_) {
985 eve::DiagnosticCode::PreconditionViolation, "scene script VM is not ready", "scene"));
986 }
987 HSQOBJECT raw = instance.getRaw();
988 if (raw._type != OT_INSTANCE) {
990 eve::DiagnosticCode::InvalidArgument, "scheduleDetachEntityAt expects a script instance",
991 "instance"));
992 }
993 SceneHost *h = resolveHost(hostName);
994 if (!h) {
996 eve::DiagnosticCode::NotFound, "scene host was not found", "hostName"));
997 }
998 SceneNode *n = borrowSceneResult(h->findById(nodeId));
999 if (!n || !n->objectId) {
1001 eve::DiagnosticCode::NotFound, "scene node was not found", "nodeId"));
1002 }
1003 SceneObject *obj = findSceneObjectById(n->objectId);
1004 if (!obj) {
1006 eve::DiagnosticCode::NotFound, "scene object was not found", "nodeId"));
1007 }
1008 bool found = false;
1009 for (const auto &b : obj->scriptBindings()->instances) {
1010 if (sameScriptObject(b, raw)) {
1011 found = true;
1012 break;
1013 }
1014 }
1015 if (!found) {
1017 eve::DiagnosticCode::NotFound, "script entity is not rooted on that node", "instance"));
1018 }
1019 for (const auto &pending : delayedDetaches_) {
1020 if (pending.hostName == (hostName.empty() ? h->getName() : hostName) && pending.nodeId == nodeId &&
1021 sameScriptObject(pending.instance, raw))
1022 return eve::Result<void>::success(eve::Status::success(eve::StatusCode::NoOp));
1023 }
1024 DelayedDetach item;
1025 item.hostName = hostName.empty() ? h->getName() : hostName;
1026 item.nodeId = nodeId;
1027 item.instance = raw;
1028 sq_addref(vm_, &item.instance);
1029 delayedDetaches_.push_back(item);
1031}
1032
1034 if (!vm_ || delayedDetaches_.empty() || flushingDelayedDetaches_) return;
1035 flushingDelayedDetaches_ = true;
1036 std::vector<DelayedDetach> pending;
1037 pending.swap(delayedDetaches_);
1038 for (auto &item : pending) {
1039 // Reuse the script detach path so onDetach/destroy/unroot stay consistent.
1040 // Locate index then mirror detachEntityAt.
1041 SceneHost *h = resolveHost(item.hostName);
1042 SceneNode *n = h ? borrowSceneResult(h->findById(item.nodeId)) : nullptr;
1043 SceneObject *obj = (n && n->objectId) ? findSceneObjectById(n->objectId) : nullptr;
1044 if (obj) {
1045 auto &vec = obj->scriptBindings()->instances;
1046 for (size_t i = 0; i < vec.size(); ++i) {
1047 if (!sameScriptObject(vec[i], item.instance)) continue;
1048 callMethod0(item.instance, "onDetach");
1049 callMethod0(item.instance, "destroy");
1050 unrootEntityAt(item.hostName, item.nodeId, int(i));
1051 break;
1052 }
1053 }
1054 sq_release(vm_, &item.instance);
1055 }
1056 flushingDelayedDetaches_ = false;
1057 // Nested scheduleDetach during flush is drained on the next updateScripts.
1059
1060std::string Scene::currentHostName() const {
1061 return selected_ ? selected_->getName() : std::string{};
1062}
1063
1064SceneNodeRef *Scene::getNodeRefAt(const std::string &hostName,
1065 const std::string &nodeId) const {
1066 std::string h = hostName.empty()
1067 ? (selected_ ? selected_->getName() : std::string{})
1068 : hostName;
1069 return new SceneNodeRef(std::move(h), nodeId);
1070}
1071
1072SceneNodeRef *Scene::getNodeRefByPathAt(const std::string &hostName,
1073 const std::string &path) const {
1074 std::string h = hostName.empty()
1075 ? (selected_ ? selected_->getName() : std::string{})
1076 : hostName;
1077 SceneHost *host = resolveHost(hostName);
1078 if (!host) return new SceneNodeRef(std::move(h), "");
1079 SceneNode *n = borrowSceneResult(host->findByPath(path));
1080 return new SceneNodeRef(std::move(h), n ? n->id : std::string{});
1081}
1082
1083void Scene::pruneOrphanObjects() {
1084 if (ecs::current()->getManager<SceneObject>() == nullptr) return;
1085 std::vector<SceneObject *> orphans;
1086 {
1087 auto view = ecs::View<SceneObject, SceneObject::Meta, SceneObject::ScriptBindings>();
1088 for (auto it = view.begin(); it != view.end(); ++it) {
1089 auto [meta, sb] = *it;
1090 if (!meta->entity) continue;
1091 SceneHost *h = findHostByName(meta->hostName);
1092 if (!h) {
1093 orphans.push_back(meta->entity);
1094 continue;
1095 }
1096 SceneNode *n = borrowSceneResult(h->findById(meta->nodeId));
1097 if (!n || n->objectId != uint32_t(meta->entity->id) + 1u) {
1098 orphans.push_back(meta->entity);
1099 continue;
1100 }
1101 if (!n->persistentId.isNil()) meta->persistentId = n->persistentId;
1102 (void)sb;
1103 // Self-heal: node id / host renamed (reconcile patch), keep binding.
1104 if (meta->hostName != h->getName() || meta->nodeId != n->id) {
1105 meta->hostName = h->getName();
1106 meta->nodeId = n->id;
1107 syncBindingRefs(meta->entity);
1108 }
1109 }
1110 }
1111 for (SceneObject *o : orphans) teardownBindings(o);
1112}
1113
1114void Scene::syncBindingRefs(SceneObject *obj) {
1115 if (!vm_ || !obj) return;
1116 for (auto &inst : obj->scriptBindings()->instances) {
1117 setStringField(vm_, inst, "hostName", obj->meta()->hostName);
1118 setStringField(vm_, inst, "nodeId", obj->meta()->nodeId);
1119 }
1120}
1121
1122void Scene::teardownBindings(SceneObject *obj) {
1123 if (!obj) return;
1124 auto &vec = obj->scriptBindings()->instances;
1125 if (vm_) {
1126 for (auto &inst : vec) {
1127 callMethod0(inst, "onDetach");
1128 callMethod0(inst, "destroy");
1129 sq_release(vm_, &inst);
1130 }
1131 }
1132 vec.clear();
1133 obj->release();
1134}
1135
1136bool Scene::callMethod(HSQOBJECT inst, const char *name, float dt) {
1137 if (!vm_ || inst._type != OT_INSTANCE) return false;
1138 const SQInteger top = sq_gettop(vm_);
1139 sq_pushobject(vm_, inst);
1140 sq_pushstring(vm_, name, -1);
1141 if (SQ_FAILED(sq_get(vm_, -2))) {
1142 sq_settop(vm_, top);
1143 return false;
1144 }
1145 const SQObjectType t = sq_gettype(vm_, -1);
1146 if (t != OT_CLOSURE && t != OT_NATIVECLOSURE) {
1147 sq_settop(vm_, top);
1148 return false;
1149 }
1150 // Resolve the method, then call it through the helper: the receiver is the instance
1151 // (`this`) and the single argument is dt. A script `update()` that throws used to be
1152 // indistinguishable from one that returned early, because the failed call was turned
1153 // into a bare `false` with no report.
1154 HSQOBJECT method;
1155 sq_getstackobj(vm_, -1, &method);
1156 const SQRESULT result = script::callFunction(vm_, method, inst, dt);
1157 sq_settop(vm_, top);
1158 return SQ_SUCCEEDED(result);
1159}
1160
1161bool Scene::callMethod0(HSQOBJECT inst, const char *name) {
1162 if (!vm_ || inst._type != OT_INSTANCE) return false;
1163 const SQInteger top = sq_gettop(vm_);
1164 sq_pushobject(vm_, inst);
1165 sq_pushstring(vm_, name, -1);
1166 if (SQ_FAILED(sq_get(vm_, -2))) {
1167 sq_settop(vm_, top);
1168 return false;
1169 }
1170 const SQObjectType t = sq_gettype(vm_, -1);
1171 if (t != OT_CLOSURE && t != OT_NATIVECLOSURE) {
1172 sq_settop(vm_, top);
1173 return false;
1174 }
1175 // Same as callMethod() with no arguments (onAttach / onDetach).
1176 HSQOBJECT method;
1177 sq_getstackobj(vm_, -1, &method);
1178 const SQRESULT result = script::callFunction(vm_, method, inst);
1179 sq_settop(vm_, top);
1180 return SQ_SUCCEEDED(result);
1181}
1182
1183bool Scene::callCallback(HSQOBJECT fn, HSQOBJECT inst, int index) {
1184 if (!vm_) return false;
1185 // The callback sees (entity, index) as ordinary parameters with `this` bound to the
1186 // entity. Hand-writing sq_call's count here is what previously handed the callback
1187 // the index in place of the entity (see script::callFunction: the count is derived).
1188 return SQ_SUCCEEDED(script::callFunction(vm_, fn, inst, inst, index));
1189}
1190
1191void Scene::expose(ssq::Table &table) {
1192 if (Scene *self = Scene::create()) self->vm_ = table.getHandle();
1193 auto cls = table.addClass(name, Scene::create, false);
1194 expose(cls);
1195
1196 // Lightweight node handle (owned by script; created via getNodeRef*).
1197 auto refCls = table.addClass<SceneNodeRef>(
1198 "SceneNodeRef",
1199 std::function<SceneNodeRef *()>([]() -> SceneNodeRef * { return nullptr; }), true);
1200 refCls.addFunc("getNodeId", &SceneNodeRef::getNodeId);
1201 refCls.addFunc("getHostName", &SceneNodeRef::getHostName);
1202 refCls.addFunc("getPersistentId",
1203 [](SceneNodeRef *ref) { return ref ? ref->persistentId().format() : std::string{}; });
1204 refCls.addFunc("isValid", &SceneNodeRef::isValid);
1205 refCls.addFunc("getScene", &SceneNodeRef::getScene);
1206 refCls.addFunc("setPosition", &SceneNodeRef::setPosition);
1207 refCls.addFunc("getPositionX", &SceneNodeRef::getPositionX);
1208 refCls.addFunc("getPositionY", &SceneNodeRef::getPositionY);
1209 refCls.addFunc("getPositionZ", &SceneNodeRef::getPositionZ);
1210 refCls.addFunc("getPosition", &SceneNodeRef::getPosition);
1211 refCls.addFunc("setRotation", &SceneNodeRef::setRotation);
1212 refCls.addFunc("getRotationYaw", &SceneNodeRef::getRotationYaw);
1213 refCls.addFunc("getRotationPitch", &SceneNodeRef::getRotationPitch);
1214 refCls.addFunc("getRotationRoll", &SceneNodeRef::getRotationRoll);
1215 refCls.addFunc("getRotation", &SceneNodeRef::getRotation);
1216 refCls.addFunc("setScale", &SceneNodeRef::setScale);
1217 refCls.addFunc("getScaleX", &SceneNodeRef::getScaleX);
1218 refCls.addFunc("getScaleY", &SceneNodeRef::getScaleY);
1219 refCls.addFunc("getScaleZ", &SceneNodeRef::getScaleZ);
1220 refCls.addFunc("getScale", &SceneNodeRef::getScale);
1221 refCls.addFunc("setVisible", &SceneNodeRef::setVisible);
1222 refCls.addFunc("isVisible", &SceneNodeRef::isVisible);
1223 refCls.addFunc("getWorldPositionX", &SceneNodeRef::getWorldPositionX);
1224 refCls.addFunc("getWorldPositionY", &SceneNodeRef::getWorldPositionY);
1225 refCls.addFunc("getWorldPositionZ", &SceneNodeRef::getWorldPositionZ);
1226 refCls.addFunc("getWorldPosition", &SceneNodeRef::getWorldPosition);
1227 refCls.addFunc("getWorldMatrix", &SceneNodeRef::getWorldMatrix);
1228 refCls.addFunc("getForward", &SceneNodeRef::getForward);
1229 refCls.addFunc("getRight", &SceneNodeRef::getRight);
1230 refCls.addFunc("getUp", &SceneNodeRef::getUp);
1231 refCls.addFunc("getParentId", &SceneNodeRef::getParentId);
1232 refCls.addFunc("getChildCount", &SceneNodeRef::getChildCount);
1233 refCls.addFunc("getChildIdAt", &SceneNodeRef::getChildIdAt);
1234 refCls.addFunc("getPath", &SceneNodeRef::getPath);
1235
1237 injectSceneEntityScript(table);
1242}
1243
1244void Scene::expose(ssq::Class &cls) {
1245 cls.addFunc("getName", &Scene::getName);
1246 cls.addFunc("select", &Scene::select);
1247 cls.addFunc("bindOwner", &Scene::bindOwner);
1248 cls.addFunc("setHostVisible", &Scene::setHostVisible);
1249 cls.addFunc("setHostLayer", &Scene::setHostLayer);
1250 cls.addFunc("currentHostName", &Scene::currentHostName);
1251 cls.addFunc("updateTransforms", &Scene::updateTransforms);
1252 cls.addFunc("updateTransformsAll", &Scene::updateTransformsAll);
1253 cls.addFunc("updateScripts", &Scene::updateScripts);
1254 cls.addFunc("setNodePosition", &Scene::setNodePosition);
1255 cls.addFunc("setNodeRotation", &Scene::setNodeRotation);
1256 cls.addFunc("setNodeScale", &Scene::setNodeScale);
1257 cls.addFunc("setNodeVisible", &Scene::setNodeVisible);
1258 cls.addFunc("linkRenderable2D", &Scene::linkRenderable2D);
1259 cls.addFunc("linkRenderable3D", &Scene::linkRenderable3D);
1260 cls.addFunc("unlinkNode", &Scene::unlinkNode);
1261
1262 // Generic link system primitives (host-scoped; script wrappers below)
1263 cls.addFunc("linkRenderable2DAt", &Scene::linkRenderable2DAt);
1264 cls.addFunc("linkRenderable3DAt", &Scene::linkRenderable3DAt);
1265 cls.addFunc("linkPhysics2DAt", &Scene::linkPhysics2DAt);
1266 cls.addFunc("linkPhysics3DAt", &Scene::linkPhysics3DAt);
1267 cls.addFunc("linkCamera3DAt", &Scene::linkCamera3DAt);
1268 cls.addFunc("linkAudio3DAt", &Scene::linkAudio3DAt);
1269 cls.addFunc("unlinkNodeAt", &Scene::unlinkNodeAt);
1270 cls.addFunc("unlinkNodeKindAt", &Scene::unlinkNodeKindAt);
1271 cls.addFunc("linkCountAt", &Scene::linkCountAt);
1272 // The "script" link kind's own face; defined with the kind in ScriptLinks.cpp.
1274
1275 // Script-API completeness primitives (host-scoped)
1276 cls.addFunc("getNodePositionAt", &Scene::getNodePositionAt);
1277 cls.addFunc("getNodeRotationAt", &Scene::getNodeRotationAt);
1278 cls.addFunc("getNodeScaleAt", &Scene::getNodeScaleAt);
1279 cls.addFunc("getNodeVisibleAt", &Scene::getNodeVisibleAt);
1280 cls.addFunc("getNodeWorldPositionAt", &Scene::getNodeWorldPositionAt);
1281 cls.addFunc("getNodeWorldRotationAt", &Scene::getNodeWorldRotationAt);
1282 cls.addFunc("getNodeWorldScaleAt", &Scene::getNodeWorldScaleAt);
1283 cls.addFunc("localToWorldAt", &Scene::localToWorldAt);
1284 cls.addFunc("worldToLocalAt", &Scene::worldToLocalAt);
1285 cls.addFunc("setNodeParentAt", &Scene::setNodeParentAt);
1286 cls.addFunc("removeNodeAt", &Scene::removeNodeAt);
1287 cls.addFunc("addChildAt", &Scene::addChildAt);
1288 cls.addFunc("removeChildAt", &Scene::removeChildAt);
1289 cls.addFunc("setNodeQuaternionAt", &Scene::setNodeQuaternionAt);
1290 cls.addFunc("getNodeQuaternionAt", &Scene::getNodeQuaternionAt);
1291 cls.addFunc("setNodeLookAtAt", &Scene::setNodeLookAtAt);
1292 cls.addFunc("addNodeTagAt", &Scene::addNodeTagAt);
1293 cls.addFunc("removeNodeTagAt", &Scene::removeNodeTagAt);
1294 cls.addFunc("hasNodeTagAt", &Scene::hasNodeTagAt);
1295 cls.addFunc("getNodeTagsAt", &Scene::getNodeTagsAt);
1296 cls.addFunc("collectIdsByTagAt", &Scene::collectIdsByTagAt);
1297 cls.addFunc("setNodeLayerAt", &Scene::setNodeLayerAt);
1298 cls.addFunc("getNodeLayerAt", &Scene::getNodeLayerAt);
1299 cls.addFunc("setNodeEventHandlerAt",
1300 [](Scene *self, std::string hostName, ssq::Object cb) {
1301 return self->setNodeEventHandlerAt(hostName, cb);
1302 });
1303
1304 // Bounds / serialization / picking / culling
1305 cls.addFunc("setNodeBoundsAt", &Scene::setNodeBoundsAt);
1306 cls.addFunc("hasNodeBoundsAt", &Scene::hasNodeBoundsAt);
1307 cls.addFunc("getNodeBoundsAt", &Scene::getNodeBoundsAt);
1308 cls.addFunc("serializeHostAt", &Scene::serializeHostAt);
1309 cls.addFunc("deserializeHostAt", &Scene::deserializeHostAt);
1310 cls.addFunc("pickRayAt", &Scene::pickRayAt);
1311 cls.addFunc("pickScreenAt", &Scene::pickScreenAt);
1312 cls.addFunc("collectFrustumIdsAt", &Scene::collectFrustumIdsAt);
1313 cls.addFunc("applyPcgTerrainCullingAt", [vm=cls.getHandle()](Scene* self,const std::string& host,
1314 graphics::Camera3D* cam,float w,float h,const std::string& tag) {
1315 return eve::script::projectResult(vm,self->applyPcgTerrainCullingAt(host,cam,w,h,tag),
1316 [](int changed){return Value(changed);});
1317 });
1318 cls.addFunc("syncSpatialIndexAt", &Scene::syncSpatialIndexAt);
1319 cls.addFunc("nodeIdFromSpatialIdAt", &Scene::nodeIdFromSpatialIdAt);
1320
1321 // Per-node script entity primitives (called from injected script wrappers).
1322 // ssq::Object params are bound via lambdas (member-pointer path may not
1323 // support raw script objects; lambda path is used by eve.component too).
1324 cls.addFunc("rootEntity",
1325 [](Scene *self, std::string hostName, std::string nodeId,
1326 ssq::Object instance) {
1327 return self->rootEntity(hostName, nodeId, instance);
1328 });
1329 cls.addFunc("unrootEntityAt", &Scene::unrootEntityAt);
1330 cls.addFunc("scheduleDetachEntityAt",
1331 [](Scene *self, std::string hostName, std::string nodeId,
1332 ssq::Object instance) {
1333 // Script surface stays bool (parity with attach/detach helpers);
1334 // native API is Result<void> for architecture api-shape.
1335 return self->scheduleDetachEntityAt(hostName, nodeId, instance).ok();
1336 });
1337 cls.addFunc("forEachEntity",
1338 [](Scene *self, std::string hostName, std::string nodeId,
1339 ssq::Object cb) {
1340 return self->forEachEntity(hostName, nodeId, cb);
1341 });
1342 cls.addFunc("getNodeRefAt", &Scene::getNodeRefAt);
1343 cls.addFunc("getNodeRefByPathAt", &Scene::getNodeRefByPathAt);
1344
1345 cls.addFunc("hasNode", &Scene::hasNode);
1346 cls.addFunc("getNodeCount", &Scene::getNodeCount);
1347 cls.addFunc("getRootId", &Scene::getRootId);
1348 cls.addFunc("getParentId", &Scene::getParentId);
1349 cls.addFunc("getChildCount", &Scene::getChildCount);
1350 cls.addFunc("getChildIdAt", &Scene::getChildIdAt);
1351 cls.addFunc("findIdByName", &Scene::findIdByName);
1352 cls.addFunc("findIdByPath", &Scene::findIdByPath);
1353 cls.addFunc("getNodePath", &Scene::getNodePath);
1354 cls.addFunc("isAncestor", &Scene::isAncestor);
1355 cls.addFunc("isDescendant", &Scene::isDescendant);
1356 cls.addFunc("collectIds", &Scene::collectIds);
1357 cls.addFunc("collectIdsFrom", &Scene::collectIdsFrom);
1358 cls.addFunc("collectIdsByName", &Scene::collectIdsByName);
1359 cls.addFunc("collectIdsVisible", &Scene::collectIdsVisible);
1360 cls.addFunc("collectChildIds", &Scene::collectChildIds);
1361 cls.addFunc("walkDepthFirstIds", &Scene::walkDepthFirstIds);
1362 cls.addFunc("walkBreadthFirstIds", &Scene::walkBreadthFirstIds);
1363
1364 cls.addFunc("beginBuild", &Scene::beginBuild);
1365 cls.addFunc("beginNode", &Scene::beginNode);
1366 cls.addFunc("beginGroup", &Scene::beginGroup);
1367 cls.addFunc("end", &Scene::end);
1368 cls.addFunc("addNode", &Scene::addNode);
1369 cls.addFunc("setBuildPosition", &Scene::setBuildPosition);
1370 cls.addFunc("setBuildRotation", &Scene::setBuildRotation);
1371 cls.addFunc("setBuildScale", &Scene::setBuildScale);
1372 cls.addFunc("setBuildSpace", &Scene::setBuildSpace);
1373 cls.addFunc("setBuildVisible", &Scene::setBuildVisible);
1374 cls.addFunc("mountBuild", &Scene::mountBuild);
1375 cls.addFunc("mountBuildAs", &Scene::mountBuildAs);
1376 cls.addFunc("remountBuildAs", &Scene::remountBuildAs);
1377}
1378
1379} // namespace eve::scene
1380
double z
double y
double x
float w
Definition AnimClip.cpp:738
int root
Definition AnimSmr.cpp:119
std::vector< QuestEvent > pending
float yaw
Definition BushMesh.cpp:37
struct SQVM * HSQUIRRELVM
std::string nodeId
HSQUIRRELVM vm
Definition ECS.cpp:38
HSQOBJECT cls
Definition ECS.cpp:39
std::string name
Definition ECS.cpp:154
double raw
std::uint16_t method
scene::NodeDesc desc
glm::vec3 n
Definition Grass.cpp:63
std::int32_t c
int h
std::string id
Poco::JSON::Object::Ptr result
Snapshot snapshot
std::unordered_set< std::string > tags
MeleePoint3 b
Definition MeleeHit.cpp:41
MeleePoint3 a
Definition MeleeHit.cpp:40
const std::string * tag
#define Module_IMPL(ModuleName, newExpr)
Definition Module.h:27
double dt
OceanSprayView view
std::string error
Definition Package.cpp:174
TileLayer * layer
std::string path
Definition PlayHost.cpp:111
PrimitiveHandle handle
Object::Ptr value
float d
int detail
float t
const RoadNode * node
bool found
int created
ScriptStructure out
std::string string
int count
The single Squirrel projection for common Result, Status and Value.
AbilityActivationGroup group
bool visible
UIHostHandle host
uint32_t index
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
virtual std::string getName() const =0
Returns the name.
Move-only operation result carrying either a value or Status.
Definition Result.h:176
static Result success(T value)
Construct a successful result owning value.
Definition Result.h:185
static Result failure(Status status)
Construct a failed result from a structured status.
Definition Result.h:196
Structured status and zero or more diagnostics for an operation.
Definition Status.h:70
static Status success(StatusCode code=StatusCode::Ok)
Construct a successful status with an explicit non-error outcome.
Definition Status.cpp:19
Id128 public API.
Definition Identity.h:111
static std::optional< Id128 > parse(std::string_view text) noexcept
Parses canonical UUID text.
Definition Identity.h:150
ECS mount point for one scene graph (full scene or nested subtree root). Isomorphic to eve::ui::UIHos...
Definition SceneHost.h:89
static eve::Result< SceneHost * > createHost(const std::string &name="")
Creates an ECS-owned scene host with an explicit Result contract.
const std::string & getName()
float getPositionX() const
Returns the position x.
float getWorldPositionZ() const
Returns the world position z.
std::vector< float > getForward() const
Normalized local axes in world space (forward = +Z).
bool isValid() const
True when host + node currently resolve.
std::string getHostName() const
Returns the host name.
float getWorldPositionX() const
Returns the world position x.
float getRotationYaw() const
Returns the rotation yaw.
float getWorldPositionY() const
Returns the world position y.
float getRotationPitch() const
Returns the rotation pitch.
bool setVisible(bool v)
Sets the visible.
std::string getNodeId() const
Returns the node id.
float getScaleZ() const
Returns the scale z.
float getScaleX() const
Returns the scale x.
Scene * getScene() const
Returns the eve.Scene module instance for entity-binding forwarding.
std::string getPath() const
Returns the path.
std::string getChildIdAt(int ordinal) const
Returns the child id at.
std::vector< float > getPosition() const
Returns the position.
std::vector< float > getWorldPosition() const
Returns the world position.
std::vector< float > getRotation() const
Returns the rotation.
bool setPosition(float x, float y, float z)
Sets the position.
float getPositionY() const
Returns the position y.
bool setScale(float sx, float sy, float sz)
Sets the scale.
float getRotationRoll() const
Returns the rotation roll.
std::vector< float > getScale() const
Returns the scale.
int getChildCount() const
Returns the child count.
bool isVisible() const
True when visible.
float getScaleY() const
Returns the scale y.
std::string getParentId() const
Returns the parent id.
std::vector< float > getUp() const
Returns the up.
bool setRotation(float yaw, float pitch, float roll)
Sets the rotation.
std::vector< float > getRight() const
Returns the right.
float getPositionZ() const
Returns the position z.
std::vector< float > getWorldMatrix() const
Column-major 4x4 world matrix, 16 floats.
Per-node ECS identity (created lazily when a node needs script bindings or engine components)....
Definition SceneObject.h:25
static eve::Result< SceneObject * > createObject(const std::string &hostName, const std::string &nodeId, eve::SceneObjectId persistentId={})
Creates an ECS-owned companion object with an explicit ownership contract.
Declarative scene module (eve.Scene).
Definition Scene.h:52
void beginNode(const std::string &id, const std::string &name="")
Begins node.
Definition Scene.cpp:771
SceneNodeRef * getNodeRefByPathAt(const std::string &hostName, const std::string &path) const
Returns the node ref by path at.
Definition Scene.cpp:1150
bool linkPhysics3DAt(const std::string &hostName, const std::string &nodeId, physics::Body3D *b, const std::string &mode)
Link physics 3 d at.
SceneHost * resolveHost(const std::string &hostName) const
Host-qualified resolution: empty hostName → currently selected host.
Definition Scene.cpp:869
eve::Result< SceneHost * > findHostByOwner(uint32_t ownerId) const
Finds the host bound to an owner id with an explicit status.
Definition Scene.cpp:679
void setBuildSpace(const std::string &space)
Sets the build space.
Definition Scene.cpp:824
bool mountBuild()
Mounts build.
Definition Scene.cpp:830
std::vector< std::string > collectIdsFrom(const std::string &id)
Collect ids from.
void updateTransforms()
Propagate transforms (+ link sync) for all hosts (or current if selected).
Definition Scene.cpp:702
bool setNodeParentAt(const std::string &hostName, const std::string &childId, const std::string &parentId)
Reparent by id; empty parentId detaches. Cycle-safe.
std::vector< std::string > collectIds()
Collect ids.
bool linkCamera3DAt(const std::string &hostName, const std::string &nodeId, graphics::Camera3D *c)
Link camera 3 d at.
std::string serializeHostAt(const std::string &hostName) const
Serialize host at.
Definition Scene.cpp:738
std::vector< std::string > collectIdsByTagAt(const std::string &hostName, const std::string &tag) const
Collect ids by tag at.
void setBuildVisible(bool visible)
Sets the build visible.
Definition Scene.cpp:826
std::vector< float > getNodeRotationAt(const std::string &hostName, const std::string &nodeId) const
Returns the node rotation at.
std::string findIdByPath(const std::string &path)
Finds id by path.
bool rootEntity(const std::string &hostName, const std::string &nodeId, ssq::Object instance)
Root one script instance on a node (creates SceneObject lazily).
Definition Scene.cpp:919
std::string pickScreenAt(const std::string &hostName, graphics::Camera3D *cam, float screenX, float screenY, float viewW, float viewH) const
Screen-space picking through a Camera3D (camera.screenToRay).
eve::Result< void > scheduleDetachEntityAt(const std::string &hostName, const std::string &nodeId, ssq::Object instance)
Queue a script instance for detach at the end of the current/next updateScripts.
Definition Scene.cpp:1058
void beginBuild()
Begins build.
Definition Scene.cpp:750
~Scene() override
Tears down script bindings and delayed-detach state.
Definition Scene.cpp:49
bool setNodeQuaternionAt(const std::string &hostName, const std::string &nodeId, float qx, float qy, float qz, float qw)
Sets the node quaternion at.
eve::Result< SceneHost * > mountAs(const std::string &name, NodeDesc root)
Creates/replaces a named host from a NodeDesc tree and selects it.
Definition Scene.cpp:597
bool getNodeVisibleAt(const std::string &hostName, const std::string &nodeId) const
Returns the node visible at.
std::vector< float > worldToLocalAt(const std::string &hostName, const std::string &nodeId, float x, float y, float z) const
World to local at.
void setBuildRotation(float yaw, float pitch=0.f, float roll=0.f)
Sets the build rotation.
Definition Scene.cpp:810
eve::Result< SceneHost * > mount(NodeDesc root)
Mounts the tree as the default host and selects it.
Definition Scene.cpp:616
void updateScripts(float dt)
updateTransformsAll() + call update(dt) on every rooted instance.
Definition Scene.cpp:1020
std::vector< float > getNodePositionAt(const std::string &hostName, const std::string &nodeId) const
Returns the node position at.
std::vector< float > getNodeWorldPositionAt(const std::string &hostName, const std::string &nodeId) const
Returns the node world position at.
int getNodeLayerAt(const std::string &hostName, const std::string &nodeId) const
Returns the node layer at.
bool linkPhysics2DAt(const std::string &hostName, const std::string &nodeId, physics::Body *b, const std::string &mode)
Link physics 2 d at.
bool removeNodeAt(const std::string &hostName, const std::string &nodeId)
Detach node from its parent (arena node stays; rebuild to delete).
void flushDelayedDetaches()
Drain the delayed-detach queue (called automatically by updateScripts).
Definition Scene.cpp:1111
SceneNodeRef * getNodeRefAt(const std::string &hostName, const std::string &nodeId) const
Returns the node ref at.
Definition Scene.cpp:1142
void end()
Ends .
Definition Scene.cpp:783
std::vector< std::string > collectChildIds(const std::string &parentId)
Collect child ids.
void setHostVisible(bool visible)
Shows/hides every host (or the selected one when a host is selected).
Definition Scene.cpp:694
bool unlinkNodeAt(const std::string &hostName, const std::string &nodeId)
Remove every link on the node.
bool setNodePosition(const std::string &id, float x, float y, float z)
Script-friendly TRS setters on the current host; each marks the transform dirty.
std::vector< std::string > collectIdsVisible(bool visible)
Collect ids visible.
bool linkAudio3DAt(const std::string &hostName, const std::string &nodeId, audio::Source *s)
Link audio 3 d at.
bool setNodeLookAtAt(const std::string &hostName, const std::string &nodeId, float tx, float ty, float tz)
Orient node so its local +Z axis points at (tx,ty,tz).
std::string currentHostName() const
Current host name.
Definition Scene.cpp:1138
std::vector< float > getNodeWorldRotationAt(const std::string &hostName, const std::string &nodeId) const
Returns the node world rotation at.
bool hasNode(const std::string &id)
True when node.
void bindOwner(uint32_t ownerId)
Binds the selected host to a UI/scene owner id.
Definition Scene.cpp:689
std::string getNodePath(const std::string &id)
Returns the node path.
std::string findIdByName(const std::string &name)
Finds id by name.
int getChildCount(const std::string &id)
Returns the child count.
bool removeNodeTagAt(const std::string &hostName, const std::string &nodeId, const std::string &tag)
Removes node tag at.
bool linkRenderable3DAt(const std::string &hostName, const std::string &nodeId, graphics::Renderable3D *r)
Link renderable 3 d at.
eve::Result< SceneHost * > remount(NodeDesc root)
Replaces the selected host's tree.
Definition Scene.cpp:618
void setBuildPosition(float x, float y, float z=0.f)
Sets the build position.
Definition Scene.cpp:803
bool mountBuildAs(const std::string &name)
Mounts build as.
Definition Scene.cpp:839
bool isAncestor(const std::string &ancestorId, const std::string &nodeId)
True when ancestor.
void beginGroup(const std::string &id="")
Begins group.
Definition Scene.cpp:777
bool setNodeScale(const std::string &id, float sx, float sy, float sz)
Sets the local scale of a node.
std::string getParentId(const std::string &id)
Returns the parent id.
std::vector< std::string > collectIdsByName(const std::string &name)
Collect ids by name.
void setHostLayer(int layer)
Sets the render layer of every host (or the selected one).
Definition Scene.cpp:698
std::vector< ScriptComponentInstanceState > scriptComponentStatesAt(const std::string &hostName, const std::string &nodeId) const
一个节点上所有脚本实体的**已登记**组件状态(编辑器/工具面)。
Definition Scene.cpp:1006
bool unlinkNodeKindAt(const std::string &hostName, const std::string &nodeId, const std::string &kind)
Remove links of one kind ("renderable2d"|"renderable3d"|"physics2d"|...).
std::vector< float > getNodeScaleAt(const std::string &hostName, const std::string &nodeId) const
Returns the node scale at.
std::string nodeIdFromSpatialIdAt(const std::string &hostName, int index) const
Map a spatial-index id (arena index) back to a node id.
eve::Result< SceneHost * > remountAs(const std::string &name, NodeDesc root)
Creates/replaces a named host through the canonical mount path.
Definition Scene.cpp:659
std::vector< std::string > getNodeTagsAt(const std::string &hostName, const std::string &nodeId) const
Returns the node tags at.
void updateTransformsAll()
Propagate transforms for every host regardless of selection.
Definition Scene.cpp:707
int linkCountAt(const std::string &hostName, const std::string &nodeId)
Link count at.
bool hasNodeBoundsAt(const std::string &hostName, const std::string &nodeId) const
True when node bounds at.
bool deserializeHostAt(const std::string &hostName, const std::string &json)
Deserialize host at.
Definition Scene.cpp:743
std::vector< std::string > walkBreadthFirstIds()
Walk breadth first ids.
bool unrootEntityAt(const std::string &hostName, const std::string &nodeId, int index)
Remove a rooted script instance by its index in the binding list.
Definition Scene.cpp:939
bool remountBuildAs(const std::string &name)
Remount build as.
Definition Scene.cpp:848
bool linkRenderable3D(const std::string &nodeId, graphics::Renderable3D *r)
Links a 3D renderable to a node in the current host.
bool setNodeLayerAt(const std::string &hostName, const std::string &nodeId, int layer)
Sets the node layer at.
bool setNodeRotation(const std::string &id, float yaw, float pitch, float roll)
Sets the local rotation (yaw/pitch/roll in degrees) of a node.
bool unlinkNode(const std::string &nodeId)
Removes every link on a node in the current host.
bool syncSpatialIndexAt(const std::string &hostName, spatial::Octree *ot) const
Insert every bounded node's world AABB into an octree (id = arena index).
std::vector< float > getNodeQuaternionAt(const std::string &hostName, const std::string &nodeId) const
Returns the node quaternion at.
void addNode(const std::string &id, const std::string &name="")
Adds node.
Definition Scene.cpp:798
bool removeChildAt(const std::string &hostName, const std::string &parentId, const std::string &childId)
Removes child at.
eve::Result< SceneHost * > findHost(const std::string &name) const
Finds a host by name with an explicit not-found status.
Definition Scene.cpp:670
bool setNodeBoundsAt(const std::string &hostName, const std::string &nodeId, float minX, float minY, float minZ, float maxX, float maxY, float maxZ)
Sets the node bounds at.
bool setNodeVisible(const std::string &id, bool visible)
Shows/hides a node.
std::string getRootId()
Returns the root id.
bool addChildAt(const std::string &hostName, const std::string &parentId, const std::string &childId)
Adds child at.
std::string getChildIdAt(const std::string &parentId, int childOrdinal)
Returns the child id at.
std::vector< ssq::Object > scriptEntitiesAt(const std::string &hostName, const std::string &nodeId) const
取某个节点上挂着的脚本实体实例(eve.SceneEntity 子类实例)的**原生**快照。
Definition Scene.cpp:983
bool linkRenderable2DAt(const std::string &hostName, const std::string &nodeId, graphics::Renderable2D *r)
Link renderable 2 d at.
Scene()
Scene.
Definition Scene.cpp:43
std::vector< float > localToWorldAt(const std::string &hostName, const std::string &nodeId, float x, float y, float z) const
Local to world at.
std::vector< float > getNodeWorldScaleAt(const std::string &hostName, const std::string &nodeId) const
Returns the node world scale at.
bool select(const std::string &name)
Selects a named host; false when it does not exist.
Definition Scene.cpp:663
bool isDescendant(const std::string &nodeId, const std::string &ancestorId)
True when descendant.
bool hasNodeTagAt(const std::string &hostName, const std::string &nodeId, const std::string &tag) const
True when node tag at.
int getNodeCount()
Returns the node count.
std::vector< std::string > walkDepthFirstIds()
DFS order of ids under root (same as collectIds). Kept for script naming clarity.
std::vector< std::string > collectFrustumIdsAt(const std::string &hostName, graphics::Camera3D *cam, float viewW, float viewH) const
Ids of nodes whose world AABB intersects the camera frustum.
void setBuildScale(float sx, float sy, float sz=1.f)
Sets the build scale.
Definition Scene.cpp:817
eve::Result< SceneHost * > remountReconcile(NodeDesc root)
Reconciles the selected host, reporting whether replacement failed.
Definition Scene.cpp:638
std::vector< float > getNodeBoundsAt(const std::string &hostName, const std::string &nodeId) const
Returns the node bounds at.
std::string pickRayAt(const std::string &hostName, float ox, float oy, float oz, float dx, float dy, float dz) const
Nearest node id hit by a world ray (nodes with bounds), or "".
bool addNodeTagAt(const std::string &hostName, const std::string &nodeId, const std::string &tag)
Adds node tag at.
bool linkRenderable2D(const std::string &nodeId, graphics::Renderable2D *r)
Links a 2D renderable to a node in the current host.
int forEachEntity(const std::string &hostName, const std::string &nodeId, ssq::Object cb)
Call cb(instance, index) for every rooted instance; returns count.
Definition Scene.cpp:960
static void updateHost(SceneHost *host)
Updates host.
static void updateAll()
Updates all.
SQInteger top
Definition Snapshot.cpp:115
ForceVector add(ForceVector a, ForceVector b)
Definition ForceMath.h:13
std::unordered_map< std::string, SkillDefinition > & table()
Definition Skill.cpp:73
void injectSceneComponentClass(ssq::Table &eveTable)
void registerSceneSearch()
Install the process-lifetime provider using the existing capability registry.
void invalidateSceneSearch()
Invalidate the registered projection before Scene/runtime teardown; engine thread,...
void registerSceneCapabilities()
Registers scene capabilities.
void registerSceneArtifactProvider()
Register the scene provider in the common capability registry.
void exposeFollowPlayerBindings(ssq::Table &table)
Register FollowPlayer value types and evaluator with the root script table.
void exposePcgBuildConfigBindings(ssq::Table &t)
Register Pcg build-config bindings.
EVENGINE_API_PLATFORM void exposeScriptLinkBindings(ssq::Class &cls)
Register eve.Scene's script-link surface.
void exposePcgGrowthBindings(ssq::Table &t)
Register Pcg Growth bindings.
void exposeLocationProfileBindings(ssq::Table &table)
Register Pcg location profile value types and operations.
SQRESULT callFunction(HSQUIRRELVM vm, const HSQOBJECT &fn, const Receiver &receiver, Args &&... args)
Call a script function, deriving sq_call's parameter count from the pushes.
SQRESULT compileAndRunChunk(HSQUIRRELVM vm, const char *name, const char *source)
Compile and run one embedded script chunk against the root table.
Build metadata (engine git commit, build time, third-party version).
Definition Build.cpp:16
StatusCode
Stable outcome category for an operation.
Definition Status.h:28
void registerPostEcsHook(PostEcsHook fn)
Registers post ecs hook.
Definition ECS.cpp:1646
EVENGINE_API_FOUNDATION Result< std::vector< ScriptComponentInstanceState > > scriptComponentInstancesOf(const ssq::Object &entityInstance)
读一个脚本实体实例上挂着的全部**已登记**组件的状态。
SettlementPipeline::Stage fn
bool enabled
Scene-owned CPU registry provider for generated artifacts.
一个脚本实体实例上某个组件的**当前状态**(供引擎工具读取)。
Declarative scene-node description (build once / on dirty → flatten into SceneHost::Tree)....
Definition NodeDesc.h:19
std::vector< NodeDesc > children
Definition NodeDesc.h:45
std::string space
"2d" or "3d" (string enum per module convention).
Definition NodeDesc.h:33
Retained scene node (arena). Conceptual GameObject; isomorphic to eve::ui::UINode.
Definition SceneHost.h:46