/
scene.cpp
5670 lines (4625 loc) · 277 KB
/
scene.cpp
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
#include <vector>
#include <fstream>
#include <sstream>
#include <string>
#include <iomanip>
#include <limits>
#include "scene.h"
#include "district.h"
#include "plant.h"
#include "models.h"
#include "RENIndexedFaceSet.h" // for the attempt of triangulation
#ifndef DEBUG
#include <omp.h> // for the OpenMP parallelisation
#endif
#ifdef FMI
// helper function for printing debug info
void importlogger(jm_callbacks* c, jm_string module, jm_log_level_enu_t log_level, jm_string message)
{
printf("module = %s, log level = %s: %s\n", module, jm_log_level_to_string(log_level), message);
}
#endif
// *** Scene class, CitySim *** //
// *** jerome.kaempf@epfl.ch *** //
Scene::Scene(string inputFile, string climateFile):inputFile(inputFile),logStream(std::cout.rdbuf()) {
// loads the climate file
if (!climateFile.empty()) {
pClimate = new Climate(climateFile);
// shows the information about the location
logStream << "Location: " << pClimate->getLocation();
logStream << "\t(Latitude: " << pClimate->getLatitudeN() << " N, Longitude: " << pClimate->getLongitudeE();
logStream << " E, Altitude: " << pClimate->getAltitude() << " m, Meridian: " << pClimate->getMeridian() << " h)" << endl << flush;
// gets the information from the climate file
float latN = pClimate->getLatitudeN();
float longE = pClimate->getLongitudeE();
float merE = pClimate->getMeridian()*360.f/24.f;
float northW = 0.f;
// initilisation of the location for the sun and the scene
SKYSiteLocation location(GENAngle::Degrees(latN), GENAngle::Degrees(longE), GENAngle::Degrees(merE), GENAngle::Degrees(northW));
pSun = new SKYSun(location);
scene.SetLocation(location);
}
// rapid initialisation of the parameters (to avoid segmentation faults)
mNbReflections = 0;
lv.assign(tregenzaSky.PatchCount()/2, 0.f);
groundRadiance = 0.f;
}
void Scene::computeViewFactors() {
// calculates the view factors of the scene
// N.B.: the view factor calculation starts the direct, diffuse and daylight calculations in sequence
// the direct calculation needs the Site Location in order to compute all sun positions
v.CalculateViewFactors(scene);
logStream << "View factors calculated." << endl << flush;
// computes the projected solid angles of the vault (ground, sky and hemisphere) -> to get the SVF, GVF for each surface
computeProjectedSolidAngles();
// computes the sparse matrix for inter-reflections
buildSparseMatrix();
}
void Scene::computeProjectedSolidAngles() {
// an hemisphere is attached to each surface of the scene, this method
// computes the projected solid angles of the vault (ground, sky and hemisphere) -> to get the SVF, GVF for each surface
vector<double> sky(scene.SurfaceCount(), 0.), ground(scene.SurfaceCount(), 0.), hemisphere(scene.SurfaceCount(), 0.); // the seen projected hemisphere from and on the surface itself
#pragma omp parallel for schedule(dynamic)
for (unsigned int surfaceIndex=0; surfaceIndex<scene.SurfaceCount(); ++surfaceIndex) {
// diffuse part
for (DATAViewFactorSetSparse::const_iterator factors=scene.GetSurface(surfaceIndex).SWViewFactors().GetVFs();
factors!=scene.GetSurface(surfaceIndex).SWViewFactors().GetLastVF();
++factors) // loop on the patches that are non-zero
{
// unobstructed part of the Tregenza patch -> meaning not obstructed by a surface
// the factors->unobstructed contains the patchSolidAngle and the cos of the angles between the surface normal and the center of patch
if (factors->unobstructed > 0.f) {
if ( factors->patchNo < static_cast<int>(tregenzaSky.PatchCount()/2) ) {
// diffuse part sky
sky[surfaceIndex] += factors->unobstructed;
}
else {
// diffuse part ground
ground[surfaceIndex] += factors->unobstructed;
}
}
// the sum of the hemisphere (around Pi)
hemisphere[surfaceIndex] += factors->unobstructed + factors->obstructed;
}
// saves all the projected solid angles
((Surface*)(scene.GetSurface(surfaceIndex).SurfaceDelegate()))->setProjectedSolidAngle(sky[surfaceIndex], ground[surfaceIndex], hemisphere[surfaceIndex]);
}
return;
}
void Scene::buildSparseMatrix() {
logStream << "Building inter-reflection matrix." << endl << flush;
logStream << "Number of surfaces: " << scene.SurfaceCount() << endl << flush;
logStream << "Number of reflections: " << mNbReflections << endl << flush;
// initialise the parameters
Ai.clear();
Aj.clear();
An.clear();
#ifdef DEBUG
ostringstream saveVault;
// for each patch
for (unsigned int i=0; i<tregenzaSky.PatchCount(); ++i)
{
saveVault << i << "\t" << fmod(tregenzaSky.GetPatch(i)->centroid().Azimuth().degrees()+360.,360.) << "\t"
<< tregenzaSky.GetPatch(i)->centroid().Altitude().degrees() << "\t"
<< tregenzaSky.GetPatch(i)->solidAngle() << endl << flush;
// for each Cell in the patch
for (unsigned int j=0; j<tregenzaSky.GetPatch(i)->cellCount(); ++j)
{
saveVault << i << "\t" << j << "\t" << tregenzaSky.GetPatch(i)->getCell(j).direction().Azimuth().degrees() << "\t"
<< tregenzaSky.GetPatch(i)->getCell(j).direction().Altitude().degrees() << "\t"
<< tregenzaSky.GetPatch(i)->getCell(j).solidAngle() << endl << flush;
}
}
save(string("vault.txt"),saveVault);
#endif
// only interesting when considering reflections
if ( mNbReflections == 0 ) return;
// loop on all surfaces to get the values in the matrices
for (unsigned int surfaceIndex = 0; surfaceIndex < scene.SurfaceCount(); surfaceIndex++) { // selection of a surface
// the surface index is the row number
// logStream << "Surface index: " << surfaceIndex << endl << flush;
// logStream << "Surface ID: " << ((Surface*)(scene.GetSurface(surfaceIndex).SurfaceDelegate()))->getId() << endl << flush;
// add the reference in the Ai vector for surfaceIndex (corresponding line i)
Ai.push_back( An.size() );
// stores the end of the actual vector of row indices
unsigned int endOfRowIndex = Aj.size();
// going through the Tregenza patches
for (DATAViewFactorSetSparse::const_iterator factors=scene.GetSurface(surfaceIndex).SWViewFactors().GetVFs();
factors!=scene.GetSurface(surfaceIndex).SWViewFactors().GetLastVF();
++factors)
{
// if the obstructed fraction is null, nothing is taken into account (many values equal to zero come out from SRA, when unobstructed > 0.f)
if ( !(factors->obstructed > 0.f) ) continue;
// is the main obstructing surface already in the set?
vector<unsigned int>::iterator it;
it = find(Aj.begin()+endOfRowIndex, Aj.end(), factors->mainobstructing);
if ( it == Aj.end() ) { // not found in the set
An.push_back( ( ((Surface*)(scene.GetSurface(factors->mainobstructing).SurfaceDelegate()))->getShortWaveReflectance() / M_PI )*(factors->obstructed) );
Aj.push_back( factors->mainobstructing );
}
else {
An[distance(Aj.begin(),it)] += ( ((Surface*)(scene.GetSurface(factors->mainobstructing).SurfaceDelegate()))->getShortWaveReflectance() / M_PI )*(factors->obstructed);
}
// logStream << "mainobstructing: " << factors->mainobstructing << "\tobstructed: " << factors->obstructed << "\tfor patch: " << factors->patchNo << endl << flush;
// logStream << "An: " << An << endl << flush;
// logStream << "Aj: " << Aj << endl << flush;
// logStream << "Ai: " << Ai << endl << flush;
}
}
// shows the matrix in CRS format
if (An.empty()) {
logStream << "Empty Compressed Row Storage inter-reflection Sparse Matrix." << endl << flush;
}
else {
//logStream << "An: " << An << endl << flush;
//logStream << "Aj: " << Aj << endl << flush;
//logStream << "Ai: " << Ai << endl << flush;
logStream << "Compressed Row Storage inter-reflections Sparse Matrix ready." << endl << flush;
logStream << "Surfaces: " << getnAi() << "\tNon-zero elements: " << An.size() << "\tAverage non-zero elements / surface: " << static_cast<float>(An.size())/getnAi() << endl << flush;
}
return;
}
void Scene::showViewFactors() {
// output on the screen of the view factors
for (DATASurfaceIterator it=scene.GetAllSurfaces();
!it.isAtEnd();
++it)
{
// selection of a surface it
for (DATAViewFactorSetSparse::const_iterator factors=it->SWViewFactors().GetVFs();
factors!=it->SWViewFactors().GetLastVF();
++factors)
{
// for that surface it, output of the informations in the sparse format
logStream << "Unobstructed factor to patch " << factors->patchNo << ": " << factors->unobstructed << "\n";
logStream << "Obstructed factor to the same patch: " << factors->obstructed << endl << flush;
logStream << "Main obstructing surface: " << factors->mainobstructing << endl << flush;
}
pSun->SetDay(30); //absolute day from the start of the year [1,365]
pSun->SetClockTime(10.5); // clock time [0,24[
logStream << "Insolation factor: " << it->InsolationFactors().GetInsolationFactor(*pSun) << "\n" << flush;
}
}
void Scene::exportRadFile(string radFile,bool triangulated) {
// keeps the name of the inputFile if radFile empty
if (radFile.empty()) radFile=inputFile;
// open the output file
ofstream outputRad((radFile.substr(0,radFile.size()-4) + ".rad").c_str(), ios::binary);
outputRad.setf(ios::fixed); // set fixed floating format
outputRad.unsetf(ios::floatfield); // precision will only specifies the maximum number of digits to be displayed, but not the minimum
outputRad.precision(numeric_limits<float>::max_digits10); // set the precision to the maximum digits possible with float
// test d'ouverture
if (!outputRad.is_open()) throw string("Error opening file: " + (radFile.substr(0,radFile.size()-4) + ".rad"));
// writing the material
outputRad << "void plastic surface\n" << "0\n" << "0\n" << "5 .2 .2 .2 0 0\n" << endl;
if (triangulated) {
// get Indexed Triangulated Surfaces
std::shared_ptr<RENIndexedFaceSet> pIndexedFaceSet = scene.IndexedFaceSet();
const std::vector<unsigned int>& pointIndices=pIndexedFaceSet->GetIndices();
// loop on triangles
for (unsigned int i=0; i<pointIndices.size()/3; i++) {
outputRad << "surface polygon SURFACE#" << i << endl;
outputRad << "0\n" << "0\n";
// 9 coordinates given
outputRad << "9\n";
for (unsigned int k=0; k<3; k++) outputRad << GENPoint(pIndexedFaceSet->GetVertex(pointIndices[i*3]))[k] << " ";
outputRad << endl;
for (unsigned int k=0; k<3; k++) outputRad << GENPoint(pIndexedFaceSet->GetVertex(pointIndices[i*3+1]))[k] << " ";
outputRad << endl;
for (unsigned int k=0; k<3; k++) outputRad << GENPoint(pIndexedFaceSet->GetVertex(pointIndices[i*3+2]))[k] << " ";
outputRad << "\n" << endl;
}
}
else {
// loop on all surfaces
for (DATASurfaceIterator it=scene.GetAllSurfaces();
!it.isAtEnd();
++it)
{
outputRad << "surface polygon SURFACE#" << scene.SurfaceCount()-distance(it,scene.GetAllSurfaces().end()) << endl;
outputRad << "0\n" << "0\n";
// write the number of vertices for surface it
outputRad << 3*(it->SurfaceDelegate()->vertexCount()) << endl;
// get the surface vertices
struct Vertices : public DATASurfaceDelegateABC::VertexVisitor
{
virtual void operator()(const GENPoint& v)
{
vertices.push_back(v);
}
virtual ~Vertices() {};
std::vector<GENPoint> vertices;
} polygon;
it->SurfaceDelegate()->sendVertices(polygon);
// loop on the vertices to write them out
for (unsigned int i=0; i<it->SurfaceDelegate()->vertexCount(); i++) {
outputRad << "\t" << polygon.vertices[i][0] << " "
<< polygon.vertices[i][1] << " "
<< polygon.vertices[i][2] << endl;
}
outputRad << endl;
}
}
outputRad.close();
}
void Scene::exportInpFile(string radFile, bool buildingsOnly) {
// keeps the name of the inputFile if radFile empty
if (radFile.empty()) radFile=inputFile;
// open the output file
ofstream outputInp((radFile.substr(0,radFile.size()-4) + ".inp").c_str(), ios::binary);
outputInp.setf(ios::fixed); // set fixed floating format
outputInp.unsetf(ios::floatfield); // precision will only specifies the maximum number of digits to be displayed, but not the minimum
outputInp.precision(numeric_limits<float>::max_digits10); // set the precision to the maximum digits possible with float
// test d'ouverture
if (!outputInp.is_open()) throw string("Error opening file: " + (radFile.substr(0,radFile.size()-4) + ".inp"));
if (buildingsOnly) {
// loop on all surfaces
for (DATASurfaceIterator it=scene.GetBuildingSurfaces();
!it.isAtEnd();
++it)
{
double gap = 0.05;
// selection of a surface it
//outputInp << "#Surface number: " << scene.SurfaceCount()-distance(it,scene.GetAllSurfaces().end()) << endl;
GENPoint centroid = it->Centroid() + (it->Normal())*gap;
outputInp << centroid[0] << "\t" << centroid[1] << "\t" << centroid[2] << "\t";
outputInp << it->Normal()[0] << "\t" << it->Normal()[1] << "\t" << it->Normal()[2] << endl;
}
}
else {
// loop on all surfaces
for (DATASurfaceIterator it=scene.GetAllSurfaces();
!it.isAtEnd();
++it)
{
double gap = 0.05;
// selection of a surface it
//outputInp << "#Surface number: " << scene.SurfaceCount()-distance(it,scene.GetAllSurfaces().end()) << endl;
GENPoint centroid = it->Centroid() + (it->Normal())*gap;
outputInp << centroid[0] << "\t" << centroid[1] << "\t" << centroid[2] << "\t";
outputInp << it->Normal()[0] << "\t" << it->Normal()[1] << "\t" << it->Normal()[2] << endl;
}
}
outputInp.close();
}
void Scene::exportDXF(string fileName) {
if(fileName=="") fileName=inputFile.substr(0,inputFile.size()-4) + ".dxf";
else if(fileName.substr(fileName.size()-4,4)!=".dxf") fileName.append(".dxf");
// open the output file
ofstream outputDxf(fileName.c_str());
if (!outputDxf.good()) throw(string("Error creating model: " + fileName));
// setting good precision for the points
outputDxf.setf(ios::fixed); // set fixed floating format
outputDxf.unsetf(ios::floatfield); // precision will only specifies the maximum number of digits to be displayed, but not the minimum
outputDxf.precision(numeric_limits<float>::max_digits10); // set the precision to the maximum digits possible with float
// writing the HEADER
outputDxf << "999\n" << "CitySim DXF" << endl;
outputDxf << "0\n" << "SECTION" << endl;
outputDxf << "2\n" << "HEADER" << endl;
outputDxf << "9\n" << "$ACADVER" << endl;
outputDxf << "1\n" << "AC1006" << endl;
outputDxf << "9\n" << "$INSUNITS" << endl;
outputDxf << "70\n" << "6" << endl;
outputDxf << "0\n" << "ENDSEC" << endl;
// section of the ENTITIES
outputDxf << " 0\n" << "SECTION\n" << " 2\n" << "ENTITIES" << endl;
// loop on the surfaces for the export
for (DATASurfaceIterator it=scene.GetAllSurfaces();
!it.isAtEnd();
++it)
{
outputDxf << " 0\n" << "3DFACE" << endl;
outputDxf << "8" << endl; // now comes the layer, 1 is for wall and 0 is for the ground
if (it->IsBuildingSurface()) { outputDxf << "1" << endl; }
else { outputDxf << "0" << endl; }
outputDxf << "62" << endl; // 62 stands for the color of the surface
if (it->IsBuildingSurface()) { outputDxf << "1" << endl; } // red for the buildings
else { outputDxf << "2" << endl; } // yellow for the ground
// now the vertices...
struct Vertices : public DATASurfaceDelegateABC::VertexVisitor
{
virtual void operator()(const GENPoint& v)
{
vertices.push_back(v);
}
virtual ~Vertices() {}
std::vector<GENPoint> vertices;
} polygon;
it->SurfaceDelegate()->sendVertices(polygon);
if ( polygon.vertices.size() > 4 ) {
// proceed to the triangulation
std::shared_ptr<RENIndexedFaceSet> indexedFaceSet(new RENIndexedFaceSet());
RENIndexedFaceSetBuilder meshBuilder(indexedFaceSet);
meshBuilder.AddSurface(polygon.vertices.begin(),polygon.vertices.end(),0);
const std::vector<unsigned int>& pointIndices=indexedFaceSet->GetIndices();
for (unsigned int i=0; i<indexedFaceSet->TriangleCount()*3; i+=3) {
// write those three points and repeat the first one
for (unsigned int j=0; j<4; ++j) {
outputDxf << " 1" << i << "\n" << GENPoint(indexedFaceSet->GetVertex(pointIndices[i+(j%3)]))[0] << "\n"
<< " 2" << i << "\n" << GENPoint(indexedFaceSet->GetVertex(pointIndices[i+(j%3)]))[1] << "\n"
<< " 3" << i << "\n" << GENPoint(indexedFaceSet->GetVertex(pointIndices[i+(j%3)]))[2] << endl;
}
}
}
else {
// loop on the vertices to write them out
for (unsigned int i=0; i<polygon.vertices.size(); i++) {
outputDxf << " 1" << i << "\n" << polygon.vertices[i][0] << "\n"
<< " 2" << i << "\n" << polygon.vertices[i][1] << "\n"
<< " 3" << i << "\n" << polygon.vertices[i][2] << endl;
}
if ( polygon.vertices.size() == 3 ) { // to close the loop the the 3 vertices
outputDxf << " 13\n" << polygon.vertices[0][0] << "\n"
<< " 23\n" << polygon.vertices[0][1] << "\n"
<< " 33\n" << polygon.vertices[0][2] << endl;
}
}
}
outputDxf << " 0\n" << "ENDSEC\n" << " 0\n" << "EOF" << endl;
outputDxf.close();
}
void Scene::computeRadiance(const unsigned int& day, const float& Idh, const float& Ibn, const float& albedo) {
// erases and prepares the new vector
lv.assign( tregenzaSky.PatchCount()/2, 0.f);
groundRadiance = 0.f;
// computes the 145 Tregenza patches' Radiance
if (sky.SetSkyConditions(Idh,Ibn,pSun->GetPosition().Altitude().radians(), pSun->GetPosition().Azimuth().radians(),day)) {
// if true Idh is positive and the diffuse sky can be created
double intHemisphere = 0.;
for (unsigned int i=0; i<tregenzaSky.PatchCount()/2; i++) {
lv[i] = sky.GetRelativeLuminance(tregenzaSky.getPatchCenterAltitude(i),tregenzaSky.getPatchCenterAzimuth(i));
intHemisphere += lv[i]*tregenzaSky.GetPatch(i)->solidAngle()*sin(tregenzaSky.getPatchCenterAltitude(i));
}
if (intHemisphere > 0.) for (unsigned int i=0; i<tregenzaSky.PatchCount()/2; i++) lv[i]*=Idh/intHemisphere;
// computes the ground radiance value
// as a lambertian reflection of the total sky and sun irradiances on the horizontal plane
for (unsigned int p = 0; p < tregenzaSky.PatchCount()/2; p++){
groundRadiance += lv[p] * tregenzaSky.GetPatch(p)->formFactor( GENPoint::Cartesian(0.f,0.f,1.f) ); // projected solidAngle in the horizontal plane
}
groundRadiance += (Ibn * sin(pSun->GetPosition().Altitude().radians())); //add solar irradiance, transform to beam horizontal
groundRadiance *= albedo/M_PI;
}
return;
}
void Scene::computeCumulativeRadiance(unsigned int beginDay, unsigned int endDay, float albedo) {
// vector to save the cumulative radiance
vector<float> cumLv(tregenzaSky.PatchCount()/2, 0.f);
float cumGroundRadiance = 0.f;
// debut de la simulation sur la periode consideree
for (unsigned int day = beginDay; day<=endDay; ++day) {
for (unsigned int hour = 1; hour <= 24; ++hour) {
// initialisation of the sun (for the VFC)
pSun->SetDay(day);
if (pSun->SetClockTime1(hour)) { // if sun is up
// computes the patches radiance without obstructions
computeRadiance(day, pClimate->getIdh(day,hour), pClimate->getIbn(day,hour), albedo);
// accumulate it in the cumulative vector and value
for (size_t i = 0; i < tregenzaSky.PatchCount()/2; ++i) {
cumLv[i] += lv[i];
}
cumGroundRadiance += groundRadiance;
}
}
}
// save the result in lv and groundRadiance
for (size_t i = 0; i < tregenzaSky.PatchCount()/2; ++i) { lv[i] = cumLv[i]; }
groundRadiance = cumGroundRadiance;
// save the data
//save("cumulativeSkyRadiance.txt", lv);
//save("cumulativeGroundRadiance.txt", groundRadiance);
// save as well the vault data
// ostringstream saveVault;
// for each patch
// for (size_t i=0; i<tregenzaSky.PatchCount(); ++i)
// {
// saveVault << i << "\t" << fmod(tregenzaSky.GetPatch(i)->centroid().Azimuth().degrees()+360.f,360.f) << "\t"
// << tregenzaSky.GetPatch(i)->centroid().Altitude().degrees() << "\t"
// << tregenzaSky.GetPatch(i)->solidAngle() << endl;
// }
// save("skyVault.txt",saveVault);
return;
}
void Scene::exportSkyAndGround(string radFile, float luminousEfficacy) {
// create the rad file with reference to .cal file
ofstream radOut(radFile.c_str(), ios::binary);
if (!radOut.is_open()) throw(string("Error creating sky file: " + radFile));
radOut << "#Sky and Ground file generated by CitySim (jerome.kaempf@kaemco.ch)"
<< "\n" << endl;
// preparation of the sky
radOut << "void brightfunc skyfunc" << endl
<< "2 skybright " << radFile.substr(0,radFile.size()-4) << ".cal" << endl
<< "0" << endl << "0\n" << endl
<< "skyfunc glow sky_glow" << endl
<< "0" << endl << "0" << endl << "4 1 1 1 0\n" << endl
<< "sky_glow source sky" << endl
<< "0" << endl << "0" << endl << "4 0 0 1 180\n" << endl
<< "void glow ground_glow\n"
<< "0\n0\n4 " << groundRadiance*luminousEfficacy << " " << groundRadiance*luminousEfficacy << " " << groundRadiance*luminousEfficacy << " 0\n" << endl
<< "ground_glow source ground"
<< "\n0\n0\n4 0 0 -1 180";
radOut.close();
// create the .cal file with the radiance values
ofstream skyCalOut((radFile.substr(0,radFile.size()-4) + ".cal").c_str(), ios::binary);
if (!skyCalOut.is_open()) throw(string("Error creating sky file: " + radFile.substr(0,radFile.size()-4) + ".cal"));
skyCalOut << "skybright=";
for (unsigned int j=0; j<tregenzaSky.getBands()-1; j++)
{
skyCalOut << "row" << j << "+";
}
skyCalOut << "row" << tregenzaSky.getBands()-1 << ";" << endl << endl;
unsigned int counter = 0;
for (unsigned int j=0; j<tregenzaSky.getBands()-1; j++)
{
// note first patch split into two parts - first part (> 0 deg) and last patch (<360)
skyCalOut << "row" << j << "=if(and(alt-" << j*tregenzaSky.getDeltaAltitude()*180./M_PI << ", " << (j+1)*tregenzaSky.getDeltaAltitude()*180./M_PI << "-alt),";
skyCalOut << "select(floor(0.5+az/" << tregenzaSky.getDeltaAzimuth(j)*180./M_PI << ")+1," << endl;
for (unsigned int i=counter; i< counter + tregenzaSky.getPatchesPerBand(j); i++)
{
skyCalOut << "\t" << lv[i]*luminousEfficacy << "," << endl;
}
// rewrite the first one.
skyCalOut << "\t" << lv[counter]*luminousEfficacy << "),0);" << endl << endl;
counter += tregenzaSky.getPatchesPerBand(j);
}
// top patch.
skyCalOut << "row" << tregenzaSky.getBands()-1 << "=if(alt-"<< 90.-(tregenzaSky.getDeltaAltitude()*180./M_PI / 2.)<< "," << lv[counter]*luminousEfficacy << ",0);"<< endl << endl;
skyCalOut << "alt=asin(Dz)*180/PI;" << endl << endl;
skyCalOut << "az=if(azi,azi,azi+360);" << endl;
skyCalOut << "azi=atan2(Dx,Dy)*180/PI;" << endl << endl;
skyCalOut.close();
return;
}
void Scene::exportCumulativeRadiance()
{
// computes the sky and ground file
computeCumulativeRadiance();
exportSkyAndGround((inputFile.substr(0,inputFile.size()-4) + "_cumSkyGrnd.rad"));
// preparation of the cumulative suns file
ofstream radOut((inputFile.substr(0,inputFile.size()-4) + "_cumSuns.rad").c_str(), ios::binary);
if (!radOut.is_open()) throw string("Error creating the cumulative Suns file.");
double sunLuminance = 0.;
GENPoint sunPosition;
for (unsigned int day = 1; day<=365; ++day) {
for (unsigned int hour = 1; hour <= 24; ++hour) {
// initialisation of the sun (for the VFC)
pSun->SetDay(day);
pSun->SetClockTime1(hour);
if (pSun->SunUp()) { // if sun is up
sunLuminance = pClimate->getIbn(day,hour) / pSun->getSolidAngle();
radOut << "void light solar_" << day << "_" << hour << "\n"
<< "0\n"
<< "0\n"
<< "3 " << sunLuminance << " " << sunLuminance << " " << sunLuminance << endl;
sunPosition = pSun->GetPosition();
radOut << "solar_" << day << "_" << hour << " source sun_" << day << "_" << hour << "\n"
<< "0\n"
<< "0\n"
<< "4 " << sunPosition[0] << " "
<< sunPosition[1] << " "
<< sunPosition[2] << " "
<< pSun->getAperture() << "\n"
<< endl;
}
}
}
}
// THE RADIANCE SCENE
Radscene::Radscene(string inputFile, string climateFile):Scene(inputFile, climateFile) {
// reads the Radiance file description and put the facades in the surfaceVector
logStream << "Reading Radiance file..." << endl << flush;
string tampon;
char tampon1[200];
// chargement des donnees a afficher
ifstream input1 (inputFile.c_str(), ios::binary);
// test d'ouverture
if (!input1.is_open()) throw string("Error opening Radiance file");
// initialise le compteur de surfaces
unsigned int count = 0;
while (!input1.eof()) {
input1 >> tampon; // first keyword
if ( tampon[0] == '#' ) input1.getline(tampon1, 200,'\n');
else if ( tampon == "void" ) { // material definition
input1 >> tampon; // material type
input1 >> tampon; // label of material
input1 >> tampon; // 0
input1 >> tampon; // 0
input1 >> tampon; // number of parameters
unsigned int number = atoi(tampon.c_str());
for (unsigned int i=0; i<number; i++) input1 >> tampon;
}
else { // whatever the name of the polygon
input1 >> tampon; // polygon
if ( tampon == "polygon" ) { // it has to be a polygon
if (input1.eof()) break;
// create the polygon
//surfaceVector.push_back(GENHandle<MySurfaceDelegate>(new MySurfaceDelegate()));
GENHandle<Surface> surface(new Surface(count++,0.2f,0.f,0.f,0.f,0.f));
input1 >> tampon; // label
input1 >> tampon; // 0
input1 >> tampon; // 0
input1 >> tampon; // number of points (3x3)
unsigned int number = atoi(tampon.c_str())/3;
double x,y,z;
for (unsigned int i=0; i<number; i++) {
input1 >> tampon;
x = atof(tampon.c_str());
input1 >> tampon;
y = atof(tampon.c_str());
input1 >> tampon;
z = atof(tampon.c_str());
logStream << "Point: " << x << ", " << y << ", " << z << endl << flush;
//surfaceVector.back()->pushVertex(x,y,z);
surface->pushVertex(x,y,z);
}
// computation of the surface normal (anti-clockwise -> positive)
//surfaceVector.back()->computeNormal();
surface->computeNormal();
//logStream << "Normal computed: (" << surfaceVector.back()->normal()[0] << ",";
//logStream << surfaceVector.back()->normal()[1] << "," << surfaceVector.back()->normal()[2] << ")" << endl << flush;
logStream << "Normal computed: (" << surface->normal()[0] << ",";
logStream << surface->normal()[1] << "," << surface->normal()[2] << ")" << endl << flush;
// computation of the surface area
//surfaceVector.back()->computeArea();
surface->computeArea();
//logStream << "Area computed: " << surfaceVector.back()->getArea() << endl << flush;
logStream << "Area computed: " << surface->getArea() << endl << flush;
if (surface->getArea() > 0) { // if non degenerate area
// adds the surface to the scene
scene.AddGroundSurface(surface); // no need of the daylighting model
}
else { logStream << "Null surface area not taken into account." << endl << flush; }
}
else {
input1 >> tampon; // label of material
input1 >> tampon; // number of ascii parameters
unsigned int number = atoi(tampon.c_str());
for (unsigned int i=0; i<number; i++) input1 >> tampon;
input1 >> tampon; // 0
input1 >> tampon; // number of parameters
number = atoi(tampon.c_str());
for (unsigned int i=0; i<number; i++) input1 >> tampon;
}
}
}
input1.close();
// calculates the view factors of the scene
// N.B.: the view factor calculation starts the direct, diffuse and daylight calculations in sequence
// the direct calculation needs the Site Location in order to compute all sun positions
computeViewFactors();
// initialise the vectors for intermediary results
irradiationDiffuseSky.assign(scene.SurfaceCount(),0.f);
irradiationDiffuseGround.assign(scene.SurfaceCount(),0.f);
irradiationBeam.assign(scene.SurfaceCount(),0.f);
irradiationReflection.assign(scene.SurfaceCount(),0.f);
}
void Radscene::clearResults() {
irradiationDiffuseSky.assign(scene.SurfaceCount(),0.f);
irradiationDiffuseGround.assign(scene.SurfaceCount(),0.f);
irradiationBeam.assign(scene.SurfaceCount(),0.f);
irradiationReflection.assign(scene.SurfaceCount(),0.f);
outData.str(""); // clearing the ostringstream
}
void Radscene::exportSWFile(string filename) {
fstream output (filename.c_str(), ios::out | ios::binary);
output.setf(ios::fixed); // set fixed floating format
output.unsetf(ios::floatfield); // precision will only specifies the maximum number of digits to be displayed, but not the minimum
output.precision(numeric_limits<float>::max_digits10); // set the precision to the maximum digits possible with float
for (unsigned int i=0;i<irradiationBeam.size();++i) output << irradiationBeam[i]+irradiationDiffuseSky[i]+irradiationDiffuseGround[i]+irradiationReflection[i] << endl;
output.close();
return;
}
void Radscene::computeShortWave(unsigned int day, unsigned int hour) {
// irradiationSW: irradiation without reflections, irradiationSWn: irradiation with reflections
vector<float> irradiationSW(scene.SurfaceCount(), 0.f), irradiationSWn(irradiationSW);
// initialisation of the sun (for the VFC)
pSun->SetDay(day);
if (pSun->SetClockTime1(hour)) { // if the day has started
// gets Idh and Ibn from the climate file
float Idh = pClimate->getIdh(day,hour);
float Ibn = pClimate->getIbn(day,hour);
// computes the patches radiance without and then with obstructions
computeRadiance(day,Idh,Ibn);
//save("cumRadiance_" + toString(day) + "_" + toString(hour) + ".txt", lv);
// now the main loop on surfaces
#pragma omp parallel for schedule(dynamic)
for (unsigned int surfaceIndex=0; surfaceIndex<scene.SurfaceCount(); ++surfaceIndex) {
// diffuse part sky
for (DATAViewFactorSetSparse::const_iterator factors=scene.GetSurface(surfaceIndex).SWViewFactors().GetVFs();
factors!=scene.GetSurface(surfaceIndex).SWViewFactors().GetLastVF();
++factors) // loop on the patches that are non-zero
{
// the factors->unobstructed contains the patchSolidAngle and the cos of the angles between the surface normal and the center of patch
if (factors->unobstructed > 0.f) {
if ( factors->patchNo < static_cast<int>(tregenzaSky.PatchCount()/2) ) {
// diffuse part sky
irradiationSW[surfaceIndex] += factors->unobstructed * lv[factors->patchNo];
irradiationDiffuseSky[surfaceIndex] += factors->unobstructed * lv[factors->patchNo];
}
}
}
// diffuse part ground
irradiationSW[surfaceIndex] += ((Surface*)(scene.GetSurface(surfaceIndex).SurfaceDelegate()))->getProjectedSolidAngle_ground() * groundRadiance;
irradiationDiffuseGround[surfaceIndex] += ((Surface*)(scene.GetSurface(surfaceIndex).SurfaceDelegate()))->getProjectedSolidAngle_ground() * groundRadiance;
// direct part
double cosTheta = GEN::dot_product(scene.GetSurface(surfaceIndex).Normal(),pSun->GetPosition());
if (cosTheta > 0.) {
irradiationSW[surfaceIndex] += scene.GetSurface(surfaceIndex).InsolationFactors().GetInsolationFactor(*pSun) * Ibn * cosTheta; // fraction of the surface that is light by the sun
irradiationBeam[surfaceIndex] += scene.GetSurface(surfaceIndex).InsolationFactors().GetInsolationFactor(*pSun) * Ibn * cosTheta; // fraction of the surface that is light by the sun
}
} // end the loop on the surfaces
// adds the reflections on the surfaces
irradiationSWn = irradiationSW;
for (unsigned int r = 0; r < mNbReflections; ++r) {
// using the CRS sparse matrix format, multiplication of the matrix by the former vector
vector<float> irradiationSWnew(irradiationSW);
#pragma omp parallel for schedule(dynamic)
for (unsigned int i=0; i < getnAi(); ++i) { // loop on the number of elements
for (unsigned int index=getAi(i); index < getAi(i+1); ++index) {
irradiationSWnew[i] += getAn(index) * irradiationSWn[getAj(index)];
}
}
// saves the new irradiation vector in the current
irradiationSWn = irradiationSWnew;
}
} // end if sun is up
// computes what is due to inter-reflections
for (unsigned int i=0; i<irradiationSWn.size(); ++i) irradiationReflection[i] = irradiationSWn[i] - irradiationSW[i];
// end of the calculations, save in all surfaces the irradiation
for (DATASurfaceIterator it=scene.GetAllSurfaces();!it.isAtEnd();++it)
{
// saves all the irradiation
((Surface*)(it->SurfaceDelegate()))->setShortWaveIrradiance(irradiationSWn[scene.SurfaceCount()-distance(it,scene.GetAllSurfaces().end())]);
}
return;
}
void Radscene::compareWithRadianceExternalIrradiance(unsigned int day, unsigned int hour) {
// test if the sun is up
pSun->SetDay(day);
if (pSun->SetClockTime1(hour)) {
// loop on the surfaces to create the _mesh.inp
ofstream outputInp((inputFile.substr(0,inputFile.size()-4) + "_mesh.inp").c_str(), ios::binary);
if (!outputInp.is_open()) throw string("Error opening file: " + (inputFile.substr(0,inputFile.size()-4) + "_mesh.inp"));
outputInp.setf(ios::fixed); // set fixed floating format
outputInp.unsetf(ios::floatfield); // precision will only specifies the maximum number of digits to be displayed, but not the minimum
outputInp.precision(numeric_limits<float>::max_digits10); // set the precision to the maximum digits possible with float
// save the number of points per surface
vector<unsigned int> numberOfPointsPerSurface;
// loop on all surfaces
for (DATASurfaceIterator it=scene.GetAllSurfaces();
!it.isAtEnd();
++it)
{
double gap = 0.05;
double maxDetectorArea = 1.0;
// get the surface vertices
struct Vertices : public DATASurfaceDelegateABC::VertexVisitor
{
virtual void operator()(const GENPoint& v)
{
vertices.push_back(v);
}
virtual ~Vertices() {}
std::vector<GENPoint> vertices;
} polygon;
it->SurfaceDelegate()->sendVertices(polygon);
unsigned int numberOfPoints = 0;
for (unsigned int i=0;i<it->SurfaceDelegate()->vertexCount();i++) {
vector<GENPoint> triangle,grid;
triangle.push_back(it->Centroid());
triangle.push_back(polygon.vertices[i]);
triangle.push_back(polygon.vertices[(i+1)%(it->SurfaceDelegate()->vertexCount())]);
// creation of the grid
gridTriangle(triangle,maxDetectorArea,grid);
// save the number of vertices
numberOfPoints += grid.size();
// loop on the points in the grid
for (unsigned int j=0;j<grid.size();j++) {
// output of the couple grid and normal
outputInp << grid[j][0]+it->Normal()[0]*gap << " " << grid[j][1]+it->Normal()[1]*gap << " " << grid[j][2]+it->Normal()[2]*gap << " ";
outputInp << it->Normal()[0] << " " << it->Normal()[1] << " " << it->Normal()[2] << endl;
}
}
// put the number of points in the vector
numberOfPointsPerSurface.push_back(numberOfPoints);
}
outputInp.close();
// vectors to save the results
vector<float> sunIrrad, skyIrrad, groundIrrad, reflectionIrrad;
// export the sun, the sky and the ground in Radiance format
exportSunRadFile(inputFile.substr(0,inputFile.size()-4) + "_" + toString(day) + "_" + toString(hour) + "_sun.rad",day,hour);
exportSkyRadFile(inputFile.substr(0,inputFile.size()-4) + "_" + toString(day) + "_" + toString(hour) + "_sky.rad",day,hour);
exportGroundRadFile(inputFile.substr(0,inputFile.size()-4) + "_" + toString(day) + "_" + toString(hour) + "_ground.rad",day,hour);
// export the .inp files for the direct and diffuse
exportInpFile();
int error = 0; // error handling for the system command
// computes the direct component, start Radiance and read the results
ostringstream command;
command << "oconv " << inputFile << " " << inputFile.substr(0,inputFile.size()-4) << "_" << toString(day)
<< "_" << toString(hour) << "_sun.rad > " << inputFile.substr(0,inputFile.size()-4) << "_" << toString(day) << "_"
<< toString(hour) << "_sun.oct";
error = system(command.str().c_str());
if (error!=0) throw(string("Cannot start oconv (.oct)"));
command.str("");
command << "rtrace -w -I -h -dj 0 -ds 0 -dt 0 -dc 0.6 -dr 0 -dp 0 -ab 0 -aa 0 "
<< inputFile.substr(0,inputFile.size()-4) << "_" << toString(day) << "_" << toString(hour) << "_sun.oct"
<< " < " << inputFile.substr(0,inputFile.size()-4) << "_mesh.inp | rcalc -e '$1=0.265*$1+0.67*$2+0.065*$3' > "
<< inputFile.substr(0,inputFile.size()-4) << "_" << toString(day) << "_" << toString(hour) << "_sun.out";
error = system(command.str().c_str());
if (error!=0) throw(string("Cannot start rtrace (.out)"));
// computes the sky component
command.str("");
command << "oconv " << inputFile << " " << inputFile.substr(0,inputFile.size()-4) << "_" << toString(day)
<< "_" << toString(hour) << "_sky.rad > " << inputFile.substr(0,inputFile.size()-4) << "_" << toString(day) << "_"
<< toString(hour) << "_sky.oct";
error = system(command.str().c_str());
if (error!=0) throw(string("Cannot start oconv (.oct)"));
command.str("");
command << "rtrace -w -I -h -dj 0 -ds 0 -dt 0 -dc 0.6 -dr 0 -dp 0 -ab 1 -ad 2048 -as 512 -aa 0 "
<< inputFile.substr(0,inputFile.size()-4) << "_" << toString(day) << "_" << toString(hour) << "_sky.oct"
<< " < " << inputFile.substr(0,inputFile.size()-4) << ".inp | rcalc -e '$1=0.265*$1+0.67*$2+0.065*$3' > "
<< inputFile.substr(0,inputFile.size()-4) << "_" << toString(day) << "_" << toString(hour) << "_sky.out";
error = system(command.str().c_str());
if (error!=0) throw(string("Cannot start rtrace (.out)"));
// computes the ground component
command.str("");
command << "oconv " << inputFile << " " << inputFile.substr(0,inputFile.size()-4) << "_" << toString(day)
<< "_" << toString(hour) << "_ground.rad > " << inputFile.substr(0,inputFile.size()-4) << "_" << toString(day) << "_"
<< toString(hour) << "_ground.oct";
error = system(command.str().c_str());
if (error!=0) throw(string("Cannot start oconv (.oct)"));
command.str("");
command << "rtrace -w -I -h -dj 0 -ds 0 -dt 0 -dc 0.6 -dr 0 -dp 0 -ab 1 -ad 2048 -as 512 -aa 0 "
<< inputFile.substr(0,inputFile.size()-4) << "_" << toString(day) << "_" << toString(hour) << "_ground.oct"
<< " < " << inputFile.substr(0,inputFile.size()-4) << ".inp | rcalc -e '$1=0.265*$1+0.67*$2+0.065*$3' > "
<< inputFile.substr(0,inputFile.size()-4) << "_" << toString(day) << "_" << toString(hour) << "_ground.out";
error = system(command.str().c_str());
if (error!=0) throw(string("Cannot start rtrace (.out)"));
// computes the inter-reflection
command.str("");
command << "oconv " << inputFile << " " << inputFile.substr(0,inputFile.size()-4) << "_" << toString(day)
<< "_" << toString(hour) << "_sun.rad" << " " << inputFile.substr(0,inputFile.size()-4) << "_" << toString(day)
<< "_" << toString(hour) << "_sky.rad" << " " << inputFile.substr(0,inputFile.size()-4) << "_" << toString(day)
<< "_" << toString(hour) << "_ground.rad > " << inputFile.substr(0,inputFile.size()-4) << "_" << toString(day) << "_"
<< toString(hour) << ".oct";
error = system(command.str().c_str());
if (error!=0) throw(string("Cannot start oconv (.oct)"));
command.str("");
command << "rtrace -w -I -h -dj 0 -ds 0 -dt 0 -dc 0.6 -dr 0 -dp 0 -ab " << mNbReflections+1 << " -ad 2048 -as 512 -aa 0 "
<< inputFile.substr(0,inputFile.size()-4) << "_" << toString(day) << "_" << toString(hour) << ".oct"
<< " < " << inputFile.substr(0,inputFile.size()-4) << "_mesh.inp | rcalc -e '$1=0.265*$1+0.67*$2+0.065*$3' > "
<< inputFile.substr(0,inputFile.size()-4) << "_" << toString(day) << "_" << toString(hour) << "_reflection.out";