Estella 0.113.0
A fast 2D and 3D game engine powered by WebAssembly and ECS
Loading...
Searching...
No Matches
TrailPlugin.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
3#include "TrailPlugin.hpp"
8#include "../rhi/Texture.hpp"
12
13#include <algorithm>
14#include <cmath>
15#include <limits>
16
17namespace esengine {
18
20 if (!trail_system_) return;
21
22 auto& registry = collect_ctx.registry;
23 auto& frustum = collect_ctx.frustum;
24 auto& clips = collect_ctx.clip_state;
25 auto& buffers = collect_ctx.buffer_pool;
26 auto& draw_list = collect_ctx.draw_list;
27 auto& ctx = collect_ctx.frame_context;
28
29 const f32 now = trail_system_->now();
30
31 auto view = registry.activeView<ecs::Transform, ecs::TrailRenderer>();
32 const ecs::GroupOpacityLookup groupOpacity(registry);
33 for (auto entity : view) {
34 const auto& trail = view.get<ecs::TrailRenderer>(entity);
35 if (!trail.enabled) continue;
36 const f32 groupAlpha = groupOpacity.of(entity);
37 if (groupAlpha <= 0.0f) continue;
38
39 const trail::TrailState* state = trail_system_->getState(entity);
40 if (!state || state->points.empty()) continue;
41
42 auto& transform = view.get<ecs::Transform>(entity);
43 transform.ensureDecomposed();
44 const glm::vec3 headWorld = rebased(transform.worldPosition);
45
46 // --- Build the centerline: anchors (oldest→newest), then the live head. -----
47 const f32 invTime = trail.time > 1e-6f ? 1.0f / trail.time : 0.0f;
48 scratch_center_.clear();
49 glm::vec3 lo(std::numeric_limits<f32>::max());
50 glm::vec3 hi(std::numeric_limits<f32>::lowest());
51 auto extend = [&](const glm::vec3& p) { lo = glm::min(lo, p); hi = glm::max(hi, p); };
52
53 for (const auto& pt : state->points) {
54 f32 age01 = std::min(std::max((now - pt.birth_time) * invTime, 0.0f), 1.0f);
55 const glm::vec3 at = rebased(pt.position);
56 scratch_center_.push_back({at, age01});
57 extend(at);
58 }
59 // The live head glues the ribbon to the moving entity between recorded
60 // anchors. Skip it when frozen (the streak fades where it was left) or when it
61 // coincides with the newest anchor (avoids a degenerate zero-length segment).
62 if (trail.emitting) {
63 glm::vec3 d = headWorld - scratch_center_.back().pos;
64 if (glm::dot(d, d) > 1e-4f) {
65 scratch_center_.push_back({headWorld, 0.0f});
66 extend(headWorld);
67 } else {
68 scratch_center_.back().age01 = 0.0f;
69 }
70 }
71
72 const usize n = scratch_center_.size();
73 if (n < 2) continue; // need at least one segment to form a ribbon
74
75 // --- Cull against the frustum (centerline AABB padded by half the max width). -
76 const f32 maxHalf = 0.5f * std::max(trail.startWidth, trail.endWidth);
77 const glm::vec3 aabbCenter = (lo + hi) * 0.5f;
78 const glm::vec3 halfExtents = (hi - lo) * 0.5f + maxHalf;
79 if (!frustum.intersectsAABB(aabbCenter, halfExtents)) { ++collect_ctx.culled; continue; }
80
81 // --- Draw key (mirrors MeshPlugin: material owns shading when present). ------
82 u32 textureId = ctx.white_texture_id;
83 if (trail.texture.isValid()) {
84 if (Texture* tex = ctx.resources.getTexture(trail.texture)) {
85 textureId = tex->getId();
86 }
87 }
88
89 BatchDrawKey key{
90 .stage = ctx.current_stage,
91 .layer = trail.layer,
92 .shaderId = ctx.batch_shader_id,
93 .blend = static_cast<BlendMode>(trail.blendMode),
94 .textureId = textureId,
95 .depth = collect_ctx.camera.viewDepth(headWorld),
96 .y = headWorld.y,
97 .entity = entity,
98 .type = RenderType::Trail,
99 };
100 if (trail.material != 0) {
101 if (const MaterialRecord* m = ctx.materials ? ctx.materials->find(trail.material) : nullptr) {
102 key.shaderId = (m->shader != 0) ? m->shader : ctx.batch_shader_id;
103 key.blend = m->blend;
104 key.materialId = trail.material;
105 key.depthTest = m->depthTest;
106 key.depthWrite = m->depthWrite;
107 key.cull = static_cast<u8>(m->cull);
108 key.depthBias = m->depthBias;
109 }
110 }
111
112 // --- Emit the ribbon: 2 verts per centerline point, 6 indices per segment. ---
113 scratch_verts_.clear();
114 scratch_verts_.reserve(n * 2);
115 glm::vec3 lastTangent(1.0f, 0.0f, 0.0f);
116 glm::vec3 lastSide(0.0f, 1.0f, 0.0f);
117 for (usize i = 0; i < n; ++i) {
118 const TrailCenter& c = scratch_center_[i];
119 // Central-difference tangent (forward/backward at the ends).
120 const glm::vec3& a = scratch_center_[i == 0 ? 0 : i - 1].pos;
121 const glm::vec3& b = scratch_center_[i + 1 == n ? i : i + 1].pos;
122 glm::vec3 seg = b - a;
123 f32 len = glm::length(seg);
124 glm::vec3 tangent = len > 1e-6f ? seg / len : lastTangent;
125 lastTangent = tangent;
126 const glm::vec3 side = ribbonSide(tangent, c.pos, collect_ctx.camera, lastSide);
127 lastSide = side;
128
129 f32 halfW = 0.5f * (trail.startWidth + (trail.endWidth - trail.startWidth) * c.age01);
130 glm::vec4 trailColor = glm::mix(trail.startColor, trail.endColor, c.age01);
131 trailColor.a *= groupAlpha;
132 u32 color = packColor(trailColor);
133 f32 u = c.age01; // U runs head(0)→tail(1) along the ribbon
134
135 scratch_verts_.push_back({c.pos + side * halfW, color, glm::vec2(u, 0.0f)});
136 scratch_verts_.push_back({c.pos - side * halfW, color, glm::vec2(u, 1.0f)});
137 }
138
139 scratch_indices_.clear();
140 scratch_indices_.reserve((n - 1) * 6);
141 for (u32 i = 0; i + 1 < n; ++i) {
142 u32 l0 = i * 2, r0 = l0 + 1, l1 = l0 + 2, r1 = l0 + 3;
143 scratch_indices_.push_back(l0);
144 scratch_indices_.push_back(r0);
145 scratch_indices_.push_back(r1);
146 scratch_indices_.push_back(l0);
147 scratch_indices_.push_back(r1);
148 scratch_indices_.push_back(l1);
149 }
150
151 appendIndexedBatch(buffers, draw_list, clips,
152 scratch_verts_.data(), static_cast<u32>(scratch_verts_.size()),
153 scratch_indices_.data(), static_cast<u32>(scratch_indices_.size()), key);
154 }
155}
156
157} // namespace esengine
The single submission face: the ONLY place a DrawCommand is assembled.
Engine-side material registry — the resolved "how to draw" for a material handle.
Frame resources and the shared scene rendering contract.
GPU texture abstraction for 2D images.
World-space motion trail renderable (sword swipes, projectile/dash streaks, ribbon effects).
Per-App motion-trail simulation: records each TrailRenderer entity's world position over time into a ...
Unified Transform component with local and world-space data.
2D texture for GPU rendering
Definition Texture.hpp:116
void collect(RenderCollectContext &ctx) override
The opacity a draw inherits from the GroupOpacity above it.
std::size_t usize
Size type for indexing and sizes.
Definition Types.hpp:64
u32 packColor(f32 r, f32 g, f32 b, f32 a)
std::uint32_t u32
Unsigned 32-bit integer.
Definition Types.hpp:45
BlendMode
Predefined blend modes for rendering.
Definition BlendMode.hpp:22
glm::vec3 rebased(const glm::vec3 &world)
A world position as the frame draws it: from the origin.
std::uint8_t u8
Unsigned 8-bit integer.
Definition Types.hpp:41
void appendIndexedBatch(TransientBufferPool &pool, DrawList &drawList, const ClipState &clips, const BatchVertex *verts, u32 vertexCount, const u32 *localIndices, u32 indexCount, const BatchDrawKey &key)
Copies verts into the Batch stream, then pushes one DrawCommand spanning them.
static EstellaContext & ctx()
glm::vec3 ribbonSide(const glm::vec3 &tangent, const glm::vec3 &worldPos, const CameraView &camera, const glm::vec3 &lastSide)
The side vector a ribbon widens along: perpendicular to both its path and the viewer,...
float f32
32-bit floating point
Definition Types.hpp:59
Non-geometry attributes of a batch draw — everything needed to build the sort key + DrawCommand.
i16 depthBias
Depth-buffer units toward the eye.
u8 cull
CullMode: 0 = none, 1 = back, 2 = front.
f32 viewDepth(const glm::vec3 &worldPos) const
How near worldPos is to the viewer, larger = nearer — the order the sort key wants,...
A material's resolved render state (P0) plus its packed std140 constants (P1).
u32 culled
How many renderables this collect's frustum rejected.
One centerline sample: world position + normalized age (0 head, 1 tail).
Unified transform component.
Definition Transform.hpp:45
Per-entity point history. Front = oldest (tail), back = newest (near head).
std::deque< TrailPoint > points