-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
1872 lines (1663 loc) · 57 KB
/
index.html
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.0" />
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous"></script>
<title>Three.js Building Analysis with BIPV and Rooftop Solar</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
<style>
:root {
--primary-color: #2196f3;
--secondary-color: #1976d2;
--success-color: #4caf50;
--warning-color: #ffc107;
--shadow-color: #607d8b;
--text-color: #333;
--panel-bg: rgba(255, 255, 255, 0.95);
}
body {
margin: 0;
overflow: hidden;
font-family: "Segoe UI", system-ui, -apple-system, sans-serif;
color: var(--text-color);
}
canvas {
display: block;
}
.controls {
position: fixed;
top: 0;
left: 0;
width: 100%;
background: var(--panel-bg);
padding: 5px 20px;
display: flex;
justify-content: space-between;
align-items: center;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
z-index: 100;
}
.control-group {
display: flex;
align-items: center;
margin-right: 1px;
}
.control-group label {
margin-right: 5px;
font-weight: 500;
font-size: 14px;
white-space: nowrap;
}
input[type="datetime-local"],
input[type="number"] {
padding: 8px;
border: 1px solid #ddd;
border-radius: 4px;
margin-bottom: 10px;
font-size: 14px;
margin: 0 10px;
width: 200px;
}
button {
background: var(--primary-color);
color: white;
border: none;
padding: 10px 15px;
border-radius: 4px;
cursor: pointer;
font-weight: 500;
width: 100%;
margin-bottom: 8px;
transition: background-color 0.2s;
}
button:hover {
background: var(--secondary-color);
}
.info-panel {
position: fixed;
top: 100px;
right: 10px;
background: var(--panel-bg);
padding: 20px;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
z-index: 100;
max-height: 80vh;
overflow-y: auto;
width: 550px;
}
.info-section {
margin-bottom: 20px;
}
.info-section h3 {
margin: 0 0 10px 0;
padding-bottom: 5px;
border-bottom: 2px solid var(--primary-color);
font-size: 16px;
}
.info-row {
display: flex;
justify-content: space-between;
margin-bottom: 5px;
font-size: 14px;
}
.light-bar {
height: 20px;
margin: 5px 0;
border-radius: 4px;
}
.fully-lit {
background-color: var(--success-color);
}
.partially-lit {
background-color: var(--warning-color);
}
.shadowed {
background-color: var(--shadow-color);
}
.facadeChart {
position: absolute;
background: var(--panel-bg);
padding: 20px;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
width: 600px;
z-index: 1000;
}
canvas#facadeBIPVchart {
width: 100% !important;
height: 300px !important;
margin: 0;
}
/* Scrollbar styling */
::-webkit-scrollbar {
width: 8px;
}
::-webkit-scrollbar-track {
background: #f1f1f1;
border-radius: 4px;
}
::-webkit-scrollbar-thumb {
background: #888;
border-radius: 4px;
}
::-webkit-scrollbar-thumb:hover {
background: #666;
}
/* Tooltip */
[data-tooltip] {
position: relative;
cursor: help;
}
[data-tooltip]:before {
content: attr(data-tooltip);
position: absolute;
bottom: 100%;
left: 50%;
transform: translateX(-50%);
padding: 5px 10px;
background: rgba(0, 0, 0, 0.8);
color: white;
border-radius: 4px;
font-size: 12px;
white-space: nowrap;
visibility: hidden;
opacity: 0;
transition: opacity 0.2s;
}
[data-tooltip]:hover:before {
visibility: visible;
opacity: 1;
}
.heatmap-legend {
display: flex;
flex-direction: column;
margin-top: 10px;
padding: 10px;
border: 1px solid #ddd;
border-radius: 4px;
position: absolute;
bottom: 20px;
left: 20px;
background: var(--panel-bg);
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
width: 250px;
z-index: 1000;
}
.heatmap-gradient {
height: 20px;
width: 100%;
margin: 10px 0;
border-radius: 4px;
background: linear-gradient(to right,
#440154,
#472c7a,
#3b528b,
#2c728e,
#21918c,
#28ae80,
#5ec962,
#addc30,
#fde725);
}
.heatmap-labels {
display: flex;
justify-content: space-between;
font-size: 12px;
color: var(--text-color);
margin-top: 5px;
}
.legend-title {
font-size: 14px;
font-weight: 500;
margin-bottom: 10px;
color: var(--text-color);
}
.facadeChart{
background: var(--panel-bg);
padding: 20px;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
width: 600px;
z-index: 1000;
}
.solar-chart-container {
background: var(--panel-bg);
padding: 20px;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
width: 600px;
z-index: 1000;
}
canvas#solarChart {
width: 100% !important;
height: 300px !important;
margin: 0;
}
.chart-container {
background: var(--panel-bg);
padding: 20px;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
width: 600px;
z-index: 1000;
}
.chart-title {
font-size: 16px;
font-weight: 500;
margin-bottom: 15px;
color: var(--text-color);
border-bottom: 2px solid var(--primary-color);
padding-bottom: 5px;
}
canvas#lightingChart {
width: 100% !important;
height: 300px !important;
margin: 0;
}
.modal{
z-index: 100000;
}
</style>
</head>
<body>
<div class="controls">
<div class="control-group">
<label for="timeInput" data-tooltip="Select date and time">Date & Time</label>
<input type="text" id="timeInput" />
</div>
<div class="control-group">
<label for="latInput" data-tooltip="Building latitude">Latitude</label>
<input type="number" id="latInput" step="0.0001" />
</div>
<div class="control-group">
<label for="longInput" data-tooltip="Building longitude">Longitude</label>
<input type="number" id="longInput" step="0.0001" />
</div>
<div class="control-group">
<label for="ghiInput" data-tooltip="Global Horizontal Irradiance">GHI (kWh/m²/day)</label>
<input type="number" id="ghiInput" step="0.01" />
</div>
<button onclick="updateFromInputs()">
Update Sun Position
</button>
<button onclick="startSimulation()">
Start Day Simulation
</button>
</div>
<div id="infoPanel" class="info-panel"><button onclick="printInfoPanel()">Print</button>
</div>
<script src="https://cdn.jsdelivr.net/npm/three@0.132.2/build/three.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three@0.132.2/examples/js/controls/OrbitControls.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three@0.132.2/examples/js/loaders/OBJLoader.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/suncalc/1.9.0/suncalc.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three@0.132.2/examples/js/utils/BufferGeometryUtils.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
<script>
flatpickr("#timeInput", {
enableTime: true,
dateFormat: "Y-m-d H:i",
});
function printInfoPanel() {
var content = document.getElementById('infoPanel').innerHTML;
var originalContent = document.body.innerHTML;
document.body.innerHTML = content;
window.print();
// Restore original content after printing
document.body.innerHTML = originalContent;
window.location.reload(); // Optional: Reload the page to restore DOM state
}
const GHI_VALS = [3.5, 3.6, 3.7, 3.8, 4.4, 5.0, 5.5, 5.0, 4.4, 3.8, 3.2, 2.0];
let globalAddArray = null;
// Constants
const AHMEDABAD_LAT = 23.0225;
const AHMEDABAD_LONG = 72.5714;
const DEFAULT_GHI = 5.5; // Default GHI value for Ahmedabad
const MIN_HEIGHT = 1; // Minimum height above ground
const MOVEMENT_SPEED = 5;
let keys = {};
// Scene setup
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(
75,
window.innerWidth / window.innerHeight,
0.1,
1000
);
camera.position.set(100, 100, 100);
camera.lookAt(0, 0, 0);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
document.body.appendChild(renderer.domElement);
const controls = new THREE.OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
controls.dampingFactor = 0.05;
controls.maxDistance = 500;
controls.minDistance = 10;
// First, disable orbit controls auto-rotation
controls.autoRotate = false;
controls.enableDamping = false; // Optional: disable damping for more direct control
controls.autoRotate = false;
controls.enableDamping = false;
controls.enablePan = true;
controls.enableZoom = true;
controls.minDistance = 1;
controls.maxDistance = 1000;
controls.minPolarAngle = 0;
controls.maxPolarAngle = Math.PI / 2; // Limit to 90 degrees to prevent going below ground
// Lighting
const ambientLight = new THREE.AmbientLight(0x404040, 0.5);
scene.add(ambientLight);
const sunLight = new THREE.DirectionalLight(0xffffff, 1.2);
sunLight.castShadow = true;
sunLight.shadow.mapSize.width = 8000;
sunLight.shadow.mapSize.height = 8000;
sunLight.shadow.camera.near = 1;
sunLight.shadow.camera.far = 500;
sunLight.shadow.camera.left = -200;
sunLight.shadow.camera.right = 200;
sunLight.shadow.camera.top = 200;
sunLight.shadow.camera.bottom = -200;
sunLight.shadow.bias = -0.0005;
scene.add(sunLight);
const sunGeometry = new THREE.SphereGeometry(0, 32, 32);
const sunMaterial = new THREE.MeshBasicMaterial({
color: 0xffff00,
emissive: 0xffff00,
emissiveIntensity: 1,
});
const sunMesh = new THREE.Mesh(sunGeometry, sunMaterial);
scene.add(sunMesh);
// Sky dome
const skyGeometry = new THREE.SphereGeometry(500, 32, 32);
const skyMaterial = new THREE.ShaderMaterial({
uniforms: {
topColor: { value: new THREE.Color(0x0077ff) },
bottomColor: { value: new THREE.Color(0xffffff) },
offset: { value: 400 },
exponent: { value: 0.6 },
sunPosition: { value: new THREE.Vector3() },
},
vertexShader: `
varying vec3 vWorldPosition;
void main() {
vec4 worldPosition = modelMatrix * vec4(position, 1.0);
vWorldPosition = worldPosition.xyz;
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}
`,
fragmentShader: `
uniform vec3 topColor;
uniform vec3 bottomColor;
uniform float offset;
uniform float exponent;
uniform vec3 sunPosition;
varying vec3 vWorldPosition;
void main() {
float h = normalize(vWorldPosition + offset).y;
float sunFactor = max(dot(normalize(vWorldPosition), normalize(sunPosition)), 0.0);
vec3 skyColor = mix(bottomColor, topColor, pow(max(h, 0.0), exponent));
if(sunFactor > 0.98) {
skyColor = mix(skyColor, vec3(1.0, 0.8, 0.4), 0.6);
}
gl_FragColor = vec4(skyColor, 1.0);
}
`,
side: THREE.BackSide,
depthWrite: false,
});
const skyDome = new THREE.Mesh(skyGeometry, skyMaterial);
scene.add(skyDome);
// Ground
const groundGeometry = new THREE.PlaneGeometry(8000, 8000);
const groundMaterial = new THREE.MeshStandardMaterial({
color: 0x555555,
roughness: 0.8,
metalness: 0.2,
side: THREE.DoubleSide,
});
const ground = new THREE.Mesh(groundGeometry, groundMaterial);
ground.rotation.x = -Math.PI / 2;
ground.position.y = 0;
ground.receiveShadow = true;
scene.add(ground);
// Variables
let selectedObject = null;
const originalMaterials = new Map();
const objects = new Map();
// Highlight material
const highlightMaterial = new THREE.MeshStandardMaterial({
color: 0x00ff00,
transparent: true,
opacity: 0.3,
side: THREE.DoubleSide,
});
// Add at top with other globals
let isSimulating = false;
let simulationObject = null;
// Add after your variable declarations
let raycaster = new THREE.Raycaster();
let mouse = new THREE.Vector2();
// Functions
function updateSunPosition(latitude, longitude, datetime) {
const sunPos = SunCalc.getPosition(datetime, latitude, longitude);
const distance = 100;
const phi = Math.PI / 2 - sunPos.altitude;
const theta = sunPos.azimuth;
const x = distance * Math.sin(phi) * Math.cos(theta);
const y = distance * Math.cos(phi);
const z = distance * Math.sin(phi) * Math.sin(theta);
sunLight.position.set(x, y, z);
sunMesh.position.set(x, y, z);
// Update sky shader sun position
skyMaterial.uniforms.sunPosition.value.copy(sunLight.position);
}
function updateFromInputs() {
const datetime = new Date(document.getElementById("timeInput").value);
const lat =
parseFloat(document.getElementById("latInput").value) ||
AHMEDABAD_LAT;
const long =
parseFloat(document.getElementById("longInput").value) ||
AHMEDABAD_LONG;
updateSunPosition(lat, long, datetime);
}
function analyzeObject(object, ghi_index) {
if (!object?.isMesh) return null;
const geometry = object.geometry;
if (
!geometry?.attributes?.position ||
!geometry?.attributes?.normal ||
!geometry?.index
)
return null;
const sunDir = sunLight.position.clone().normalize();
const normalMatrix = new THREE.Matrix3().getNormalMatrix(
object.matrixWorld
);
let totalArea = 0;
let roofArea = 0;
let fullyLitArea = 0;
let partiallyLitArea = 0;
let shadowedArea = 0;
// New variables for face-specific calculations
let NBipv = 0, SBipv = 0, EBipv = 0, WBipv = 0;
let NA = 0, SA = 0, EA = 0, WA = 0;
const position = geometry.attributes.position;
const normalAttr = geometry.attributes.normal;
const index = geometry.index;
const triangleCount = index.count / 3;
const intensities = new Float32Array(triangleCount);
const ghi = GHI_VALS[ghi_index] || DEFAULT_GHI;
const pvEfficiency = 0.2;
const performanceRatio = 0.75;
const verticalEfficiency = 0.7;
for (let i = 0; i < triangleCount; i++) {
const i3 = i * 3;
const ai = index.getX(i3);
const bi = index.getX(i3 + 1);
const ci = index.getX(i3 + 2);
const a = new THREE.Vector3().fromBufferAttribute(position, ai);
const b = new THREE.Vector3().fromBufferAttribute(position, bi);
const c = new THREE.Vector3().fromBufferAttribute(position, ci);
const normal = new THREE.Vector3()
.fromBufferAttribute(normalAttr, ai)
.applyMatrix3(normalMatrix)
.normalize();
// Skip bottom surfaces (facing downward)
if (normal.y < -0.7) {
intensities[i] = 0; // Set intensity to 0 for bottom surfaces
continue; // Skip area calculations for bottom surfaces
}
const area = Math.floor(calculateTriangleArea(a, b, c) * 100) / 100;
// Only add to total area if not a bottom surface
totalArea += area;
// Calculate intensity for non-bottom surfaces
const intensity = calculateIntensity(normal, sunDir);
intensities[i] = intensity;
// Identify roof surfaces (facing upward)
if (normal.y > 0.7) {
roofArea += area;
} else {
// For vertical surfaces, determine which face they belong to
const absX = Math.abs(normal.x);
const absZ = Math.abs(normal.z);
if (absX > absZ) {
// East or West face
if (normal.x > 0) {
EA += area;
if (intensity > 0.3) {
EBipv += area * intensity * ghi * pvEfficiency * performanceRatio * verticalEfficiency;
}
} else {
WA += area;
if (intensity > 0.3) {
WBipv += area * intensity * ghi * pvEfficiency * performanceRatio * verticalEfficiency;
}
}
} else {
// North or South face
if (normal.z > 0) {
SA += area;
if (intensity > 0.3) {
SBipv += area * intensity * ghi * pvEfficiency * performanceRatio * verticalEfficiency;
}
} else {
NA += area;
if (intensity > 0.3) {
NBipv += area * intensity * ghi * pvEfficiency * performanceRatio * verticalEfficiency;
}
}
}
}
// Categorize lighting based on intensity
if (intensity > 0.6) {
fullyLitArea += area;
} else if (intensity > 0.3) {
partiallyLitArea += area;
} else {
shadowedArea += area;
}
}
// Calculate vertical area (total area minus roof area, bottom surfaces already excluded)
const verticalArea = totalArea - roofArea;
const bipvPotential =
Math.floor(
fullyLitArea *
ghi *
pvEfficiency *
performanceRatio *
verticalEfficiency *
100
) / 100;
const roofEfficiency = 0.9;
const rooftopPotential =
Math.floor(
roofArea *
ghi *
pvEfficiency *
performanceRatio *
roofEfficiency *
100
) / 100;
const totalLitArea = fullyLitArea + partiallyLitArea + shadowedArea;
// Round the new values
NBipv = Math.floor(NBipv * 100) / 100;
SBipv = Math.floor(SBipv * 100) / 100;
EBipv = Math.floor(EBipv * 100) / 100;
WBipv = Math.floor(WBipv * 100) / 100;
NA = Math.floor(NA * 100) / 100;
SA = Math.floor(SA * 100) / 100;
EA = Math.floor(EA * 100) / 100;
WA = Math.floor(WA * 100) / 100;
return {
name: object.name || `Unnamed (${object.id})`,
vertices: geometry.attributes.position.count,
position: object.position,
totalArea: Math.floor(totalArea * 100) / 100,
roofArea: Math.floor(roofArea * 100) / 100,
fullyLitArea: Math.floor(fullyLitArea * 100) / 100,
partiallyLitArea: Math.floor(partiallyLitArea * 100) / 100,
shadowedArea: Math.floor(shadowedArea * 100) / 100,
fullyLitPercent:
Math.floor((fullyLitArea / totalLitArea) * 100 * 100) / 100,
partiallyLitPercent:
Math.floor((partiallyLitArea / totalLitArea) * 100 * 100) / 100,
shadowedPercent:
Math.floor((shadowedArea / totalLitArea) * 100 * 100) / 100,
bipvPotential,
rooftopPotential,
totalPotential:
Math.floor((bipvPotential + rooftopPotential) * 100) / 100,
intensities,
// New values
NBipv,
SBipv,
EBipv,
WBipv,
NA,
SA,
EA,
WA,
};
}
function displayObjectInfo(info) {
if (!info) {
console.warn("No info object provided to displayObjectInfo");
return;
}
const infoPanel = document.getElementById("infoPanel");
if (!infoPanel) {
console.error("Info panel element not found");
return;
}
// Format number safely with fallback to 0
const formatNumber = (num) => {
return typeof num === "number" ? num.toLocaleString() : "0";
};
// Format decimal number safely with fallback to 0
const formatDecimal = (num, decimals = 2) => {
return typeof num === "number" ? num.toFixed(decimals) : "0.00";
};
const position = info.position || { x: 0, y: 0, z: 0 };
infoPanel.innerHTML = `
<button onclick="printInfoPanel()">Print</button>
<div class="info-section">
<h3>Area Analysis (Current Time)</h3>
<div class="info-row">
<span>Total Surface Area:</span>
<span>${formatDecimal(info.totalArea)} square meters</span>
</div>
<div class="info-row">
<span>Roof Area:</span>
<span>${formatDecimal(info.roofArea)} square meters</span>
</div>
<div class="info-row">
<span>Fully Lit Area:</span>
<span>${formatDecimal(info.fullyLitArea)} square meters</span>
</div>
<div class="info-row">
<span>Partially Lit Area:</span>
<span>${formatDecimal(info.partiallyLitArea)} square meters</span>
</div>
<div class="info-row">
<span>Shadowed Area:</span>
<span>${formatDecimal(info.shadowedArea)} square meters</span>
</div>
</div>
<div class="info-section">
<h3>Solar Potential (Current Time)</h3>
<div class="info-row">
<span>Rooftop Solar Potential:</span>
<span>${formatDecimal(info.rooftopPotential)} kWh/day</span>
</div>
<div class="info-row">
<span>BIPV Potential:</span>
<span>${formatDecimal(
(info.bipvPotential + info.rooftopPotential))}
kWh/day</span>
</div>
</div>
`;
}
function AddPixelArray(pixelBuffer, currentArray) {
console.log("Incoming pixelBuffer:", pixelBuffer);
console.log("Current addArray:", currentArray);
if (!currentArray) {
// Initialize a new array with scaled values from pixelBuffer
const newArray = Array.from(pixelBuffer, (value) => 0);
console.log("Newly created addArray:", newArray);
return newArray;
} else {
// Accumulate values in a normal array
const resultArray = [];
for (let i = 0; i < currentArray.length; i++) {
resultArray[i] = currentArray[i] + pixelBuffer[i];
}
console.log("Resultant addArray:", resultArray);
return resultArray;
}
}
function DivideBy12(array) {
if (!array || !Array.isArray(array)) {
console.warn("Invalid array input");
return [];
}
return array.map((value) => Math.floor((value / 12) * 100) / 100);
}
async function simulateDay(latitude, longitude, date) {
renderer.render(scene, camera);
if (!selectedObject?.isMesh) {
console.warn("Please select a valid building first");
return;
}
isSimulating = true;
simulationObject = selectedObject;
const results = [];
let globalIntensities = []; // Initialize as empty array
try {
for (let hour = 6; hour <= 18; hour++) {
const datetime = new Date(date);
datetime.setHours(hour);
updateSunPosition(latitude, longitude, datetime);
const hourResult = analyzeObject(simulationObject,hour-6);
if (hourResult) {
results.push(hourResult);
// Add current intensities to global array
globalIntensities = globalIntensities.concat(
Array.from(hourResult.intensities || [])
);
}
await new Promise((resolve) => setTimeout(resolve, 500));
}
// Calculate average intensities
const averagedIntensities = DivideBy12(globalIntensities);
// Apply heatmap with averaged intensities
applyHeatmapToObject(selectedObject, averagedIntensities);
const averageResult = calculateAverageResults(results);
displayAverageResults(averageResult);
// After simulation completes, display graph
displaySimulationGraph(results);
displaySolarPotentialGraph(results);
displayNorthSouthwalaGraph(results);
} catch (error) {
console.error("Simulation failed:", error);
} finally {
setNoonPosition(latitude, longitude, date);
isSimulating = false;
simulationObject = null;
}
}
function calculateAverageResults(results) {
if (!results || !results.length) {
console.warn("No results to average");
return null;
}
const averageResult = {
fullyLitPercent: 0,
partiallyLitPercent: 0,
shadowedPercent: 0,
totalArea: 0,
roofArea: 0,
fullyLitArea: 0,
partiallyLitArea: 0,
shadowedArea: 0,
bipvPotential: 0,
rooftopPotential: 0,
};
// Sum all values
results.forEach((result) => {
const totalArea =
(result.fullyLitArea || 0) +
(result.partiallyLitArea || 0) +
(result.shadowedArea || 0);
// Calculate percentages for this result
const fullyLitPercent =
totalArea > 0 ? ((result.fullyLitArea || 0) / totalArea) * 100 : 0;
const partiallyLitPercent =
totalArea > 0
? ((result.partiallyLitArea || 0) / totalArea) * 100
: 0;
const shadowedPercent =
totalArea > 0 ? ((result.shadowedArea || 0) / totalArea) * 100 : 0;
averageResult.fullyLitPercent += fullyLitPercent;
averageResult.partiallyLitPercent += partiallyLitPercent;
averageResult.shadowedPercent += shadowedPercent;
averageResult.totalArea += totalArea;
averageResult.roofArea += result.roofArea || 0;
averageResult.fullyLitArea += result.fullyLitArea || 0;
averageResult.partiallyLitArea += result.partiallyLitArea || 0;
averageResult.shadowedArea += result.shadowedArea || 0;
averageResult.bipvPotential += result.bipvPotential || 0;
averageResult.rooftopPotential += result.rooftopPotential || 0;
});
// Calculate averages
const count = results.length;
for (let key in averageResult) {
averageResult[key] = averageResult[key] / count;
}
return averageResult;
}
function displayAverageResults(averageResult) {
const infoPanel = document.getElementById("infoPanel");
infoPanel.innerHTML += `
<br><h3>Daily Average Results</h3><br>
Total Surface Area: ${averageResult.totalArea.toFixed(
2
)} square meters<br>
Roof Area: ${averageResult.roofArea.toFixed(2)} square meters<br>
Fully Lit Area: ${averageResult.fullyLitArea.toFixed(
2
)} square meters<br>
Partially Lit Area: ${averageResult.partiallyLitArea.toFixed(
2
)} square meters<br>
Shadowed Area: ${averageResult.shadowedArea.toFixed(
2
)} square meters<br>
Rooftop Solar Potential: ${averageResult.rooftopPotential.toFixed(
2
)} kWh/day<br>
BIPV Potential: ${(
averageResult.bipvPotential + averageResult.rooftopPotential
).toFixed(2)} kWh/day
`;
}
function calculateMeshLighting(mesh) {
// Use a simple approximation based on mesh normals and sun direction
const sunDir = sunLight.position.clone().normalize();
const normalMatrix = new THREE.Matrix3().getNormalMatrix(
mesh.matrixWorld
);
let totalIntensity = 0;
const normals = mesh.geometry.attributes.normal;
for (let i = 0; i < normals.count; i++) {
const normal = new THREE.Vector3(
normals.getX(i),
normals.getY(i),
normals.getZ(i)
);
normal.applyMatrix3(normalMatrix).normalize();
const intensity = Math.max(normal.dot(sunDir), 0);
totalIntensity += intensity;
}
// Return average intensity
return totalIntensity / normals.count;
}
function applyHeatmap(meshLightingData) {
// Determine min and max intensities
let minIntensity = Infinity;
let maxIntensity = -Infinity;
meshLightingData.forEach((intensity) => {
if (intensity < minIntensity) minIntensity = intensity;
if (intensity > maxIntensity) maxIntensity = intensity;
});
// Apply color to each mesh based on accumulated intensity
meshLightingData.forEach((intensity, mesh) => {
// Normalize intensity
const normalizedIntensity =
(intensity - minIntensity) / (maxIntensity - minIntensity);
// Map normalized intensity to color from blue (low) to red (high)
const hue = ((1 - normalizedIntensity) * 240) / 360; // Map intensity from blue (240°) to red (0°)
const color = new THREE.Color().setHSL(hue, 1, 0.5);
// Apply color to mesh
mesh.material = new THREE.MeshBasicMaterial({ color: color });
});
}
function startSimulation() {
const latitude =
parseFloat(document.getElementById("latInput").value) ||
AHMEDABAD_LAT;
const longitude =
parseFloat(document.getElementById("longInput").value) ||
AHMEDABAD_LONG;