//! Example 4.9: Additive Blending. The smoke of 4.8 tinted magenta, three //! particles a step, and drawn with `f.blend(.add)` (`blendMode(ADD)`), //! so where they pile up they glow towards white. The pointer's x sets //! the wind. const std = @import("std"); const sk = @import("sketch"); const vec = sk.math; const windArrow = @import("smoke.zig").windArrow; pub const name = "additive_blending"; pub const width = 640; pub const height = 360; /// A particle lives 41 steps (100 down by 2.5 until below 0), and three /// are added a step. const max_particles = 128; const origin: vec.Vec = .{ width / 2, height - 75 }; const Particle = struct { position: vec.Vec, velocity: vec.Vec, lifespan: f32 = 100, fn init(rng: std.Random) Particle { return .{ .position = origin, .velocity = .{ rng.floatNorm(f32) * 0.3, rng.floatNorm(f32) * 0.3 - 1 } }; } }; pub const State = struct { rng: std.Random.Xoshiro256 = .init(49), particles: sk.List(Particle, max_particles) = .{}, wind: f32 = 0, clock: sk.Clock = .{}, }; pub fn update(s: *State, in: *const sk.Input) void { for (0..s.clock.steps(in)) |_| { s.wind = std.math.lerp(-0.2, 0.2, in.mouse_x / width); var i = s.particles.count(); while (i > 0) { i -= 1; const p = &s.particles.slice()[i]; p.velocity += vec.Vec{ s.wind, 0 }; p.position += p.velocity; p.lifespan -= 2.5; if (p.lifespan < 0) _ = s.particles.orderedRemove(i); } for (0..3) |_| s.particles.appendBounded(.init(s.rng.random())) catch {}; } } const magenta = sk.Color.hex(0xff64ff); pub fn draw(s: *const State, f: *sk.Frame) void { f.clear(.black); f.blend(.add); const texture = f.host.loadImage("assets/texture.png"); for (s.particles.constSlice()) |p| { if (p.lifespan == 100) continue; // added this step: not shown yet f.imageAt(texture, .translate(p.position[0], p.position[1]), .{ .tint = magenta.alphaFloat(p.lifespan / 255) }); } windArrow(f, s.wind); }