Repository navigation
Expand file tree
/
Copy pathscreenmap.cpp.hpp
More file actions
759 lines (653 loc) · 26.7 KB
/
Copy pathscreenmap.cpp.hpp
File metadata and controls
759 lines (653 loc) · 26.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
/* Screenmap maps strip indexes to x,y coordinates. This is used for FastLED Web
* to map the 1D strip to a 2D grid. Note that the strip can have arbitrary
* size. this was first motivated during the (attempted? Oct. 19th 2024) port of
* the Chromancer project to FastLED Web.
*/
#include "fl/math/screenmap.h"
// Heavy includes moved from header to reduce compilation time
#include "fl/math/lut.h" // Full LUT definitions needed for implementation
#include "fl/stl/json.h" // 61.1ms - only needed for ParseJson/toJson implementations
#include "fl/stl/string.h" // 129.4ms - only needed for string parameters in implementations
#include "fl/stl/flat_map.h" // 12.4ms - only needed for flat_map parameters in implementations
// IWYU pragma: begin_keep
#include "fl/stl/function.h"
// IWYU pragma: end_keep // ~5ms - only needed for function<> constructor implementation
#include "fl/stl/static_assert.h"
// Other implementation dependencies
#include "fl/math/math.h"
#include "fl/math/math.h"
#include "fl/stl/vector.h"
#include "fl/log/log.h"
#include "fl/stl/noexcept.h"
namespace fl {
namespace {
// Every value that reaches `mDiameter` from a caller passes through here.
//
// The class accepts any `float` -- three constructors and `setDiameter` all
// take one unfiltered -- but only two kinds of value mean anything: a
// positive size, and the -1 sentinel for "unset". A caller who stores 0.0f
// or -2.0f has named a diameter no LED has. The emitter cannot publish
// those (a consumer reading `"diameter": -2` learns nothing it can use) and
// the parsers read an absent key back as -1, so before this normalization a
// stored 0.0f came back from a round trip as -1.0f: silently different from
// what was set, and different in a way `getDiameter()` did not show until
// the file had been through JSON.
//
// Folding them to the sentinel at the boundary makes the two agree. A
// non-positive diameter now reads back as -1 immediately, from the setter
// onward, so the round trip is the identity on every value the class holds.
float normalizedDiameter(float diameter) FL_NO_EXCEPT {
return diameter > 0.0f ? diameter : -1.0f;
}
} // namespace
// Default constructor and destructor - must be in .cpp for proper smart_ptr handling
ScreenMap::ScreenMap() FL_NO_EXCEPT = default;
ScreenMap::~ScreenMap() FL_NO_EXCEPT = default;
// Helper function to extract a vector of floats from a JSON array
fl::vector<float> jsonArrayToFloatVector(const fl::json& jsonArray) FL_NO_EXCEPT {
fl::vector<float> result;
if (!jsonArray.has_value() || !jsonArray.is_array()) {
return result;
}
auto begin_float = jsonArray.begin_array<float>();
auto end_float = jsonArray.end_array<float>();
using T = decltype(*begin_float);
FL_STATIC_ASSERT(fl::is_same<T, fl::parse_result<float>>::value, "Value type must be parse_result<float>");
// Use explicit array iterator style as demonstrated in FEATURE.md
// DO NOT CHANGE THIS CODE. FIX THE IMPLIMENTATION IF NECESSARY.
for (auto it = begin_float; it != end_float; ++it) {
// assert that the value type is parse_result<float>
// get the name of the type
auto parseResult = *it;
if (!parseResult.has_error()) {
result.push_back(parseResult.get_value());
} else {
FL_WARN("jsonArrayToFloatVector: parse_result<float> has error: " << parseResult.get_error().message);
}
}
return result;
}
ScreenMap ScreenMap::Circle(int numLeds, float cm_between_leds,
float cm_led_diameter, float completion) FL_NO_EXCEPT {
ScreenMap screenMap(numLeds);
// radius from LED spacing
float circumference = numLeds * cm_between_leds;
float radius = circumference / (2 * FL_PI);
// how big an arc we light vs leave dark
float totalAngle = completion * 2 * FL_PI;
float gapAngle = 2 * FL_PI - totalAngle;
// shift so the dark gap is centered at the bottom (–π/2)
float startAngle = -FL_PI / 2 + gapAngle / 2.0f;
// if partial, land last LED exactly at startAngle+totalAngle
float divisor =
(completion < 1.0f && numLeds > 1) ? (numLeds - 1) : numLeds;
for (int i = 0; i < numLeds; ++i) {
float angle = startAngle + (i * totalAngle) / divisor;
float x = radius * cos(angle) * 2;
float y = radius * sin(angle) * 2;
screenMap[i] = {x, y};
}
screenMap.setDiameter(cm_led_diameter);
return screenMap;
}
ScreenMap ScreenMap::DefaultStrip(int numLeds, float cm_between_leds,
float cm_led_diameter, float completion) FL_NO_EXCEPT {
return Circle(numLeds, cm_between_leds, cm_led_diameter, completion);
}
// Helper: parse a v2 screenmap document into the flat segmentMaps.
// v2 shape (see ledmapper #92):
// {
// "version": 2, // optional, explicit
// "groups": { "<name>": { "color": "...", ... } }, // optional, ignored by firmware
// "segments": [
// { "id": "<unique>", "pin": <int|str>, "group": "<name>",
// "x": [...], "y": [...], "z": [...], // z optional
// "parent": "<id>", "offset": <int|null> } // parent+offset on forks only
// ]
// }
//
// Flatten policy: each segment becomes one ScreenMap entry keyed by `id`.
// `pin`, `group`, `parent`, `offset` are not represented in the firmware-side
// flat_map; they're UI/wiring metadata the editor and video tools care about.
// `z` is dropped (firmware-side ScreenMap is 2D today).
static bool parseV2SegmentArray(const fl::json& segmentsArr,
fl::flat_map<string, ScreenMap> *segmentMaps,
string *err) FL_NO_EXCEPT {
if (!segmentsArr.has_value() || !segmentsArr.is_array()) {
*err = "v2 'segments' is not an array";
return false;
}
auto arrPtr = segmentsArr.as_array();
if (!arrPtr) {
*err = "v2 'segments' array could not be read";
return false;
}
for (const auto& elem : *arrPtr) {
if (!elem) {
*err = "v2 segment is null";
return false;
}
fl::json segVal(elem);
if (!segVal.has_value() || !segVal.is_object()) {
*err = "v2 segment is not an object";
return false;
}
// Required: id
if (!segVal.contains("id") || !segVal["id"].has_value()) {
*err = "v2 segment missing 'id'";
return false;
}
auto idOpt = segVal["id"].as_string();
if (!idOpt) {
*err = "v2 segment 'id' is not a string";
return false;
}
string id = *idOpt;
// Required: x
if (!segVal.contains("x") || !segVal["x"].has_value() || !segVal["x"].is_array()) {
*err = "v2 segment '" + id + "' missing or invalid 'x' array";
return false;
}
fl::vector<float> x_array = jsonArrayToFloatVector(segVal["x"]);
// Required: y
if (!segVal.contains("y") || !segVal["y"].has_value() || !segVal["y"].is_array()) {
*err = "v2 segment '" + id + "' missing or invalid 'y' array";
return false;
}
fl::vector<float> y_array = jsonArrayToFloatVector(segVal["y"]);
string type = "led_strip";
if (segVal.contains("type") && segVal["type"].has_value()) {
auto typeOpt = segVal["type"].as_string();
if (!typeOpt) { *err = "v2 segment '" + id + "' has invalid 'type'"; return false; }
type = *typeOpt;
}
const bool isWire = type == "el_wire";
const bool isPanel = type == "el_panel";
if (type != "led_strip" && !isWire && !isPanel) {
*err = "v2 segment '" + id + "' has unsupported type '" + type + "'";
return false;
}
if (x_array.size() != y_array.size()) {
*err = "v2 segment '" + id + "' has mismatched x/y lengths";
return false;
}
const size_t minVertices = isWire ? 2 : isPanel ? 3 : 0;
if ((isWire || isPanel) && x_array.size() < minVertices) {
*err = "v2 segment '" + id + "' has too few vertices";
return false;
}
float thickness = 0.0f;
if (isWire) {
if (!segVal.contains("thickness") || !segVal["thickness"].has_value()) {
*err = "v2 el_wire segment '" + id + "' missing thickness";
return false;
}
auto thicknessOpt = segVal["thickness"].as_float();
if (!thicknessOpt || *thicknessOpt <= 0.0f) {
*err = "v2 el_wire segment '" + id + "' requires positive thickness";
return false;
}
thickness = static_cast<float>(*thicknessOpt);
} else if (segVal.contains("thickness")) {
*err = "v2 segment '" + id + "' thickness is only valid for el_wire";
return false;
}
// Optional: diameter (not in canonical v2 but accepted as a backward-compat
// hint when present; otherwise the per-group `diameter` could be wired here
// in a future iteration).
float diameter = -1.0f;
if (segVal.contains("diameter") && segVal["diameter"].has_value()) {
auto diameterOpt = segVal["diameter"].as_float();
if (diameterOpt) {
diameter = static_cast<float>(*diameterOpt);
}
}
auto n = fl::min(x_array.size(), y_array.size());
ScreenMap segment_map(isWire || isPanel ? 1 : static_cast<u32>(n), diameter);
if (isWire || isPanel) {
fl::vector<vec2f> vertices;
vertices.reserve(n);
for (size_t i = 0; i < n; i++) vertices.push_back({x_array[i], y_array[i]});
segment_map.setShape(0, isWire ? ScreenMap::Shape::EL_WIRE : ScreenMap::Shape::EL_PANEL, vertices.data(), static_cast<u32>(n), thickness);
}
if (!isWire && !isPanel) {
for (size_t i = 0; i < n; i++) {
segment_map.set(static_cast<u16>(i), vec2f{x_array[i], y_array[i]});
}
}
(*segmentMaps)[id] = fl::move(segment_map);
}
return true;
}
bool ScreenMap::ParseJson(const char *jsonStrScreenMap,
fl::flat_map<string, ScreenMap> *segmentMaps, string *err) FL_NO_EXCEPT {
#if FASTLED_NO_JSON
FL_UNUSED(jsonStrScreenMap);
FL_UNUSED(segmentMaps);
FL_UNUSED(err);
FL_WARN("ScreenMap::ParseJson called with FASTLED_NO_JSON");
if (err) {
*err = "JSON is not supported in this build";
}
return false;
#else
//FL_WARN_SCREENMAP("ParseJson called with JSON: " << jsonStrScreenMap);
string _err;
if (!err) {
err = &_err;
}
auto jsonDoc = fl::json::parse(jsonStrScreenMap);
if (!jsonDoc.has_value()) {
*err = "Failed to parse JSON";
FL_WARN("Failed to parse JSON");
return false;
}
if (!jsonDoc.is_object()) {
*err = "JSON root is not an object";
FL_WARN("JSON root is not an object");
return false;
}
// ── v2 dispatch ──────────────────────────────────────────────────────
// v2 if: explicit "version": 2 OR has top-level "segments" array.
// v1 if: explicit "version": 1 OR has top-level "map" object.
bool explicitV2 = false;
bool explicitV1 = false;
if (jsonDoc.contains("version") && jsonDoc["version"].has_value()) {
auto versionOpt = jsonDoc["version"].as_int();
if (versionOpt) {
int v = static_cast<int>(*versionOpt);
if (v == 2) explicitV2 = true;
else if (v == 1) explicitV1 = true;
}
}
bool hasSegments = jsonDoc.contains("segments") && jsonDoc["segments"].has_value()
&& jsonDoc["segments"].is_array();
bool hasMap = jsonDoc.contains("map") && jsonDoc["map"].has_value()
&& jsonDoc["map"].is_object();
if (explicitV2 || (!explicitV1 && hasSegments && !hasMap)) {
return parseV2SegmentArray(jsonDoc["segments"], segmentMaps, err);
}
// Fall through to v1 path.
// Check if "map" key exists and is an object
if (!jsonDoc.contains("map")) {
*err = "Missing 'map' key in JSON";
FL_WARN("Missing 'map' key in JSON");
return false;
}
// Get the map object
auto mapObj = jsonDoc["map"];
if (!mapObj.has_value() || !mapObj.is_object()) {
*err = "Invalid 'map' object in JSON";
FL_WARN("Invalid 'map' object in JSON");
return false;
}
auto jsonMapPtr = mapObj.as_object();
if (!jsonMapPtr || jsonMapPtr->empty()) {
*err = "Failed to parse map from JSON or map is empty";
FL_WARN("Failed to parse map from JSON or map is empty");
return false;
}
auto& jsonMap = *jsonMapPtr;
for (const auto& kv : jsonMap) {
auto name = kv.first;
// Check that the value is not null before creating json object
if (!kv.second) {
*err = "Null value for segment " + name;
return false;
}
// Create json object directly from shared_ptr
fl::json val(kv.second);
if (!val.has_value()) {
*err = "Invalid value for segment " + name;
return false;
}
if (!val.is_object()) {
*err = "Segment value for " + name + " is not an object";
return false;
}
// Check if x array exists and is actually an array
if (!val.contains("x")) {
*err = "Missing x array for " + name;
return false;
}
if (!val["x"].has_value() || !val["x"].is_array()) {
*err = "Invalid x array for " + name;
return false;
}
// Extract x array using our helper function
fl::vector<float> x_array = jsonArrayToFloatVector(val["x"]);
// Check if y array exists and is actually an array
if (!val.contains("y")) {
*err = "Missing y array for " + name;
return false;
}
if (!val["y"].has_value() || !val["y"].is_array()) {
*err = "Invalid y array for " + name;
return false;
}
// Extract y array using our helper function
fl::vector<float> y_array = jsonArrayToFloatVector(val["y"]);
// Get diameter (optional) with default value
float diameter = -1.0f; // default value
if (val.contains("diameter") && val["diameter"].has_value()) {
auto diameterOpt = val["diameter"].as_float();
if (diameterOpt) {
diameter = static_cast<float>(*diameterOpt);
}
}
auto n = fl::min(x_array.size(), y_array.size());
if (n != x_array.size() || n != y_array.size()) {
if (n != x_array.size()) {
}
if (n != y_array.size()) {
}
}
ScreenMap segment_map(n, diameter);
for (size_t i = 0; i < n; i++) {
segment_map.set(i, vec2f{x_array[i], y_array[i]});
}
(*segmentMaps)[name] = fl::move(segment_map);
}
return true;
#endif
}
bool ScreenMap::ParseJson(const char *jsonStrScreenMap,
const char *screenMapName, ScreenMap *screenmap,
string *err) FL_NO_EXCEPT {
fl::flat_map<string, ScreenMap> segmentMaps;
bool ok = ParseJson(jsonStrScreenMap, &segmentMaps, err);
if (!ok) {
return false;
}
if (segmentMaps.size() == 0) {
return false;
}
if (segmentMaps.contains(screenMapName)) {
*screenmap = segmentMaps[screenMapName];
return true;
}
string _err = "ScreenMap not found: ";
_err.append(screenMapName);
if (err) {
*err = _err;
}
return false;
}
void ScreenMap::toJson(const fl::flat_map<string, ScreenMap> &segmentMaps,
fl::json *doc) FL_NO_EXCEPT {
#if FASTLED_NO_JSON
FL_WARN("ScreenMap::toJson called with FASTLED_NO_JSON");
return;
#else
if (!doc) {
FL_WARN("ScreenMap::toJson called with nullptr doc");
return;
}
// Emits the v2 screenmap shape (issue ledmapper#143):
// { "version": 2,
// "groups": { "<name>": { "color": "#hex" } },
// "segments": [ { "id": "<name>", "group": "<name>",
// "x": [...], "y": [...], "diameter": ... } ] }
//
// `pin` is part of the v2 shape but is not emitted here -- see the note
// at the segment object below. Writing the example value from a comment
// as data is how it came to be there.
// Bilingual readers (`ScreenMap::ParseJson`, ledmapper) accept both v1
// and v2, so any existing on-disk v1 JSON keeps loading. v1 emission
// is no longer supported.
*doc = fl::json::object();
fl::json groupsObj = fl::json::object();
fl::json segmentsArr = fl::json::array();
// Distinct palette so each strip lights up differently in the editor
// preview without the user having to pick a colour. Cycle on overflow.
static const char *const kPalette[] = {
"#3b82f6", "#10b981", "#f59e0b", "#ef4444",
"#a855f7", "#06b6d4", "#ec4899", "#84cc16",
};
constexpr size_t kPaletteSize = sizeof(kPalette) / sizeof(kPalette[0]);
size_t idx = 0;
for (const auto& kv : segmentMaps) {
if (kv.second.getLength() == 0) {
FL_WARN("ScreenMap::toJson called with empty segment: " << (fl::string(kv.first)));
continue;
}
const auto& name = kv.first;
const auto& segment = kv.second;
const float diameter = segment.getDiameter();
fl::json xArray = fl::json::array();
for (u16 i = 0; i < segment.getLength(); i++) {
xArray.push_back(fl::json(segment[i].x));
}
fl::json yArray = fl::json::array();
for (u16 i = 0; i < segment.getLength(); i++) {
yArray.push_back(fl::json(segment[i].y));
}
fl::json groupObj = fl::json::object();
groupObj.set("color", fl::json(fl::string(kPalette[idx % kPaletteSize])));
groupsObj.set(name, groupObj);
fl::json segmentObj = fl::json::object();
segmentObj.set("id", fl::json(fl::string(name)));
// No `pin`. The v2 shape carries one and the parser above drops it --
// it is wiring metadata with nowhere to live on this side -- so there
// is nothing here to write. What used to be written was the literal
// `"pin1"` from the shape example in the comment above, copied into
// the emitter as data.
//
// That is worse than omitting it, because it is wrong rather than
// absent. A three-segment file wired to pin1/pin2/pin3 came back with
// all three on pin1, and a numeric `"pin": 7` came back as the string
// `"pin1"`. A consumer reading that mis-wires a strip and has no way
// to tell; a consumer reading a missing optional key can see that it
// is missing.
//
// Carrying the value through instead is FastLED #3322, which needs
// somewhere on `ScreenMap` to put it and a decision about the
// `<int|str>` union. Until then this loses the field visibly rather
// than rewriting it silently.
segmentObj.set("group", fl::json(fl::string(name)));
segmentObj.set("x", xArray);
segmentObj.set("y", yArray);
// Only when there is one. `mDiameter` defaults to -1 as a sentinel
// meaning "unset", and writing that out publishes an impossible
// physical size: no LED is -1 units across. The parser already reads
// an absent key back as -1 (both the v1 and v2 paths default it), so
// omitting round-trips to exactly the same value inside FastLED and
// stops a consumer from having to know the sentinel.
//
// The field's own comment in screenmap.h asked for this and had the
// sense inverted -- "Only serialized if it's not > 0.0f" -- which is
// presumably how the writer came to do the opposite.
if (diameter > 0.0f) {
segmentObj.set("diameter", fl::json(diameter));
}
segmentsArr.push_back(segmentObj);
idx++;
}
doc->set("version", fl::json(i64(2)));
doc->set("groups", groupsObj);
doc->set("segments", segmentsArr);
fl::string debugStr = doc->to_string();
FL_WARN("ScreenMap::toJson generated JSON: " << debugStr);
#endif
}
void ScreenMap::toJsonStr(const fl::flat_map<string, ScreenMap> &segmentMaps,
string *jsonBuffer) FL_NO_EXCEPT {
fl::json doc;
toJson(segmentMaps, &doc);
*jsonBuffer = doc.to_string();
}
ScreenMap::ScreenMap(u32 length, float mDiameter) FL_NO_EXCEPT
: length(length), mDiameter(normalizedDiameter(mDiameter)) {
if (length > 0) {
mLookUpTable = fl::make_shared<LUTXYFLOAT>(length);
LUTXYFLOAT &lut = *mLookUpTable.get();
vec2f *data = lut.getDataMutable();
for (u32 x = 0; x < length; x++) {
data[x] = {0, 0};
}
}
}
ScreenMap::ScreenMap(const vec2f *lut, u32 length, float diameter) FL_NO_EXCEPT
: length(length), mDiameter(normalizedDiameter(diameter)) {
mLookUpTable = fl::make_shared<LUTXYFLOAT>(length);
LUTXYFLOAT &lut16xy = *mLookUpTable.get();
vec2f *data = lut16xy.getDataMutable();
for (u32 x = 0; x < length; x++) {
data[x] = lut[x];
}
}
ScreenMap::ScreenMap(int count, float diameter, fl::function<void(int, vec2f& pt_out)> func) FL_NO_EXCEPT
: length(count), mDiameter(normalizedDiameter(diameter)) {
if (count > 0) {
mLookUpTable = fl::make_shared<LUTXYFLOAT>(count);
LUTXYFLOAT &lut = *mLookUpTable.get();
vec2f *data = lut.getDataMutable();
for (int i = 0; i < count; i++) {
func(i, data[i]);
}
}
}
ScreenMap::ScreenMap(const ScreenMap &other) FL_NO_EXCEPT {
mDiameter = other.mDiameter;
length = other.length;
mLookUpTable = other.mLookUpTable;
mSourceXYMap = other.mSourceXYMap;
mShapes = other.mShapes;
}
ScreenMap::ScreenMap(ScreenMap&& other) FL_NO_EXCEPT {
mDiameter = other.mDiameter;
length = other.length;
fl::swap(mLookUpTable, other.mLookUpTable);
fl::swap(mSourceXYMap, other.mSourceXYMap);
fl::swap(mShapes, other.mShapes);
other.mLookUpTable.reset();
other.mSourceXYMap.reset();
}
void ScreenMap::set(u16 index, const vec2f &p) FL_NO_EXCEPT {
if (mLookUpTable) {
LUTXYFLOAT &lut = *mLookUpTable.get();
auto *data = lut.getDataMutable();
data[index] = p;
}
}
void ScreenMap::setDiameter(float diameter) FL_NO_EXCEPT {
mDiameter = normalizedDiameter(diameter);
}
vec2f ScreenMap::mapToIndex(u32 x) const FL_NO_EXCEPT {
if (x >= length || !mLookUpTable) {
return {0, 0};
}
LUTXYFLOAT &lut = *mLookUpTable.get();
vec2f screen_coords = lut[x];
return screen_coords;
}
u32 ScreenMap::getLength() const FL_NO_EXCEPT { return length; }
float ScreenMap::getDiameter() const FL_NO_EXCEPT { return mDiameter; }
vec2f ScreenMap::getBounds() const FL_NO_EXCEPT {
if (length == 0 || !mLookUpTable) {
return {0, 0};
}
LUTXYFLOAT &lut = *mLookUpTable.get();
fl::vec2f *data = lut.getDataMutable();
// float minX = lut[0].x;
// float maxX = lut[0].x;
// float minY = lut[0].y;
// float maxY = lut[0].y;
float minX = data[0].x;
float maxX = data[0].x;
float minY = data[0].y;
float maxY = data[0].y;
for (u32 i = 1; i < length; i++) {
const vec2f &p = lut[i];
minX = fl::min(minX, p.x);
maxX = fl::max(maxX, p.x);
minY = fl::min(minY, p.y);
maxY = fl::max(maxY, p.y);
}
return {maxX - minX, maxY - minY};
}
void ScreenMap::setShape(u32 index, Shape::Type type, const vec2f *vertices, u32 count,
float thickness) FL_NO_EXCEPT {
if (!vertices || count == 0) return;
if (index >= mShapes.size()) mShapes.resize(index + 1);
Shape &shape = mShapes[index];
shape.type = type;
shape.thickness = thickness;
shape.vertices.clear();
shape.vertices.reserve(count);
for (u32 i = 0; i < count; ++i) shape.vertices.push_back(vertices[i]);
}
bool ScreenMap::hasShapes() const FL_NO_EXCEPT { return !mShapes.empty(); }
u32 ScreenMap::getShapeCount() const FL_NO_EXCEPT { return static_cast<u32>(mShapes.size()); }
const ScreenMap::Shape &ScreenMap::getShape(u32 index) const FL_NO_EXCEPT {
static const Shape emptyShape = [] {
Shape shape;
shape.type = Shape::EL_PANEL;
return shape;
}();
return index < mShapes.size() ? mShapes[index] : emptyShape;
}
const vec2f &ScreenMap::empty() FL_NO_EXCEPT {
static const vec2f s_empty = vec2f(0, 0); // okay static in header
return s_empty;
}
const vec2f &ScreenMap::operator[](u32 x) const FL_NO_EXCEPT {
if (x >= length || !mLookUpTable) {
return empty(); // better than crashing.
}
LUTXYFLOAT &lut = *mLookUpTable.get();
return lut[x];
}
vec2f &ScreenMap::operator[](u32 x) FL_NO_EXCEPT {
if (x >= length || !mLookUpTable) {
return const_cast<vec2f &>(empty()); // better than crashing.
}
LUTXYFLOAT &lut = *mLookUpTable.get();
auto *data = lut.getDataMutable();
return data[x];
}
ScreenMap &ScreenMap::operator=(const ScreenMap &other) FL_NO_EXCEPT {
if (this != &other) {
mDiameter = other.mDiameter;
length = other.length;
mLookUpTable = other.mLookUpTable;
mSourceXYMap = other.mSourceXYMap;
mShapes = other.mShapes;
}
return *this;
}
ScreenMap &ScreenMap::operator=(ScreenMap &&other) FL_NO_EXCEPT {
if (this != &other) {
mDiameter = other.mDiameter;
length = other.length;
mLookUpTable = fl::move(other.mLookUpTable);
mSourceXYMap = fl::move(other.mSourceXYMap);
mShapes = fl::move(other.mShapes);
other.length = 0;
other.mDiameter = -1.0f;
}
return *this;
}
void ScreenMap::setSourceXYMap(const fl::shared_ptr<XYMap>& xymap) FL_NO_EXCEPT {
mSourceXYMap = xymap;
}
const XYMapPtr& ScreenMap::getSourceXYMapPtr() const FL_NO_EXCEPT {
return mSourceXYMap;
}
const XYMap* ScreenMap::getXYMap() const FL_NO_EXCEPT {
return mSourceXYMap.get();
}
bool ScreenMap::hasSourceXYMap() const FL_NO_EXCEPT {
return mSourceXYMap != nullptr;
}
void ScreenMap::addOffset(const vec2f &p) FL_NO_EXCEPT {
vec2f *data = mLookUpTable->getDataMutable();
for (u32 i = 0; i < length; i++) {
vec2f &curr = data[i];
curr.x += p.x;
curr.y += p.y;
}
}
ScreenMap& ScreenMap::addOffsetX(float x) FL_NO_EXCEPT { addOffset({x, 0}); return *this; }
ScreenMap& ScreenMap::addOffsetY(float y) FL_NO_EXCEPT { addOffset({0, y}); return *this; }
} // namespace fl