24 collision_queries_.clear(); collision_pending_.clear(); collision_events_.clear();
25 collision_stats_.clear(); collision_cameras_.clear();
26 event_attempts_ = 0; collision_child_bursts_ = 0;
27 if (!std::isfinite(frameDt) || frameDt < 0)
return;
29 for (
auto entity : cameras) {
33 collision_cameras_.push_back(transform.worldPosition);
35 if (!destroyConn_.isConnected()) {
37 states_.erase(entity);
38 pending_play_.erase(entity);
39 colorLuts_.erase(entity);
40 sizeLuts_.erase(entity);
41 speedLuts_.erase(entity);
42 burstSchedules_.erase(entity);
48 force_fields_.clear();
50 for (
auto ffEntity : ffView) {
52 if (!ff.enabled || ff.strength == 0.0f)
continue;
55 f32 dl = std::sqrt(ff.direction.x * ff.direction.x + ff.direction.y * ff.direction.y
56 + ff.direction.z * ff.direction.z);
59 inst.
position = ffTransform.worldPosition;
60 inst.
direction = dl > 1e-6f ? ff.direction / dl : glm::vec3(1.0f, 0.0f, 0.0f);
63 inst.
radiusSq = ff.radius * ff.radius;
65 force_fields_.push_back(inst);
68 sdf_colliders_.clear();
70 for (
auto colliderEntity : colliderView) {
72 if (!collider.enabled)
continue;
73 auto& colliderTransform = colliderView.get<
ecs::Transform>(colliderEntity);
75 const glm::vec3 scale = colliderTransform.worldScale;
77 inst.
position = colliderTransform.worldPosition;
78 inst.
rotation = colliderTransform.worldRotation;
79 inst.
shape =
static_cast<f32>(collider.shape);
80 inst.
inverted = collider.inverted ? 1.0f : 0.0f;
81 inst.
mask = collider.mask & 0xffffu;
83 const f32 round = std::max({std::abs(scale.x), std::abs(scale.y), std::abs(scale.z)});
85 inst.
ext[0] = collider.halfExtents.x * std::abs(scale.x);
86 inst.
ext[1] = collider.halfExtents.y * std::abs(scale.y);
87 inst.
ext[2] = collider.halfExtents.z * std::abs(scale.z);
89 inst.
ext[0] = collider.radius * round;
90 inst.
ext[1] = collider.halfHeight * std::abs(scale.y);
92 sdf_colliders_.push_back(inst);
97 for (
auto& [stateEntity, childState] : states_) childState.gpuFed =
false;
98 for (
auto parentEntity : view) {
100 if (parent.subEmitter == 0 || !parent.enabled)
continue;
101 auto parentState = states_.find(parentEntity), childState = states_.find(
Entity::fromRaw(parent.subEmitter));
102 if (parentState != states_.end() && childState != states_.end() && parentState->second.gpu && childState->second.gpu) {
103 childState->second.gpuFed =
true;
108 collision_quotas_.clear();
109 scene_emitters_.clear();
110 for (
auto entity : view) {
112 if (e.enabled && e.collisionEnabled && e.collisionMode != 0) scene_emitters_.push_back(entity);
114 const u32 n =
static_cast<u32>(scene_emitters_.size());
115 for (
u32 i = 0; i < n; ++i) {
116 const u32 rank = (i + n - collision_frame_ % n) % n;
117 collision_quotas_[scene_emitters_[i]] = query_budget_ / n + (rank < query_budget_ % n ? 1u : 0u);
120 for (
auto entity : view) {
124 if (!emitter.enabled) {
128 const f32 dt = frameDt * std::max(emitter.simulationSpeed, 0.0f);
132 const bool useGpu = emitter.gpuSimulation && gpu_available_;
133 u32 capacity =
static_cast<u32>(std::clamp(emitter.maxParticles, 0, 1'000'000));
134 if (emitter.gpuSimulation && !gpu_available_) capacity = std::min(capacity,
kGpuFallbackCapacity);
135 if (useGpu) capacity =
static_cast<u32>(std::clamp(emitter.maxParticles, 0,
static_cast<i32>(
kGpuMaxCapacity)));
137 auto it = states_.find(entity);
138 if (it != states_.end() && (it->second.gpu != useGpu || (useGpu && it->second.gpuCapacity != capacity))) {
144 auto [moved, _] = states_.emplace(entity,
EmitterState(useGpu ? 0u : capacity));
158 if (it == states_.end()) {
159 auto [insertIt, _] = states_.emplace(
168 it->second.gpu = useGpu;
169 it->second.gpuCapacity = useGpu ? capacity : 0;
170 if (emitter.playOnStart) {
171 it->second.playing =
true;
175 if (pending_play_.erase(entity) > 0) {
176 it->second.playing =
true;
177 it->second.elapsed_time = 0.0f;
181 auto& state = it->second;
186 if (emitter.trailEnabled && state.trail_count.size() != state.pool.capacity()) {
187 state.trail_count.assign(state.pool.capacity(), 0);
188 state.trail_pos.assign(
static_cast<std::size_t
>(state.pool.capacity()) *
kMaxTrailPoints,
192 if (state.first_update && emitter.playOnStart) {
193 state.playing =
true;
194 state.first_update =
false;
198 const f32 startDelay = std::max(emitter.startDelay, 0.0f);
199 bool emitting = state.playing;
200 if (!emitter.looping && state.elapsed_time >= startDelay + emitter.duration) {
205 auto emit = [&](
u32 count,
bool burst) {
206 if (!state.gpu) { emitParticles(emitter, transform, state, count);
return; }
207 u32& pending = burst ? state.gpuBurst : state.gpuSmooth;
208 pending = std::min(pending + count, state.gpuCapacity);
212 state.elapsed_time += dt;
214 if (emitting && state.elapsed_time >= startDelay) {
215 if (
auto schedule = burstSchedules_.find(entity); schedule != burstSchedules_.end()) {
216 const f32 clock = state.elapsed_time - startDelay;
217 const u32 due =
burstsDue(schedule->second, state.burst_clock, clock, emitter.duration, emitter.looping);
218 state.burst_clock = clock;
219 if (due > 0) emit(due,
true);
221 if (emitter.rate > 0.0f) {
222 state.emission_accumulator += emitter.rate * dt;
223 u32 toEmit =
static_cast<u32>(state.emission_accumulator);
225 state.emission_accumulator -=
static_cast<f32>(toEmit);
230 if (emitter.burstCount > 0) {
231 if (state.burst_timer <= 0.0f) {
232 emit(
static_cast<u32>(emitter.burstCount),
true);
233 state.burst_timer = emitter.burstInterval;
235 state.burst_timer -= dt;
241 state.noise_time += dt;
243 if (emitter.collisionEnabled) {
245 stats.
mode =
static_cast<u32>(emitter.collisionMode);
246 for (
const GpuCollisions& reported : gpu_collisions_) {
247 if (reported.entity != entity)
continue;
248 stats.
hits += reported.total;
249 stats.
events +=
static_cast<u32>(reported.events.size());
250 stats.
eventDropped += reported.total -
static_cast<u32>(reported.events.size());
251 collision_events_.insert(collision_events_.end(), reported.events.begin(), reported.events.end());
253 collision_stats_.push_back(stats);
258 const EmitterFrame frame{transform.worldPosition, transform.worldRotation,
259 transform.worldScale};
260 bool isWorldSpace = emitter.simulationSpace ==
263 collision_emitter_ = entity;
264 collision_stats_index_ = collision_stats_.size();
265 if (emitter.collisionEnabled) {
267 stats.
mode =
static_cast<u32>(emitter.collisionMode);
268 collision_stats_.push_back(stats);
270 auto lutIt = colorLuts_.find(entity);
271 auto sizeIt = sizeLuts_.find(entity);
272 auto speedIt = speedLuts_.find(entity);
273 updateParticles(emitter, state, dt,
274 lutIt != colorLuts_.end() ? &lutIt->second :
nullptr,
275 sizeIt != sizeLuts_.end() ? &sizeIt->second :
nullptr,
276 speedIt != speedLuts_.end() ? &speedIt->second :
nullptr,
277 frame, isWorldSpace);
279 if (state.pool.capacity() > 0) {
280 const u32 step = std::max(1u, std::min(
static_cast<u32>(std::clamp(emitter.collisionQueryBudget, 0, 4096)), collisionQuota(entity)));
281 state.collisionCursor = (state.collisionCursor + step) % std::max(1u,state.pool.aliveCount());
285 if (emitter.subEmitter != 0 && !subemit_requests_.empty()) {
286 drainSubEmitters(registry, entity,
Entity::fromRaw(emitter.subEmitter),
287 emitter.subEmitterInheritVelocity, emitter.subEmitterChance);
290 gpu_collisions_.clear();
294 auto it = states_.find(entity);
295 if (it != states_.end()) {
296 it->second.playing =
true;
297 it->second.elapsed_time = 0.0f;
301 pending_play_.insert(entity);
306 pending_play_.erase(entity);
307 auto it = states_.find(entity);
308 if (it != states_.end()) {
309 it->second.playing =
false;
314 pending_play_.erase(entity);
315 auto it = states_.find(entity);
316 if (it != states_.end()) {
317 it->second.pool.clear();
318 if (it->second.gpu) {
319 it->second.gpuSmooth = it->second.gpuBurst = it->second.gpuSpawned = 0;
320 it->second.gpuDt = 0.0f;
321 it->second.gpuReset =
true;
323 it->second.emission_accumulator = 0.0f;
324 it->second.elapsed_time = 0.0f;
325 it->second.burst_timer = 0.0f;
326 it->second.burst_clock = -1.0f;
327 it->second.playing =
false;
333 colorLuts_.erase(entity);
338 lut[i] = glm::vec4(rgba[i * 4], rgba[i * 4 + 1], rgba[i * 4 + 2], rgba[i * 4 + 3]);
344 sizeLuts_.erase(entity);
347 SizeLut& lut = sizeLuts_[entity];
348 for (std::size_t i = 0; i <
kColorLutSize; ++i) lut[i] = values[i];
353 speedLuts_.erase(entity);
356 SizeLut& lut = speedLuts_[entity];
357 for (std::size_t i = 0; i <
kColorLutSize; ++i) lut[i] = values[i];
361 if (count <= 0 || values ==
nullptr) {
362 burstSchedules_.erase(entity);
365 std::vector<ScheduledBurst>& schedule = burstSchedules_[entity];
367 for (
i32 i = 0; i < count && i < 64; ++i) {
368 schedule.push_back({values[i * 2],
static_cast<u32>(std::max(values[i * 2 + 1], 0.0f))});
373 auto it = states_.find(entity);
374 if (it != states_.end()) {
376 if (it->second.gpu)
return std::min(it->second.gpuSpawned, it->second.gpuCapacity);
377 return it->second.pool.aliveCount();
383 auto it = states_.find(entity);
384 if (it == states_.end() || !it->second.gpu)
return false;
389 out.
dt = std::min(state.
gpuDt, 0.1f);
402 auto it = states_.find(entity);
403 if (it == states_.end() || !it->second.gpu)
return;
409 if (step.reset) state.
gpuReset =
false;
414 for (
const auto& [_, state] : states_) {
415 total += state.pool.aliveCount();
421 auto it = states_.find(entity);
422 return it != states_.end() ? &it->second :
nullptr;
426 auto it = states_.find(entity);
427 return it != states_.end() ? &it->second :
nullptr;
437 emitInto(emitter, state, frame, isWorldSpace, glm::vec3(0.0f), count,
441void ParticleSystem::emitInto(
const ecs::ParticleEmitter& emitter, EmitterState& state,
442 const EmitterFrame& frame,
bool isWorldSpace,
443 glm::vec3 velocityBias,
u32 count,
bool allowBirthTrigger,
u32 depth,
444 const EmitterFrame* storageFrame) {
447 bool recordBirth = allowBirthTrigger &&
448 emitter.subEmitter != 0 &&
449 emitter.subEmitterTrigger ==
452 if (particle_limit_ != 0xffffffffu) {
454 count = std::min(count, alive < particle_limit_ ? particle_limit_ - alive : 0u);
456 for (
u32 i = 0; i < count; ++i) {
457 Particle* p = state.pool.allocate();
464 if (emitter.trailEnabled && !state.trail_count.empty()) {
465 auto idx =
static_cast<std::size_t
>(p - state.pool.particles().data());
466 if (idx < state.trail_count.size()) state.trail_count[idx] = 0;
469 p->lifetime = randomRange(emitter.lifetimeMin, emitter.lifetimeMax);
472 p->start_size = randomRange(emitter.startSizeMin, emitter.startSizeMax);
473 p->end_size = randomRange(emitter.endSizeMin, emitter.endSizeMax);
474 p->size = p->start_size;
476 p->start_color = emitter.startColor;
477 p->end_color = emitter.endColor;
478 p->color = p->start_color;
480 p->rotation = randomRange(emitter.rotationMin, emitter.rotationMax);
481 p->angular_velocity = randomRange(emitter.angularVelocityMin,
482 emitter.angularVelocityMax);
486 const SpawnSample sample =
490 : sample.position * frame.scale;
492 const f32 speed = randomRange(emitter.speedMin, emitter.speedMax);
493 const glm::vec3 dir = isWorldSpace ?
worldDirOf(sample.direction, frame)
495 p->velocity = dir * speed + velocityBias;
496 p->added_velocity = glm::vec3(randomRange(emitter.addedVelocityMin.x, emitter.addedVelocityMax.x),
497 randomRange(emitter.addedVelocityMin.y, emitter.addedVelocityMax.y),
498 randomRange(emitter.addedVelocityMin.z, emitter.addedVelocityMax.z));
501 p->subEmitterDepth = depth;
504 glm::vec3 worldPos = isWorldSpace ? p->position
505 : frame.position + frame.rotation * p->position;
506 glm::vec3 worldVel = isWorldSpace ? p->velocity : frame.rotation * p->velocity;
507 subemit_requests_.push_back({worldPos, worldVel, p->subEmitterDepth});
510 const auto inverseRotation = glm::inverse(storageFrame->rotation);
511 p->position = inverseRotation * (p->position - storageFrame->position);
512 p->velocity = inverseRotation * p->velocity;
518 const glm::vec3& normal,
const glm::vec3& velocity) {
521 if (emitter.gpuSimulation && gpu_available_)
return 0;
522 auto it = states_.find(entity);
523 if (it == states_.end()) {
524 it = states_.emplace(entity,
EmitterState(
static_cast<u32>(std::clamp(emitter.maxParticles, 0, 1'000'000)))).first;
527 if (state.
gpu)
return 0;
529 glm::quat rotation(1.0f, 0.0f, 0.0f, 0.0f);
530 glm::vec3 scale(1.0f);
535 scale = t.worldScale;
536 storage = {t.worldPosition, t.worldRotation, t.worldScale};
538 const f32 n = glm::length(normal);
541 const glm::vec3 to = normal / n;
542 const f32 d = glm::dot(glm::vec3(0.0f, 1.0f, 0.0f), to);
543 if (d < -0.9999f) rotation = glm::quat(0.0f, 1.0f, 0.0f, 0.0f);
545 const glm::vec3 axis = glm::cross(glm::vec3(0.0f, 1.0f, 0.0f), to);
546 rotation = glm::normalize(glm::quat(1.0f + d, axis.x, axis.y, axis.z));
551 emitInto(emitter, state,
EmitterFrame{position, rotation, scale},
true, velocity, count,
552 true, 0, local ? &storage :
nullptr);
556u32 ParticleSystem::collisionQuota(
Entity emitter)
const {
557 const auto it = collision_quotas_.find(emitter);
558 return it != collision_quotas_.end() ? it->second : 0u;
562 f32 inheritVelocity,
f32 chance) {
563 drain_scratch_.clear();
564 drain_scratch_.swap(subemit_requests_);
569 const auto& childEmitter = registry.
get<ecs::ParticleEmitter>(child);
573 auto it = states_.find(child);
574 if (it == states_.end()) {
575 auto [insertIt, _] = states_.emplace(
576 child, EmitterState(
static_cast<u32>(std::clamp(childEmitter.maxParticles, 0, 1'000'000))));
579 EmitterState& childState = it->second;
580 EmitterFrame storageFrame;
582 if (local && registry.
has<ecs::Transform>(child)) {
583 const auto& transform = registry.
get<ecs::Transform>(child);
589 u32 count = childEmitter.burstCount > 0 ?
static_cast<u32>(childEmitter.burstCount) : 1;
590 count = std::min(count, childState.pool.capacity());
591 for (
const auto& req : drain_scratch_) {
592 if (req.depth >= 8)
continue;
593 if (chance < 1.0f && randomRange(0.0f, 1.0f) >= chance) {
599 emitInto(childEmitter, childState, EmitterFrame{req.position, glm::quat(1, 0, 0, 0),
600 glm::vec3(1.0f)},
true,
601 req.velocity * inheritVelocity, count,
false, req.depth + 1,
602 local ? &storageFrame :
nullptr);
610 auto i =
static_cast<std::size_t
>(f);
611 std::size_t j = std::min(i + 1,
static_cast<std::size_t
>(
kColorLutSize - 1));
617 auto i =
static_cast<std::size_t
>(f);
618 std::size_t j = std::min(i + 1,
static_cast<std::size_t
>(
kColorLutSize - 1));
626 f32 distSq = toField.x * toField.x + toField.y * toField.y + toField.z * toField.z;
630 if (ff.
falloff) factor = 1.0f - std::sqrt(distSq) / ff.
radius;
637 f32 d = std::sqrt(distSq);
642 f32 d = std::sqrt(distSq);
644 glm::vec3 radial = -toField / d;
647 glm::vec3 axis = glm::length(ff.
direction) > 1e-6f
648 ? glm::normalize(ff.
direction) : glm::vec3(0.0f, 0.0f, 1.0f);
649 glm::vec3 perp = glm::cross(axis, radial);
650 f32 pl = glm::length(perp);
662 EmitterState& state,
f32 dt,
665 const EmitterFrame& frame,
680 state.noise_time += dt;
685 bool trailOn = emitter.
trailEnabled && !state.trail_count.empty();
691 dead_particle_indices_.clear();
692 state.collisionOrdinal = 0;
694 state.pool.forEachAlive([&](Particle& p) {
697 if (p.age >= p.lifetime) {
699 glm::vec3 worldPos = isWorldSpace ? p.position
700 : frame.position + frame.rotation * p.position;
701 glm::vec3 worldVel = isWorldSpace ? p.velocity : frame.rotation * p.velocity;
702 subemit_requests_.push_back({worldPos, worldVel, p.subEmitterDepth});
704 u32 idx =
static_cast<u32>(&p - &state.pool.particles()[0]);
705 dead_particle_indices_.push_back(idx);
709 f32 t = p.age / p.lifetime;
711 p.velocity += emitter.
gravity * dt;
712 if (isWorldSpace && !force_fields_.empty()) {
716 p.velocity *= (1.0f - emitter.
damping * dt);
724 const glm::vec3 collisionFrom = p.position;
731 glm::vec2 sample = glm::vec2(p.position) * emitter.
noiseFrequency + noiseScroll;
733 p.position += glm::vec3(flow, 0.0f) * emitter.
noiseStrength * dt;
737 collisionStep(emitter, state, p, collisionFrom, frame, isWorldSpace);
738 if (p.age >= p.lifetime) {
739 dead_particle_indices_.push_back(
static_cast<u32>(&p - state.pool.particles().data()));
747 auto idx =
static_cast<std::size_t
>(&p - state.pool.particles().data());
748 u8& cnt = state.trail_count[idx];
750 bool record = cnt == 0;
752 glm::vec3 d = p.position - ring[cnt - 1];
753 record = glm::dot(d, d) >= trailMinDistSq;
756 if (cnt < trailKeep) {
757 ring[cnt++] = p.position;
759 for (
int k = 1; k < trailKeep; ++k) ring[k - 1] = ring[k];
760 ring[trailKeep - 1] = p.position;
765 p.rotation += p.angular_velocity * dt;
771 p.size =
math::lerp(p.start_size, p.end_size, sizeT);
778 p.color =
math::lerp(p.start_color, p.end_color, colorT);
781 if (totalFrames > 1 && emitter.
spriteFPS > 0.0f) {
782 f32 frameDuration = 1.0f / emitter.spriteFPS;
783 f32 rawFrame = p.age / frameDuration;
788 if (emitter.spriteLoop) {
789 frame = static_cast<u16>(std::fmod(rawFrame, static_cast<f32>(totalFrames)));
791 frame = static_cast<u16>(std::min(rawFrame, static_cast<f32>(totalFrames - 1)));
793 p.sprite_frame = frame;
797 for (
u32 idx : dead_particle_indices_) {
798 state.pool.deallocateByIndex(idx);
803f32 ParticleSystem::randomRange(
f32 min,
f32 max) {
807 std::uniform_real_distribution<f32> dist(min, max);
816bool finitePoint(glm::vec3 p) {
return std::isfinite(p.x) && std::isfinite(p.y) && std::isfinite(p.z); }
817f32 unitValue(
f32 x) {
return std::isfinite(x) ? std::clamp(x, 0.0f, 1.0f) : 0.0f; }
821 Particle& p, glm::vec3 from,
const EmitterFrame& frame,
bool world) {
822 const u32 ordinal = state.collisionOrdinal++;
823 if (emitter.collisionMode == 0) { floorCollision(emitter, state, p, frame, world);
return; }
825 auto& stats = collision_stats_[collision_stats_index_];
826 auto fallback = [&] {
827 if (emitter.collisionFallback == 0) { ++stats.fallbacks; floorCollision(emitter, state, p, frame, world); }
830 if (emitter.collisionMode != 1 && emitter.collisionMode != 2) { ++stats.unavailable; fallback();
return; }
831 const glm::vec3 start =
world ? from : frame.position + frame.rotation * from;
832 const glm::vec3 end =
world ? p.position : frame.position + frame.rotation * p.position;
833 glm::vec3 delta = end - start;
834 if (emitter.collisionMode == 1) delta.z = 0;
835 if ((emitter.collisionMask & 0xffffu) == 0)
return;
836 if (!finitePoint(start) || !finitePoint(end) || !std::isfinite(glm::dot(delta,delta)) || glm::dot(delta, delta) < 1e-12f)
return;
837 if (std::isfinite(emitter.collisionMaxDistance) && emitter.collisionMaxDistance > 0 && !collision_cameras_.empty()) {
838 const f32 maxSq = emitter.collisionMaxDistance * emitter.collisionMaxDistance;
840 for (
auto camera : collision_cameras_) {
841 const auto offset = end - camera;
842 if (glm::dot(offset, offset) <= maxSq) { near =
true;
break; }
844 if (!near) { ++stats.distanceSkipped; fallback();
return; }
846 const u32 slot =
static_cast<u32>(&p - state.pool.particles().data());
847 const u32 limit = std::min(
static_cast<u32>(std::clamp(emitter.collisionQueryBudget, 0, 4096)), collisionQuota(collision_emitter_));
848 const u32 alive = std::max(1u,state.pool.aliveCount());
849 const u32 rank = (ordinal + alive - state.collisionCursor % alive) % alive;
850 if (rank >= limit || stats.queries >= limit || collision_queries_.size() >= query_budget_) {
851 ++stats.budgetSkipped; fallback();
return;
853 collision_queries_.push_back({collision_emitter_.raw, slot,
static_cast<u32>(emitter.collisionMode),
854 emitter.collisionMask & 0xffffu, start.x,start.y,start.z,delta.x,delta.y,delta.z});
855 collision_pending_.push_back({collision_emitter_, p.generation, frame,
world, collision_stats_index_});
860 Particle& p,
const EmitterFrame& frame,
bool world) {
861 const glm::vec3 point =
world ? p.position : frame.position + frame.rotation * p.position;
862 const glm::vec3 velocity =
world ? p.velocity : frame.rotation * p.velocity;
863 if (std::isfinite(emitter.collisionFloor) && point.y < emitter.collisionFloor && velocity.y < 0) {
864 collide(emitter, state, p, {point.x,emitter.collisionFloor,point.z}, {0,1,0}, 0xffffffffu, frame,
world);
871 if (c.
shape > 1.5f) {
872 const f32 along = std::clamp(q.y, -c.
ext[1], c.
ext[1]);
873 d = glm::length(glm::vec3(q.x, q.y - along, q.z)) - c.
ext[0];
874 }
else if (c.
shape > 0.5f) {
875 const glm::vec3 over = glm::abs(q) - glm::vec3(c.
ext[0], c.
ext[1], c.
ext[2]);
876 d = glm::length(glm::max(over, glm::vec3(0.0f))) + std::min(std::max({over.x, over.y, over.z}), 0.0f);
878 d = glm::length(q) - c.
ext[0];
883void ParticleSystem::sdfCollision(
const ecs::ParticleEmitter& emitter, EmitterState& state, Particle& p,
884 const EmitterFrame& frame,
bool world) {
885 const glm::vec3 point = world ? p.position : frame.position + frame.rotation * p.position;
886 const glm::vec3 velocity = world ? p.velocity : frame.rotation * p.velocity;
887 const SdfColliderInstance* nearest =
nullptr;
889 for (
const SdfColliderInstance& c : sdf_colliders_) {
891 const f32 d = sdfDistance(c, point);
892 if (d < least) { least = d; nearest = &c; }
894 if (!nearest)
return;
896 const f32 e = std::max(0.01f, -least * 0.1f);
897 const glm::vec3 gradient(
901 const f32 size = glm::length(gradient);
902 if (size < 1e-6f)
return;
903 const glm::vec3 normal = gradient / size;
904 if (glm::dot(velocity, normal) >= 0.0f)
return;
905 collide(emitter, state, p, point - normal * least, normal, 0xffffffffu, frame, world);
909 gpu_collisions_.push_back({entity, total, std::vector<CollisionEvent>(events, events + count)});
913 glm::vec3 point, glm::vec3 normal,
u32 body,
const EmitterFrame& frame,
bool world) {
914 auto& stats = collision_stats_[collision_stats_index_];
917 const glm::vec3 incoming = velocity;
918 const f32 approach = glm::dot(velocity, normal);
920 velocity = (velocity - normal * approach) * (1 - unitValue(emitter.
collisionFriction))
930 if (stats.events < perEmitter && event_attempts_ < event_budget_) {
931 ++stats.events; ++event_attempts_;
932 if (emitter.
collisionEvents || collision_debug_) collision_events_.push_back({collision_emitter_.raw,slot,body,stats.mode,
933 point.x,point.y,point.z,normal.x,normal.y,normal.z,incoming.x,incoming.y,incoming.z,emitter.
collisionEvents ? 1u : 0u});
934 if (child && p.
subEmitterDepth < 8 && collision_child_bursts_ < event_budget_) {
935 subemit_requests_.push_back({point,velocity,p.
subEmitterDepth}); ++collision_child_bursts_;
937 }
else ++stats.eventDropped;
945 for (std::size_t i = 0; i < collision_queries_.size(); ++i) {
946 const auto& query = collision_queries_[i];
const auto& pending = collision_pending_[i];
948 auto stateIt = states_.find(pending.emitter);
949 if (stateIt == states_.end() || query.slot >= stateIt->second.pool.capacity())
continue;
950 auto& state = stateIt->second;
auto& p = state.
pool.
particles()[query.slot];
954 collision_emitter_ = pending.emitter; collision_stats_index_ = pending.stats;
955 auto& stats = collision_stats_[pending.stats];
958 glm::vec3 normal(reply.
nx,reply.
ny,reply.
nz), point(reply.
x,reply.
y,reply.
z);
959 if (query.mode == 1) { normal.z = 0; point.z = pending.world ? p.
position.z : (pending.frame.position + pending.frame.rotation * p.
position).z; }
960 const f32 normSq = glm::dot(normal,normal);
961 const glm::vec3 from(query.ox,query.oy,query.oz), delta(query.dx,query.dy,query.dz);
964 const f32 deltaSq = glm::dot(delta,delta);
965 const f32 fraction = glm::dot(point - from,delta) / deltaSq;
966 glm::vec3 offset = point - (from + delta * fraction);
967 if (query.mode == 1) offset.z = 0;
968 if (finitePoint(normal) && finitePoint(point) && std::isfinite(normSq) && normSq > 1e-12f &&
969 fraction >= -1e-4f && fraction <= 1.0001f && glm::dot(offset,offset) <= std::max(1e-6f,deltaSq*1e-6f)) {
970 normal /= std::sqrt(normSq);
971 if (glm::dot(delta,normal) > 0) normal = -normal;
972 collide(emitter,state,p,point + normal * 1e-4f,normal,reply.
body,pending.frame,pending.world);
973 }
else { ++stats.unavailable;
if (emitter.
collisionFallback == 0) { ++stats.fallbacks; floorCollision(emitter,state,p,pending.frame,pending.world); } }
974 }
else if (reply.
status != 0) {
976 if (emitter.
collisionFallback == 0) { ++stats.fallbacks; floorCollision(emitter,state,p,pending.frame,pending.world); }
985 collision_queries_.clear(); collision_pending_.clear();
Camera component for rendering viewpoints.
Deterministic curl-noise flow field for the particle Noise/Turbulence module — a pure-CPU,...
The engine's randomness, and the only place its seed lives.
std::mt19937 stream(std::string_view name) const
Central container for all entities and components.
T & get(Entity entity)
Gets a component from an entity (must exist).
bool has(Entity entity) const
Checks if an entity has a specific component.
Connection onDestroy(DestroyCallback callback)
Subscribe to entity destruction.
bool valid(Entity entity) const
Checks if an entity is currently valid.
std::vector< Particle > & particles()
void deallocateByIndex(u32 index)
Deallocate a particle by its pool index.
const SizeLut * speedLut(Entity entity) const
void setSizeLut(Entity entity, const f32 *values, i32 count)
EmitterState * getState(Entity entity)
void reset(Entity entity)
void update(ecs::Registry ®istry, f32 dt)
u32 totalAliveParticles() const
void setBursts(Entity entity, const f32 *values, i32 count)
static constexpr u32 kGpuMaxCapacity
static constexpr u32 kGpuFallbackCapacity
void reseedFrom(const esengine::RandomSource &source)
const SizeLut * sizeLut(Entity entity) const
u32 aliveCount(Entity entity) const
void addGpuCollisions(Entity entity, u32 total, const CollisionEvent *events, u32 count)
Collisions a kernel reported, a frame or two late since they come back from the GPU; they reach the g...
u32 emitAt(ecs::Registry ®istry, Entity entity, u32 count, const glm::vec3 &position, const glm::vec3 &normal, const glm::vec3 &velocity)
Spawn count of entity's particles at a world point, now: an impact's sparks, a muzzle's flash,...
void resolveCollisions(ecs::Registry ®istry, const CollisionReply *replies, u32 count)
void commitGpuStep(Entity entity, const GpuStep &step)
The kernel ran this step: the time and births it covered are spent.
static constexpr const char * kRandomStream
const ColorLut * colorLut(Entity entity) const
The over-life curves an entity was given, for the GPU kernel to read; null where none was set.
bool peekGpuStep(Entity entity, GpuStep &out) const
void setSpeedLut(Entity entity, const f32 *values, i32 count)
void setColorLut(Entity entity, const f32 *rgba, i32 count)
T lerp(const T &a, const T &b, float t)
Linear interpolation between two values.
glm::vec2 curl(glm::vec2 sample, i32 octaves)
constexpr int kColorLutSize
ecs::ParticleEasing EasingType
static f32 sampleSizeLut(const SizeLut &lut, f32 t)
static void applyForceField(const ForceFieldInstance &ff, Particle &p, f32 dt)
f32 sdfDistance(const SdfColliderInstance &c, const glm::vec3 &point)
How far a world point is outside a collider, negative inside; what the kernel's sdfOne answers.
f32 applyEasing(EasingType type, f32 t)
std::array< f32, kColorLutSize > SizeLut
SpawnSample sampleShape(const ecs::ParticleEmitter &emitter, const RandomRange &rand)
constexpr int kMaxTrailPoints
glm::vec3 limitedVelocity(glm::vec3 velocity, f32 limit, f32 dampen, f32 dt)
A particle's velocity after its speed limit has pulled it back.
glm::vec3 worldDirOf(const glm::vec3 &local, const EmitterFrame &f)
A local direction placed in the world — rotation ALONE.
std::array< glm::vec4, kColorLutSize > ColorLut
u32 burstsDue(const std::vector< ScheduledBurst > &schedule, f32 prev, f32 cur, f32 duration, bool looping)
How many particles the schedule releases while the emitter's clock goes from prev to cur.
static glm::vec4 sampleColorLut(const ColorLut &lut, f32 t)
glm::vec3 worldPointOf(const glm::vec3 &local, const EmitterFrame &f)
std::int32_t i32
Signed 32-bit integer.
std::uint32_t u32
Unsigned 32-bit integer.
std::uint8_t u8
Unsigned 8-bit integer.
float f32
32-bit floating point
Entity identifier with packed index + generation.
static constexpr Entity fromRaw(u32 v)
Reconstructs an Entity from a raw packed value.
Camera component for rendering viewpoints.
bool isActive
Whether this is the active camera.
f32 subEmitterInheritVelocity
f32 collisionLifetimeLoss
std::vector< glm::vec3 > trail_pos
f32 burst_clock
Where the scheduled bursts last looked: the emitting clock of the previous step, below zero before th...
std::vector< u8 > trail_count
What one frame asks of a GPU-simulated emitter: how long to advance, how many to spawn and where in t...
bool fed
A GPU parent's events spawn into it, so any slot may be live whatever was scheduled.
u32 firstIndex
Absolute index of the first particle born this step (slot = index % capacity).
u32 spawnCount
Born this step: smoothCount spread across dt, then the rest as one burst.
bool reset
Kill everything first (a reset() since the last step).
u32 drawCount
Slots that may hold a live particle once this step has run.