载入中...
搜索中...
未找到
PrimitivePath.cpp
浏览该文件的文档.
2#include <algorithm>
3#include <atomic>
4#include <cmath>
5#include <functional>
6#include <glm/common.hpp>
7#include <glm/geometric.hpp>
8#include <glm/gtc/constants.hpp>
9#include <limits>
10#include <memory>
11#include <numeric>
12#include <simplesquirrel/simplesquirrel.hpp>
13#include <type_traits>
14#include <utility>
15#include "common/Assert.h"
18#include "graphics/Graphics.h"
22
23// PrimitivePath.cpp
24namespace eve::graphics {
25namespace {
26
27void validatePoint(glm::vec2 point) {
28 const bool finite = std::isfinite(point.x) && std::isfinite(point.y);
29 EV_PARAM_CHECK(finite, "path points must be finite");
30}
31
32float pointLineDistance(glm::vec2 point, glm::vec2 a, glm::vec2 b) {
33 const glm::vec2 line = b - a;
34 const float lengthSquared = glm::dot(line, line);
35 if (lengthSquared <= 1e-20f) return glm::length(point - a);
36 const float t = glm::clamp(glm::dot(point - a, line) / lengthSquared, 0.f, 1.f);
37 return glm::length(point - (a + line * t));
38}
39
40void flattenQuad(glm::vec2 a, glm::vec2 control, glm::vec2 b, float tolerance, std::uint32_t depth,
41 std::uint32_t maxDepth, std::vector<glm::vec2>& output) {
42 if (depth >= maxDepth || pointLineDistance(control, a, b) <= tolerance) {
43 output.push_back(b);
44 return;
45 }
46 const glm::vec2 ac = (a + control) * 0.5f;
47 const glm::vec2 cb = (control + b) * 0.5f;
48 const glm::vec2 middle = (ac + cb) * 0.5f;
49 flattenQuad(a, ac, middle, tolerance, depth + 1, maxDepth, output);
50 flattenQuad(middle, cb, b, tolerance, depth + 1, maxDepth, output);
51}
52
53void flattenCubic(glm::vec2 a, glm::vec2 c1, glm::vec2 c2, glm::vec2 b, float tolerance, std::uint32_t depth,
54 std::uint32_t maxDepth, std::vector<glm::vec2>& output) {
55 const float deviation = std::max(pointLineDistance(c1, a, b), pointLineDistance(c2, a, b));
56 if (depth >= maxDepth || deviation <= tolerance) {
57 output.push_back(b);
58 return;
59 }
60 const glm::vec2 a1 = (a + c1) * 0.5f;
61 const glm::vec2 c12 = (c1 + c2) * 0.5f;
62 const glm::vec2 c2b = (c2 + b) * 0.5f;
63 const glm::vec2 leftControl = (a1 + c12) * 0.5f;
64 const glm::vec2 rightControl = (c12 + c2b) * 0.5f;
65 const glm::vec2 middle = (leftControl + rightControl) * 0.5f;
66 flattenCubic(a, a1, leftControl, middle, tolerance, depth + 1, maxDepth, output);
67 flattenCubic(middle, rightControl, c2b, b, tolerance, depth + 1, maxDepth, output);
68}
69
70} // namespace
71
73 validatePoint(point);
74 verbs_.push_back(Verb::Move);
75 points_.push_back(point);
76 contourOpen_ = true;
77 return *this;
78}
79
81 EV_PARAM_CHECK(contourOpen_, "lineTo requires a preceding moveTo");
82 validatePoint(point);
83 verbs_.push_back(Verb::Line);
84 points_.push_back(point);
85 return *this;
86}
87
88Path2D& Path2D::quadTo(glm::vec2 control, glm::vec2 point) {
89 EV_PARAM_CHECK(contourOpen_, "quadTo requires a preceding moveTo");
90 validatePoint(control);
91 validatePoint(point);
92 verbs_.push_back(Verb::Quad);
93 points_.push_back(control);
94 points_.push_back(point);
95 return *this;
96}
97
98Path2D& Path2D::cubicTo(glm::vec2 control1, glm::vec2 control2, glm::vec2 point) {
99 EV_PARAM_CHECK(contourOpen_, "cubicTo requires a preceding moveTo");
100 validatePoint(control1);
101 validatePoint(control2);
102 validatePoint(point);
103 verbs_.push_back(Verb::Cubic);
104 points_.push_back(control1);
105 points_.push_back(control2);
106 points_.push_back(point);
107 return *this;
108}
109
111 EV_PARAM_CHECK(contourOpen_, "close requires an open contour");
112 verbs_.push_back(Verb::Close);
113 contourOpen_ = false;
114 return *this;
115}
116
117void Path2D::clear() noexcept {
118 verbs_.clear();
119 points_.clear();
120 contourOpen_ = false;
121}
122
123std::vector<FlattenedContour2D> Path2D::flatten(float tolerance, std::uint32_t maxDepth) const {
124 const bool validTolerance = std::isfinite(tolerance) && tolerance > 0.f;
125 EV_PARAM_CHECK(validTolerance, "path flatten tolerance must be finite and positive");
126 const bool validMaxDepth = maxDepth > 0 && maxDepth <= 24;
127 EV_PARAM_CHECK(validMaxDepth, "path flatten maxDepth must be in [1, 24]");
128
129 std::vector<FlattenedContour2D> result;
130 std::size_t pointIndex = 0;
131 glm::vec2 current{0.f};
132 for (Verb verb : verbs_) {
133 switch (verb) {
134 case Verb::Move:
135 result.push_back({});
136 current = points_[pointIndex++];
137 result.back().points.push_back(current);
138 break;
139 case Verb::Line:
140 current = points_[pointIndex++];
141 result.back().points.push_back(current);
142 break;
143 case Verb::Quad: {
144 const glm::vec2 control = points_[pointIndex++];
145 const glm::vec2 end = points_[pointIndex++];
146 flattenQuad(current, control, end, tolerance, 0, maxDepth, result.back().points);
147 current = end;
148 break;
149 }
150 case Verb::Cubic: {
151 const glm::vec2 control1 = points_[pointIndex++];
152 const glm::vec2 control2 = points_[pointIndex++];
153 const glm::vec2 end = points_[pointIndex++];
154 flattenCubic(current, control1, control2, end, tolerance, 0, maxDepth, result.back().points);
155 current = end;
156 break;
157 }
158 case Verb::Close: result.back().closed = true; break;
159 }
160 }
161 return result;
162}
163
164} // namespace eve::graphics
165
166// PrimitiveScene.cpp
167namespace eve::graphics {
168namespace {
169
170bool finite(glm::vec3 value) { return std::isfinite(value.x) && std::isfinite(value.y) && std::isfinite(value.z); }
171
172bool nonZero(glm::vec3 value) {
173 constexpr float minimumLengthSquared = 1e-12f;
174 return finite(value) && glm::dot(value, value) > minimumLengthSquared;
175}
176
177bool independent(glm::vec3 a, glm::vec3 b) {
178 constexpr float minimumRelativeAreaSquared = 1e-12f;
179 const float aLengthSquared = glm::dot(a, a);
180 const float bLengthSquared = glm::dot(b, b);
181 const glm::vec3 crossValue = glm::cross(a, b);
182 const float areaSquared = glm::dot(crossValue, crossValue);
183 return aLengthSquared > 0.f && bLengthSquared > 0.f &&
184 areaSquared > minimumRelativeAreaSquared * aLengthSquared * bLengthSquared;
185}
186
187bool formsBasis(glm::vec3 a, glm::vec3 b, glm::vec3 c) {
188 constexpr float minimumRelativeVolumeSquared = 1e-12f;
189 const float volume = glm::dot(a, glm::cross(b, c));
190 return volume * volume > minimumRelativeVolumeSquared * glm::dot(a, a) * glm::dot(b, b) * glm::dot(c, c);
191}
192
193eve::Result<void> validateDescriptor(const PrimitiveDescriptor3D& descriptor) {
194 const auto& paint = descriptor.paint;
195 const auto& stroke = paint.stroke;
196 if (!std::isfinite(stroke.width) || stroke.width < 0.f || !std::isfinite(stroke.miterLimit) ||
197 stroke.miterLimit <= 0.f || !std::isfinite(paint.color.r) || !std::isfinite(paint.color.g) ||
198 !std::isfinite(paint.color.b) || !std::isfinite(paint.color.a))
200 "primitive paint must be finite and valid",
201 "primitive", {}, "graphics"));
202 if (stroke.dash) {
203 const auto& dash = *stroke.dash;
204 float period = 0.f;
205 if (dash.intervals.empty() || dash.intervals.size() % 2 != 0 || !std::isfinite(dash.phase))
207 eve::DiagnosticCode::InvalidArgument, "invalid primitive dash pattern", "primitive", {}, "graphics"));
208 for (float interval : dash.intervals) {
209 if (!std::isfinite(interval) || interval <= 0.f)
211 "invalid primitive dash interval", "primitive",
212 {}, "graphics"));
213 period += interval;
214 }
215 if (!std::isfinite(period))
217 eve::DiagnosticCode::InvalidArgument, "primitive dash period overflow", "primitive", {}, "graphics"));
218 }
219 try {
220 descriptor.paint.validate();
221 } catch (const std::exception& error) {
223 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, error.what(), "primitive", {}, "graphics"));
224 }
225 for (glm::length_t column = 0; column < 4; ++column)
226 for (glm::length_t row = 0; row < 4; ++row)
227 if (!std::isfinite(descriptor.transform[column][row]))
229 "primitive transform must be finite",
230 "primitive", {}, "graphics"));
231 const bool valid = std::visit(
232 [](const auto& geometry) {
233 using Geometry = std::decay_t<decltype(geometry)>;
234 if constexpr (std::is_same_v<Geometry, PrimitivePolyline3D>) {
235 return geometry.points.size() >= (geometry.closed ? 3u : 2u) &&
236 std::all_of(geometry.points.begin(), geometry.points.end(), finite);
237 } else if constexpr (std::is_same_v<Geometry, PrimitiveAabb3D>) {
238 return finite(geometry.minimum) && finite(geometry.maximum) &&
239 geometry.minimum.x <= geometry.maximum.x && geometry.minimum.y <= geometry.maximum.y &&
240 geometry.minimum.z <= geometry.maximum.z;
241 } else if constexpr (std::is_same_v<Geometry, PrimitiveObb3D>) {
242 return finite(geometry.center) && nonZero(geometry.halfAxes[0]) && nonZero(geometry.halfAxes[1]) &&
243 nonZero(geometry.halfAxes[2]) && independent(geometry.halfAxes[0], geometry.halfAxes[1]) &&
244 independent(geometry.halfAxes[1], geometry.halfAxes[2]) &&
245 independent(geometry.halfAxes[2], geometry.halfAxes[0]) &&
246 formsBasis(geometry.halfAxes[0], geometry.halfAxes[1], geometry.halfAxes[2]);
247 } else if constexpr (std::is_same_v<Geometry, PrimitiveDisk3D>) {
248 return finite(geometry.center) && nonZero(geometry.normal) && std::isfinite(geometry.radius) &&
249 geometry.radius > 0.f && geometry.segments >= 3;
250 } else if constexpr (std::is_same_v<Geometry, PrimitiveArc3D>) {
251 return finite(geometry.center) && nonZero(geometry.normal) && nonZero(geometry.zeroDirection) &&
252 independent(geometry.normal, geometry.zeroDirection) && std::isfinite(geometry.radius) &&
253 geometry.radius > 0.f && std::isfinite(geometry.startRadians) &&
254 std::isfinite(geometry.sweepRadians) && geometry.segments >= 1;
255 } else if constexpr (std::is_same_v<Geometry, PrimitiveSphere3D>) {
256 return finite(geometry.center) && std::isfinite(geometry.radius) && geometry.radius > 0.f &&
257 geometry.segments >= 3;
258 } else if constexpr (std::is_same_v<Geometry, PrimitiveCapsule3D> ||
259 std::is_same_v<Geometry, PrimitiveCylinder3D>) {
260 return finite(geometry.a) && finite(geometry.b) && nonZero(geometry.b - geometry.a) &&
261 std::isfinite(geometry.radius) && geometry.radius > 0.f && geometry.segments >= 3;
262 } else if constexpr (std::is_same_v<Geometry, PrimitiveCone3D>) {
263 return finite(geometry.apex) && nonZero(geometry.axis) && std::isfinite(geometry.height) &&
264 geometry.height > 0.f && std::isfinite(geometry.radius) && geometry.radius > 0.f &&
265 geometry.segments >= 3;
266 } else if constexpr (std::is_same_v<Geometry, PrimitiveGrid3D>) {
267 return finite(geometry.origin) && nonZero(geometry.axisU) && nonZero(geometry.axisV) &&
268 independent(geometry.axisU, geometry.axisV) && geometry.cellsU > 0 && geometry.cellsV > 0;
269 } else if constexpr (std::is_same_v<Geometry, PrimitiveArrow3D>) {
270 return finite(geometry.from) && finite(geometry.to) && nonZero(geometry.to - geometry.from) &&
271 std::isfinite(geometry.headLength) && geometry.headLength > 0.f &&
272 std::isfinite(geometry.headRadius) && geometry.headRadius > 0.f;
273 } else {
274 return std::all_of(geometry.corners.begin(), geometry.corners.end(), finite);
275 }
276 },
277 descriptor.geometry);
278 if (!valid)
280 "primitive geometry is invalid or non-finite",
281 "primitive", {}, "graphics"));
283}
284
285} // namespace
286
288 static std::atomic<PrimitiveHandle::owner_type> nextOwner{1};
289 owner_ = nextOwner.fetch_add(1, std::memory_order_relaxed);
290 if (owner_ == 0) owner_ = nextOwner.fetch_add(1, std::memory_order_relaxed);
291}
292
294 auto validation = validateDescriptor(descriptor);
295 if (!validation) return eve::Result<PrimitiveHandle>::failure(validation.status());
297 if (!freeSlots_.empty()) {
298 index = freeSlots_.back();
299 freeSlots_.pop_back();
300 slots_[index].descriptor = std::move(descriptor);
301 } else {
302 if (slots_.size() >= PrimitiveHandle::invalidIndex) {
304 eve::DiagnosticCode::Failed, "primitive scene slot capacity exceeded", "primitive", {}, "graphics"));
305 }
306 index = static_cast<PrimitiveHandle::index_type>(slots_.size());
307 slots_.push_back(Slot{std::move(descriptor), 1, false, {}});
308 }
309 ++liveCount_;
311}
312
314 if (!matches(handle)) {
316 eve::DiagnosticCode::StaleHandle, "primitive handle is stale", "primitive", {}, "graphics"));
317 }
318 auto validation = validateDescriptor(descriptor);
319 if (!validation) return eve::Result<PrimitiveUpdateStatus>::failure(validation.status());
320 slots_[handle.index()].descriptor = std::move(descriptor);
321 slots_[handle.index()].cache.reset();
323}
324
326 if (!matches(handle)) {
328 eve::DiagnosticCode::StaleHandle, "primitive handle is stale", "primitive", {}, "graphics"));
329 }
330 Slot& slot = slots_[handle.index()];
331 slot.descriptor.reset();
332 slot.cache.reset();
333 --liveCount_;
334 const auto next = PrimitiveHandle::nextGeneration(slot.generation);
335 if (next) {
336 slot.generation = *next;
337 freeSlots_.push_back(handle.index());
338 } else {
339 slot.retired = true;
340 }
342}
343
344eve::Result<std::size_t> PrimitiveScene::updateMany(std::span<const PrimitiveBatchUpdate> updates) {
345 for (const PrimitiveBatchUpdate& update : updates) {
346 if (!matches(update.handle))
348 "primitive batch contains a stale handle",
349 "primitive", {}, "graphics"));
350 auto validation = validateDescriptor(update.descriptor);
351 if (!validation) return eve::Result<std::size_t>::failure(validation.status());
352 }
353 // Copy every owning payload before publishing any mutation. A later allocation
354 // failure must not leave earlier descriptors in the batch already replaced.
355 std::vector<PrimitiveBatchUpdate> prepared(updates.begin(), updates.end());
356 static_assert(std::is_nothrow_move_assignable_v<PrimitiveDescriptor3D>);
357 for (PrimitiveBatchUpdate& update : prepared) {
358 *slots_[update.handle.index()].descriptor = std::move(update.descriptor);
359 slots_[update.handle.index()].cache.reset();
360 }
361 return eve::Result<std::size_t>::success(updates.size());
362}
363
365 if (!matches(handle)) return nullptr;
366 return &*slots_[handle.index()].descriptor;
367}
368
369bool PrimitiveScene::isStale(PrimitiveHandle handle) const noexcept { return !matches(handle); }
370
372 freeSlots_.clear();
373 liveCount_ = 0;
374 for (PrimitiveHandle::index_type index = 0; index < slots_.size(); ++index) {
375 Slot& slot = slots_[index];
376 slot.descriptor.reset();
377 slot.cache.reset();
378 if (slot.retired) continue;
379 const auto next = PrimitiveHandle::nextGeneration(slot.generation);
380 if (next) {
381 slot.generation = *next;
382 freeSlots_.push_back(index);
383 } else {
384 slot.retired = true;
385 }
386 }
387}
388
390 auto result = tryRender(destination);
391 std::move(result).expect("primitive scene exceeded its command budget");
392}
393
395 for (const Slot& slot : slots_) {
396 if (!slot.descriptor || !slot.descriptor->visible) continue;
397 const PrimitiveDescriptor3D& descriptor = *slot.descriptor;
398 const bool hit = slot.cache.has_value();
399 if (!hit) {
400 PrimitiveSceneCanvas3D canvas(destination.context_, std::numeric_limits<std::size_t>::max());
401 canvas.concat(descriptor.transform);
402 std::visit(
403 [&](const auto& geometry) {
404 using Geometry = std::decay_t<decltype(geometry)>;
405 if constexpr (std::is_same_v<Geometry, PrimitivePolyline3D>) {
406 canvas.drawPolyline(geometry.points, geometry.closed, descriptor.paint);
407 } else if constexpr (std::is_same_v<Geometry, PrimitiveAabb3D>) {
408 canvas.drawAabb(geometry.minimum, geometry.maximum, descriptor.paint);
409 } else if constexpr (std::is_same_v<Geometry, PrimitiveObb3D>) {
410 canvas.drawObb(geometry.center, geometry.halfAxes, descriptor.paint);
411 } else if constexpr (std::is_same_v<Geometry, PrimitiveDisk3D>) {
412 canvas.drawDisk(geometry.center, geometry.normal, geometry.radius, descriptor.paint,
413 geometry.segments);
414 } else if constexpr (std::is_same_v<Geometry, PrimitiveArc3D>) {
415 canvas.drawArc(geometry.center, geometry.normal, geometry.zeroDirection, geometry.radius,
416 geometry.startRadians, geometry.sweepRadians, descriptor.paint,
417 geometry.segments);
418 } else if constexpr (std::is_same_v<Geometry, PrimitiveSphere3D>) {
419 canvas.drawSphere(geometry.center, geometry.radius, descriptor.paint, geometry.segments);
420 } else if constexpr (std::is_same_v<Geometry, PrimitiveCapsule3D>) {
421 canvas.drawCapsule(geometry.a, geometry.b, geometry.radius, descriptor.paint,
422 geometry.segments);
423 } else if constexpr (std::is_same_v<Geometry, PrimitiveCylinder3D>) {
424 canvas.drawCylinder(geometry.a, geometry.b, geometry.radius, descriptor.paint,
425 geometry.segments);
426 } else if constexpr (std::is_same_v<Geometry, PrimitiveCone3D>) {
427 canvas.drawCone(geometry.apex, geometry.axis, geometry.height, geometry.radius,
428 descriptor.paint, geometry.segments);
429 } else if constexpr (std::is_same_v<Geometry, PrimitiveGrid3D>) {
430 canvas.drawGrid(geometry.origin, geometry.axisU, geometry.axisV, geometry.cellsU,
431 geometry.cellsV, descriptor.paint);
432 } else if constexpr (std::is_same_v<Geometry, PrimitiveArrow3D>) {
433 canvas.drawArrow(geometry.from, geometry.to, geometry.headLength, geometry.headRadius,
434 descriptor.paint);
435 } else if constexpr (std::is_same_v<Geometry, PrimitiveFrustum3D>) {
436 canvas.drawFrustum(geometry.corners, descriptor.paint);
437 }
438 },
439 descriptor.geometry);
440 slot.cache = std::move(canvas);
441 }
442 const auto& cached = *slot.cache;
443 const auto count = cached.commands_.size() + cached.triangles_.size();
444 const auto used = destination.commands_.size() + destination.triangles_.size();
445 if (used > destination.hardCommandLimit_ || count > destination.hardCommandLimit_ - used) {
446 destination.statistics_.droppedCommands += count + cached.statistics_.droppedCommands;
448 eve::DiagnosticCode::Failed, "primitive scene command budget exceeded", "primitive", {}, "graphics"));
449 }
450 // Prepare all owning payloads and capacity before publishing this slot.
451 auto lines = cached.commands_;
452 auto triangles = cached.triangles_;
453 for (auto& command : lines) command.transform = destination.transform_ * command.transform;
454 for (auto& command : triangles) command.transform = destination.transform_ * command.transform;
455 destination.commands_.reserve(destination.commands_.size() + lines.size());
456 destination.triangles_.reserve(destination.triangles_.size() + triangles.size());
457 static_assert(std::is_nothrow_move_constructible_v<PolylineCommand3D>);
458 static_assert(std::is_nothrow_move_constructible_v<TriangleCommand3D>);
459 for (auto& command : lines) destination.commands_.push_back(std::move(command));
460 for (auto& command : triangles) destination.triangles_.push_back(std::move(command));
461 destination.statistics_.commandCount += cached.statistics_.commandCount;
462 destination.statistics_.segmentCount += cached.statistics_.segmentCount;
463 destination.statistics_.triangleCount += cached.statistics_.triangleCount;
464 destination.statistics_.cacheHits += hit ? 1u : 0u;
465 }
467}
468
469bool PrimitiveScene::matches(PrimitiveHandle handle) const noexcept {
470 if (!handle.isValid() || handle.owner() != owner_ || handle.index() >= slots_.size()) return false;
471 const Slot& slot = slots_[handle.index()];
472 return !slot.retired && slot.descriptor.has_value() && slot.generation == handle.generation();
473}
474
475} // namespace eve::graphics
476
477// PrimitiveScriptBindings.cpp
478namespace eve::graphics {
479namespace {
480struct ScriptPrimitive3D {
481 ScriptPrimitive3D(std::weak_ptr<PrimitiveScene> sceneValue, PrimitiveHandle handleValue)
482 : scene(std::move(sceneValue)), handle(handleValue) {}
483 ~ScriptPrimitive3D() noexcept {
484 if (auto owner = scene.lock(); owner && !owner->isStale(handle))
485 owner->remove(handle).ignore("script primitive proxy destruction");
486 }
487
488 std::weak_ptr<PrimitiveScene> scene;
489 PrimitiveHandle handle;
490};
491
492eve::Result<PrimitiveDescriptor3D> primitiveDescriptor(ScriptPrimitive3D* value) {
493 if (!value)
495 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "primitive proxy must not be null",
496 "primitive", {}, "graphics.primitive.binding"));
497 auto scene = value->scene.lock();
498 if (!scene)
500 eve::Diagnostic::error(eve::DiagnosticCode::StaleHandle, "primitive scene owner no longer exists",
501 "primitive", {}, "graphics.primitive.binding"));
502 const PrimitiveDescriptor3D* descriptor = scene->tryGet(value->handle);
503 if (!descriptor)
505 eve::Diagnostic::error(eve::DiagnosticCode::StaleHandle, "primitive handle is stale", "primitive", {},
506 "graphics.primitive.binding"));
508}
509
510template <class Mutator>
511eve::Result<PrimitiveUpdateStatus> mutatePrimitive(ScriptPrimitive3D* value, Mutator&& mutator) {
512 auto descriptor = primitiveDescriptor(value);
514 PrimitiveDescriptor3D copy = std::move(descriptor).takeValue();
515 std::invoke(std::forward<Mutator>(mutator), copy);
516 auto scene = value->scene.lock();
517 if (!scene)
519 eve::Diagnostic::error(eve::DiagnosticCode::StaleHandle, "primitive scene owner no longer exists",
520 "primitive", {}, "graphics.primitive.binding"));
521 return scene->update(value->handle, std::move(copy));
522}
523
524ssq::Table makePrimitiveProxy(HSQUIRRELVM vm, const std::shared_ptr<PrimitiveScene>& scene,
526 if (!result) return eve::script::projectStatusResult(vm, result.status());
527 const PrimitiveHandle handle = std::move(result).takeValue();
528 auto object = eve::script::makeOwnedSquirrelInstance<ScriptPrimitive3D>(
529 vm, std::make_unique<ScriptPrimitive3D>(scene, handle));
530 if (!object) {
531 const eve::Status status = object.status();
532 object.ignore("failed to create owned primitive proxy");
533 scene->remove(handle).ignore("rollback failed primitive proxy allocation");
535 }
537 projected.set("value", std::move(object).takeValue());
538 projected.set("ownership", std::string("owned"));
539 projected.set("owner", static_cast<std::int64_t>(handle.owner()));
540 projected.set("index", static_cast<std::int64_t>(handle.index()));
541 projected.set("generation", static_cast<std::int64_t>(handle.generation()));
542 return projected;
543}
544
545ScenePrimitivePaint scriptPrimitivePaint(float r, float g, float b, float a, float width) {
546 ScenePrimitivePaint paint;
547 paint.color = Color(r, g, b, a);
548 paint.mode = PaintMode::Stroke;
549 paint.stroke.width = width;
550 paint.stroke.widthSpace = WidthSpace::ScreenPixels;
551 return paint;
552}
553
554eve::Result<std::vector<glm::vec3>> scriptPoints(ssq::Array values, std::size_t minimum, std::size_t maximum) {
555 if (values.size() % 3 != 0 || values.size() / 3 < minimum || values.size() / 3 > maximum)
557 eve::DiagnosticCode::InvalidArgument, "expected a flat xyz array with the required point count", "points",
558 {}, "graphics.primitive.binding"));
559 std::vector<glm::vec3> points;
560 points.reserve(values.size() / 3);
561 try {
562 for (std::size_t i = 0; i < values.size(); i += 3)
563 points.push_back({values.get<float>(i), values.get<float>(i + 1), values.get<float>(i + 2)});
564 } catch (const std::exception& error) {
566 eve::DiagnosticCode::InvalidArgument, error.what(), "points", {}, "graphics.primitive.binding"));
567 }
568 return eve::Result<std::vector<glm::vec3>>::success(std::move(points));
569}
570} // namespace
571
572void exposePrimitiveScriptBindings(ssq::Table& table, ssq::Class& cls) {
573 const auto vm = table.getHandle();
574 cls.addFunc("newPrimitiveGrid3D", [vm](Graphics* self, ssq::Array xyz, int cellsU, int cellsV, float r, float g,
575 float b, float a, float width) {
576 auto parsed = scriptPoints(xyz, 3, 3);
577 if (!parsed) return eve::script::projectStatusResult(vm, parsed.status());
578 auto points = std::move(parsed).takeValue();
579 if (cellsU <= 0 || cellsV <= 0 || cellsU > 4096 || cellsV > 4096)
582 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "grid cells must be in [1,4096]",
583 "cells", {}, "graphics.primitive.binding"))
584 .status());
585 auto scene = self->getPrimitiveScene();
587 descriptor.geometry = PrimitiveGrid3D{points[0], points[1], points[2], static_cast<std::uint32_t>(cellsU),
588 static_cast<std::uint32_t>(cellsV)};
589 descriptor.paint = scriptPrimitivePaint(r, g, b, a, width);
590 return makePrimitiveProxy(vm, scene, scene->add(std::move(descriptor)));
591 });
592 cls.addFunc("newPrimitiveArc3D", [vm](Graphics* self, ssq::Array xyz, float radius, float start, float sweep,
593 float r, float g, float b, float a, float width) {
594 auto parsed = scriptPoints(xyz, 3, 3);
595 if (!parsed) return eve::script::projectStatusResult(vm, parsed.status());
596 auto points = std::move(parsed).takeValue();
597 auto scene = self->getPrimitiveScene();
600 descriptor.paint = scriptPrimitivePaint(r, g, b, a, width);
601 return makePrimitiveProxy(vm, scene, scene->add(std::move(descriptor)));
602 });
603 cls.addFunc("newPrimitivePolyline3D",
604 [vm](Graphics* self, ssq::Array xyz, bool closed, float r, float g, float b, float a, float width) {
605 auto parsed = scriptPoints(xyz, closed ? 3 : 2, 65536);
606 if (!parsed) return eve::script::projectStatusResult(vm, parsed.status());
607 auto points = std::move(parsed).takeValue();
608 auto scene = self->getPrimitiveScene();
611 descriptor.paint = scriptPrimitivePaint(r, g, b, a, width);
612 return makePrimitiveProxy(vm, scene, scene->add(std::move(descriptor)));
613 });
614 cls.addFunc("newPrimitiveObb3D",
615 [vm](Graphics* self, ssq::Array xyz, float r, float g, float b, float a, float width) {
616 auto parsed = scriptPoints(xyz, 4, 4);
617 if (!parsed) return eve::script::projectStatusResult(vm, parsed.status());
618 auto points = std::move(parsed).takeValue();
619 auto scene = self->getPrimitiveScene();
622 descriptor.paint = scriptPrimitivePaint(r, g, b, a, width);
623 return makePrimitiveProxy(vm, scene, scene->add(std::move(descriptor)));
624 });
625 cls.addFunc("newPrimitiveFrustum3D",
626 [vm](Graphics* self, ssq::Array xyz, float r, float g, float b, float a, float width) {
627 auto parsed = scriptPoints(xyz, 8, 8);
628 if (!parsed) return eve::script::projectStatusResult(vm, parsed.status());
629 auto points = std::move(parsed).takeValue();
630 auto scene = self->getPrimitiveScene();
633 {points[0], points[1], points[2], points[3], points[4], points[5], points[6], points[7]}};
634 descriptor.paint = scriptPrimitivePaint(r, g, b, a, width);
635 return makePrimitiveProxy(vm, scene, scene->add(std::move(descriptor)));
636 });
637 cls.addFunc("newPrimitiveDisk3D", [vm](Graphics* self, float x, float y, float z, float nx, float ny, float nz,
638 float radius, float r, float g, float b, float a, float width) {
639 auto scene = self->getPrimitiveScene();
641 descriptor.geometry = PrimitiveDisk3D{{x, y, z}, {nx, ny, nz}, radius, 32};
642 descriptor.paint = scriptPrimitivePaint(r, g, b, a, width);
643 return makePrimitiveProxy(vm, scene, scene->add(std::move(descriptor)));
644 });
645 cls.addFunc("newPrimitiveCylinder3D",
646 [vm](Graphics* self, float ax, float ay, float az, float bx, float by, float bz, float radius, float r,
647 float g, float b, float a, float width) {
648 auto scene = self->getPrimitiveScene();
650 descriptor.geometry = PrimitiveCylinder3D{{ax, ay, az}, {bx, by, bz}, radius, 32};
651 descriptor.paint = scriptPrimitivePaint(r, g, b, a, width);
652 return makePrimitiveProxy(vm, scene, scene->add(std::move(descriptor)));
653 });
654 cls.addFunc("newPrimitiveCapsule3D", [vm](Graphics* self, float ax, float ay, float az, float bx, float by,
655 float bz, float radius, float r, float g, float b, float a, float width) {
656 auto scene = self->getPrimitiveScene();
658 descriptor.geometry = PrimitiveCapsule3D{{ax, ay, az}, {bx, by, bz}, radius, 32};
659 descriptor.paint = scriptPrimitivePaint(r, g, b, a, width);
660 return makePrimitiveProxy(vm, scene, scene->add(std::move(descriptor)));
661 });
662 cls.addFunc("newPrimitiveCone3D",
663 [vm](Graphics* self, float x, float y, float z, float dx, float dy, float dz, float height,
664 float radius, float r, float g, float b, float a, float width) {
665 auto scene = self->getPrimitiveScene();
668 descriptor.paint = scriptPrimitivePaint(r, g, b, a, width);
669 return makePrimitiveProxy(vm, scene, scene->add(std::move(descriptor)));
670 });
671 cls.addFunc("newPrimitiveArrow3D",
672 [vm](Graphics* self, float ax, float ay, float az, float bx, float by, float bz, float headLength,
673 float headRadius, float r, float g, float b, float a, float width) {
674 auto scene = self->getPrimitiveScene();
676 descriptor.geometry = PrimitiveArrow3D{{ax, ay, az}, {bx, by, bz}, headLength, headRadius};
677 descriptor.paint = scriptPrimitivePaint(r, g, b, a, width);
678 return makePrimitiveProxy(vm, scene, scene->add(std::move(descriptor)));
679 });
680 auto primitive = table.addClass<ScriptPrimitive3D>(
681 "Primitive3D", std::function<ScriptPrimitive3D*()>([]() { return nullptr; }), false);
682 const auto primitiveTag = primitive.getTypeTag();
683 cls.addFunc(
684 "setPrimitiveTransforms3D", [vm, primitiveTag](Graphics* self, ssq::Array proxies, ssq::Array matrices) {
685 auto failure = [vm](const std::string& message) {
688 message, "transforms", {},
689 "graphics.primitive.binding"))
690 .status());
691 };
692 if (!self || proxies.size() > 65536 || matrices.size() != proxies.size() * 16)
693 return failure("expected one column-major matrix per primitive, at most 65536 primitives");
694 auto scene = self->getPrimitiveScene();
695 std::vector<PrimitiveBatchUpdate> updates;
696 updates.reserve(proxies.size());
697 try {
698 for (std::size_t i = 0; i < proxies.size(); ++i) {
699 auto object = proxies.get<ssq::Object>(i);
700 if (object.getType() != ssq::Type::INSTANCE || object.getTypeTag() != primitiveTag)
701 return failure("batch entries must be Primitive3D proxies");
702 auto* proxy = object.toPtrUnsafe<ScriptPrimitive3D*>();
703 auto descriptor = primitiveDescriptor(proxy);
705 auto copy = std::move(descriptor).takeValue();
706 for (int column = 0; column < 4; ++column)
707 for (int row = 0; row < 4; ++row)
708 copy.transform[column][row] = matrices.get<float>(i * 16 + column * 4 + row);
709 updates.push_back({proxy->handle, std::move(copy)});
710 }
711 } catch (const std::exception& error) {
712 return failure(error.what());
713 }
714 auto result = scene->updateMany(updates);
715 const auto status = result.status();
717 const auto count = std::move(result).takeValue();
718 auto projected = eve::script::projectStatusResult(vm, status);
719 projected.set("count", static_cast<std::int64_t>(count));
720 return projected;
721 });
722 primitive.addFunc("ownership", [](ScriptPrimitive3D*) { return std::string("owned"); });
723 primitive.addFunc("setPolyline", [vm](ScriptPrimitive3D* value, ssq::Array xyz, bool closed) {
724 auto parsed = scriptPoints(xyz, closed ? 3 : 2, 65536);
725 if (!parsed) return eve::script::projectStatusResult(vm, parsed.status());
726 auto points = std::move(parsed).takeValue();
727 auto result = mutatePrimitive(value, [&](PrimitiveDescriptor3D& descriptor) {
728 descriptor.geometry = PrimitivePolyline3D{std::move(points), closed};
729 });
730 const auto status = result.status();
732 std::move(result).takeValue();
734 });
735 primitive.addFunc("setLayer", [vm](ScriptPrimitive3D* value, std::int64_t layer) {
736 if (layer < 0 || layer > 0xffffffffLL)
739 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "layer must fit uint32", "layer",
740 {}, "graphics.primitive.binding"))
741 .status());
742 auto result = mutatePrimitive(value, [layer](PrimitiveDescriptor3D& descriptor) {
743 descriptor.paint.layer = static_cast<std::uint32_t>(layer);
744 });
745 const auto status = result.status();
747 std::move(result).takeValue();
749 });
750 primitive.addFunc("setTransform", [vm](ScriptPrimitive3D* value, ssq::Array elements) {
751 if (elements.size() != 16)
755 "transform requires 16 column-major floats", "transform", {},
756 "graphics.primitive.binding"))
757 .status());
758 glm::mat4 transform(1.f);
759 try {
760 for (int column = 0; column < 4; ++column)
761 for (int row = 0; row < 4; ++row) transform[column][row] = elements.get<float>(column * 4 + row);
762 } catch (const std::exception& error) {
766 "graphics.primitive.binding"))
767 .status());
768 }
769 auto result =
770 mutatePrimitive(value, [&](PrimitiveDescriptor3D& descriptor) { descriptor.transform = transform; });
771 const auto status = result.status();
773 std::move(result).takeValue();
775 });
776 primitive.addFunc("setWidthSpace", [vm](ScriptPrimitive3D* value, const std::string& mode) {
777 std::optional<WidthSpace> parsed;
778 if (mode == "screen") parsed = WidthSpace::ScreenPixels;
779 if (mode == "world") parsed = WidthSpace::WorldUnits;
780 if (!parsed)
783 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "unsupported setWidthSpace value",
784 "setWidthSpace", {}, "graphics.primitive.binding"))
785 .status());
786 auto result = mutatePrimitive(
787 value, [mode = *parsed](PrimitiveDescriptor3D& descriptor) { descriptor.paint.stroke.widthSpace = mode; });
788 const auto status = result.status();
790 std::move(result).takeValue();
792 });
793 primitive.addFunc("setPaintMode", [vm](ScriptPrimitive3D* value, const std::string& mode) {
794 std::optional<PaintMode> parsed;
795 if (mode == "fill") parsed = PaintMode::Fill;
796 if (mode == "stroke") parsed = PaintMode::Stroke;
797 if (mode == "fill-stroke") parsed = PaintMode::FillAndStroke;
798 if (!parsed)
801 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "unsupported setPaintMode value",
802 "setPaintMode", {}, "graphics.primitive.binding"))
803 .status());
804 auto result = mutatePrimitive(
805 value, [mode = *parsed](PrimitiveDescriptor3D& descriptor) { descriptor.paint.mode = mode; });
806 const auto status = result.status();
808 std::move(result).takeValue();
810 });
811 primitive.addFunc("setLineCap", [vm](ScriptPrimitive3D* value, const std::string& mode) {
812 std::optional<LineCap> parsed;
813 if (mode == "butt") parsed = LineCap::Butt;
814 if (mode == "square") parsed = LineCap::Square;
815 if (mode == "round") parsed = LineCap::Round;
816 if (!parsed)
819 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "unsupported setLineCap value",
820 "setLineCap", {}, "graphics.primitive.binding"))
821 .status());
822 auto result = mutatePrimitive(
823 value, [mode = *parsed](PrimitiveDescriptor3D& descriptor) { descriptor.paint.stroke.cap = mode; });
824 const auto status = result.status();
826 std::move(result).takeValue();
828 });
829 primitive.addFunc("setLineJoin", [vm](ScriptPrimitive3D* value, const std::string& mode) {
830 std::optional<LineJoin> parsed;
831 if (mode == "miter") parsed = LineJoin::Miter;
832 if (mode == "bevel") parsed = LineJoin::Bevel;
833 if (mode == "round") parsed = LineJoin::Round;
834 if (!parsed)
837 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "unsupported setLineJoin value",
838 "setLineJoin", {}, "graphics.primitive.binding"))
839 .status());
840 auto result = mutatePrimitive(
841 value, [mode = *parsed](PrimitiveDescriptor3D& descriptor) { descriptor.paint.stroke.join = mode; });
842 const auto status = result.status();
844 std::move(result).takeValue();
846 });
847 primitive.addFunc("setCullMode", [vm](ScriptPrimitive3D* value, const std::string& mode) {
848 std::optional<PrimitiveCullMode> parsed;
849 if (mode == "none") parsed = PrimitiveCullMode::None;
850 if (mode == "back") parsed = PrimitiveCullMode::Back;
851 if (mode == "front") parsed = PrimitiveCullMode::Front;
852 if (!parsed)
855 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "unsupported setCullMode value",
856 "setCullMode", {}, "graphics.primitive.binding"))
857 .status());
858 auto result = mutatePrimitive(
859 value, [mode = *parsed](PrimitiveDescriptor3D& descriptor) { descriptor.paint.cull = mode; });
860 const auto status = result.status();
862 std::move(result).takeValue();
864 });
865 primitive.addFunc("setBlendMode", [vm](ScriptPrimitive3D* value, const std::string& mode) {
866 std::optional<BlendMode> parsed;
867 if (mode == "alpha") parsed = BlendMode::Alpha;
868 if (mode == "opaque") parsed = BlendMode::Opaque;
869 if (mode == "additive") parsed = BlendMode::Additive;
870 if (mode == "premultiplied") parsed = BlendMode::Premultiplied;
871 if (mode == "multiply") parsed = BlendMode::Multiply;
872 if (!parsed)
875 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "unsupported setBlendMode value",
876 "setBlendMode", {}, "graphics.primitive.binding"))
877 .status());
878 auto result = mutatePrimitive(
879 value, [mode = *parsed](PrimitiveDescriptor3D& descriptor) { descriptor.paint.blend = mode; });
880 const auto status = result.status();
882 std::move(result).takeValue();
884 });
885 primitive.addFunc("isStale", [](ScriptPrimitive3D* value) {
886 if (!value) return true;
887 auto scene = value->scene.lock();
888 return !scene || scene->isStale(value->handle);
889 });
890 primitive.addFunc("remove", [vm](ScriptPrimitive3D* value) {
891 if (!value)
894 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "primitive proxy must not be null",
895 "primitive", {}, "graphics.primitive.binding"))
896 .status());
897 auto scene = value->scene.lock();
898 if (!scene)
900 vm,
902 eve::Diagnostic::error(eve::DiagnosticCode::StaleHandle, "primitive scene owner no longer exists",
903 "primitive", {}, "graphics.primitive.binding"))
904 .status());
905 auto result = scene->remove(value->handle);
906 const eve::Status status = result.status();
908 std::move(result).takeValue();
909 value->handle = {};
911 });
912 primitive.addFunc("setVisible", [vm](ScriptPrimitive3D* value, bool visible) {
913 auto result =
914 mutatePrimitive(value, [visible](PrimitiveDescriptor3D& descriptor) { descriptor.visible = visible; });
915 const eve::Status status = result.status();
917 std::move(result).takeValue();
919 });
920 primitive.addFunc("setColor", [vm](ScriptPrimitive3D* value, float r, float g, float b, float a) {
921 auto result = mutatePrimitive(
922 value, [=](PrimitiveDescriptor3D& descriptor) { descriptor.paint.color = Color(r, g, b, a); });
923 const eve::Status status = result.status();
925 std::move(result).takeValue();
927 });
928 primitive.addFunc("setLineWidth", [vm](ScriptPrimitive3D* value, float width) {
929 auto result = mutatePrimitive(
930 value, [width](PrimitiveDescriptor3D& descriptor) { descriptor.paint.stroke.width = width; });
931 const eve::Status status = result.status();
933 std::move(result).takeValue();
935 });
936 primitive.addFunc("setDash", [vm](ScriptPrimitive3D* value, float drawLength, float gapLength, float phase,
937 const std::string& space) {
938 if (space != "screen" && space != "world")
940 vm,
942 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "dash space must be screen or world",
943 "dashSpace", {}, "graphics.primitive.binding"))
944 .status());
945 auto result = mutatePrimitive(value, [=](PrimitiveDescriptor3D& descriptor) {
946 DashPattern dash;
947 dash.intervals = {drawLength, gapLength};
948 dash.phase = phase;
949 dash.space = space == "screen" ? DashSpace::ScreenPixels : DashSpace::WorldUnits;
950 descriptor.paint.stroke.dash = std::move(dash);
951 });
952 const eve::Status status = result.status();
954 std::move(result).takeValue();
956 });
957 primitive.addFunc("clearDash", [vm](ScriptPrimitive3D* value) {
958 auto result =
959 mutatePrimitive(value, [](PrimitiveDescriptor3D& descriptor) { descriptor.paint.stroke.dash.reset(); });
960 const eve::Status status = result.status();
962 std::move(result).takeValue();
964 });
965 primitive.addFunc("setDepthMode", [vm](ScriptPrimitive3D* value, const std::string& mode) {
966 std::optional<PrimitiveDepthMode> parsed;
967 if (mode == "test-write")
969 else if (mode == "test")
971 else if (mode == "ignore")
973 if (!parsed)
977 "depth mode must be test-write, test, or ignore", "depthMode", {},
978 "graphics.primitive.binding"))
979 .status());
980 auto result = mutatePrimitive(
981 value, [mode = *parsed](PrimitiveDescriptor3D& descriptor) { descriptor.paint.depth = mode; });
982 const eve::Status status = result.status();
984 std::move(result).takeValue();
986 });
987 primitive.addFunc("setObjectId", [vm](ScriptPrimitive3D* value, std::int64_t objectId) {
988 if (objectId < 0)
991 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "object id must be non-negative",
992 "objectId", {}, "graphics.primitive.binding"))
993 .status());
994 auto result = mutatePrimitive(value, [objectId](PrimitiveDescriptor3D& descriptor) {
995 descriptor.paint.objectId = static_cast<std::uint64_t>(objectId);
996 });
997 const eve::Status status = result.status();
999 std::move(result).takeValue();
1001 });
1002
1003 cls.addFunc("newPrimitiveLine3D", [vm](Graphics* self, float ax, float ay, float az, float bx, float by, float bz,
1004 float r, float g, float b, float a, float width) {
1005 auto scene = self->getPrimitiveScene();
1007 descriptor.geometry = PrimitivePolyline3D{{{ax, ay, az}, {bx, by, bz}}, false};
1008 descriptor.paint = scriptPrimitivePaint(r, g, b, a, width);
1009 return makePrimitiveProxy(vm, scene, scene->add(std::move(descriptor)));
1010 });
1011 cls.addFunc("newPrimitiveSphere3D", [vm](Graphics* self, float x, float y, float z, float radius, float r, float g,
1012 float b, float a, float width) {
1013 auto scene = self->getPrimitiveScene();
1016 descriptor.paint = scriptPrimitivePaint(r, g, b, a, width);
1017 return makePrimitiveProxy(vm, scene, scene->add(std::move(descriptor)));
1018 });
1019 cls.addFunc("newPrimitiveAabb3D", [vm](Graphics* self, float minX, float minY, float minZ, float maxX, float maxY,
1020 float maxZ, float r, float g, float b, float a, float width) {
1021 auto scene = self->getPrimitiveScene();
1023 descriptor.geometry = PrimitiveAabb3D{{minX, minY, minZ}, {maxX, maxY, maxZ}};
1024 descriptor.paint = scriptPrimitivePaint(r, g, b, a, width);
1025 return makePrimitiveProxy(vm, scene, scene->add(std::move(descriptor)));
1026 });
1027}
1028} // namespace eve::graphics
1029
1030// PrimitiveTypes.cpp
1031namespace eve::graphics {
1032
1033std::uint32_t resolveRadialSegments(const RadialTessellation& tessellation, float projectedRadiusPixels) {
1034 const bool validError = std::isfinite(tessellation.maxScreenErrorPixels) && tessellation.maxScreenErrorPixels > 0.f;
1035 EV_PARAM_CHECK(validError, "radial tessellation screen error must be finite and positive");
1036 if (tessellation.customSegments != 0) {
1037 const bool validCustom = tessellation.customSegments >= 3 && tessellation.customSegments <= 4096;
1038 EV_PARAM_CHECK(validCustom, "custom radial segment count must be in [3, 4096]");
1039 return tessellation.customSegments;
1040 }
1041 switch (tessellation.quality) {
1042 case PrimitiveQuality::Low: return 16;
1043 case PrimitiveQuality::Medium: return 32;
1044 case PrimitiveQuality::High: return 64;
1045 case PrimitiveQuality::Adaptive: break;
1046 }
1047 const bool validRadius = std::isfinite(projectedRadiusPixels) && projectedRadiusPixels >= 0.f;
1048 EV_PARAM_CHECK(validRadius, "adaptive radial projected radius must be finite and non-negative");
1049 if (projectedRadiusPixels <= tessellation.maxScreenErrorPixels) return 8;
1050 const float cosine = glm::clamp(1.f - tessellation.maxScreenErrorPixels / projectedRadiusPixels, -1.f, 1.f);
1051 const float halfAngle = std::acos(cosine);
1052 if (halfAngle <= 1e-6f) return 256;
1053 return std::clamp(static_cast<std::uint32_t>(std::ceil(glm::pi<float>() / halfAngle)), 8u, 256u);
1054}
1055
1057 EV_PARAM_CHECK(!intervals.empty(), "dash intervals must not be empty");
1058 EV_PARAM_CHECK(intervals.size() % 2 == 0, "dash intervals must contain draw/gap pairs");
1059 EV_PARAM_CHECK(std::isfinite(phase), "dash phase must be finite");
1060 for (float interval : intervals) {
1061 const bool validInterval = std::isfinite(interval) && interval > 0.f;
1062 EV_PARAM_CHECK(validInterval, "dash intervals must be finite and greater than zero");
1063 }
1064}
1065
1066float DashPattern::period() const {
1067 validate();
1068 return std::accumulate(intervals.begin(), intervals.end(), 0.f);
1069}
1070
1072 const bool validWidth = std::isfinite(width) && width >= 0.f;
1073 EV_PARAM_CHECK(validWidth, "stroke width must be finite and non-negative");
1074 const bool validMiterLimit = std::isfinite(miterLimit) && miterLimit > 0.f;
1075 EV_PARAM_CHECK(validMiterLimit, "stroke miter limit must be finite and greater than zero");
1076 if (dash) dash->validate();
1077}
1078
1080
1082 const bool validViewport = viewportSize.x > 0 && viewportSize.y > 0;
1083 EV_PARAM_CHECK(validViewport, "scene primitive viewport must be positive");
1084 const bool validNearPlane = std::isfinite(nearPlane) && nearPlane > 0.f;
1085 EV_PARAM_CHECK(validNearPlane, "scene primitive near plane must be finite and positive");
1086 const bool validFarPlane = std::isfinite(farPlane) && farPlane > nearPlane;
1087 EV_PARAM_CHECK(validFarPlane, "scene primitive far plane must be finite and greater than near plane");
1088}
1089
1090} // namespace eve::graphics
double z
double y
double x
Duration start
EVEngine assertion entry point, backed by zeroerr.
#define EV_PARAM_CHECK(cond,...)
Validate a function parameter / public API precondition.
Definition Assert.h:30
std::string output
std::string descriptor
double volume
struct SQVM * HSQUIRRELVM
HSQUIRRELVM vm
Definition ECS.cpp:38
HSQOBJECT cls
Definition ECS.cpp:39
Generation generation
Definition ECS.cpp:40
std::string message
float maximum[3]
float minimum[3]
tensor::Graph g
Definition GpuGraph.cpp:7
wgpu::PopErrorScopeStatus status
float u
Definition Grass.cpp:233
double r
std::uint32_t ac
std::int32_t c
std::uint32_t height
std::uint32_t width
Poco::JSON::Object::Ptr result
uint64_t used
bool valid
MeleePoint3 b
Definition MeleeHit.cpp:41
double radius
Definition MeleeHit.cpp:42
MeleePoint3 a
Definition MeleeHit.cpp:40
std::vector< TriangleRef > triangles
std::shared_ptr< OceanGpuSpectrum > owner
glm::dvec3 dx
glm::dvec3 dz
bool finite
std::string error
Definition Package.cpp:174
TileLayer * layer
std::shared_ptr< const std::vector< glm::vec2 > > points
bool hit
std::weak_ptr< PrimitiveScene > scene
PrimitiveHandle handle
std::set< std::string > values
Object::Ptr value
float t
std::string slot
std::string geometry
unsigned line
unsigned column
size_t end
double current
float dy
Definition Shadow.cpp:151
std::size_t elements
int count
The single Squirrel projection for common Result, Status and Value.
Explicit Value/Owned/Borrowed semantics at the Squirrel boundary.
float phase
bool visible
std::vector< std::string_view > lines
std::uint32_t depth
uint32_t index
glm::vec3 point
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
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
const Status & status() const noexcept
Inspect the structured operation status.
Definition Result.h:300
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
std::shared_ptr< PrimitiveScene > getPrimitiveScene() const noexcept
Returns the authoritative persistent spatial-primitive scene.
Definition Graphics.h:508
Owning backend-neutral 2D vector path.
Path2D & lineTo(glm::vec2 point)
Adds a straight segment to point.
Path2D & moveTo(glm::vec2 point)
Starts a new contour at point.
Path2D & quadTo(glm::vec2 control, glm::vec2 point)
Adds a quadratic Bezier segment.
Path2D & cubicTo(glm::vec2 control1, glm::vec2 control2, glm::vec2 point)
Adds a cubic Bezier segment.
Path2D & close()
Closes the current contour.
std::vector< FlattenedContour2D > flatten(float tolerance=0.25f, std::uint32_t maxDepth=12) const
Flattens curves into owning line contours.
void clear() noexcept
Removes all verbs and points while retaining capacity.
Instance-qualified persistent primitive handle.
constexpr generation_type generation() const noexcept
Generation.
constexpr bool isValid() const noexcept
True when valid.
LocalHandle::index_type index_type
constexpr owner_type owner() const noexcept
Owner.
static constexpr index_type invalidIndex
constexpr index_type index() const noexcept
Index.
static constexpr std::optional< generation_type > nextGeneration(generation_type current) noexcept
Next generation.
Frame-local scene recorder for 3D line primitives.
void drawArrow(glm::vec3 from, glm::vec3 to, float headLength, float headRadius, const ScenePrimitivePaint &paint)
Records a shaft and four-sided arrow head.
void drawSphere(glm::vec3 center, float radius, const ScenePrimitivePaint &paint, std::uint32_t segments=32)
Records three orthogonal great circles.
void concat(const glm::mat4 &transform)
Concat.
void drawCapsule(glm::vec3 a, glm::vec3 b, float radius, const ScenePrimitivePaint &paint, std::uint32_t segments=32)
Draws capsule.
void drawFrustum(const std::array< glm::vec3, 8 > &corners, const ScenePrimitivePaint &paint)
Draws frustum.
void drawObb(glm::vec3 center, const std::array< glm::vec3, 3 > &halfAxes, const ScenePrimitivePaint &paint)
Draws obb.
void drawGrid(glm::vec3 origin, glm::vec3 axisU, glm::vec3 axisV, std::uint32_t cellsU, std::uint32_t cellsV, const ScenePrimitivePaint &paint)
Records a planar grid spanned by two caller-provided axes.
void drawAabb(glm::vec3 minimum, glm::vec3 maximum, const ScenePrimitivePaint &paint)
Records the twelve edges of an axis-aligned box.
void drawPolyline(std::span< const glm::vec3 > points, bool closed, const ScenePrimitivePaint &paint)
Draws polyline.
void drawArc(glm::vec3 center, glm::vec3 normal, glm::vec3 zeroDirection, float radius, float startRadians, float sweepRadians, const ScenePrimitivePaint &paint, std::uint32_t segments=32)
Draws arc.
void drawCylinder(glm::vec3 a, glm::vec3 b, float radius, const ScenePrimitivePaint &paint, std::uint32_t segments=32)
Records endpoint circles and four side lines of a cylinder.
void drawDisk(glm::vec3 center, glm::vec3 normal, float radius, const ScenePrimitivePaint &paint, std::uint32_t segments=32)
Draws disk.
void drawCone(glm::vec3 apex, glm::vec3 axis, float height, float radius, const ScenePrimitivePaint &paint, std::uint32_t segments=32)
Records the base circle and four side lines of a cone.
void clear()
Invalidates all live handles while retaining slot capacity.
void render(PrimitiveSceneCanvas3D &canvas) const
Compatibility-only wrapper over tryRender; throws on budget failure.
eve::Result< PrimitiveRemoveStatus > remove(PrimitiveHandle handle)
Removes .
eve::Result< PrimitiveHandle > add(PrimitiveDescriptor3D descriptor)
Adds .
eve::Result< std::size_t > updateMany(std::span< const PrimitiveBatchUpdate > updates)
Atomically replaces several live descriptors after validating every handle.
eve::Result< PrimitiveUpdateStatus > update(PrimitiveHandle handle, PrimitiveDescriptor3D descriptor)
Updates .
eve::Result< void > tryRender(PrimitiveSceneCanvas3D &canvas) const
Projects visible descriptors in stable slot order using per-slot CPU caches. Successful updates inval...
const PrimitiveDescriptor3D * tryGet(PrimitiveHandle handle) const noexcept
Resolves a live primitive handle.
bool isStale(PrimitiveHandle handle) const noexcept
Returns true when a handle is invalid, removed, foreign, or generation-stale.
float lengthSquared(Vec3 value)
Length squared.
卡牌游戏 UI 工具模块:工厂 + 脚本绑定入口。 功能参考 ycarowr/UiCard:扇形手牌布局、抽牌/洗牌、悬浮放大、拖拽到落牌区、 敌方手牌(背面/偷看)、费用不足置灰,以及可实时调节的布局...
Definition Animation.h:25
void exposePrimitiveScriptBindings(ssq::Table &table, ssq::Class &cls)
Registers owning primitive proxies on the VM owner thread; retains no table references.
eve::Color Color
RGBA color used by every graphics draw call. Lives inside eve::graphics so including a graphics heade...
Definition Color.h:13
std::uint32_t resolveRadialSegments(const RadialTessellation &tessellation, float projectedRadiusPixels)
Resolves a radial tessellation policy to a validated segment count.
ssq::Table projectStatusResult(HSQUIRRELVM vm, const Status &status)
Project a checked native status that carries no payload.
WidgetDesc row(std::vector< WidgetDesc > children, std::string id)
Horizontal elastic layout row.
Definition Widget.cpp:870
Owning alternating draw/gap pattern for stroked primitives.
float period() const
Returns the sum of all draw and gap intervals.
void validate() const
Validates finite positive intervals and an even interval count.
std::vector< float > intervals
PrimitiveAabb3D public API.
PrimitiveArc3D public API.
PrimitiveArrow3D public API.
PrimitiveBatchUpdate public API.
PrimitiveCapsule3D public API.
PrimitiveCone3D public API.
PrimitiveCylinder3D public API.
One persistent scene primitive owned by PrimitiveScene.
PrimitiveDisk3D public API.
PrimitiveFrustum3D public API.
PrimitiveGrid3D public API.
PrimitiveObb3D public API.
void validate() const
Validates paint state used by a draw command.
Owning persistent polyline descriptor.
PrimitiveSphere3D public API.
Quality and screen-error policy used by circles and curved spatial primitives.
void validate() const
Validates viewport and clip-plane values.
void validate() const
Validates all scalar and optional dash state.
std::optional< DashPattern > dash