Lamp-Da 0.1
A compact lantern project
Loading...
Searching...
No Matches
fadeout.hpp
Go to the documentation of this file.
1
5#ifndef MODES_ANIM_FADEOUT_HPP
6#define MODES_ANIM_FADEOUT_HPP
7
8#include <etl/bitset.h>
9
11
12namespace lampda::modes::anims {
14namespace fadeout {
15
25{
30 template<typename ContextType>
31 static bool depop_one(ContextType& ctx, const etl::bitset<LampTy::ledCount>& maskedLeds, uint32_t& pixelId)
32 {
33 const auto bufferSize = ctx.lamp.ledCount;
34
35 // check lines by lines from bottom to top, keeping the first one with pixels left
36 for (int16_t y = ctx.lamp.maxHeight; y >= 0; y--)
37 {
38 // count pixels set in this line
39 uint8_t pixelSetCount = 0;
40 for (uint16_t x = 0; x <= ctx.lamp.maxWidth; x++)
41 {
42 const auto buffIndex = modes::to_strip(x, y);
43 if (buffIndex < 0 or buffIndex >= bufferSize)
44 continue;
45 if (not maskedLeds[buffIndex])
46 pixelSetCount += 1;
47 }
48
49 // found the first line with pixels left
50 if (pixelSetCount > 0)
51 {
52 // select random pixel in this line
53 uint8_t selectedLed = lmpd_map<uint8_t>(rand(), 0, RAND_MAX, 0, pixelSetCount);
54 for (uint16_t x = 0; x <= ctx.lamp.maxWidth; x++)
55 {
56 const auto tempPixelId = modes::to_strip(x, y);
57 if (tempPixelId < 0 or tempPixelId >= bufferSize)
58 continue;
59 if (not maskedLeds[tempPixelId])
60 {
61 if (selectedLed == 0)
62 {
63 pixelId = tempPixelId; // Return the pixel ID to depop
64 return true;
65 }
66 selectedLed -= 1;
67 }
68 }
69 break;
70 }
71 }
72 return false; // No pixel found
73 }
74};
75
81{
85 template<typename ContextType>
86 static bool has_pixel_below(ContextType& ctx, const etl::bitset<LampTy::ledCount>& maskedLeds, uint16_t x, int16_t y)
87 {
88 const auto bufferSize = ctx.lamp.ledCount;
89
90 if (y >= ctx.lamp.maxHeight or (y + 1) > ctx.lamp.maxHeight)
91 {
92 return false;
93 }
94
95 // check the line below
96 const auto pixelId = modes::to_strip(x, y + 1);
97 if (pixelId >= 0 and pixelId < bufferSize)
98 {
99 if (not maskedLeds[pixelId])
100 return true; // Found a pixel below
101 }
102 // check offsetted line, lamp is not wrapped straight !
103 const auto pixelIdOffseted = modes::to_strip(x - 1, y + 1);
104 if (pixelIdOffseted >= 0 and pixelIdOffseted < bufferSize)
105 {
106 if (not maskedLeds[pixelIdOffseted])
107 return true; // Found a pixel below
108 }
109 return false;
110 }
111
112 template<typename ContextType>
113 static bool depop_one(ContextType& ctx, const etl::bitset<LampTy::ledCount>& maskedLeds, uint32_t& pixelId)
114 {
115 const auto bufferSize = ctx.lamp.ledCount;
116 uint8_t orphanCount = 0;
117
118 int16_t minYLine = ctx.lamp.maxHeight;
119 int16_t maxYLine = 0;
120
121 // Count all orphan pixels
122 for (int16_t y = ctx.lamp.maxHeight; y >= 0; y--)
123 {
124 bool hasSetPixels = false;
125 bool hasOrphanPixels = false;
126 for (uint16_t x = 0; x <= ctx.lamp.maxWidth; x++)
127 {
128 const auto tempPixelId = modes::to_strip(x, y);
129 if (tempPixelId < 0 or tempPixelId >= bufferSize)
130 continue;
131 if (not maskedLeds[tempPixelId])
132 {
133 hasSetPixels = true;
134
135 // Check if this pixel is an orphan (no pixel below it)
136 if (not has_pixel_below<ContextType>(ctx, maskedLeds, x, y))
137 {
138 orphanCount += 1;
139 hasOrphanPixels = true;
140
141 minYLine = min<int16_t>(minYLine, y);
142 maxYLine = max<int16_t>(maxYLine, y);
143 }
144 }
145 }
146 // line with pixels and no orphans, we can quit the check here
147 if (hasSetPixels and not hasOrphanPixels)
148 {
149 break;
150 }
151 }
152
153 if (orphanCount <= 0)
154 {
155 bsp::lampda_print("Could not find orphan nodes, skipping");
156 return false;
157 }
158
159 uint8_t selectedLed = lmpd_map<uint8_t>(rand(), 0, RAND_MAX, 0, orphanCount);
160
161 // drop a random orphan pixels
162 for (int16_t y = maxYLine; y >= minYLine; y--)
163 {
164 for (uint16_t x = 0; x <= ctx.lamp.maxWidth; x++)
165 {
166 const auto tempPixelId = modes::to_strip(x, y);
167 if (tempPixelId < 0 or tempPixelId >= bufferSize)
168 continue;
169 if (not maskedLeds[tempPixelId])
170 {
171 // Check if this pixel is an orphan (no pixel below it)
172 if (not has_pixel_below<ContextType>(ctx, maskedLeds, x, y))
173 {
174 if (selectedLed == 0)
175 {
176 pixelId = tempPixelId; // Found the selected orphan
177 return true;
178 }
179 selectedLed -= 1;
180 }
181 }
182 }
183 }
184 return false; // No orphan pixel found
185 }
186};
187
192template<typename DropMode = DropModeOrphansOnly> struct GravityDissolve
193{
194 void reset(auto& ctx)
195 {
196 // set all values to no masking
197 maskedLeds.reset();
198
199 // reset particles
200 particuleSystem.reset();
201 particuleSystem.set_max_particle_count(20);
202
203 latestProgress = -1.0;
204 latestProgressTime = 0;
205 particlesToDepopPerIteration = 0.0;
206 depopRate = 0.0;
207 particlesDropped = 0;
208 }
209
210 void loop(auto& ctx)
211 {
212 // find the particles to depop
213 depopRate += particlesToDepopPerIteration;
214 // time to depop one of more particle
215 float integer;
216 const float fractional = modf(depopRate, &integer);
217 if (integer >= 1.0 and particlesDropped < ctx.lamp.ledCount)
218 {
219 // time to depop !
220 for (uint8_t depopIndex = 0; depopIndex < integer; depopIndex++)
221 {
222 // depop one particle, yay !
223 depop_one_particles(ctx);
224 }
225
226 // drop depop rate
227 depopRate = fractional;
228 }
229
230 // mask all the leds that needs masking
231 for (uint16_t i = 0; i < maskedLeds.size(); i++)
232 {
233 if (maskedLeds[i])
234 ctx.lamp.mask_led_at_index(i, true);
235 }
236
237 // no updates if no particles
238 if (particuleSystem.get_number_of_active() > 0)
239 {
240 // depop particles out of bounds
241 static constexpr bool shouldKeepInLampBounds = false;
242 particuleSystem.iterate_no_collisions(
243 utils::vec3d(0.0, 0.0, -9.81 / 4.0), ctx.lamp.frameDurationMs / 1000.0, shouldKeepInLampBounds);
244 particuleSystem.depop_particules(recycle_particules_if_too_far);
245
246 // Force display because we masked the pixels before
247 static constexpr bool forceDisplayParticles = true;
248 particuleSystem.show(ctx.lamp, forceDisplayParticles);
249 }
250 }
251
256 void update_progress_rate(auto& ctx, const float expectedProgress)
257 {
258 // Artifically lenghten the progress to let particles disappear
259 const float progress = expectedProgress / gracePeriod;
260
261 const float updateDuration = static_cast<float>((ctx.lamp.now - latestProgressTime) / 1000.0);
262 if (updateDuration <= 0.0f)
263 return;
264
265 const float progressPerSecond = (progress - latestProgress) / updateDuration;
266 bool isValidCall = latestProgress >= 0 and updateDuration > 0;
267
268 // cancel the particle spawn
269 if (progress <= 0.0)
270 {
271 particlesToDepopPerIteration = 0.0;
272 latestProgress = 0.0;
273 isValidCall = false;
274 }
275 // update progress
276 else if (latestProgress != progress)
277 {
278 latestProgress = progress;
279 latestProgressTime = ctx.lamp.now;
280 }
281 else
282 isValidCall = false;
283
284 // not valid call, skip update
285 if (not isValidCall)
286 {
287 return;
288 }
289
290 const uint16_t particleMax = ctx.lamp.ledCount;
291 const float frameFrequency = 1000.0f / ctx.lamp.frameDurationMs;
292
293 const float particlesLeft = particleMax - particlesDropped;
294 const float trueProgress = 1.0f - particlesLeft / static_cast<float>(particleMax);
295
296 // How many particles SHOULD have been dropped by now?
297 const float expectedParticlesDropped = particleMax * progress;
298 const float particleDeficit = expectedParticlesDropped - static_cast<float>(particlesDropped);
299
300 const float remainingProgressRatio = 1.0f - progress;
301
302 // SMOOTH CATCH-UP: Distribute deficit + normal depop over remaining progress window
303 // This ensures we catch up gradually, not all at once
304 if (remainingProgressRatio > 0.0f && particlesLeft > 0.0f)
305 {
306 // Normal depop rate (if we were on track)
307 float normalDepopRate = progressPerSecond * particlesLeft / frameFrequency;
308
309 // Spread the deficit evenly over the remaining progress window
310 // deficit / (remaining_progress / progress_rate) = deficit / time_to_finish
311 float deficitCatchupRate = 0.0f;
312 if (progressPerSecond > 0.0f)
313 {
314 const float timeToFinish = remainingProgressRatio / progressPerSecond;
315 deficitCatchupRate = particleDeficit / timeToFinish / frameFrequency;
316 }
317
318 // Combine: normal rate + deficit catch-up spread over remaining time
319 particlesToDepopPerIteration = normalDepopRate + deficitCatchupRate;
320 }
321 else if (particlesLeft > 0.0f && progress >= 1.0f)
322 {
323 // Progress reached 1.0 but particles remain; depop everything immediately
324 particlesToDepopPerIteration = particlesLeft;
325 }
326 else
327 {
328 particlesToDepopPerIteration = 0.0;
329 }
330
331 // Safeguard: cap depop rate to prevent overshoot
332 const float maxParticlesToDepop = particlesLeft;
333 if (particlesToDepopPerIteration > maxParticlesToDepop)
334 particlesToDepopPerIteration = maxParticlesToDepop;
335 }
336
337protected:
338 static bool recycle_particules_if_too_far(const Particle& p)
339 {
340 static constexpr float bounds = 3.0;
341 return p.z_mm > LampTy::maxWidth * bounds or p.z_mm < -(LampTy::lampHeight_mm + LampTy::maxWidth * bounds);
342 }
343
344 bool depop_one_particles(auto& ctx)
345 {
346 const auto bufferSize = ctx.lamp.ledCount;
347
348 // Select a pixel to drop
349 uint32_t pixelId;
350 if (not DropMode::template depop_one<decltype(ctx)>(ctx, maskedLeds, pixelId) or pixelId < 0 or
351 pixelId >= bufferSize)
352 {
353 bsp::lampda_print("Error: Invalid pixel ID from drop mode");
354 return false;
355 }
356
357 // save current color
358 const uint32_t color = ctx.lamp.getPixelColor(pixelId);
359 // THEN mask it
360 maskedLeds.set(pixelId);
361 particlesDropped += 1;
362
363 // spawn a new particle
364 const bool isCreated = particuleSystem.init_deferred_particules(
365 1,
366 [pixelId](size_t) {
367 return pixelId;
368 },
369 // spawn with the right color
370 [color](size_t) {
371 return color;
372 });
373 // Particle spawn can fail, it's only visual so ok
374 std::ignore = isCreated;
375 return true;
376 }
377
378private:
379 static constexpr float gracePeriod = 0.99f;
380 //
381 float latestProgress = -1.0f;
382 uint32_t latestProgressTime = 0;
383
384 float particlesToDepopPerIteration = 0.0f;
385 float depopRate = 0.0f;
386 size_t particlesDropped = 0;
387
388 modes::ParticleSystem<20> particuleSystem;
389 etl::bitset<LampTy::ledCount> maskedLeds;
390};
391
392} // namespace fadeout
393} // namespace lampda::modes::anims
394
395#endif
void iterate_no_collisions(const utils::vec3d &accelerationCartesian, const float deltaTime_s, const bool shouldContrain=true)
Advance the particle simulation, ignoring collisions.
Definition: particle_system.hpp:124
uint16_t get_number_of_active() const
Return the number of active particles.
Definition: particle_system.hpp:276
uint16_t depop_particules(const ShouldDepopFunction &shouldDepopFunction)
Filter particles depending on condition.
Definition: particle_system.hpp:179
bool init_deferred_particules(uint8_t maxParticlesToPop, const PositionGeneratorFunction &positionGeneratorFunction)
Init the particles from a initialization function, in a timed defered way.
Definition: particle_system.hpp:80
void reset()
reset system to zero count
Definition: particle_system.hpp:38
uint16_t show(const SampleColorFunction &sample_color, LampTy &lamp, const bool forceDisplay=false) const
Display this particle system.
Definition: particle_system.hpp:241
void set_max_particle_count(const uint16_t _particleCount)
Call when you want to change the particle count of the simulation Can be called once when starting th...
Definition: particle_system.hpp:49
void lampda_print(const char *format,...)
C linkage to print functions.
Definition: text_out.cpp:336
static constexpr uint16_t to_strip(uint16_t, uint16_t)
convert grid coordinates to strip index
Definition: lamp_type.hpp:1224
Define a particle system, with particle based logic.
Define a particle in 3D space. it has a position and speed.
Definition: particle.hpp:44
float z_mm
height, in millimeters.
Definition: particle.hpp:267
Drop mode policy: remove particles line by line from bottom to top Only pixels from the lowest non-em...
Definition: fadeout.hpp:25
static bool depop_one(ContextType &ctx, const etl::bitset< LampTy::ledCount > &maskedLeds, uint32_t &pixelId)
Find and depop one particle according to this mode.
Definition: fadeout.hpp:31
Drop mode policy: remove only "orphan" particles A particle can only be dropped if there is no other ...
Definition: fadeout.hpp:81
static bool has_pixel_below(ContextType &ctx, const etl::bitset< LampTy::ledCount > &maskedLeds, uint16_t x, int16_t y)
Check if a pixel at (x, y) has a pixel below it.
Definition: fadeout.hpp:86
Make an animation disapear with gravity.
Definition: fadeout.hpp:193
void update_progress_rate(auto &ctx, const float expectedProgress)
Update the drop rate.
Definition: fadeout.hpp:256
static constexpr float lampHeight_mm
Computation of the lamp height.
Definition: lamp_type.hpp:447
static constexpr uint16_t maxWidth
(indexable) Width of "pixel space" w/ lamp taken as a LED matrix
Definition: lamp_type.hpp:376
3d vector in any space
Definition: vector_math.h:54