Lamp-Da 0.1
A compact lantern project
Loading...
Searching...
No Matches
helix_mask.hpp
1// helix_mask.hpp - "pine cone" lattice masks for an LED strip wound as a helix. C++17, header only.
2//
3// For every level the table builder chooses, at compile time and without any hand-tuned value:
4// * the step `mu` (one LED out of `mu` belongs to the lattice, `mu` is a real number),
5// * the polarity: the lattice is always the MINORITY set (lit LEDs at high levels, dark LEDs
6// at low levels), so the eye always sees a regular dot pattern.
7// The runtime test is one 32-bit multiply and one compare.
8#pragma once
9#include <array>
10#include <cstddef>
11#include <cstdint>
12
13namespace lampda::helixmask {
14
15// ---------------------------------------------------------------- constexpr maths
16constexpr double kPi = 3.141592653589793;
17constexpr double kSqrt3 = 1.7320508075688772;
18
19constexpr double cx_abs(double x) { return x < 0.0 ? -x : x; }
20constexpr double cx_floor(double x)
21{
22 const long long i = static_cast<long long>(x);
23 return static_cast<double>(x < static_cast<double>(i) ? i - 1 : i);
24}
25constexpr double cx_round(double x) { return cx_floor(x + 0.5); }
26constexpr double cx_frac(double x) { return x - cx_floor(x); }
27constexpr double cx_max(double a, double b) { return a > b ? a : b; }
28constexpr double cx_min(double a, double b) { return a < b ? a : b; }
29constexpr double cx_sqrt(double x)
30{
31 if (x <= 0.0)
32 return 0.0;
33 double r = x < 1.0 ? 1.0 : x;
34 for (int i = 0; i < 40; ++i)
35 r = 0.5 * (r + x / r);
36 return r;
37}
38
39// ---------------------------------------------------------------- physical description
41{
42 double radius_mm; // cylinder radius
43 double pitch_mm; // axial advance per turn (strip width + gap between turns)
44 double led_spacing_mm; // distance between two LEDs along the strip (1000 / LED-per-metre)
45 std::size_t led_count; // number of LEDs on the strip
46
47 constexpr double circumference() const { return 2.0 * kPi * radius_mm; }
48 constexpr double turn_length() const
49 { // strip length for one full turn
50 return cx_sqrt(circumference() * circumference() + pitch_mm * pitch_mm);
51 }
52 constexpr double leds_per_turn() const { return turn_length() / led_spacing_mm; } // = your _fwidth
53 constexpr double height() const
54 { // axial height covered by the strip
55 return static_cast<double>(led_count) * led_spacing_mm / turn_length() * pitch_mm;
56 }
57 constexpr double area_per_led() const { return circumference() * pitch_mm / leds_per_turn(); }
58};
59
60// ---------------------------------------------------------------- tuning knobs
61struct Params
62{
63 int max_level = 10;
64 double ratio = 1.35; // lit fraction at level L is ratio^-L
65 double window = 0.12; // search +-12 % around the target step
66 double resolution = 0.004; // search resolution, relative to the target step
67 double density_w = 2.0; // penalty for straying from the target density
68 double stripe_w = 5.0; // penalty for visible stripes / bands (see stripe_score)
69 double invert_above = 0.5; // lit fraction above which the DARK LEDs become the lattice
70 double clump_w = 2.0; // penalty for lattice LEDs that have a lattice neighbour too close
71 double clump_radius = 0.75; // "too close" = closer than clump_radius x ideal lattice spacing
72 double ring_min = 2.0; // stripe test: neighbours between ring_min and ring_max spacings
73 double ring_max = 5.0;
74 double height_cap = 0.4; // ... but never farther than height_cap * strip height
75};
76
77constexpr std::size_t kMaxLevels = 16;
78constexpr std::size_t kMaxOffsets = 1536;
79constexpr int kBins = 12;
80
81// ------------------------------------------------- lattice quality (1.0 = perfect hexagonal)
82// Keeping one LED every `mu` LEDs gives a 2D lattice on the unrolled cylinder, generated by
83// g = (frac(mu/N)*C, -pitch*mu/N) and w = (C, 0). Returns covering radius / ideal hex covering radius.
84constexpr double lattice_badness(double mu, const Geometry& g)
85{
86 const double N = g.leds_per_turn(), C = g.circumference();
87 const double turns = mu / N;
88 double b1x = cx_frac(turns) * C, b1y = -g.pitch_mm * turns;
89 double b2x = C, b2y = 0.0;
90 for (int it = 0; it < 64; ++it)
91 { // Gauss (Lagrange) reduction
92 if (b1x * b1x + b1y * b1y > b2x * b2x + b2y * b2y)
93 {
94 const double tx = b1x, ty = b1y;
95 b1x = b2x;
96 b1y = b2y;
97 b2x = tx;
98 b2y = ty;
99 }
100 const double n1 = b1x * b1x + b1y * b1y;
101 if (n1 < 1e-12)
102 return 1e9;
103 const double k = cx_round((b1x * b2x + b1y * b2y) / n1);
104 if (k == 0.0)
105 break;
106 b2x -= k * b1x;
107 b2y -= k * b1y;
108 }
109 const double a2 = b1x * b1x + b1y * b1y, c2n = b2x * b2x + b2y * b2y;
110 const double d = cx_abs(b1x * b2x + b1y * b2y);
111 const double cell2 = a2 * c2n - d * d;
112 if (cell2 < 1e-12)
113 return 1e9;
114 const double c2 = a2 + c2n - 2.0 * d;
115 const double cell = cx_sqrt(cell2);
116 const double R2 = a2 * c2n * c2 / (4.0 * cell2);
117 const double R02 = 2.0 * cell / (3.0 * kSqrt3);
118 return cx_sqrt(R2 / R02);
119}
120
121// ------------------------------------------------- stripe score (0 = isotropic, >= 0.1 = visible bands)
122// Two LEDs k positions apart on the strip lie at a known offset on the cylinder. A mask with density
123// alpha = 1/mu gives them the same state with an exactly computable probability. If, for neighbours
124// lying in one direction, that probability stays above chance, the eye sees stripes in that direction.
126{
127 struct Item
128 {
129 uint16_t k;
130 uint8_t bin;
131 };
132 std::array<Item, kMaxOffsets> item {};
133 std::array<int, kBins> count {};
134 std::size_t size = 0;
135};
136
137// Neighbours of an LED that lie in the ring [ring_min, ring_max] x spacing. Depends only on the
138// geometry and on the target density of the lattice set, not on the candidate step.
139constexpr OffsetList make_offsets(
140 const Geometry& g, double alpha_target, double ring_min, double ring_max, double height_cap)
141{
142 OffsetList o {};
143 const double C = g.circumference(), Lt = g.turn_length();
144 const double sp = cx_sqrt(2.0 * g.area_per_led() / (alpha_target * kSqrt3)); // hex spacing
145 const double rmin = ring_min * sp;
146 const double rmax = cx_min(ring_max * sp, height_cap * g.height());
147 if (rmax <= rmin)
148 return o;
149 const double ex = g.led_spacing_mm * C / Lt; // circumferential advance per LED
150 const double ez = g.led_spacing_mm * g.pitch_mm / Lt; // axial advance per LED
151 const std::size_t kmax = static_cast<std::size_t>(rmax / ez) + 1;
152 const std::size_t kend = kmax < g.led_count - 1 ? kmax : g.led_count - 1;
153 const std::size_t stride = 1 + (3 * kend) / kMaxOffsets; // sub-sample if the list would overflow
154 for (std::size_t k = 1; k <= kend; k += stride)
155 {
156 const double vy = static_cast<double>(k) * ez;
157 const double vx0 = cx_frac(static_cast<double>(k) * ex / C) * C;
158 for (int j = -1; j <= 1; ++j)
159 {
160 const double vx = vx0 + j * C;
161 const double r2 = vx * vx + vy * vy;
162 if (r2 < rmin * rmin || r2 > rmax * rmax || o.size >= kMaxOffsets)
163 continue;
164 const double s = vx / (cx_abs(vx) + vy); // monotone pseudo-angle in (-1, 1)
165 int b = static_cast<int>((1.0 - s) * 0.5 * kBins);
166 b = b < 0 ? 0 : (b >= kBins ? kBins - 1 : b);
167 o.item[o.size] = {static_cast<uint16_t>(k), static_cast<uint8_t>(b)};
168 ++o.size;
169 ++o.count[static_cast<std::size_t>(b)];
170 }
171 }
172 return o;
173}
174
175// Strongest directional excess of "same state" probability for the mask with density alpha = 1/mu.
176constexpr double stripe_score(double alpha, const OffsetList& o)
177{
178 const double chance = alpha * alpha + (1.0 - alpha) * (1.0 - alpha);
179 std::array<double, kBins> acc {};
180 for (std::size_t i = 0; i < o.size; ++i)
181 {
182 const double t = cx_frac(static_cast<double>(o.item[i].k) * alpha);
183 const double p11 = cx_max(0.0, alpha - t) + cx_max(0.0, alpha - (1.0 - t)); // both LEDs in the lattice
184 acc[o.item[i].bin] += (1.0 - 2.0 * alpha + 2.0 * p11) - chance;
185 }
186 double best = 0.0;
187 for (int b = 0; b < kBins; ++b)
188 {
189 const std::size_t u = static_cast<std::size_t>(b);
190 if (o.count[u] > 0)
191 best = cx_max(best, acc[u] / o.count[u]);
192 }
193 return best;
194}
195
196// Probability that a lattice LED has another lattice LED closer than clump_radius x ideal spacing
197// (two lattice LEDs side by side look like one blob and break the regularity).
198constexpr double clump_score(double alpha, const OffsetList& o)
199{
200 double sum = 0.0;
201 for (std::size_t i = 0; i < o.size; ++i)
202 {
203 const double t = cx_frac(static_cast<double>(o.item[i].k) * alpha);
204 sum += cx_max(0.0, alpha - t) + cx_max(0.0, alpha - (1.0 - t));
205 }
206 const double frac = 2.0 * sum / alpha; // a pair is seen from both of its members
207 return frac > 1.0 ? 1.0 : frac;
208}
209
210// ---------------------------------------------------------------- per-level step table
212{
213 std::array<double, kMaxLevels> mu {}; // step of the lattice set (fractional, in LEDs)
214 std::array<uint32_t, kMaxLevels> A {}; // round(2^32 / mu)
215 std::array<bool, kMaxLevels> invert {}; // true: lattice LEDs are the dark ones
216 std::array<double, kMaxLevels> lit {}; // resulting lit fraction
217 std::array<double, kMaxLevels> angle {}; // divergence angle between consecutive lattice LEDs (deg)
218 std::array<double, kMaxLevels> quality {}; // lattice_badness, 1.0 = perfect hexagonal
219 std::array<double, kMaxLevels> stripes {}; // stripe_score, 0 = isotropic
220 std::array<double, kMaxLevels> clumps {}; // clump_score, 0 = no lattice LED has a close neighbour
221 int max_level = 0;
222};
223
224constexpr StepTable make_step_table(const Geometry& g, const Params& p = {})
225{
226 StepTable t {};
227 t.max_level = p.max_level;
228 const double N = g.leds_per_turn();
229 t.mu[0] = 1.0;
230 t.lit[0] = 1.0;
231 double f = 1.0; // target lit fraction
232 for (int L = 1; L <= p.max_level && L < static_cast<int>(kMaxLevels); ++L)
233 {
234 f /= p.ratio;
235 const bool inv = f > p.invert_above;
236 const double alpha_t = inv ? 1.0 - f : f; // density of the lattice set
237 const double mu_t = 1.0 / alpha_t;
238 const OffsetList offs = make_offsets(g, alpha_t, p.ring_min, p.ring_max, p.height_cap);
239 const OffsetList close_offs = make_offsets(g, alpha_t, 0.0, p.clump_radius, 1.0);
240 double best = 1e18, bestmu = mu_t, bq = 0.0, bs = 0.0, bc = 0.0;
241 const double lo = mu_t * (1.0 - p.window), hi = mu_t * (1.0 + p.window);
242 for (double mu = lo < 1.05 ? 1.05 : lo; mu <= hi; mu += mu_t * p.resolution)
243 {
244 const double q = lattice_badness(mu, g);
245 const double s = stripe_score(1.0 / mu, offs);
246 const double c = clump_score(1.0 / mu, close_offs);
247 const double pen = q * (1.0 + p.density_w * cx_abs(mu / mu_t - 1.0)) + p.stripe_w * s + p.clump_w * c;
248 if (pen < best)
249 {
250 best = pen;
251 bestmu = mu;
252 bq = q;
253 bs = s;
254 bc = c;
255 }
256 }
257 const std::size_t l = static_cast<std::size_t>(L);
258 t.mu[l] = bestmu;
259 t.A[l] = static_cast<uint32_t>(cx_round(4294967296.0 / bestmu));
260 t.invert[l] = inv;
261 t.lit[l] = inv ? 1.0 - 1.0 / bestmu : 1.0 / bestmu;
262 t.angle[l] = cx_frac(bestmu / N) * 360.0;
263 t.quality[l] = bq;
264 t.stripes[l] = bs;
265 t.clumps[l] = bc;
266 }
267 return t;
268}
269
270// ---------------------------------------------------------------- per-LED test (hot path)
271constexpr bool led_on(const StepTable& t, std::size_t index, int level)
272{
273 if (level <= 0 || level > t.max_level)
274 return level <= 0; // level 0: all on
275 const std::size_t L = static_cast<std::size_t>(level);
276 const uint32_t A = t.A[L];
277 const bool lattice = static_cast<uint32_t>(static_cast<uint32_t>(index) * A) < A; // wraps mod 2^32
278 return t.invert[L] ? !lattice : lattice;
279}
280
281} // namespace lampda::helixmask
Definition: helix_mask.hpp:41
Definition: helix_mask.hpp:128
Definition: helix_mask.hpp:126
Definition: helix_mask.hpp:62
Definition: helix_mask.hpp:212