Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

16.5 KB
Raw Blame
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
#include "ParticlePlugin.hpp"
#include "../draw/BatchBuilder.hpp"
#include "../frame/RenderContext.hpp"
#include "../frame/RenderFrame.hpp"
#ifdef ES_ENABLE_GPU_PARTICLES
#include "../frame/GpuParticles.hpp"
#endif
#include "../rhi/Shader.hpp"
#include "../rhi/ShaderEmbeds.generated.hpp"
#include "../rhi/Texture.hpp"
#include "../draw/BatchVertex.hpp"   // packColor
#include "../../resource/ShaderParser.hpp"
#include "../../ecs/components/Transform.hpp"
#include "../../ecs/components/ParticleEmitter.hpp"
#include "../../particle/ParticleSystem.hpp"
#include "../../particle/Particle.hpp"

#include "../../particle/ParticleStretch.hpp"
#include <algorithm>
#include <string>
#include <cmath>

namespace esengine {

namespace {
// One record per live particle, matching the PARTICLE_INSTANCE vertex attributes
// (locations 2-7). The GPU expands the 4-vertex quad; the CPU only fills these 44 bytes
// per particle (vs. the old 4 verts + 6 indices), which is the whole point of RC7-1.
struct ParticleInstanceData {
    f32 px, py, pz;      // a_inst_position (world)
    f32 sx, sy;          // a_inst_size
    f32 rotation;        // a_inst_rotation
    u32 color;           // a_inst_color (RGBA8)
    f32 uvOffsetX, uvOffsetY;
    f32 uvScaleX, uvScaleY;
};
static_assert(sizeof(ParticleInstanceData) == 44, "instance stride must match the VAO layout");
}  // namespace

void ParticlePlugin::init(RenderFrameContext& ctx) {
    // Whether emitters that ask to simulate on the GPU can: the device says, and the CPU sim falls back where it cannot.
#ifdef ES_ENABLE_GPU_PARTICLES
    if (particle_system_ && ctx.frame && ctx.frame->gpuParticles()) {
        particle_system_->setGpuAvailable(ctx.frame->gpuParticles()->available());
    }
#endif
    // Particle instancing shader, authored as particle.esshader (single source,
    // WGSL twin included) and embedded for the web build. Attribute locations
    // are explicit, so no name bindings.
    if (particle_shader_handle_.isValid()) ctx.resources.releaseShader(particle_shader_handle_);
    const auto target = ctx.resources.preferredShaderTarget();
    auto parsed = resource::ShaderParser::parse(ShaderEmbeds::PARTICLE);
    // The same feature a material's particle variant is compiled with, so the
    // built-in fragment and an authored one sit on one vertex stage.
    const std::vector<std::string> features{ "PARTICLE" };
    resource::ShaderHandle& handle = particle_shader_handle_;
    handle = ctx.resources.createShaderWithBindings(
        resource::ShaderParser::assembleStage(parsed, resource::ShaderStage::Vertex, "", features, target),
        resource::ShaderParser::assembleStage(parsed, resource::ShaderStage::Fragment, "", features, target),
        {}, ctx.resources.preferredShaderLanguage(), ctx.resources.deferLinks());
    Shader* shader = ctx.resources.getShader(handle);
    if (shader && shader->isValid()) {
        particle_shader_id_ = shader->getProgramId();
        if (shader->language() == GfxShaderLanguage::GLSL_ES300) {
            // Sampler seeding is a GLSL concept; on WGSL the texture rides the
            // bind group. After it links: at once, or when a draw first needs it.
            shader->whenLinked([](Shader& s) {
                s.bind();
                for (i32 unit = 0; unit < 8; ++unit) {
                    s.setUniform("u_textures[" + std::to_string(unit) + "]", unit);
                }
                s.unbind();
            });
        }
    }
}

void ParticlePlugin::collect(RenderCollectContext& collect_ctx) {
    auto& registry = collect_ctx.registry;
    auto& clips = collect_ctx.clip_state;
    auto& buffers = collect_ctx.buffer_pool;
    auto& draw_list = collect_ctx.draw_list;
    auto& ctx = collect_ctx.frame_context;
    if (!particle_system_ || particle_shader_id_ == 0) return;

    auto emitterView = registry.activeView<ecs::Transform, ecs::ParticleEmitter>();

    for (auto entity : emitterView) {
        if (!collect_ctx.accepts(entity)) continue;
        const auto& emitter = emitterView.get<ecs::ParticleEmitter>(entity);
        if (!emitter.enabled) continue;

        auto& transform = emitterView.get<ecs::Transform>(entity);
        transform.ensureDecomposed();

        const auto* state = particle_system_->getState(entity);
        if (!state) continue;

        // A GPU emitter's particles are in a buffer a kernel writes: this frame's step is queued, and the draw is told
        // where to read them. The CPU has nothing per particle to do.
        BufferHandle gpuInstances = BufferHandle::Invalid;
        BufferHandle gpuSegments = BufferHandle::Invalid;
        u32 gpuSegmentCount = 0;
        u32 particleCount = 0;
        if (state->gpu) {
#ifdef ES_ENABLE_GPU_PARTICLES
            GpuParticles* gpu = ctx.frame ? ctx.frame->gpuParticles() : nullptr;
            // The screen's overlay is not drawn through the graph the kernel runs in.
            if (!gpu || collect_ctx.isOverlay()) continue;
            buffers.reserveStream(LayoutId::ParticleInstance);
            particle::GpuStep step;
            if (!particle_system_->peekGpuStep(entity, step)) continue;
            if (!gpu->submit(entity, emitter, transform, *particle_system_, step, collect_ctx.camera.eye, gpuInstances, gpuSegments, gpuSegmentCount)) continue;
            particleCount = step.drawCount;
#else
            continue;  // no compute in this build: ParticleSystem never marks an emitter GPU-simulated
#endif
        } else {
            particleCount = state->pool.aliveCount();
        }
        if (particleCount == 0) continue;

        u32 textureId = ctx.white_texture_id;
        if (emitter.texture.isValid()) {
            Texture* tex = ctx.resources.getTexture(emitter.texture);
            if (tex) textureId = tex->getId();
        }

        i32 cols = std::max(emitter.spriteColumns, 1);
        i32 rows = std::max(emitter.spriteRows, 1);
        f32 uvScaleX = 1.0f / static_cast<f32>(cols);
        f32 uvScaleY = 1.0f / static_cast<f32>(rows);
        bool sheet = (cols > 1 || rows > 1);

        bool isLocalSpace = emitter.simulationSpace ==
                            static_cast<i32>(ecs::SimulationSpace::Local);
        glm::vec3 emitterWorldPos = rebased(transform.worldPosition);
        f32 emitterAngle = 0.0f;
        glm::vec2 emitterScale(transform.worldScale);
        f32 cosA = 1.0f, sinA = 0.0f;
        if (isLocalSpace) {
            const auto& rot = transform.worldRotation;
            emitterAngle = 2.0f * std::atan2(rot.z, rot.w);
            if (std::abs(emitterAngle) > 0.001f) {
                cosA = std::cos(emitterAngle);
                sinA = std::sin(emitterAngle);
            }
        }

        BlendMode blendMode = static_cast<BlendMode>(emitter.blendMode);

        u32 instByteOffset = 0;
        ParticleInstanceData* inst = nullptr;
        if (!state->gpu) {
            instByteOffset = buffers.allocVertices(LayoutId::ParticleInstance,
                                                   particleCount * sizeof(ParticleInstanceData));
            inst = reinterpret_cast<ParticleInstanceData*>(
                buffers.vertexData(LayoutId::ParticleInstance) + instByteOffset);
        }

        const bool stretched = emitter.renderMode == static_cast<i32>(ecs::ParticleRenderMode::Stretched);
        const f32 lengthScale = emitter.lengthScale;
        const f32 velocityScale = emitter.velocityScale;

        u32 i = 0;
        if (!state->gpu) state->pool.forEachAlive([&](const particle::Particle& p) {
            glm::vec3 worldPos;
            glm::vec2 size;
            if (isLocalSpace) {
                // The emitter's own turn is about Z, as a flat scene's is; depth
                // rides through it untouched rather than being dropped.
                glm::vec3 rel = p.position * glm::vec3(emitterScale, 1.0f);
                if (std::abs(emitterAngle) > 0.001f) {
                    worldPos = emitterWorldPos +
                        glm::vec3(rel.x * cosA - rel.y * sinA, rel.x * sinA + rel.y * cosA, rel.z);
                } else {
                    worldPos = emitterWorldPos + rel;
                }
                size = glm::vec2(p.size) * emitterScale;
            } else {
                worldPos = rebased(p.position);
                size = glm::vec2(p.size);
            }

            f32 u0 = 0.0f, v0 = 0.0f;
            if (sheet) {
                i32 col = p.sprite_frame % cols;
                i32 row = p.sprite_frame / cols;
                u0 = static_cast<f32>(col) * uvScaleX;
                v0 = static_cast<f32>(row) * uvScaleY;
            }

            f32 rotation = p.rotation;
            if (stretched) {
                // The velocity as the world sees it: a local-space emitter's turn and scale carry it too.
                glm::vec2 v(p.velocity);
                if (isLocalSpace) {
                    v *= emitterScale;
                    v = glm::vec2(v.x * cosA - v.y * sinA, v.x * sinA + v.y * cosA);
                }
                const particle::StretchedQuad quad = particle::stretchedQuad(v, rotation, size.y, lengthScale, velocityScale);
                rotation = quad.rotation;
                size.y = quad.length;
            }

            ParticleInstanceData& d = inst[i++];
            d.px = worldPos.x;       d.py = worldPos.y;       d.pz = worldPos.z;
            d.sx = size.x;           d.sy = size.y;
            d.rotation = rotation;
            d.color = packColor(p.color);
            d.uvOffsetX = u0;        d.uvOffsetY = v0;
            d.uvScaleX = sheet ? uvScaleX : 1.0f;
            d.uvScaleY = sheet ? uvScaleY : 1.0f;
        });

        // A material owns shading fully: its program is this one compiled for the
        // particle vertex source, so the author's fragment sees the same quad the
        // built-in one does. A handle nothing registered draws plainly.
        u32 shaderId = particle_shader_id_;
        u32 materialId = 0;
        BlendMode blend = blendMode;
        if (emitter.material != 0 && ctx.materials) {
            if (const MaterialRecord* m = ctx.materials->find(emitter.material)) {
                const u32 program = ctx.materials->particleProgram(emitter.material, ctx.resources);
                if (program != 0) {
                    shaderId = program;
                    materialId = emitter.material;
                    blend = m->blend;
                }
            }
        }

        const i32 layer = collect_ctx.treeLayer(entity, emitter.layer);
        BatchDrawKey key{
            .stage = ctx.current_stage,
            .layer = layer,
            .shaderId = shaderId,
            .blend = blend,
            .textureId = textureId,
            .depth = collect_ctx.sortDepth(emitterWorldPos),
            // Sorted by world Y like every other draw — a burst left at y = 0
            // loses to any sprite standing anywhere else, so an emitter placed on
            // a character disappears behind them.
            .y = emitterWorldPos.y,
            .entity = entity,
            .type = RenderType::Particle,
            .materialId = materialId,
            .layoutId = LayoutId::ParticleInstance,
            .instanceCount = particleCount,
            .instanceBuffer = gpuInstances,
        };
        // The stream's static unit-quad indices (offset 0) drawn once per particle,
        // with the instance slice based at instByteOffset.
        pushBatchDraw(draw_list, clips, instByteOffset, 0, 0, 6, key);

        // A kernel writes a GPU emitter's trails as quads the particle draw already knows how to draw.
        if (gpuSegments != BufferHandle::Invalid && gpuSegmentCount > 0) {
            BatchDrawKey segmentKey = key;
            segmentKey.textureId = ctx.white_texture_id;
            segmentKey.instanceCount = gpuSegmentCount;
            segmentKey.instanceBuffer = gpuSegments;
            pushBatchDraw(draw_list, clips, 0, 0, 0, 6, segmentKey);
        }

        // --- Per-particle trails --------------------------------------------------
        // Each live particle drags a tapering ribbon along its recorded path. Built on
        // the CPU and streamed through the Batch face (triangle strip), exactly like the
        // standalone TrailRenderer — no new GPU path. Off unless the emitter opts in.
        if (!state->gpu && emitter.trailEnabled && emitter.trailWidth > 0.0f &&
            state->trail_count.size() == state->pool.particles().size()) {
            BatchDrawKey trailKey{
                .stage = ctx.current_stage,
                .layer = layer,
                .shaderId = ctx.batch_shader_id,
                .blend = blendMode,
                .textureId = ctx.white_texture_id,
                .depth = collect_ctx.sortDepth(emitterWorldPos),
                .y = emitterWorldPos.y,
                .entity = entity,
                .type = RenderType::Trail,
            };
            const int keep = std::min(std::max(emitter.trailPoints, 2), particle::kMaxTrailPoints);
            const auto& particles = state->pool.particles();
            auto toWorld = [&](glm::vec3 pos) -> glm::vec3 {
                if (!isLocalSpace) return pos;
                glm::vec3 rel = pos * glm::vec3(emitterScale, 1.0f);
                if (std::abs(emitterAngle) > 0.001f)
                    return emitterWorldPos +
                           glm::vec3(rel.x * cosA - rel.y * sinA, rel.x * sinA + rel.y * cosA, rel.z);
                return emitterWorldPos + rel;
            };

            for (std::size_t idx = 0; idx < particles.size(); ++idx) {
                const particle::Particle& p = particles[idx];
                if (!p.alive || state->trail_count[idx] == 0) continue;
                const glm::vec3* ring = &state->trail_pos[idx * particle::kMaxTrailPoints];

                // Centerline: recorded points (oldest→newest) then the live head.
                trail_center_.clear();
                int m = std::min<int>(state->trail_count[idx], keep);
                for (int k = 0; k < m; ++k) trail_center_.push_back(toWorld(ring[k]));
                glm::vec3 head = toWorld(p.position);
                glm::vec3 dHead = head - trail_center_.back();
                if (glm::dot(dHead, dHead) > 1e-4f) trail_center_.push_back(head);
                const int n = static_cast<int>(trail_center_.size());
                if (n < 2) continue;

                // 2 verts per point: t runs 0 at the faded zero-width tail (oldest) → 1
                // at the full-width head carrying the particle's current colour.
                // Widened along ribbonSide, so a trail whose centreline leaves the
                // XY plane still presents its width to the viewer.
                trail_verts_.clear();
                glm::vec3 lastTangent(1.0f, 0.0f, 0.0f);
                glm::vec3 lastSide(0.0f, 1.0f, 0.0f);
                for (int j = 0; j < n; ++j) {
                    const glm::vec3& a = trail_center_[j == 0 ? 0 : j - 1];
                    const glm::vec3& b = trail_center_[j + 1 == n ? j : j + 1];
                    glm::vec3 seg = b - a;
                    f32 len = glm::length(seg);
                    glm::vec3 tangent = len > 1e-6f ? seg / len : lastTangent;
                    lastTangent = tangent;

                    f32 t = static_cast<f32>(j) / static_cast<f32>(n - 1);
                    f32 halfW = 0.5f * emitter.trailWidth * t;
                    glm::vec4 col = p.color;
                    col.a *= t;
                    u32 packed = packColor(col);

                    const glm::vec3& c = trail_center_[j];
                    const glm::vec3 side = ribbonSide(tangent, c, collect_ctx.camera, lastSide);
                    lastSide = side;
                    trail_verts_.push_back({c + side * halfW, packed, glm::vec2(1.0f - t, 0.0f)});
                    trail_verts_.push_back({c - side * halfW, packed, glm::vec2(1.0f - t, 1.0f)});
                }

                trail_indices_.clear();
                for (int j = 0; j + 1 < n; ++j) {
                    u32 l0 = static_cast<u32>(j) * 2, r0 = l0 + 1, l1 = l0 + 2, r1 = l0 + 3;
                    trail_indices_.push_back(l0); trail_indices_.push_back(r0); trail_indices_.push_back(r1);
                    trail_indices_.push_back(l0); trail_indices_.push_back(r1); trail_indices_.push_back(l1);
                }

                appendIndexedBatch(buffers, draw_list, clips,
                                   trail_verts_.data(), static_cast<u32>(trail_verts_.size()),
                                   trail_indices_.data(), static_cast<u32>(trail_indices_.size()),
                                   trailKey);
            }
        }
    }
}

}  // namespace esengine