Repository navigation
Expand file tree
/
Copy pathmoon_sphere.cpp
More file actions
680 lines (608 loc) · 30 KB
/
Copy pathmoon_sphere.cpp
File metadata and controls
680 lines (608 loc) · 30 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
/**
* @file moon_sphere.cpp
* @brief Render the Moon page as a textured, sub-solar-lit 3D sphere using the
* tgx software renderer (https://github.com/vindar/tgx).
*
* Ported from the ESP-IDF NINA project to this ESP32-P4 Arduino project.
* Adaptations vs. the NINA source:
* - Texture comes from the vendored byte array MOON_EQUIRECT_JPG (moon_equirect_data.h)
* decoded with stb_image, instead of a linker-embedded binary asset.
* - Orientation config comes from the global `configStorage` (config_storage.h)
* instead of app_config_get().
* - Logging uses the project LOG_*_F macros (logging.h) instead of ESP_LOG*.
* - New: moon_sphere_set_disk_scale() controls the disk size within the frame so
* the starfield/glow background can fill out to the screen edge.
*
* ESP32-P4 notes:
* - The P4 FPU is single precision only. tgx defaults TGX_SINGLE_PRECISION_COMPUTATIONS
* to 1, and all math in this file uses float / sqrtf. No double in hot paths.
* - Big buffers (color + z-buffer) live in PSRAM, 128-byte aligned for PPA.
*/
/* Force single precision before pulling in tgx (matches tgx default; explicit
* here in case a global -D ever flips it). */
#ifndef TGX_SINGLE_PRECISION_COMPUTATIONS
#define TGX_SINGLE_PRECISION_COMPUTATIONS 1
#endif
#include "moon_sphere.h"
#include "esp_heap_caps.h"
#include "freertos/FreeRTOS.h"
#include "freertos/semphr.h"
#include <math.h>
#include <string.h>
#include <tgx.h>
/* Project's vendored stb_image (implementation lives in stb_image.c, already
* compiled as C). Include the header with C linkage so this C++ TU does not
* name-mangle stbi_load_from_memory / stbi_image_free. Do NOT define
* STB_IMAGE_IMPLEMENTATION here. */
extern "C" {
#include "stb_image.h"
}
/* Vendored embedded lunar texture byte array (moon_equirect.jpg). Declares
* const unsigned char MOON_EQUIRECT_JPG[] and const unsigned int
* MOON_EQUIRECT_JPG_LEN. Included from exactly one TU (this one). */
#include "moon_equirect_data.h"
/* Runtime orientation config (moon flip U/V, roll/yaw/pitch offsets, north-up).
* This is the global ConfigStorage instance declared in config_storage.h. */
#include "config_storage.h"
/* Project logging macros (LOG_INFO_F / LOG_WARNING_F / LOG_ERROR_F). */
#include "logging.h"
using namespace tgx;
/* ----------------------------------------------------------------------------
* Disk scale (NEW vs. NINA). 1.0 = disk fills the frame edge-to-edge (identical
* to NINA's fixed ORTHO_R = 1.08). <1.0 shrinks the disk within the frame so the
* starfield/glow background fills out to the screen edge. Larger ORTHO_R -> a
* smaller disk, so ORTHO_R is derived as 1.08f / s_disk_scale. Clamped in the
* setter. Applied to the next render. */
static float s_disk_scale = 1.0f;
void moon_sphere_set_disk_scale(float scale)
{
if (scale < 0.2f) scale = 0.2f;
if (scale > 4.0f) scale = 4.0f;
s_disk_scale = scale;
}
/* ----------------------------------------------------------------------------
* Orientation tunables (compile-time fallbacks; the live path reads config).
* Defaults yield the STANDARD near-side naked-eye view: north up, selenographic
* EAST (Mare Crisium, +lon) on the RIGHT, lunar south (Tycho) at the BOTTOM.
*
* The texture U/V flips and the roll/yaw/pitch trims are RUNTIME config
* (configStorage.getMoonFlipU/V, getMoonRollOffset/getMoonYawOffset/
* getMoonPitchOffset), all defaulting to 0, so the default behavior matches this
* base orientation. Set MOON_DEBUG_GEOCENTRIC to 1 to force roll=0 AND
* libration=0 (north-up base) for direct comparison to a reference photo.
* --------------------------------------------------------------------------*/
#ifndef MOON_ROLL_SIGN
#define MOON_ROLL_SIGN (+1) /* flip to -1 if the disc rolls the wrong way */
#endif
#ifndef MOON_DEBUG_GEOCENTRIC
#define MOON_DEBUG_GEOCENTRIC 0 /* 1 = force roll=0 AND libration=0 to show the
north-up base for direct comparison */
#endif
/* RGB565 packer with clamping, named pack565() so it does not collide with the
* tgx::RGB565 type. Used only to draw the starfield + glow background directly
* into the color buffer. */
static inline uint16_t pack565(int r, int g, int b)
{
if (r < 0) r = 0;
if (r > 255) r = 255;
if (g < 0) g = 0;
if (g > 255) g = 255;
if (b < 0) b = 0;
if (b > 255) b = 255;
return (uint16_t)(((r & 0xF8) << 8) | ((g & 0xFC) << 3) | (b >> 3));
}
/* 4x4 ordered-dither (Bayer) matrix, used to fill RGB565 truncation slack in the
* warm glow halo so it does not band. */
static const uint8_t s_bayer4[4][4] = {
{ 0, 8, 2, 10},
{12, 4, 14, 6},
{ 3, 11, 1, 9},
{15, 7, 13, 5}
};
/* ----------------------------------------------------------------------------
* Lunar texture.
*
* Primary path: decode the vendored Clementine equirectangular map
* (MOON_EQUIRECT_JPG) into an RGB565 PSRAM buffer.
* Fallback path: if decode fails, generate the procedural placeholder below so
* the page never blanks.
* --------------------------------------------------------------------------*/
static const int PLACEHOLDER_TEX_W = 512;
static const int PLACEHOLDER_TEX_H = 256;
static uint16_t *s_tex_buf = nullptr; /* RGB565, s_tex_w*s_tex_h, PSRAM */
static int s_tex_w = 0; /* actual texture width */
static int s_tex_h = 0; /* actual texture height */
static Image<RGB565> s_tex; /* wraps s_tex_buf */
static bool s_inited = false;
static SemaphoreHandle_t s_init_mtx = nullptr;
/* Runtime flip state actually baked into s_tex_buf. Used to detect a config
* change in render_core and trigger a re-flip so flip toggles from the web UI
* take effect live. -1 = "no texture decoded yet". */
static int s_applied_flip_u = -1;
static int s_applied_flip_v = -1;
/* Simple value-noise-ish banding + a few darker "maria" blobs, grayscale.
* All float math; runs once at init so cost is irrelevant. */
static void generate_placeholder_texture()
{
/* "Maria" blob centers in texture space (u,v in [0,1]) and radii. */
struct { float u, v, r, depth; } maria[] = {
{ 0.32f, 0.42f, 0.13f, 0.45f },
{ 0.44f, 0.36f, 0.09f, 0.40f },
{ 0.55f, 0.30f, 0.07f, 0.35f },
{ 0.40f, 0.55f, 0.10f, 0.30f },
{ 0.62f, 0.50f, 0.06f, 0.25f },
{ 0.26f, 0.30f, 0.05f, 0.20f },
};
const int n_maria = (int)(sizeof(maria) / sizeof(maria[0]));
for (int y = 0; y < PLACEHOLDER_TEX_H; y++) {
float v = (float)y / (float)(PLACEHOLDER_TEX_H - 1);
for (int x = 0; x < PLACEHOLDER_TEX_W; x++) {
float u = (float)x / (float)(PLACEHOLDER_TEX_W - 1);
/* Base highland brightness with subtle latitude/longitude banding. */
float base = 0.72f
+ 0.06f * sinf(u * 18.0f)
+ 0.05f * sinf(v * 22.0f + 1.3f)
+ 0.03f * sinf((u + v) * 40.0f);
/* Darken inside maria blobs (wrap u for the longitude seam). */
float dark = 0.0f;
for (int m = 0; m < n_maria; m++) {
float du = u - maria[m].u;
/* shortest wrapped distance in u */
if (du > 0.5f) du -= 1.0f;
if (du < -0.5f) du += 1.0f;
float dv = v - maria[m].v;
float d2 = du * du + dv * dv;
float r2 = maria[m].r * maria[m].r;
if (d2 < r2) {
float t = 1.0f - sqrtf(d2) / maria[m].r; /* 1 at center */
dark += maria[m].depth * t * t;
}
}
float g = base - dark;
if (g < 0.05f) g = 0.05f;
if (g > 1.00f) g = 1.00f;
/* RGB565 from float [0,1] grayscale. */
s_tex(x, y) = RGB565(g, g, g);
}
}
}
/* Allocate the PSRAM RGB565 texture buffer for w*h pixels and wrap it with s_tex.
* Returns true on success and sets s_tex_w/s_tex_h. */
static bool alloc_texture(int w, int h)
{
/* Free any previously decoded buffer so re-decode does not leak PSRAM. On
* the first call s_tex_buf is NULL and this is a no-op. */
if (s_tex_buf) {
heap_caps_free(s_tex_buf);
s_tex_buf = nullptr;
}
size_t bytes = (size_t)w * (size_t)h * sizeof(uint16_t);
s_tex_buf = (uint16_t *)heap_caps_malloc(bytes, MALLOC_CAP_SPIRAM);
if (!s_tex_buf) {
LOG_ERROR_F("[MoonSphere] PSRAM lunar texture alloc failed (%dx%d, %u bytes)\n",
w, h, (unsigned)bytes);
return false;
}
s_tex_w = w;
s_tex_h = h;
/* Wrap the PSRAM buffer; stride == width for a tight buffer. */
s_tex.set(s_tex_buf, w, h, w);
return true;
}
/* RUNTIME texture mirrors applied in place to the already-filled texture buffer.
* Flip state comes from the live config (configStorage.getMoonFlipU/V):
* - flip_u mirrors columns (x -> w-1-x): east<->west longitude swap.
* - flip_v mirrors rows (y -> h-1-y): north<->south latitude swap.
* Both default OFF, so the base orientation is unchanged on defaults. The mirror
* helpers are self-inverse, so toggling an axis from the web UI is just one more
* mirror of that axis. */
static void mirror_texture_u(void)
{
for (int y = 0; y < s_tex_h; y++) {
uint16_t *row = s_tex_buf + (size_t)y * (size_t)s_tex_w;
for (int x = 0; x < s_tex_w / 2; x++) {
uint16_t t = row[x];
row[x] = row[s_tex_w - 1 - x];
row[s_tex_w - 1 - x] = t;
}
}
}
static void mirror_texture_v(void)
{
for (int y = 0; y < s_tex_h / 2; y++) {
uint16_t *a = s_tex_buf + (size_t)y * (size_t)s_tex_w;
uint16_t *b = s_tex_buf + (size_t)(s_tex_h - 1 - y) * (size_t)s_tex_w;
for (int x = 0; x < s_tex_w; x++) {
uint16_t t = a[x];
a[x] = b[x];
b[x] = t;
}
}
}
static void apply_texture_flips(void)
{
int flip_u = configStorage.getMoonFlipU() ? 1 : 0;
int flip_v = configStorage.getMoonFlipV() ? 1 : 0;
if (flip_u) mirror_texture_u();
if (flip_v) mirror_texture_v();
/* Remember what is now baked into the buffer for live re-flip detection. */
s_applied_flip_u = flip_u;
s_applied_flip_v = flip_v;
}
/* Build the procedural placeholder texture (fallback when the real JPEG fails
* to decode). Allocates its own buffer at the placeholder dimensions. */
static bool init_placeholder_texture(void)
{
if (!alloc_texture(PLACEHOLDER_TEX_W, PLACEHOLDER_TEX_H)) return false;
generate_placeholder_texture();
apply_texture_flips();
LOG_WARNING_F("[MoonSphere] using procedural placeholder lunar texture %dx%d "
"(real texture decode unavailable)\n",
PLACEHOLDER_TEX_W, PLACEHOLDER_TEX_H);
return true;
}
/* Decode the vendored Clementine equirectangular JPEG into the RGB565 PSRAM
* texture. Returns true on success. On any failure leaves s_tex untouched and
* s_tex_buf NULL so the caller can fall back to the placeholder.
*
* Source convention: equirectangular, north-up, longitude -180..+180 left-to-
* right with 0 centered. Loaded as-is: top row = north, columns left-to-right
* as stored. */
static bool init_real_texture(void)
{
size_t len = (size_t)MOON_EQUIRECT_JPG_LEN;
if (len == 0) {
LOG_WARNING_F("[MoonSphere] embedded moon_equirect.jpg is empty\n");
return false;
}
int w = 0, h = 0, ch = 0;
/* Force 3 channels (RGB). req_comp=3 => stb returns 3 bytes per pixel (R,G,B). */
unsigned char *img = stbi_load_from_memory(MOON_EQUIRECT_JPG,
(int)len, &w, &h, &ch, 3);
if (img == nullptr) {
LOG_WARNING_F("[MoonSphere] stbi decode of moon_equirect.jpg failed: %s\n",
stbi_failure_reason() ? stbi_failure_reason() : "unknown");
return false;
}
if (w <= 0 || h <= 0) {
LOG_WARNING_F("[MoonSphere] moon_equirect.jpg bad dimensions %dx%d\n", w, h);
stbi_image_free(img);
return false;
}
if (!alloc_texture(w, h)) {
stbi_image_free(img);
return false;
}
/* Convert each RGB triplet to RGB565: R5 = r>>3, G6 = g>>2, B5 = b>>3.
* stb returned 3 bytes/pixel in R,G,B order (req_comp=3). */
const unsigned char *src = img;
for (int y = 0; y < h; y++) {
uint16_t *dst = s_tex_buf + (size_t)y * (size_t)w;
for (int x = 0; x < w; x++) {
unsigned int r = *src++;
unsigned int g = *src++;
unsigned int b = *src++;
dst[x] = (uint16_t)(((r & 0xF8) << 8) | ((g & 0xFC) << 3) | (b >> 3));
}
}
stbi_image_free(img);
apply_texture_flips();
LOG_INFO_F("[MoonSphere] decoded real lunar texture %dx%d (src channels=%d) "
"from moon_equirect.jpg\n", w, h, ch);
return true;
}
extern "C" bool moon_sphere_init(void)
{
if (!s_init_mtx) s_init_mtx = xSemaphoreCreateMutex();
if (s_init_mtx) xSemaphoreTake(s_init_mtx, portMAX_DELAY);
if (!s_inited) {
/* Primary path: real embedded texture. Fallback: procedural placeholder. */
if (init_real_texture() || init_placeholder_texture()) {
s_inited = true;
}
}
if (s_init_mtx) xSemaphoreGive(s_init_mtx);
return s_inited;
}
/* Apply a live flip-config change to the EXISTING decoded texture buffer in
* place, with no JPEG re-decode. A flip is a row/column mirror, which is its own
* inverse, so toggling an axis = mirroring that axis once. Guarded by the init
* mutex. No-op when the flip state already matches (the common steady-state
* path, zero cost). */
static void moon_sphere_reflip_if_changed(void)
{
int want_u = configStorage.getMoonFlipU() ? 1 : 0;
int want_v = configStorage.getMoonFlipV() ? 1 : 0;
if (want_u == s_applied_flip_u && want_v == s_applied_flip_v) return;
if (s_init_mtx) xSemaphoreTake(s_init_mtx, portMAX_DELAY);
/* Re-check under the lock in case another task already re-flipped. */
if (want_u != s_applied_flip_u || want_v != s_applied_flip_v) {
if (s_tex_buf == nullptr) {
/* No texture decoded yet (shouldn't happen post-init): do a full
* decode, which applies the current flips itself. */
if (!init_real_texture()) init_placeholder_texture();
} else {
/* Apply only the delta in place. Column/row mirrors commute and are
* self-inverse, so mirroring the changed axis once reaches the target
* state from any prior state. */
if (want_u != s_applied_flip_u) {
mirror_texture_u();
s_applied_flip_u = want_u;
}
if (want_v != s_applied_flip_v) {
mirror_texture_v();
s_applied_flip_v = want_v;
}
}
}
if (s_init_mtx) xSemaphoreGive(s_init_mtx);
}
/* Shaders compiled into the renderer:
* orthographic projection + z-buffer + Gouraud (per-vertex Lambert/diffuse)
* shading + bilinear texture sampling with power-of-two wrapping. GOURAUD (not
* FLAT) so the sphere is lit per-vertex with normals interpolated across each
* triangle, avoiding the faint facet grid FLAT shading produces. */
static const Shader LOADED_SHADERS =
SHADER_ORTHO | SHADER_ZBUFFER | SHADER_GOURAUD |
SHADER_TEXTURE_BILINEAR | SHADER_TEXTURE_WRAP_POW2;
/* Core sphere renderer. Rasterizes into `color_buf` (RGB565) using `zbuf` as the
* depth buffer; both must be w*h uint16 and 128-byte aligned (PPA / cache line).
* The caller owns both buffers and their lifetime. */
static uint16_t *moon_sphere_render_core(int w, int h, const moon_state_t *st,
int nb_sectors, int nb_stacks,
uint8_t bg_style,
float yaw_deg, float pitch_deg,
moon_light_mode_t light_mode,
uint16_t *color_buf, uint16_t *zbuf)
{
const size_t npix = (size_t)w * (size_t)h;
const size_t color_sz = npix * sizeof(uint16_t);
/* Disk-scale-derived orthographic half-extent (NEW vs. NINA). With
* s_disk_scale == 1.0 this equals NINA's fixed 1.08 (disk fills the frame).
* Larger ORTHO_R -> a smaller disk within the frame, leaving the starfield/
* glow background to fill out to the screen edge. Used for BOTH the renderer
* setOrtho() AND the glow-halo R_disc geometry so the glow tracks the disk. */
const float ORTHO_R = 1.08f / s_disk_scale;
/* If the flip config changed since the texture was last decoded, re-apply the
* flips now so web-UI flip toggles take effect live. No-op when unchanged. */
moon_sphere_reflip_if_changed();
/* ----- Background ----------------------------------------------------
* Drawn DIRECTLY into color_buf BEFORE the sphere is rasterized, across the
* WHOLE w*h buffer, so the background fills to the screen edge regardless of
* disk size. The Renderer3D only writes the pixels the disc covers, so the
* background shows through everywhere outside the lunar disc. Do NOT call
* im.fillScreen() after this, it would erase the background.
* bit 0 (bg_style 1 or 3): deterministic starfield
* bit 1 (bg_style 2 or 3): soft warm glow halo just outside the disc
* bg_style 0: plain black */
Image<RGB565> im(color_buf, w, h, w);
/* 1. Black base. */
memset(color_buf, 0, color_sz); /* RGB565 0x0000 */
/* 2. Deterministic starfield (fixed LCG seed for frame-stable stars). */
if (bg_style & 1) {
uint32_t seed = 1234567u;
int nstars = (w * h) / 900;
for (int i = 0; i < nstars; i++) {
seed = seed * 1103515245u + 12345u;
int sx = (int)((seed >> 8) % (uint32_t)w);
seed = seed * 1103515245u + 12345u;
int sy = (int)((seed >> 8) % (uint32_t)h);
int br = 120 + (int)((seed >> 4) & 0x7F);
color_buf[(size_t)sy * w + sx] = pack565(br, br, br);
}
}
/* 3. Soft warm glow halo: additive ring in [R_disc, R_disc*1.35].
* Disc geometry: the sphere is unit radius and setOrtho uses half-extent
* ORTHO_R, so the disc pixel radius is (1.0/ORTHO_R) * 0.5 * min(w,h). This
* uses the SAME disk-scale-derived ORTHO_R as setOrtho below, so the glow
* tracks the disk size. */
if (bg_style & 2) {
const float R_disc = (1.0f / ORTHO_R) * 0.5f * (float)((w < h) ? w : h);
const float cx = (float)(w - 1) * 0.5f;
const float cy = (float)(h - 1) * 0.5f;
const float R_disc2 = R_disc * R_disc;
const float Rout = R_disc * 1.35f;
const float Rout2 = Rout * Rout;
const float inv_band = 1.0f / (R_disc * 0.35f);
for (int py = 0; py < h; py++) {
float dy = (float)py - cy;
uint16_t *row = color_buf + (size_t)py * w;
for (int px = 0; px < w; px++) {
float dx = (float)px - cx;
float r2 = dx * dx + dy * dy;
if (r2 <= R_disc2 || r2 >= Rout2) continue;
float dist = sqrtf(r2);
float t = 1.0f - (dist - R_disc) * inv_band; /* 1 at disc edge -> 0 */
int add = (int)(40.0f * t);
uint16_t c = row[px];
int r = ((c >> 11) & 0x1F) * 255 / 31 + add;
int g = ((c >> 5) & 0x3F) * 255 / 63 + add * 9 / 10; /* warm */
int b = ( c & 0x1F) * 255 / 31 + add * 7 / 10; /* warm */
/* Ordered dither fills RGB565 truncation slack (kills rings). */
int dr = s_bayer4[py & 3][px & 3] >> 1; /* 0..7 */
int dg = s_bayer4[py & 3][px & 3] >> 2; /* 0..3 */
int db = dr;
row[px] = pack565(r + dr, g + dg, b + db);
}
}
}
/* ----- Set up the renderer ------------------------------------------- */
Renderer3D<RGB565, LOADED_SHADERS, uint16_t> renderer;
renderer.setViewportSize(w, h);
renderer.setOffset(0, 0);
renderer.setImage(&im);
renderer.setZbuffer(zbuf);
renderer.clearZbuffer();
renderer.setCulling(1);
/* Orthographic box sized to a unit sphere (radius 1) using the disk-scale-
* derived ORTHO_R half-extent. near/far bracket the sphere on the z axis. */
renderer.setOrtho(-ORTHO_R, ORTHO_R, -ORTHO_R, ORTHO_R, 0.1f, 10.0f);
/* Diffuse-only (Lambert) material: ambient low so the unlit limb goes dark
* (terminator), diffuse high, specular off. Warm tint so the lit moon reads
* warm-gray rather than neutral; the texture grayscale still shows through. */
renderer.setShaders(SHADER_GOURAUD | SHADER_TEXTURE_BILINEAR | SHADER_TEXTURE_WRAP_POW2);
renderer.setMaterialColor(RGBf(1.0f, 0.96f, 0.86f));
renderer.setMaterialAmbiantStrength(0.06f);
renderer.setMaterialDiffuseStrength(1.0f);
renderer.setMaterialSpecularStrength(0.0f);
renderer.setLightAmbiant(RGBf(1.0f, 1.0f, 1.0f));
renderer.setLightDiffuse(RGBf(1.0f, 1.0f, 1.0f));
renderer.setLightSpecular(RGBf(0.0f, 0.0f, 0.0f));
/* ----- Model matrix: orient the disc -------------------------------
* tgx sphere + camera conventions (verified against the tgx sources):
* drawSphere() places a surface vertex at stack angle phi and sector angle
* theta at P = (sinPhi*cosTheta, cosPhi, sinPhi*sinTheta), so the POLE axis
* is +Y and longitude theta winds +X -> +Z -> -X -> -Z. Texture coords are
* u = theta/2pi, v = 0.5*cosPhi + 0.5. The equirectangular map is north-up
* (top row = lunar NORTH), so the texture maps NORTH to v=0 = geometry -Y.
*
* The base orientation Ry(90)*Rx(180) maps EAST->+X (right), NORTH->+Y (up),
* SOUTH->-Y (bottom), sub-Earth -> +Z (toward the eye): the standard near
* side, not mirrored. Libration pre-rotates the body so the sub-Earth point
* lands at -X before the base rotation; Rz(roll) applies the parallactic
* roll about the view (+Z) axis.
*
* Net vertex transform (innermost -> outermost):
* Ry(lib_lon) -> Rz(-lib_lat) -> Rx(180) -> Ry(90) -> Rz(roll)
* Lighting is computed in this same body frame and rotated by R; the lit
* fraction is invariant under R, so this only re-orients the lit disc on
* screen without touching the phase. MOON_DEBUG_GEOCENTRIC zeroes libration
* + roll to expose the base.
*/
#if MOON_DEBUG_GEOCENTRIC
float lib_lon_deg = 0.0f;
float lib_lat_deg = 0.0f;
float roll_deg = 0.0f;
/* Geocentric debug exposes the clean base view: also ignore the user
* drag-to-rotate so yaw/pitch cannot perturb the reference orientation. */
yaw_deg = 0.0f;
pitch_deg = 0.0f;
#else
const float RAD2DEG = 57.2957795131f;
float lib_lon_deg = st->lib_lon * RAD2DEG;
float lib_lat_deg = st->lib_lat * RAD2DEG;
/* North-up handling: configStorage.getMoonNorthUp() == 1 forces the disc
* upright/north-up (the geocentric north-up convention) by IGNORING the
* parallactic/topocentric roll (st->roll); libration, phase, and the live
* roll-trim offset still apply. When == 0 use st->roll (the located /
* parallactic sky orientation). This mirrors NINA's moon_north_up flag.
* (st->axis_P is the pre-parallactic axis position angle; the north-up
* convention corresponds to no parallactic tilt, i.e. roll contribution 0.) */
uint8_t north_up = configStorage.getMoonNorthUp();
float roll_deg = ((north_up == 1) ? 0.0f
: (float)(MOON_ROLL_SIGN) * st->roll * RAD2DEG)
+ configStorage.getMoonRollOffset(); /* offset still applies */
/* Live yaw/pitch offsets from config, added to the drag-supplied yaw/pitch.
* Inside the #else branch so MOON_DEBUG_GEOCENTRIC (which zeroes yaw/pitch)
* still wins when debug is enabled. */
yaw_deg += configStorage.getMoonYawOffset();
pitch_deg += configStorage.getMoonPitchOffset();
#endif
/* R_sky: the SKY orientation rotation (libration + base + parallactic roll).
* Rotation-only; used UNCHANGED to place the sub-solar light into world space
* so the sun stays fixed in the sky regardless of the user's drag yaw/pitch. */
fMat4 R_sky;
R_sky.setIdentity();
R_sky.multRotate(lib_lon_deg, fVec3(0.0f, 1.0f, 0.0f)); /* longitude libration */
R_sky.multRotate(-lib_lat_deg, fVec3(0.0f, 0.0f, 1.0f)); /* latitude libration */
R_sky.multRotate(180.0f, fVec3(1.0f, 0.0f, 0.0f)); /* base: flip v (north up) */
R_sky.multRotate(90.0f, fVec3(0.0f, 1.0f, 0.0f)); /* base: sub-Earth -> +Z */
R_sky.multRotate(roll_deg, fVec3(0.0f, 0.0f, 1.0f)); /* parallactic roll */
/* M_rot: the MODEL rotation = R_sky with the user drag-to-rotate applied
* OUTERMOST (pitch then yaw appended after the sky-orientation calls). The
* light is built from R_sky only, so the features rotate under a fixed
* sub-solar point in TRUE_PHASE. */
fMat4 M_rot = R_sky;
M_rot.multRotate(pitch_deg, fVec3(1.0f, 0.0f, 0.0f)); /* drag: pitch (screen-horiz) */
M_rot.multRotate(yaw_deg, fVec3(0.0f, 1.0f, 0.0f)); /* drag: yaw (screen-vert) */
fMat4 M = M_rot;
/* Push the unit sphere down -Z so it lands between zNear (0.1) and zFar (10),
* centered at z = -2 (camera at origin looking toward -Z). */
M.multTranslate(fVec3(0.0f, 0.0f, -2.0f));
renderer.setModelMatrix(M);
/* ----- Lighting: directional light from the sub-solar point ----------
* st->sun_lon / st->sun_lat are the sub-solar selenographic coordinates.
* Build the unit vector to the sun-lit surface point in the body frame, then
* rotate it by R_sky into world space. setLightDirection() expects the
* direction pointing TOWARD the light source; sun_w already points toward the
* Sun, so pass it directly, no negation. */
float clat = cosf(st->sun_lat);
fVec3 sun_body(clat * cosf(st->sun_lon),
sinf(st->sun_lat),
clat * sinf(st->sun_lon));
fVec4 sun_w4 = R_sky.mult0(sun_body); /* rotate dir into world space */
fVec3 sun_w(sun_w4.x, sun_w4.y, sun_w4.z);
float n = sqrtf(sun_w.x * sun_w.x + sun_w.y * sun_w.y + sun_w.z * sun_w.z);
if (n > 1e-6f) { sun_w.x /= n; sun_w.y /= n; sun_w.z /= n; }
if (light_mode == MOON_LIGHT_EXPLORE) {
/* Explore view: light the whole disc so the user can inspect the far
* side while spinning. Raise ambient near full and drop diffuse to a
* gentle view-aligned headlight (-Z) for mild shading with no night side. */
renderer.setMaterialAmbiantStrength(0.95f);
renderer.setMaterialDiffuseStrength(0.15f);
renderer.setLightDirection(fVec3(0.0f, 0.0f, -1.0f));
} else {
/* True sub-solar phase: keep the directional sub-solar light so the real
* phase terminator shows (material/light defaults set above). */
renderer.setLightDirection(fVec3(sun_w.x, sun_w.y, sun_w.z));
}
/* ----- Draw the textured sphere -------------------------------------- */
renderer.drawSphere(nb_sectors, nb_stacks, &s_tex);
/* Both buffers are caller-owned; do NOT free here. Return the color buffer. */
return color_buf;
}
/* Render into CALLER-PROVIDED color + z buffers (no per-frame alloc/free). Both
* must be w*h uint16 and 128-byte aligned (PPA / cache line). Returns color_buf
* on success, nullptr on bad args. */
extern "C" uint16_t *moon_sphere_render_into(int w, int h, const moon_state_t *st,
int nb_sectors, int nb_stacks,
uint8_t bg_style,
float yaw_deg, float pitch_deg,
moon_light_mode_t light_mode,
uint16_t *color_buf, uint16_t *zbuf)
{
if (w <= 0 || h <= 0 || st == nullptr || color_buf == nullptr || zbuf == nullptr)
return nullptr;
if (!moon_sphere_init()) return nullptr;
return moon_sphere_render_core(w, h, st, nb_sectors, nb_stacks, bg_style,
yaw_deg, pitch_deg, light_mode, color_buf, zbuf);
}
extern "C" uint16_t *moon_sphere_render_ex(int w, int h, const moon_state_t *st,
int nb_sectors, int nb_stacks,
uint8_t bg_style,
float yaw_deg, float pitch_deg,
moon_light_mode_t light_mode)
{
if (w <= 0 || h <= 0 || st == nullptr) return nullptr;
/* Lazy init of the texture. */
if (!moon_sphere_init()) return nullptr;
const size_t npix = (size_t)w * (size_t)h;
const size_t color_sz = npix * sizeof(uint16_t);
const size_t z_sz = npix * sizeof(uint16_t);
/* Color + z-buffer in PSRAM, 128-byte aligned (PPA / cache line). */
uint16_t *color_buf =
(uint16_t *)heap_caps_aligned_alloc(128, color_sz, MALLOC_CAP_SPIRAM);
uint16_t *zbuf =
(uint16_t *)heap_caps_aligned_alloc(128, z_sz, MALLOC_CAP_SPIRAM);
if (!color_buf || !zbuf) {
LOG_ERROR_F("[MoonSphere] PSRAM alloc failed (color=%p z=%p, %dx%d)\n",
(void *)color_buf, (void *)zbuf, w, h);
if (color_buf) heap_caps_free(color_buf);
if (zbuf) heap_caps_free(zbuf);
return nullptr; /* caller keeps previous frame */
}
moon_sphere_render_core(w, h, st, nb_sectors, nb_stacks,
bg_style, yaw_deg, pitch_deg,
light_mode, color_buf, zbuf);
/* z-buffer no longer needed; return only the color buffer (caller frees). */
heap_caps_free(zbuf);
return color_buf;
}
/* Thin wrapper: the original sub-solar-lit, no-user-rotation render. */
extern "C" uint16_t *moon_sphere_render(int w, int h, const moon_state_t *st,
int nb_sectors, int nb_stacks,
uint8_t bg_style)
{
return moon_sphere_render_ex(w, h, st, nb_sectors, nb_stacks, bg_style,
0.0f, 0.0f, MOON_LIGHT_TRUE_PHASE);
}