Lamp-Da 0.1
A compact lantern project
Loading...
Searching...
No Matches
simulator.h
Go to the documentation of this file.
1
5#ifndef SIMULATOR_H
6#define SIMULATOR_H
7
8#include <cstring>
9#include <iostream>
10
11// include this first
12#include "src/system/global.h"
13
14#include "parameter_parser.h"
15#include "simulator_state.h"
16
17// see LMBD_LAMP_TYPE__${UPPER_SIM_NAME} hard-coded in simulator/Makefile
18#include "src/user/constants.h"
19
20#include <SFML/Graphics.hpp>
21#include <SFML/Graphics/Color.hpp>
22#include <SFML/System/Time.hpp>
23#include <SFML/Window/Keyboard.hpp>
24
26// #define LMBD_DEBUG_SIMU_REALCOLORS
27
28namespace simulator {
29// (_LampTy from simulator_state.h)
30constexpr int ledW = _LampTy::maxWidth;
31constexpr int ledH = _LampTy::maxOverflowHeight;
32constexpr int ledCount = _LampTy::ledCount;
33
34constexpr float fLedW = _LampTy::maxWidthFloat;
35constexpr float fResidueW = 1 / (2 * fLedW - 2 * floor(fLedW) - 1);
36} // namespace simulator
37
38#include "src/user/functions.h"
40
42// handle simulation of voltage and current in the system
44
45#include <thread>
46
47namespace simulator {
48
49//
50// simulator core loop
51//
52
53template<typename T> struct simulator
54{
55 static constexpr uint screenWidth = 1920;
56 static constexpr uint screenHeight = 1080;
57 static constexpr char title[] = "lampda simulator";
58
59 static constexpr uint brightnessWidth = 480;
60
61 static int run()
62 {
63 T simu;
64 sf::Clock time;
65
66 // brightness tracker
67 std::array<uint16_t, brightnessWidth> brightnessTracker {};
68 std::array<sf::RectangleShape, brightnessWidth> dots;
69
70 // matrix shift
71 int fakeXorigin = 0;
72 int fakeXend = 0;
73
74 // pixel shapes
75 std::array<sf::RectangleShape, _LampTy::ledCount> shapes;
76
77 // init font
78 sf::Font font;
79 bool enableFont = false;
80 bool enableText = false;
81 if (font.loadFromFile(LMBD_SIMULATOR_RESOURCES_DIR "/DejaVuSansMono.ttf"))
82 {
83 enableFont = true;
84 }
85 else
86 {
87 fprintf(stderr, "DejaVuSansMono.ttf not found, disabling text...");
88 }
89
90 // render window
91 sf::RenderWindow window(sf::VideoMode({screenWidth, screenHeight}), title);
92
93 sf::CircleShape buttonMask(simu.buttonSize);
94 sf::CircleShape indicator(simu.buttonSize + simu.buttonMargin);
95 buttonMask.setFillColor(sf::Color::Black);
96
97 sf::Vector2<int> mousePos = sf::Mouse::getPosition(window);
98 const float indCoordX = simu.buttonLeftPos;
99 const float indCoordY = (simu.ledSizePx + simu.ledPaddingPx) * (ledH + 3);
100
101 // TODO: #156 move mock-specific parts to another process
102 // ======================================================
103
104 // mock run the threads (do not give each subprocess a thread)
105 mock_registers::shouldStopThreads = false;
106
107 // load initial values
109 // start electrical simulation,
110 start_electrical_mock();
111
112 // force init of time clock
113 time_mocks::reset();
114
115 // Main program setup
117
118 bool lostFocus = false;
119
120 // =================================================
121
122 // reference to global state
123 auto& state = globals::state;
124
125 uint64_t skipframe = 0;
126 while (window.isOpen())
127 {
128 uint64_t mouseClick = 0;
129
130 mousePos = sf::Mouse::getPosition(window);
131 enableText = enableFont && sf::Mouse::isButtonPressed(sf::Mouse::Button::Left);
132 enableText |= state.verbose;
133
134 // read events, prevent windows lockup
135 sf::Event event;
136 while (window.pollEvent(event))
137 {
138 if (event.type == sf::Event::Closed)
139 {
140 window.close();
141 break;
142 }
143 else if (event.type == sf::Event::LostFocus)
144 lostFocus = true;
145 else if (event.type == sf::Event::GainedFocus)
146 lostFocus = false;
147
148 if (not lostFocus)
149 {
150 if (event.type == sf::Event::KeyPressed)
151 {
152 auto kpressed = event.key.code;
153 switch (kpressed)
154 {
155 default:
156 state.lastKeyPressed = 0;
157 break;
158 case sf::Keyboard::Key::P: // p == pause
159 state.lastKeyPressed = 'p';
160 break;
161 case sf::Keyboard::Key::V: // v == verbose
162 state.lastKeyPressed = 'v';
163 break;
164 case sf::Keyboard::Key::T: // t == tick +pause
165 state.lastKeyPressed = 't';
166 break;
167 case sf::Keyboard::Key::H: // h == higher speed
168 state.lastKeyPressed = 'h';
169 break;
170 case sf::Keyboard::Key::G: // g == glower speeds
171 state.lastKeyPressed = 'g';
172 break;
173 case sf::Keyboard::Key::J: // j == shift matrix left
174 state.lastKeyPressed = 'j';
175 break;
176 case sf::Keyboard::Key::K: // k == shift matrix right
177 state.lastKeyPressed = 'k';
178 break;
179 case sf::Keyboard::Key::D:
180 state.lastKeyPressed = 'd';
181 break;
182 case sf::Keyboard::Key::U:
183 state.lastKeyPressed = 'u';
184 break;
185 case sf::Keyboard::Key::I:
186 state.lastKeyPressed = 'i';
187 break;
188 case sf::Keyboard::Key::R:
189 state.lastKeyPressed = 'r';
190 break;
191 case sf::Keyboard::Key::C:
192 state.lastKeyPressed = 'c';
193 break;
194 case sf::Keyboard::Key::Q:
195 state.lastKeyPressed = 'q';
196 break;
197 }
198
199 break;
200 }
201 else if (event.type == sf::Event::KeyReleased)
202 {
203 // tick forward (once) and pause
204 if (state.lastKeyPressed == 't')
205 {
206 state.paused = false;
207 state.tickAndPause = 2;
208 }
209
210 // pause event
211 if (state.lastKeyPressed == 'p')
212 {
213 state.paused = !state.paused;
214 }
215
216 // verbose event
217 if (state.lastKeyPressed == 'v')
218 {
219 state.verbose = !state.verbose;
220 }
221
222 // slower simulation
223 if (state.lastKeyPressed == 'g')
224 {
225 if (state.slowTimeFactor > 1.50f)
226 {
227 state.slowTimeFactor *= 0.95f;
228 }
229 else if (state.slowTimeFactor > 1.0f)
230 {
231 state.slowTimeFactor = ceil(state.slowTimeFactor * 20 - 1) / 20;
232 }
233 else
234 {
235 state.slowTimeFactor = std::max<float>(0.1f, state.slowTimeFactor - 0.05f);
236 }
237 fprintf(stderr, "slower %f\n", state.slowTimeFactor);
238 }
239
240 // faster simulation
241 if (state.lastKeyPressed == 'h')
242 {
243 if (state.slowTimeFactor > 1.20f)
244 {
245 state.slowTimeFactor *= 1.05f;
246 }
247 else if (state.slowTimeFactor > 1.0f)
248 {
249 state.slowTimeFactor = ceil(state.slowTimeFactor * 20 + 1) / 20;
250 }
251 else
252 {
253 state.slowTimeFactor += 0.05f;
254 }
255 fprintf(stderr, "faster %f\n", state.slowTimeFactor);
256 }
257
258 // shift forward XY display
259 if (state.lastKeyPressed == 'k')
260 {
261 fakeXorigin += 1;
262 if (fakeXorigin > ledW - 1)
263 fakeXorigin = 0;
264 fakeXend = std::max<int>(fakeXorigin - std::min<int>(4, ledW - 1 - fakeXorigin), 0);
265 }
266
267 // shift backward XY display
268 if (state.lastKeyPressed == 'j')
269 {
270 fakeXorigin -= 1;
271 if (fakeXorigin < 0)
272 fakeXorigin = ledW - 1;
273 fakeXend = std::max<int>(fakeXorigin - std::min<int>(4, ledW - 1 - fakeXorigin), 0);
274 }
275
276 // reset key pressed
277 state.lastKeyPressed = 0;
278 break;
279 }
280 else if (event.type == sf::Event::MouseButtonPressed)
281 {
282 float dx = indCoordX - mousePos.x + simu.buttonSize;
283 float dy = indCoordY - mousePos.y + simu.buttonSize;
284 float norm = simu.buttonSize;
285
286 if (dx * dx + dy * dy < norm * norm)
287 {
288 mouseClick += 3;
289 }
290 break;
291 }
292 }
293 }
294
295 // update simulator global state
296 state.isButtonPressed = (not lostFocus) and sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Space);
297 if (mouseClick > 0)
298 {
299 mouseClick -= 1;
300 state.isButtonPressed = true;
301 }
302
303 if (state.tickAndPause > 0)
304 {
305 if (state.tickAndPause == 1)
306 {
307 state.paused = true;
308 }
309 state.tickAndPause -= 1;
310 }
311
312 // TODO: #156 move mock-specific parts to another process
313 // ======================================================
314
315 if (!state.paused)
316 {
317 // deep sleep, exit
318 if (mock_registers::isDeepSleep)
319 {
320 // close all threads
321 window.close();
322 break;
323 }
324
325 // update simu parameters
327 // update the callbacks of the gpios (simulate interrupts)
328 mock_gpios::update_callbacks();
329
330 // main program loop
331 ::lampda::main_loop(mock_registers::addedAlgoDelay);
332 }
333
334 const bool isOutputEnabled = is_output_enabled();
336 {
337#ifdef LMBD_LAMP_TYPE__INDEXABLE
338 // brightness on the indexale lamp
340 static curve_t brightnessCurve = ::lampda::common::curves::make_linear_curve(
341 curve_t::point_t {::lampda::brightness::absoluteMinimumBrightness,
342 ::lampda::minimumAllowedBrightness_8},
343 curve_t::point_t {::lampda::brightness::absoluteMaximumBrightness, 255});
344 state.brightness = brightnessCurve.sample(::lampda::logic::brightness::get_brightness());
345
346 const bool isVoltageHighEnough = mock_electrical::outputVoltage > 11.5;
347 for (size_t I = 0; I < _LampTy::ledCount; ++I)
348 {
349 state.colorBuffer[I] =
350 isOutputEnabled ?
351 (isVoltageHighEnough ? ::lampda::user::_private::strip.getRawPixelColor(I) : 0xffffff) :
352 0;
353 }
354#endif
355 }
356 else
357 {
358 state.brightness =
359 (::lampda::logic::brightness::get_brightness() * 255) / ::lampda::brightness::absoluteMaximumBrightness;
360
361 for (size_t I = 0; I < _LampTy::ledCount; ++I)
362 state.colorBuffer[I] = isOutputEnabled ? 0xffff00 : 0;
363 }
364
365 state.indicatorColor = mock_indicator::get_color();
366 // ======================================================
367
368 const float ledSz = simu.ledSizePx;
369 const auto ledPadSz = simu.ledPaddingPx + simu.ledSizePx;
370 const auto ledOffset = ledSz / _LampTy::shiftPeriod;
371
372 const float Xbase = _LampTy::extraShiftTotal > 0 ? 0 : -_LampTy::extraShiftTotal;
373 const float Xextra = _LampTy::extraShiftTotal < 0 ? 0 : _LampTy::extraShiftTotal;
374
375 // draw slightly grey background to hightlight turned off LEDs
376 window.clear(sf::Color(13, 12, 11));
377
378 for (int Ypos = 0; Ypos < ledH; ++Ypos)
379 {
380 int realRowSize = ledW;
381 if (_LampTy::allDeltaResiduesY[Ypos])
382 realRowSize += 1;
383
384 for (int fXpos = -fakeXorigin; fXpos < realRowSize - fakeXend; ++fXpos)
385 {
386 int Yoff = 0;
387 int Xoff = 0;
388
389 int Xpos = fXpos;
390 if (fXpos < 0)
391 {
392 Xpos = realRowSize + fXpos;
393 Yoff = 1;
394
395 if (_LampTy::allDeltaResiduesY[Ypos])
396 Xoff = 1;
397 }
398
399 size_t I = ::lampda::modes::to_strip(Xpos, Ypos);
400 auto& shape = shapes[I];
401
402 auto realPos = ::lampda::modes::strip_to_XY(I);
403 if (realPos.x != Xpos || realPos.y != Ypos)
404 continue;
405
406 shape.setSize({ledSz, ledSz});
407
408 int rXpos = fXpos + fakeXorigin + Xoff;
409 int rYpos = Ypos + Yoff;
410 int shiftR = _LampTy::extraShiftResiduesY[Ypos];
411 int shiftL = Ypos + shiftR + 1;
412
413 if (_LampTy::shiftResidue == 1 && _LampTy::shiftPerTurn < 0.1)
414 shiftR = 0;
415
416 float shapeX = ledSz + rXpos * ledPadSz;
417 shapeX += ledOffset * Xbase;
418 shapeX += ledOffset * (shiftL % _LampTy::shiftPeriod);
419 shapeX -= (ledOffset - simu.ledPaddingPx / 2) * (Yoff - shiftR);
420 shapeX -= Xoff * simu.ledPaddingPx;
421
422 // make the origin more obvious
423 if (fXpos >= 0)
424 shapeX += simu.ledPaddingPx;
425
426 float shapeY = rYpos * ledPadSz;
427 shape.setPosition({shapeX, shapeY});
428
429 const uint32_t color = state.colorBuffer[I];
430 float b = (color & 0xff);
431 float g = ((color >> 8) & 0xff);
432 float r = ((color >> 16) & 0xff);
433
434#ifndef LMBD_DEBUG_SIMU_REALCOLORS
435 if (state.brightness != 255)
436 {
437 // scale by brightness
438 r = (uint16_t(r) * state.brightness + state.brightness) >> 8;
439 g = (uint16_t(g) * state.brightness + state.brightness) >> 8;
440 b = (uint16_t(b) * state.brightness + state.brightness) >> 8;
441 }
442#endif
443
444 shape.setFillColor(sf::Color(r, g, b));
445 window.draw(shape);
446
447 // display text information if mouse is pressed
448 if (enableText)
449 {
450 int MouseYpos = mousePos.y;
451 int MouseXpos = mousePos.x;
452
453 auto shapeXY = shape.getPosition();
454 float dx = shapeXY.x + ledSz / 2 - MouseXpos;
455 float dy = shapeXY.y + ledSz / 2 - MouseYpos;
456
457 // all shapes too far from cursor, does not display info
458 if (abs(2 * dx) > ledPadSz || abs(2 * dy) > ledPadSz)
459 continue;
460
461 // display (X,Y) on bottom-right
462 float largestX = ledSz + (ledW + 1 + fakeXorigin - fakeXend) * ledPadSz + ledOffset * (Xextra + Xbase);
463 float largestY = (ledH + Yoff) * ledPadSz + 8;
464 {
465 auto str = "(" + std::to_string(Xpos) + ", " + std::to_string(Ypos) + ")";
466
467 sf::Text text(str, font, 12);
468 sf::Vector2f where(largestX, largestY);
469 text.setPosition(where);
470 window.draw(text);
471 }
472
473 // display Ypos on the right
474 {
475 auto str = std::to_string(Ypos);
476 if (_LampTy::allDeltaResiduesY[Ypos])
477 str += " *";
478
479 sf::Text text(str, font, 12);
480 sf::Vector2f where(largestX, shapeXY.y + ledSz / 4);
481 text.setPosition(where);
482 window.draw(text);
483 }
484
485 // display Xpos on the bottom
486 {
487 auto str = std::to_string(Xpos);
488 if (Xpos == ledW)
489 str += " *";
490
491 sf::Text text(str, font, 12);
492 sf::Vector2f where(shapeXY.x, largestY);
493 text.setPosition(where);
494 window.draw(text);
495 }
496
497 // display misc info next to button
498 {
499 auto str = "(" + std::to_string(int(r)) + ", ";
500 str += std::to_string(int(g)) + ", ";
501 str += std::to_string(int(b)) + ")";
502 str += ", " + std::to_string(I);
503
504 sf::Text text(str, font, 12);
505 sf::Vector2f where(indCoordX + simu.buttonSize * 3, indCoordY - 24.f);
506 text.setPosition(where);
507 window.draw(text);
508
509 // (avoid superposed text)
510 enableText = false;
511 }
512 }
513 }
514 }
515
516 // display the indicator button
517 const uint32_t indicatorColor = state.indicatorColor;
518 float b = (indicatorColor & 0xff);
519 float g = ((indicatorColor >> 8) & 0xff);
520 float r = ((indicatorColor >> 16) & 0xff);
521 indicator.setFillColor(sf::Color(r, g, b));
522 indicator.setPosition({indCoordX, indCoordY});
523 buttonMask.setPosition({indCoordX + simu.buttonMargin, indCoordY + simu.buttonMargin});
524 window.draw(indicator);
525 window.draw(buttonMask);
526
527 // track brightness & display dot curve
528 float now = (time.getElapsedTime().asMilliseconds() * simu.fps) / 1000.f;
529 uint32_t trackerPos = now / simu.brightnessRate;
530
531 trackerPos = trackerPos % brightnessTracker.size();
532 brightnessTracker[trackerPos] = state.brightness;
533 brightnessTracker[(trackerPos + 1) % brightnessTracker.size()] = 0;
534
535 float xDotsOrigin = indCoordX + simu.buttonSize * 2 + simu.buttonMargin * 2 + 16.f;
536 float yDotsOrigin = indCoordY + simu.brightnessScale;
537
538 for (size_t I = 0; I < brightnessTracker.size(); ++I)
539 {
540 auto& dot = dots[I];
541
542 float v = (brightnessTracker[I] * simu.brightnessScale) / 256;
543 float x = xDotsOrigin + I;
544 float y = yDotsOrigin - v;
545 dot.setSize({1, 1});
546 dot.setPosition({x, y});
547 dot.setFillColor(sf::Color(0, 0xff, 0));
548 window.draw(dot);
549 }
550
551 // draw window
552 window.display();
553 }
554
555 stop_electrical_mock();
556
557 return 0;
558 }
559};
560
561} // namespace simulator
562
563#endif
Given a set of points, will fit multiple linear segments to it.
Definition: curves.h:36
General electrical simulation of the Lampda board.
Define specific needed user functions.
Main input point of the whole program.
Handle the physical simulation paremeters of a real lamp.
brightness_t get_brightness()
Return the current brightness value.
Definition: brightness_handle.cpp:42
@ indexable
Equivalent to LMBD_LAMP_TYPE__INDEXABLE.
static constexpr uint16_t to_strip(uint16_t, uint16_t)
convert grid coordinates to strip index
Definition: lamp_type.hpp:1224
static constexpr XYTy strip_to_XY(uint16_t n)
convert strip index to grid coordinates
Definition: lamp_type.hpp:1256
void main_setup()
Setup of the program, call once on systel start.
Definition: global.cpp:81
void main_loop(const uint32_t addedDelay)
Run the main program loop.
Definition: global.cpp:239
GlobalSimStateTy state
Store the global simulation state.
Definition: simulator_state.cpp:7
Simulator dedicated namespace.
Definition: BQ25713_mock.h:23
void read_and_update_parameters()
Read parameters from the parameter file, and update the simulation.
Definition: parameter_parser.h:29
Handle the modification of the simulation parameters by a file.
Contain some simulation state.
static constexpr float maxWidthFloat
Width as a precise floating point number, equal to stripXCoordinates.
Definition: lamp_type.hpp:379
static constexpr uint16_t maxOverflowHeight
Larger height, taken as the absolute maximum Y coordinate, overflowing.
Definition: lamp_type.hpp:403
static constexpr LampTypes flavor
Which lamp flavor is currently used by the implementation?
Definition: lamp_type.hpp:346
static constexpr uint16_t maxWidth
(indexable) Width of "pixel space" w/ lamp taken as a LED matrix
Definition: lamp_type.hpp:376
static constexpr uint16_t ledCount
(indexable) Count of indexable LEDs on the lamp
Definition: lamp_type.hpp:363
User defined constants, relative to specific lamp types.
Define useful functions.