-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
2000 lines (1815 loc) · 83.2 KB
/
Copy pathindex.html
File metadata and controls
2000 lines (1815 loc) · 83.2 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
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Agrivoltaic Canopy Generator</title>
<style>
:root { --bg:#0d0f12; --panel:rgba(18,20,24,0.93); --line:#2c313a; --accent:#7cc4ff; --text:#dfe4ea; --dim:#8b939f; }
* { box-sizing: border-box; }
body { margin:0; overflow:hidden; font:12px/1.45 ui-monospace,Menlo,Consolas,monospace; background:var(--bg); color:var(--text); }
canvas { display:block; }
#ui {
position:absolute; top:12px; left:12px; width:330px; max-height:calc(100vh - 24px);
overflow-y:auto; background:var(--panel); border:1px solid var(--line); border-radius:8px;
padding:12px; box-shadow:0 8px 28px rgba(0,0,0,.6); backdrop-filter:blur(6px);
}
#ui::-webkit-scrollbar { width:8px; }
#ui::-webkit-scrollbar-thumb { background:#333a44; border-radius:4px; }
h1 { font-size:13px; margin:0 0 2px; letter-spacing:.08em; text-transform:uppercase; color:var(--accent); }
.sub { color:var(--dim); font-size:10.5px; margin:0 0 10px; }
fieldset { border:1px solid var(--line); border-radius:6px; margin:0 0 10px; padding:8px 9px 10px; }
legend { font-size:10px; letter-spacing:.1em; text-transform:uppercase; color:var(--accent); padding:0 5px; }
label { display:block; font-size:10.5px; color:var(--dim); margin-bottom:2px; }
.row { display:flex; gap:6px; align-items:flex-end; margin-bottom:7px; }
.row > div { flex:1; min-width:0; }
input[type=number], select {
width:100%; background:#181c22; color:var(--text); border:1px solid #39404b;
border-radius:4px; padding:4px 5px; font:inherit;
}
input[type=range] { width:100%; accent-color:var(--accent); }
input:focus, select:focus { outline:1px solid var(--accent); border-color:var(--accent); }
.invalid { border-color:#c0554b !important; }
button {
background:#232932; color:var(--text); border:1px solid #3c444f; border-radius:4px;
padding:5px 8px; cursor:pointer; font:inherit; width:100%;
}
button:hover { background:#2e3641; border-color:#4d5866; }
button.primary { background:#1e4a72; border-color:#2f6ea8; }
button.primary:hover { background:#245c8c; }
.btn-row { display:flex; gap:6px; }
table { width:100%; border-collapse:collapse; margin-top:6px; font-size:11px; }
th { color:var(--dim); font-weight:normal; font-size:10px; text-transform:uppercase; padding:3px 2px; border-bottom:1px solid var(--line); }
td { padding:2px; }
td input { padding:2px 3px; text-align:center; }
.del-btn { background:#3a2326; border-color:#5c3339; padding:2px 0; }
.del-btn:hover { background:#4d2c30; }
.toggles { display:flex; flex-wrap:wrap; gap:8px 12px; }
.toggles label { display:flex; align-items:center; gap:5px; margin:0; color:var(--text); font-size:11px; cursor:pointer; }
.toggles input { accent-color:var(--accent); }
#stats { display:grid; grid-template-columns:1fr auto; gap:1px 8px; font-size:11px; }
#stats .k { color:var(--dim); }
#stats .v { text-align:right; font-variant-numeric:tabular-nums; }
.sites { display:grid; grid-template-columns:1fr 1fr; gap:4px; }
.sites button { padding:4px 5px; font-size:10.5px; text-align:left; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
.sites button.on { background:#1e4a72; border-color:#2f6ea8; color:#fff; }
#sitenote { color:var(--dim); font-size:10px; margin:6px 0 8px; min-height:14px; }
#legend { margin-top:7px; font-size:10.5px; display:none; }
#legend div { display:flex; align-items:center; gap:6px; padding:1px 0; }
#legend i { width:9px; height:9px; border-radius:2px; flex:none; }
#legend b { margin-left:auto; color:var(--dim); font-weight:normal; font-variant-numeric:tabular-nums; }
#msg { min-height:15px; font-size:10.5px; color:#e0b062; margin-top:6px; }
#hud {
position:absolute; bottom:12px; left:12px; color:var(--dim); font-size:10.5px;
background:var(--panel); border:1px solid var(--line); border-radius:6px; padding:6px 9px;
}
.val { color:var(--accent); float:right; font-variant-numeric:tabular-nums; }
#loaderr { position:absolute; inset:0; display:none; place-items:center; text-align:center; padding:40px; color:#e08a7a; }
</style>
</head>
<body>
<div id="ui">
<h1>Agrivoltaic Canopy Generator</h1>
<p class="sub">Tensile canopy form-found over a grid of brick homes. Homes are the structural pylons; masts sit at the high points between them. Units = feet.</p>
<fieldset>
<legend>Site & season</legend>
<div class="sites" id="site-btns"></div>
<div id="sitenote"></div>
<label>Season <span class="val" id="lbl-day">21 Jun</span></label>
<input type="range" id="cfg-day" min="1" max="365" step="1" value="172">
</fieldset>
<fieldset>
<legend>Neighborhood</legend>
<div class="row">
<div><label>Grid</label>
<select id="cfg-grid">
<option value="2">2 × 2</option>
<option value="3" selected>3 × 3</option>
<option value="4">4 × 4</option>
<option value="5">5 × 5</option>
</select>
</div>
<div><label>Pitch (ft)</label><input type="number" id="cfg-pitch" value="80" min="40" max="200" step="4"></div>
<div><label>Home (ft)</label><input type="number" id="cfg-home" value="32" min="12" max="60" step="4"></div>
</div>
<div class="row">
<div><label>Home height</label><input type="number" id="cfg-hh" value="21" min="8" max="45" step="1"></div>
<div><label>Mast top (anchor)</label><input type="number" id="cfg-mast" value="30" min="10" max="60" step="1"></div>
</div>
</fieldset>
<fieldset>
<legend>Canopy control nodes</legend>
<p class="sub" style="margin:0 0 7px">dx / dz are measured out from a home <b>corner</b>; dy is height above grade. Each node is mirrored 8 ways around every home.</p>
<div class="row">
<div><label>dx</label><input type="number" id="inp-dx" value="24" step="1"></div>
<div><label>dy (height)</label><input type="number" id="inp-dy" value="46" step="1"></div>
<div><label>dz</label><input type="number" id="inp-dz" value="24" step="1"></div>
</div>
<button class="primary" id="btn-add">Add symmetric node</button>
<table>
<thead><tr><th>dx</th><th>dy</th><th>dz</th><th style="width:24px"></th></tr></thead>
<tbody id="point-body"></tbody>
</table>
<div class="btn-row" style="margin-top:7px">
<button id="btn-preset-peak">Peak</button>
<button id="btn-preset-saddle">Saddle</button>
<button id="btn-clear">Clear</button>
</div>
<div id="msg"></div>
</fieldset>
<fieldset>
<legend>Surface</legend>
<div class="row">
<div><label>Style</label>
<select id="cfg-style">
<option value="net" selected>Cable net</option>
<option value="fabric">Fabric / shade cloth</option>
<option value="none">Hidden</option>
</select>
</div>
<div><label>Mesh</label>
<select id="cfg-res">
<option value="4">Coarse</option>
<option value="2.5" selected>Medium</option>
<option value="1.5">Fine</option>
</select>
</div>
</div>
<label>Form-finding relaxation <span class="val" id="lbl-relax">300</span></label>
<input type="range" id="cfg-relax" min="0" max="800" step="25" value="300">
<label>Sag over the clear span <span class="val" id="lbl-sag">2.0 ft</span></label>
<input type="range" id="cfg-sag" min="0" max="12" step="0.5" value="2">
<label>Mast head Ø <span class="val" id="lbl-head">8 ft</span></label>
<input type="range" id="cfg-head" min="0" max="24" step="1" value="8">
<div class="toggles" style="margin-top:8px">
<label><input type="checkbox" id="cfg-controlnet"> Control net</label>
<label><input type="checkbox" id="cfg-masts" checked> Masts & ties</label>
</div>
</fieldset>
<fieldset>
<legend>Solar / shade</legend>
<label>Panel coverage <span class="val" id="lbl-cov">50%</span></label>
<input type="range" id="cfg-cov" min="0" max="100" step="5" value="50">
<label>Panel size (ft) <span class="val" id="lbl-panel">8</span></label>
<input type="range" id="cfg-panel" min="4" max="16" step="2" value="8">
<label>Hour of day <span class="val" id="lbl-hour">13:00</span></label>
<input type="range" id="cfg-hour" min="6" max="19" step="0.05" value="13">
<div class="toggles" style="margin-top:8px">
<label><input type="checkbox" id="cfg-shadows" checked> Shadows</label>
<label><input type="checkbox" id="cfg-homes" checked> Homes</label>
<label><input type="checkbox" id="cfg-daycycle"> Run the day (15 s / hour)</label>
</div>
</fieldset>
<fieldset>
<legend>Sun map & growth</legend>
<p class="sub" style="margin:0 0 7px">Sun per square foot, integrated over the whole day's sweep for this
latitude and season, then planted with whatever that light and moisture supports.</p>
<label>Irrigation <span class="val" id="lbl-water">30%</span></label>
<input type="range" id="cfg-water" min="0" max="100" step="5" value="30">
<div class="toggles" style="margin-top:8px">
<label><input type="checkbox" id="cfg-sunmap"> Sun map</label>
<label><input type="checkbox" id="cfg-growth" checked> Green ground</label>
<label><input type="checkbox" id="cfg-plants" checked> Planting</label>
<label><input type="checkbox" id="cfg-walls" checked> On homes</label>
</div>
<div id="legend"></div>
</fieldset>
<fieldset>
<legend>Readout</legend>
<div id="stats"></div>
</fieldset>
<fieldset>
<legend>View & export</legend>
<div class="btn-row" style="margin-bottom:6px">
<button id="v-over">Overview</button>
<button id="v-top">Plan</button>
<button id="v-street">Street</button>
</div>
<div class="btn-row">
<button id="btn-obj">Export .obj</button>
<button id="btn-json">Save .json</button>
</div>
</fieldset>
</div>
<div id="hud">drag = orbit | right-drag = pan | wheel = zoom</div>
<div id="loaderr"></div>
<script>
// ---------------------------------------------------------------------------
// Library loading: CDN first, local ./vendor copies as fallback (offline use).
// ---------------------------------------------------------------------------
const LIBS = [
['https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js', 'vendor/three.min.js'],
['https://cdn.jsdelivr.net/npm/three@0.128.0/examples/js/controls/OrbitControls.js', 'vendor/OrbitControls.js'],
['https://unpkg.com/delaunator@5.0.0/delaunator.min.js', 'vendor/delaunator.min.js'],
];
function loadScript(src) {
return new Promise((res, rej) => {
const s = document.createElement('script');
s.src = src; s.onload = res; s.onerror = () => rej(new Error(src));
document.head.appendChild(s);
});
}
(async function boot() {
for (const [cdn, local] of LIBS) {
try { await loadScript(cdn); }
catch (e) {
try { await loadScript(local); }
catch (e2) {
const el = document.getElementById('loaderr');
el.style.display = 'grid';
el.textContent = 'Could not load ' + cdn + ' (and no local copy at ' + local + ').';
return;
}
}
}
init();
})();
</script>
<script>
// ===========================================================================
// Model
// ===========================================================================
// Live configuration, all lengths in feet.
const CFG = {
grid: 3, // homes per side
pitch: 80, // home centre to home centre
home: 32, // home footprint (square)
homeH: 21, // roof height (2 storeys + parapet)
mast: 30, // top of the corner tubing = canopy anchor height
res: 2.5, // membrane mesh spacing
relax: 300, // form-finding iterations
sag: 2, // sag depth (ft) the self weight produces over one clear span
head: 8, // diameter of the spreader plate at a high point
style: 'net',
coverage: 0.5,
panel: 8,
hour: 13,
dayCycle: false, // advance the hour in real time instead of by hand
site: 0, // index into SITES
day: 172, // day of year (21 Jun)
water: 0.30, // irrigation, 0..1 on top of what the sky delivers
sunmap: false, // draw the insolation heat map on the ground
plants: true, // grow what the light and moisture support
growth: true, // tint the ground by how much growth it supports
wallPlants: true, // extend planting to roofs and walls
shadows: true,
homes: true,
controlNet: false,
masts: true,
};
// Ten arid places where this kind of shaded, irrigated block is either being
// built or actively proposed. lat/lon in degrees (+N / +E); rain is the annual
// mean in mm — between them they set the sun path and the water budget.
const SITES = [
{ name: 'Ouarzazate, MA', lat: 30.9, lon: -6.9, rain: 120, note: "Sahara's north edge; the Noor solar complex is next door." },
{ name: 'Niamey, NE', lat: 13.5, lon: 2.1, rain: 540, note: 'Sahel, on the Great Green Wall line. Wet season, high sun.' },
{ name: 'Turkana, KE', lat: 3.1, lon: 36.1, rain: 200, note: 'Equatorial: the sun barely tilts, so season changes little.' },
{ name: 'Jodhpur, IN', lat: 26.3, lon: 73.0, rain: 360, note: 'Thar desert. Monsoon-fed, then eight dry months.' },
{ name: 'Kubuqi, CN', lat: 40.4, lon: 108.5, rain: 250, note: 'Inner Mongolia; the largest desert-greening scheme running.' },
{ name: 'Tabuk, SA', lat: 28.4, lon: 36.6, rain: 40, note: 'North-west Arabia. Almost no rain — shade is the whole crop.' },
{ name: 'Phoenix, US', lat: 33.4, lon: -112.1, rain: 200, note: 'Sonoran. Summer heat, not light, is the binding limit.' },
{ name: 'Almería, ES', lat: 36.8, lon: -2.4, rain: 200, note: "Tabernas — Europe's only desert, already under plastic." },
{ name: 'Calama, CL', lat: -22.5, lon: -68.9, rain: 5, note: 'Atacama: the driest ground and the hardest sun on Earth.' },
{ name: 'Alice Springs, AU',lat: -23.7, lon: 133.9, rain: 280, note: 'Red Centre. Southern hemisphere — the seasons run backwards.' },
];
// Control nodes, offsets measured out from a home corner.
let nodes = [{ dx: 24, dy: 46, dz: 24 }];
let scene, camera, renderer, controls, sun, sunTarget, hemi;
let gHomes, gCanopy, gPanels, gStruct, gNet, gPlants, gHeat, gGrowth, ground;
let surface = null; // last form-found grid
let panelVerts = null;// module corners, 12 floats each: what casts the shade
let sunRun = null; // in-flight insolation job, pumped by the frame loop
let buildSeq = 0; // bumped on every rebuild; the headless tests wait on it
// ---------------------------------------------------------------------------
// Derived geometry helpers
// ---------------------------------------------------------------------------
const half = () => CFG.home / 2;
const span = () => (CFG.grid - 1) * CFG.pitch; // outer home centres
const centre = () => span() / 2;
function homeCentres() {
const out = [];
for (let i = 0; i < CFG.grid; i++)
for (let j = 0; j < CFG.grid; j++)
out.push([i * CFG.pitch, j * CFG.pitch]);
return out;
}
// Signed distance-ish test: is (x,z) inside a home footprint (inflated by pad)?
function insideHome(x, z, pad) {
const h = half() + (pad || 0);
for (let i = 0; i < CFG.grid; i++) {
const cx = i * CFG.pitch;
if (Math.abs(x - cx) > h) continue;
for (let j = 0; j < CFG.grid; j++) {
const cz = j * CFG.pitch;
if (Math.abs(z - cz) <= h) return true;
}
}
return false;
}
// ---------------------------------------------------------------------------
// Control point cloud: home anchors + the 8-way mirrored user nodes.
// Keyed on rounded (x,z); the highest value at a location wins, so an anchor
// can never silently clobber a peak (or vice versa) depending on loop order.
// ---------------------------------------------------------------------------
function buildControlPoints() {
const map = new Map();
const put = (x, y, z) => {
const k = Math.round(x * 100) + ',' + Math.round(z * 100);
const prev = map.get(k);
if (!prev || y > prev.y) map.set(k, { x, y, z });
};
const signs = [[1, 1], [1, -1], [-1, 1], [-1, -1]];
let skipped = 0;
for (const [cx, cz] of homeCentres()) {
// Anchor ring: the four mast tops on the home's corners.
for (const s of signs) put(cx + half() * s[0], CFG.mast, cz + half() * s[1]);
for (const n of nodes) {
const px = half() + n.dx;
const pz = half() + n.dz;
for (const s of signs) {
for (const [a, b] of [[px, pz], [pz, px]]) { // quadrants + diagonal flip
const x = cx + a * s[0], z = cz + b * s[1];
if (insideHome(x, z, -0.01)) { skipped++; continue; }
put(x, n.dy, z);
}
}
}
}
return { pts: [...map.values()], skipped };
}
// ---------------------------------------------------------------------------
// Form finding.
//
// 1. Delaunay-triangulate the control points in plan and rasterise them onto a
// regular grid -> the faceted surface (this is what the original tool drew).
// 2. Pin the control points and the home roof rings, then relax every free node
// toward the mean of its neighbours. Zero load gives a minimal surface, i.e.
// the soap-film saddle a prestressed membrane actually takes; the sag term
// adds uniform self weight.
// ---------------------------------------------------------------------------
function formFind(ctrl) {
let minX = Infinity, maxX = -Infinity, minZ = Infinity, maxZ = -Infinity;
for (const p of ctrl) {
if (p.x < minX) minX = p.x; if (p.x > maxX) maxX = p.x;
if (p.z < minZ) minZ = p.z; if (p.z > maxZ) maxZ = p.z;
}
const res = CFG.res;
const nx = Math.max(2, Math.round((maxX - minX) / res) + 1);
const nz = Math.max(2, Math.round((maxZ - minZ) / res) + 1);
const dx = (maxX - minX) / (nx - 1), dz = (maxZ - minZ) / (nz - 1);
const n = nx * nz;
const y = new Float32Array(n);
const active = new Uint8Array(n); // 1 = part of the membrane
const pinned = new Uint8Array(n);
// --- rasterise the Delaunay net -----------------------------------------
const coords = new Float64Array(ctrl.length * 2);
for (let i = 0; i < ctrl.length; i++) { coords[i * 2] = ctrl[i].x; coords[i * 2 + 1] = ctrl[i].z; }
const tri = new Delaunator(coords).triangles;
for (let t = 0; t < tri.length; t += 3) {
const A = ctrl[tri[t]], B = ctrl[tri[t + 1]], C = ctrl[tri[t + 2]];
const det = (B.z - C.z) * (A.x - C.x) + (C.x - B.x) * (A.z - C.z);
if (Math.abs(det) < 1e-9) continue;
const i0 = Math.max(0, Math.floor((Math.min(A.x, B.x, C.x) - minX) / dx));
const i1 = Math.min(nx - 1, Math.ceil((Math.max(A.x, B.x, C.x) - minX) / dx));
const j0 = Math.max(0, Math.floor((Math.min(A.z, B.z, C.z) - minZ) / dz));
const j1 = Math.min(nz - 1, Math.ceil((Math.max(A.z, B.z, C.z) - minZ) / dz));
for (let j = j0; j <= j1; j++) {
const pz = minZ + j * dz;
for (let i = i0; i <= i1; i++) {
const px = minX + i * dx;
const l1 = ((B.z - C.z) * (px - C.x) + (C.x - B.x) * (pz - C.z)) / det;
if (l1 < -1e-6) continue;
const l2 = ((C.z - A.z) * (px - C.x) + (A.x - C.x) * (pz - C.z)) / det;
if (l2 < -1e-6) continue;
const l3 = 1 - l1 - l2;
if (l3 < -1e-6) continue;
const k = j * nx + i;
active[k] = 1;
y[k] = l1 * A.y + l2 * B.y + l3 * C.y;
}
}
}
// --- holes over the homes, pinned ring on the roof edge ------------------
const inside = new Uint8Array(n);
for (let j = 0; j < nz; j++) {
const pz = minZ + j * dz;
for (let i = 0; i < nx; i++) {
if (insideHome(minX + i * dx, pz, 0)) inside[j * nx + i] = 1;
}
}
for (let j = 0; j < nz; j++) {
for (let i = 0; i < nx; i++) {
const k = j * nx + i;
if (!inside[k]) continue;
const edge =
i === 0 || i === nx - 1 || j === 0 || j === nz - 1 ||
!inside[k - 1] || !inside[k + 1] || !inside[k - nx] || !inside[k + nx];
if (edge) { active[k] = 1; pinned[k] = 1; y[k] = CFG.mast; } // perimeter beam
else active[k] = 0; // opening
}
}
// --- pin the control points ---------------------------------------------
// A high point is carried on a spreader plate, not a needle, so pin a small
// disc of nodes: a single pinned node just produces a spike no fabric holds.
const head = Math.max(res * 0.6, CFG.head / 2);
const rad = Math.ceil(head / Math.min(dx, dz));
for (const p of ctrl) {
const ci = Math.round((p.x - minX) / dx), cj = Math.round((p.z - minZ) / dz);
for (let j = cj - rad; j <= cj + rad; j++) {
if (j < 0 || j >= nz) continue;
for (let i = ci - rad; i <= ci + rad; i++) {
if (i < 0 || i >= nx) continue;
const ex = (minX + i * dx) - p.x, ez = (minZ + j * dz) - p.z;
if (ex * ex + ez * ez > head * head) continue;
const k = j * nx + i;
if (!active[k]) continue;
pinned[k] = 1; y[k] = p.y;
}
}
}
// --- relaxation ----------------------------------------------------------
// Free nodes move to the mean of their neighbours (a minimal surface, i.e.
// the soap film an evenly prestressed membrane finds) minus a uniform load.
// The load is expressed as a sag depth in feet over one clear span, so the
// result is independent of mesh resolution and of the site dimensions.
const L = Math.max(res * 4, CFG.pitch - CFG.home);
const load = 2 * CFG.sag * res * res / (L * L);
const omega = 1.85; // over-relaxation: ~400 sweeps then behaves like ~3000
for (let it = 0; it < CFG.relax; it++) {
for (let j = 0; j < nz; j++) {
for (let i = 0; i < nx; i++) {
const k = j * nx + i;
if (!active[k] || pinned[k]) continue;
let s = 0, c = 0;
if (i > 0 && active[k - 1]) { s += y[k - 1]; c++; }
if (i < nx - 1 && active[k + 1]) { s += y[k + 1]; c++; }
if (j > 0 && active[k - nx]) { s += y[k - nx]; c++; }
if (j < nz - 1 && active[k + nx]) { s += y[k + nx]; c++; }
if (c) y[k] += omega * (s / c - load - y[k]);
}
}
}
return { y, active, pinned, nx, nz, dx, dz, minX, minZ, tri, ctrl };
}
// Bilinear sample of the form-found surface; null if any corner is an opening.
function sampleSurface(s, x, z) {
const fi = (x - s.minX) / s.dx, fj = (z - s.minZ) / s.dz;
const i = Math.floor(fi), j = Math.floor(fj);
if (i < 0 || j < 0 || i >= s.nx - 1 || j >= s.nz - 1) return null;
const k = j * s.nx + i;
if (!s.active[k] || !s.active[k + 1] || !s.active[k + s.nx] || !s.active[k + s.nx + 1]) return null;
const u = fi - i, v = fj - j;
return (s.y[k] * (1 - u) + s.y[k + 1] * u) * (1 - v) +
(s.y[k + s.nx] * (1 - u) + s.y[k + s.nx + 1] * u) * v;
}
// ===========================================================================
// Mesh construction
// ===========================================================================
// Geometry only: every material in MAT is shared and outlives the rebuild.
function disposeGroup(g) {
g.traverse(o => { if (o.geometry) o.geometry.dispose(); });
g.clear();
}
// Membrane surface. Winding is chosen so face normals point up (+Y): for a
// quad with i along +X and j along +Z, (a, c, b) gives an upward cross product.
function buildMembrane(s) {
const pos = [], idx = [];
const map = new Int32Array(s.nx * s.nz).fill(-1);
let count = 0;
for (let j = 0; j < s.nz; j++) {
for (let i = 0; i < s.nx; i++) {
const k = j * s.nx + i;
if (!s.active[k]) continue;
map[k] = count++;
pos.push(s.minX + i * s.dx, s.y[k], s.minZ + j * s.dz);
}
}
for (let j = 0; j < s.nz - 1; j++) {
for (let i = 0; i < s.nx - 1; i++) {
const k = j * s.nx + i;
const a = map[k], b = map[k + 1], c = map[k + s.nx], d = map[k + s.nx + 1];
if (a < 0 || b < 0 || c < 0 || d < 0) continue;
idx.push(a, c, b, b, c, d);
}
}
const g = new THREE.BufferGeometry();
g.setAttribute('position', new THREE.Float32BufferAttribute(pos, 3));
g.setIndex(idx);
g.computeVertexNormals();
g.computeBoundingSphere();
return g;
}
// A sparse set of grid lines, drawn as the cable net.
function buildCables(s) {
const step = Math.max(1, Math.round(8 / s.dx));
const pts = [];
const at = (i, j) => [s.minX + i * s.dx, s.y[j * s.nx + i], s.minZ + j * s.dz];
for (let j = 0; j < s.nz; j += step)
for (let i = 0; i < s.nx - 1; i++) {
const k = j * s.nx + i;
if (s.active[k] && s.active[k + 1]) pts.push(...at(i, j), ...at(i + 1, j));
}
for (let i = 0; i < s.nx; i += step)
for (let j = 0; j < s.nz - 1; j++) {
const k = j * s.nx + i;
if (s.active[k] && s.active[k + s.nx]) pts.push(...at(i, j), ...at(i, j + 1));
}
const g = new THREE.BufferGeometry();
g.setAttribute('position', new THREE.Float32BufferAttribute(pts, 3));
return g;
}
// Ordered dither: spreads coverage evenly instead of clumping it, which is what
// "dappled" shade needs. Any coverage fraction stays uniformly distributed.
const BAYER = [0,8,2,10, 12,4,14,6, 3,11,1,9, 15,7,13,5];
// Height a module hangs at. Over open ground it follows the membrane; over a
// home the membrane is an opening ringed by a pinned perimeter beam, so modules
// span it flat at anchor height, hung off that ring.
function panelHeight(s, x, z) {
const y = sampleSurface(s, x, z);
if (y !== null) return y;
// The pad picks up cells straddling the ring, where the bilinear sample has
// an inactive corner and gives up but the beam is right there.
return insideHome(x, z, s.dx + 0.1) ? CFG.mast : null;
}
function buildPanels(s) {
const p = CFG.panel;
const i0 = Math.floor(s.minX / p), i1 = Math.ceil((s.minX + (s.nx - 1) * s.dx) / p);
const j0 = Math.floor(s.minZ / p), j1 = Math.ceil((s.minZ + (s.nz - 1) * s.dz) / p);
const pos = [], nor = [], idx = [];
let vcount = 0, area = 0, planArea = 0, roofArea = 0, roofCount = 0;
const insetFrac = 0.06; // gap between modules: lets wind pressure bleed through
const inset = p * insetFrac;
// The requested coverage is the shaded fraction of ground, so compensate for
// the gaps when deciding how many cells to fill.
const fill = Math.min(1, CFG.coverage / Math.pow(1 - 2 * insetFrac, 2));
for (let j = j0; j < j1; j++) {
for (let i = i0; i < i1; i++) {
const bi = ((i % 4) + 4) % 4, bj = ((j % 4) + 4) % 4;
if ((BAYER[bj * 4 + bi] + 0.5) / 16 >= fill) continue;
const x0 = i * p + inset, x1 = (i + 1) * p - inset;
const z0 = j * p + inset, z1 = (j + 1) * p - inset;
const c = [[x0, z0], [x1, z0], [x1, z1], [x0, z1]].map(([x, z]) => {
const y = panelHeight(s, x, z);
return y === null ? null : new THREE.Vector3(x, y, z);
});
if (c.some(v => v === null)) continue;
const onRoof = insideHome((x0 + x1) / 2, (z0 + z1) / 2, 0);
const n = new THREE.Vector3().subVectors(c[3], c[0]).cross(new THREE.Vector3().subVectors(c[1], c[0])).normalize();
if (n.y < 0) n.negate();
for (const v of c) { pos.push(v.x, v.y, v.z); nor.push(n.x, n.y, n.z); }
idx.push(vcount, vcount + 3, vcount + 1, vcount + 1, vcount + 3, vcount + 2);
vcount += 4;
const w = c[0].distanceTo(c[1]), h = c[0].distanceTo(c[3]);
area += w * h;
// Modules over a home shade its roof, not the ground, so they are counted
// apart: the "ground shaded" figure would otherwise overstate the dapple.
if (onRoof) { roofArea += (x1 - x0) * (z1 - z0); roofCount++; }
else planArea += (x1 - x0) * (z1 - z0);
}
}
const g = new THREE.BufferGeometry();
g.setAttribute('position', new THREE.Float32BufferAttribute(pos, 3));
g.setAttribute('normal', new THREE.Float32BufferAttribute(nor, 3));
g.setIndex(idx);
g.computeBoundingSphere();
return { geo: g, count: vcount / 4, area, planArea, roofArea, roofCount };
}
// ===========================================================================
// Scene assembly
// ===========================================================================
const MAT = {};
// Procedural brick-and-window elevation, drawn once onto a canvas. Keeps the
// tool a single self-contained file with no image assets to fetch.
function elevationTexture(withDoor) {
const W = 512, H = 336; // 32 ft x 21 ft
const ft = W / 32;
const cv = document.createElement('canvas');
cv.width = W; cv.height = H;
const g = cv.getContext('2d');
g.fillStyle = '#6d4636'; g.fillRect(0, 0, W, H); // mortar
const course = 4, brick = 13;
for (let y = 0, r = 0; y < H; y += course, r++) {
const off = (r % 2) * brick / 2;
for (let x = -brick; x < W; x += brick) {
const t = ((x * 7 + y * 13) % 11) / 11;
g.fillStyle = `rgb(${162 + t * 26 | 0},${104 + t * 22 | 0},${78 + t * 18 | 0})`;
g.fillRect(x + off + 0.7, y + 0.7, brick - 1.4, course - 1.4);
}
}
// Parapet band across the top.
g.fillStyle = '#b9ab97'; g.fillRect(0, 0, W, 3 * ft);
g.fillStyle = '#cbbfa9'; g.fillRect(0, 0, W, 0.5 * ft);
const opening = (xf, yf, wf, hf, door) => {
const x = xf * ft, y = H - (yf + hf) * ft, w = wf * ft, h = hf * ft;
g.fillStyle = '#8e8272'; g.fillRect(x - 3, y - 3, w + 6, h + 6); // reveal
const grad = g.createLinearGradient(x, y, x, y + h);
grad.addColorStop(0, door ? '#4a3323' : '#7f9bb4');
grad.addColorStop(1, door ? '#33231a' : '#1d2b39');
g.fillStyle = grad; g.fillRect(x, y, w, h);
if (!door) { // glazing bar
g.fillStyle = '#8e8272';
g.fillRect(x + w / 2 - 1.5, y, 3, h);
}
};
for (const [x, w] of [[4, 6], [13, 6], [22, 6]]) {
if (withDoor && x === 13) opening(13.5, 0.5, 5, 8, true);
else opening(x, 4.5, w, 4.5, false);
opening(x, 13.5, w, 4.5, false);
}
const tex = new THREE.CanvasTexture(cv);
tex.anisotropy = 8;
return tex;
}
function makeMaterials() {
MAT.brick = new THREE.MeshStandardMaterial({ map: elevationTexture(false), roughness: 0.95 });
MAT.front = new THREE.MeshStandardMaterial({ map: elevationTexture(true), roughness: 0.95 });
MAT.roof = new THREE.MeshStandardMaterial({ color: 0x8d8478, roughness: 0.9 });
MAT.ground = new THREE.MeshStandardMaterial({ color: 0xc2a678, roughness: 1 });
MAT.steel = new THREE.MeshStandardMaterial({ color: 0x9aa2ac, roughness: 0.45, metalness: 0.75 });
MAT.cable = new THREE.LineBasicMaterial({ color: 0x9fd4ff, transparent: true, opacity: 0.55 });
MAT.tie = new THREE.LineBasicMaterial({ color: 0x6f7d8c, transparent: true, opacity: 0.7 });
MAT.ctrlnet = new THREE.LineBasicMaterial({ color: 0xffb066, transparent: true, opacity: 0.5 });
MAT.panel = new THREE.MeshStandardMaterial({ color: 0x16294a, roughness: 0.5, metalness: 0.22, side: THREE.DoubleSide });
MAT.net = new THREE.MeshStandardMaterial({ color: 0x3d7fbf, transparent: true, opacity: 0.10, side: THREE.DoubleSide, depthWrite: false });
MAT.fabric = new THREE.MeshStandardMaterial({ color: 0xd9d2c4, transparent: true, opacity: 0.62, side: THREE.DoubleSide, roughness: 0.95 });
}
function buildHomes() {
disposeGroup(gHomes);
if (!CFG.homes) return;
const box = new THREE.BoxGeometry(CFG.home, CFG.homeH, CFG.home);
for (const [cx, cz] of homeCentres()) {
const m = new THREE.Mesh(box, [MAT.brick, MAT.brick, MAT.roof, MAT.roof, MAT.front, MAT.brick]);
m.position.set(cx, CFG.homeH / 2, cz);
m.castShadow = m.receiveShadow = true;
gHomes.add(m);
}
}
function buildStructure(ctrl) {
disposeGroup(gStruct);
if (!CFG.masts) return;
// Corner tubing: roof level up to the canopy anchor.
const len = Math.max(0.5, CFG.mast - CFG.homeH);
const tube = new THREE.CylinderGeometry(0.4, 0.4, len, 8);
for (const [cx, cz] of homeCentres()) {
for (const sx of [-1, 1]) for (const sz of [-1, 1]) {
const m = new THREE.Mesh(tube, MAT.steel);
m.position.set(cx + sx * half(), CFG.homeH + len / 2, cz + sz * half());
m.castShadow = true;
gStruct.add(m);
}
}
// High points get a ground-mounted mast; low points get a tie-down cable.
const mastGeo = new THREE.CylinderGeometry(0.55, 0.8, 1, 10);
const tiePts = [];
for (const p of ctrl) {
if (insideHome(p.x, p.z, 0)) continue;
if (p.y > CFG.mast + 0.5) {
const m = new THREE.Mesh(mastGeo, MAT.steel);
m.position.set(p.x, p.y / 2, p.z);
m.scale.y = p.y;
m.castShadow = true;
gStruct.add(m);
} else if (p.y < CFG.mast - 0.5) {
tiePts.push(p.x, p.y, p.z, p.x, 0, p.z);
}
}
if (tiePts.length) {
const g = new THREE.BufferGeometry();
g.setAttribute('position', new THREE.Float32BufferAttribute(tiePts, 3));
gStruct.add(new THREE.LineSegments(g, MAT.tie));
}
}
function buildControlNetLines(s) {
const pts = [];
for (let t = 0; t < s.tri.length; t += 3) {
const A = s.ctrl[s.tri[t]], B = s.ctrl[s.tri[t + 1]], C = s.ctrl[s.tri[t + 2]];
pts.push(A.x, A.y, A.z, B.x, B.y, B.z, B.x, B.y, B.z, C.x, C.y, C.z, C.x, C.y, C.z, A.x, A.y, A.z);
}
const g = new THREE.BufferGeometry();
g.setAttribute('position', new THREE.Float32BufferAttribute(pts, 3));
return new THREE.LineSegments(g, MAT.ctrlnet);
}
function rebuild() {
const t0 = performance.now();
const { pts: ctrl, skipped } = buildControlPoints();
const s = formFind(ctrl);
surface = s;
disposeGroup(gCanopy);
disposeGroup(gPanels);
disposeGroup(gNet);
// Membrane
const memGeo = buildMembrane(s);
let memArea = 0;
{
const p = memGeo.attributes.position, ix = memGeo.index.array;
const a = new THREE.Vector3(), b = new THREE.Vector3(), c = new THREE.Vector3();
for (let t = 0; t < ix.length; t += 3) {
a.fromBufferAttribute(p, ix[t]); b.fromBufferAttribute(p, ix[t + 1]); c.fromBufferAttribute(p, ix[t + 2]);
memArea += b.sub(a).cross(c.sub(a)).length() / 2;
}
}
window.__membrane = null; // test hook, see bottom of file
if (CFG.style !== 'none') {
const mesh = new THREE.Mesh(memGeo, CFG.style === 'fabric' ? MAT.fabric : MAT.net);
mesh.castShadow = CFG.style === 'fabric';
gCanopy.add(mesh);
window.__membrane = mesh;
if (CFG.style === 'net') gCanopy.add(new THREE.LineSegments(buildCables(s), MAT.cable));
} else {
memGeo.dispose();
}
if (CFG.controlNet) gNet.add(buildControlNetLines(s));
// Panels
const pan = buildPanels(s);
const pmesh = new THREE.Mesh(pan.geo, MAT.panel);
pmesh.castShadow = true;
gPanels.add(pmesh);
panelVerts = pan.geo.attributes.position.array; // the insolation job reads this
buildHomes();
buildStructure(ctrl);
frameSun();
// ---- stats -------------------------------------------------------------
const blockW = span() + CFG.pitch;
const site = blockW * blockW;
let peak = -Infinity, low = Infinity;
for (const p of ctrl) { if (p.y > peak) peak = p.y; if (p.y < low) low = p.y; }
const kw = (pan.planArea + pan.roofArea) * 0.019; // ~19 W/ft2 of module plan area
setStats({
'Homes': CFG.grid * CFG.grid,
'Site block': fmt(blockW) + ' × ' + fmt(blockW) + ' ft',
'Clear span': fmt(CFG.pitch - CFG.home) + ' ft',
'Anchor / peak': fmt(CFG.mast) + ' / ' + fmt(peak) + ' ft',
'Membrane area': fmt(Math.round(memArea)) + ' ft²',
'Modules': fmt(pan.count) + ' (' + fmt(pan.roofCount) + ' over homes)',
'Module area': fmt(Math.round(pan.area)) + ' ft²',
'Ground shaded': (100 * pan.planArea / site).toFixed(0) + '%',
'Array capacity': (kw > 999 ? (kw / 1000).toFixed(2) + ' MW' : Math.round(kw) + ' kW'),
'Mesh nodes': memGeo.attributes ? memGeo.attributes.position.count : 0,
'Build time': Math.round(performance.now() - t0) + ' ms',
});
msg(skipped ? skipped + ' mirrored point(s) landed on a roof and were dropped.' : '');
scheduleSunMap();
window.__diag = {
seq: ++buildSeq,
ctrl: ctrl.length, nodes: memGeo.attributes ? memGeo.attributes.position.count : 0,
panels: pan.count, roofPanels: pan.roofCount, peak, memArea, ms: performance.now() - t0,
};
}
function fmt(v) { return (Math.round(v * 10) / 10).toLocaleString(); }
// Two writers: the rebuild fills in the geometry figures, the insolation job
// adds its own later and must not wipe them out.
let statsBase = {}, statsSun = {};
function setStats(o) { statsBase = o; drawStats(); }
function setSunStats(o) { statsSun = o; drawStats(); }
function drawStats() {
document.getElementById('stats').innerHTML =
Object.entries(Object.assign({}, statsBase, statsSun))
.map(([k, v]) => `<div class="k">${k}</div><div class="v">${v}</div>`).join('');
}
function msg(t) { document.getElementById('msg').textContent = t; }
// ---------------------------------------------------------------------------
// Sun
// ---------------------------------------------------------------------------
// Built in init(): THREE is not defined until the loader resolves.
let SKY_LOW, SKY_HIGH, sky;
const HOUR_FIRST = 6, HOUR_LAST = 19; // ends of the hour slider
const HOUR_SECS = 15; // wall-clock seconds per simulated hour
// The hour is a float, so rounding minutes can land on 60 — carry it.
function hourLabel(v) {
let m = Math.round(v * 60);
const h = Math.floor(m / 60);
return h + ':' + String(m - h * 60).padStart(2, '0');
}
// Single place the hour changes: keeps CFG, the slider, the label and the light
// in step whether the move came from a drag or from the day cycle.
function setHour(v) {
CFG.hour = v;
document.getElementById('cfg-hour').value = v;
document.getElementById('lbl-hour').textContent = hourLabel(v);
frameSun();
}
// Called every frame while the day cycle runs. dt is seconds, already clamped.
function advanceDay(dt) {
const len = HOUR_LAST - HOUR_FIRST;
let h = CFG.hour + dt / HOUR_SECS;
if (h >= HOUR_LAST) h = HOUR_FIRST + (h - HOUR_FIRST) % len; // wrap to dawn
setHour(h);
}
const D2R = Math.PI / 180;
// Scene compass: +X east, -Z north, so the plan view has north up and the noon
// sun sits on +Z (south) in the northern hemisphere.
//
// Solar time, no longitude or equation-of-time correction: this is a shading
// study, not an almanac, and both only slide the clock by minutes.
function declination(day) { return 23.44 * D2R * Math.sin(2 * Math.PI * (284 + day) / 365); }
function solarPos(lat, day, hour) {
const dec = declination(day), la = lat * D2R;
const H = (hour - 12) * 15 * D2R; // hour angle
const sinEl = Math.sin(la) * Math.sin(dec) + Math.cos(la) * Math.cos(dec) * Math.cos(H);
const el = Math.asin(Math.max(-1, Math.min(1, sinEl)));
const cosAz = (Math.sin(dec) - sinEl * Math.sin(la)) /
Math.max(1e-6, Math.cos(el) * Math.cos(la));
let az = Math.acos(Math.max(-1, Math.min(1, cosAz))); // bearing from north
if (H > 0) az = 2 * Math.PI - az; // afternoon: west of north
return { el, az };
}
// Unit vector from the ground toward the sun, in scene axes.
function sunVec(p) {
const c = Math.cos(p.el);
return { x: c * Math.sin(p.az), y: Math.sin(p.el), z: -c * Math.cos(p.az) };
}
// Half-day length in hours: 0 at polar night, 12 at polar day.
function halfDay(lat, day) {
const c = -Math.tan(lat * D2R) * Math.tan(declination(day));
return (c <= -1 ? Math.PI : c >= 1 ? 0 : Math.acos(c)) / D2R / 15;
}
// Haurwitz clear sky, converted to watts per square foot of horizontal ground.
function clearSky(sinEl) {
return sinEl <= 0.01 ? 0 : 1098 * sinEl * Math.exp(-0.057 / sinEl) * 0.092903;
}
function frameSun() {
const st = SITES[CFG.site];
const p = solarPos(st.lat, CFG.day, CFG.hour);
const v = sunVec(p);
const d = Math.max(300, span() * 1.6);
const c = centre();
sun.position.set(c + d * v.x, d * v.y + 20, c + d * v.z);
sunTarget.position.set(c, 0, c);
const r = span() * 0.85 + CFG.pitch;
const cam = sun.shadow.camera;
cam.left = -r; cam.right = r; cam.top = r; cam.bottom = -r;
cam.near = 1; cam.far = d * 3;
cam.updateProjectionMatrix();
// 0 at the horizon, 1 at this latitude's own noon, so the light reads the
// same way at Turkana and at Kubuqi.
const noon = Math.max(0.08, Math.sin(solarPos(st.lat, CFG.day, 12).el));
const high = Math.max(0, Math.min(1, v.y / noon));
// Below the horizon there is still light for a while: fade over civil twilight
// instead of cutting to black the instant the disc sets.
const dusk = Math.max(0, Math.min(1, (p.el / D2R + 6) / 6));
sun.color.setHSL(0.09 + 0.02 * high, 0.55 - 0.42 * high, 0.5 + 0.12 * high);
sun.intensity = (0.5 + 1.05 * high) * dusk;
// Sky and fog follow the sun: warm haze low, pale desert blue at midday.
// Blend in RGB, not HSL — a hue ramp from orange to blue passes through green.
sky.copy(SKY_LOW).lerp(SKY_HIGH, high).multiplyScalar((0.6 + 0.4 * high) * (0.12 + 0.88 * dusk));
scene.background = sky;
scene.fog.color.copy(sky);
hemi.color.copy(sky);
hemi.intensity = (0.35 + 0.3 * high) * (0.25 + 0.75 * dusk);
}
// ===========================================================================
// Insolation: sun per square foot, integrated over the day's whole sweep
// ===========================================================================
//
// This is a shadow map done in software, in plan. For each step of the sun:
//
// 1. Every occluder above roof height (modules, and the fabric if there is
// any) is projected straight down the sun vector onto the ground and
// rasterised into a transmission mask.
// 2. A point at height h reads that same mask at (x - h·sx, z - h·sz), since
// dropping the ray from the point to the ground shifts it by exactly that.
// One mask therefore serves the ground, the roofs and the walls.
// 3. Homes are kept out of the mask — they sit below the roofs and walls that
// read it — and tested analytically instead, which is cheap for 9 boxes.
//
// Cost is O(modules x steps), not O(cells x modules x steps), which is what
// makes it fast enough to redo on every parameter change.
let sunmap = null; // last completed result
let sunSeq = 0; // bumped on completion; the headless tests wait on it
// Sun positions across the daylight window, with clear-sky watts per ft2.
function sunSteps(site, day, n) {
const H = halfDay(site.lat, day);
const out = [];
if (H <= 0.01) return out; // polar night; not at these latitudes
const dt = 2 * H / n; // hours represented by each step
for (let i = 0; i < n; i++) {
const hour = 12 - H + (i + 0.5) * dt;
const p = solarPos(site.lat, day, hour);
if (p.el <= 0.02) continue;
const v = sunVec(p);
if (v.y < 0.02) continue; // grazing: shadows run to infinity
out.push({ hour, el: p.el, v, dt, ghi: clearSky(v.y), sx: v.x / v.y, sz: v.z / v.y });
}
return out;
}