-
-
Notifications
You must be signed in to change notification settings - Fork 793
/
Landscape.cpp
2164 lines (1924 loc) · 81.6 KB
/
Landscape.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
/*
* Stellarium
* Copyright (C) 2003 Fabien Chereau
* Copyright (C) 2011 Bogdan Marinov
* Copyright (C) 2014-17 Georg Zotti
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Suite 500, Boston, MA 02110-1335, USA.
*/
#include "Landscape.hpp"
#include "StelApp.hpp"
#include "StelTextureMgr.hpp"
#include "StelFileMgr.hpp"
#include "StelLocation.hpp"
#include "StelLocationMgr.hpp"
#include "StelCore.hpp"
#include "StelPainter.hpp"
#include "StelLocaleMgr.hpp"
#include "StelModuleMgr.hpp"
#include "LandscapeMgr.hpp"
#include <QDebug>
#include <QSettings>
#include <QVarLengthArray>
#include <QFile>
#include <QDir>
#include <QtAlgorithms>
#include <QOpenGLBuffer>
#include <QRegularExpression>
#include <QOpenGLShaderProgram>
#include <QOpenGLVertexArrayObject>
namespace
{
constexpr int FS_QUAD_COORDS_PER_VERTEX = 2;
constexpr int SKY_VERTEX_ATTRIB_INDEX = 0;
}
Landscape::Landscape(float _radius)
: radius(static_cast<double>(_radius))
, id("uninitialized")
, minBrightness(-1.)
, landscapeBrightness(1.)
, lightScapeBrightness(0.)
, validLandscape(false)
, rows(20)
, cols(40)
, angleRotateZ(0.)
, angleRotateZOffset(0.)
, sinMinAltitudeLimit(-0.035) //sin(-2 degrees))
, defaultFogSetting(-1)
, defaultExtinctionCoefficient(-1.)
, defaultTemperature(-1000.)
, defaultPressure(-2.)
, horizonPolygon(Q_NULLPTR)
, fontSize(18)
, memorySize(sizeof(Landscape))
, multisamplingEnabled_(StelApp::getInstance().getSettings()->value("video/multisampling", 0).toUInt() != 0)
{
}
Landscape::~Landscape()
{}
void Landscape::initGL()
{
vbo.reset(new QOpenGLBuffer(QOpenGLBuffer::VertexBuffer));
vbo->create();
vbo->bind();
const GLfloat vertices[]=
{
// full screen quad
-1, -1,
1, -1,
-1, 1,
1, 1,
};
auto& gl = *QOpenGLContext::currentContext()->functions();
gl.glBufferData(GL_ARRAY_BUFFER, sizeof vertices, vertices, GL_STATIC_DRAW);
vbo->release();
vao.reset(new QOpenGLVertexArrayObject);
vao->create();
bindVAO();
setupCurrentVAO();
releaseVAO();
initialized = true;
}
void Landscape::setupCurrentVAO()
{
auto& gl = *QOpenGLContext::currentContext()->functions();
vbo->bind();
gl.glVertexAttribPointer(0, FS_QUAD_COORDS_PER_VERTEX, GL_FLOAT, false, 0, 0);
vbo->release();
gl.glEnableVertexAttribArray(SKY_VERTEX_ATTRIB_INDEX);
}
void Landscape::bindVAO()
{
if(vao->isCreated())
vao->bind();
else
setupCurrentVAO();
}
void Landscape::releaseVAO()
{
if(vao->isCreated())
{
vao->release();
}
else
{
auto& gl = *QOpenGLContext::currentContext()->functions();
gl.glDisableVertexAttribArray(SKY_VERTEX_ATTRIB_INDEX);
}
}
// Load attributes common to all landscapes
void Landscape::loadCommon(const QSettings& landscapeIni, const QString& landscapeId)
{
static const QRegularExpression spaceRe("\\\\n\\s*\\\\n");
id = landscapeId;
name = landscapeIni.value("landscape/name").toString();
author = landscapeIni.value("landscape/author").toString();
description = landscapeIni.value("landscape/description").toString();
description = description.replace(spaceRe, "<br />");
description = description.replace("\\n", " ");
if (name.isEmpty())
{
qWarning() << "No valid landscape definition (no name) found for landscape ID "
<< landscapeId << ". No landscape in use." << StelUtils::getEndLineChar();
validLandscape = false;
return;
}
else
{
validLandscape = true;
}
// Optional data
rows = landscapeIni.value("landscape/tesselate_rows", 20).toUInt();
cols = landscapeIni.value("landscape/tesselate_cols", 40).toUInt();
if (landscapeIni.childGroups().contains("location"))
{
if (landscapeIni.contains("location/planet"))
location.planetName = landscapeIni.value("location/planet").toString();
else
location.planetName = "Earth";
// Tolerate decimal values in .ini file, but round to nearest integer
if (landscapeIni.contains("location/altitude"))
location.altitude = qRound(landscapeIni.value("location/altitude").toDouble());
if (landscapeIni.contains("location/latitude"))
location.setLatitude(static_cast<float>(StelUtils::getDecAngle(landscapeIni.value("location/latitude").toString())*M_180_PI));
if (landscapeIni.contains("location/longitude"))
location.setLongitude(static_cast<float>(StelUtils::getDecAngle(landscapeIni.value("location/longitude").toString())*M_180_PI));
if (landscapeIni.contains("location/country"))
location.region = StelLocationMgr::pickRegionFromCountry(landscapeIni.value("location/country").toString());
if (landscapeIni.contains("location/state"))
location.state = landscapeIni.value("location/state").toString();
if (landscapeIni.contains("location/name"))
location.name = landscapeIni.value("location/name").toString();
else
location.name = name;
location.landscapeKey = name;
QString tzString=landscapeIni.value("location/timezone", "").toString();
if (!tzString.isEmpty())
location.ianaTimeZone=StelLocationMgr::sanitizeTimezoneStringFromLocationDB(tzString);
auto defaultBortleIndex = landscapeIni.value("location/light_pollution", -1).toInt();
if (defaultBortleIndex<=0) defaultBortleIndex=-1; // neg. values in ini file signal "no change".
if (defaultBortleIndex>9) defaultBortleIndex=9; // correct bad values.
const auto lum = landscapeIni.value("location/light_pollution_luminance");
if (lum.isValid())
{
defaultLightPollutionLuminance = lum;
if (defaultBortleIndex>=0)
{
qWarning() << "Landscape light pollution is specified both as luminance and as Bortle "
"scale index. Only one value should be specified, preferably luminance.";
}
}
else if (defaultBortleIndex>=0)
defaultLightPollutionLuminance = StelCore::bortleScaleIndexToLuminance(defaultBortleIndex);
defaultFogSetting = landscapeIni.value("location/display_fog", -1).toInt();
defaultExtinctionCoefficient = landscapeIni.value("location/atmospheric_extinction_coefficient", -1.0).toDouble();
defaultTemperature = landscapeIni.value("location/atmospheric_temperature", -1000.0).toDouble();
defaultPressure = landscapeIni.value("location/atmospheric_pressure", -2.0).toDouble(); // -2=no change! [-1=computeFromAltitude]
}
// Set minimal brightness for landscape
minBrightness = landscapeIni.value("landscape/minimal_brightness", -1.0f).toFloat();
// set a minimal altitude which the landscape covers. (new in 0.14)
// This is to allow landscapes with "holes" in the ground (space station?) (Bug lp:1469407)
sinMinAltitudeLimit = std::sin(M_PI_180 * landscapeIni.value("landscape/minimal_altitude", -2.0).toDouble());
// This is now optional for all classes, for mixing with a photo horizon:
// they may have different offsets, like a south-centered pano and a grid-aligned polygon.
// In case they are aligned, we can use one value angle_rotatez, or define the polygon rotation individually.
if (landscapeIni.contains("landscape/polygonal_horizon_list"))
{
createPolygonalHorizon(
StelFileMgr::findFile("landscapes/" + landscapeId + "/" +
landscapeIni.value("landscape/polygonal_horizon_list").toString()),
landscapeIni.value("landscape/polygonal_angle_rotatez", 0.f).toFloat(),
landscapeIni.value("landscape/polygonal_horizon_list_mode", "azDeg_altDeg").toString()
);
// This line can then be drawn in all classes with the color specified here.
// If not specified, don't draw it! (flagged by negative red)
horizonPolygonLineColor=Vec3f(landscapeIni.value("landscape/horizon_line_color", "-1,0,0" ).toString());
}
loadLabels(landscapeId);
}
void Landscape::createPolygonalHorizon(const QString& lineFileName, const float polyAngleRotateZ, const QString &listMode)
{
// qDebug() << _name << " " << _fullpath << " " << _lineFileName ;
const QStringList horizonModeList = { "azDeg_altDeg", "azDeg_zdDeg", "azRad_altRad",
"azRad_zdRad", "azGrad_zdGrad", "azGrad_zdGrad"};
const horizonListMode coordMode=static_cast<horizonListMode>(horizonModeList.indexOf(listMode));
QVector<Vec3d> horiPoints(0);
QFile file(lineFileName);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
{
qWarning() << "Landscape Horizon line data file" << QDir::toNativeSeparators(lineFileName) << "not found.";
return;
}
static const QRegularExpression emptyLine("^\\s*$");
static const QRegularExpression spaceRe("\\s+");
QTextStream in(&file);
while (!in.atEnd())
{
// Build list of vertices. The checks can certainly become more robust.
QString line = in.readLine();
if (line.length()==0) continue;
if (emptyLine.match(line).hasMatch()) continue;
if (line.at(0)=='#') continue; // skip comment lines.
const QStringList list = line.trimmed().split(spaceRe);
if (list.count() < 2)
{
qWarning() << "Landscape polygon file" << QDir::toNativeSeparators(lineFileName)
<< "has bad line:" << line << "with" << list.count() << "elements";
continue;
}
//if (list.count() > 2) // use first two elements but give warning.
//{
// qWarning() << "Landscape polygon file" << QDir::toNativeSeparators(lineFileName) << "has excessive elements in line:" << line << " (" << list.count() << ", not 2 elements)";
//}
Vec3d point;
//qDebug() << "Creating point for az=" << list.at(0) << " alt/zd=" << list.at(1);
float az = 0.f, alt = 0.f;
switch (coordMode)
{
case azDeg_altDeg:
az=(180.0f - polyAngleRotateZ - list.at(0).toFloat())*M_PI_180f;
alt=list.at(1).toFloat()*M_PI_180f;
break;
case azDeg_zdDeg:
az=(180.0f - polyAngleRotateZ - list.at(0).toFloat())*M_PI_180f;
alt=(90.0f-list.at(1).toFloat())*M_PI_180f;
break;
case azRad_altRad:
az=(M_PIf - polyAngleRotateZ*M_PI_180f - list.at(0).toFloat());
alt=list.at(1).toFloat();
break;
case azRad_zdRad:
az=(M_PIf - polyAngleRotateZ*M_PI_180f - list.at(0).toFloat());
alt=M_PI_2f-list.at(1).toFloat();
break;
case azGrad_altGrad:
az=(200.0f - list.at(0).toFloat())*M_PIf/200.f - polyAngleRotateZ*M_PI_180f;
alt=list.at(1).toFloat()*M_PIf/200.f;
break;
case azGrad_zdGrad:
az=(200.0f - list.at(0).toFloat())*M_PIf/200.f - polyAngleRotateZ*M_PI_180f;
alt=(100.0f-list.at(1).toFloat())*M_PIf/200.f;
break;
case invalid:
qWarning() << "invalid polygonal_horizon_list_mode while reading horizon line.";
return;
}
StelUtils::spheToRect(az, alt, point);
if (horiPoints.isEmpty() || horiPoints.last() != point)
horiPoints.append(point);
}
file.close();
//horiPoints.append(horiPoints.at(0)); // close loop? Apparently not necessary.
//qDebug() << "created horiPoints with " << horiPoints.count() << "points:";
//for (int i=0; i<horiPoints.count(); ++i)
// qDebug() << horiPoints.at(i)[0] << "/" << horiPoints.at(i)[1] << "/" << horiPoints.at(i)[2] ;
AllSkySphericalRegion allskyRegion;
SphericalPolygon aboveHorizonPolygon(horiPoints);
horizonPolygon = allskyRegion.getSubtraction(aboveHorizonPolygon);
// If this now contains the zenith, invert the solution:
if (horizonPolygon->contains(Vec3d(0.,0.,1.)))
{
//qDebug() << "Must invert polygon vector!";
std::reverse(horiPoints.begin(), horiPoints.end());
AllSkySphericalRegion allskyRegion;
SphericalPolygon aboveHorizonPolygon(horiPoints);
horizonPolygon = allskyRegion.getSubtraction(aboveHorizonPolygon);
AllSkySphericalRegion allskyRegion2;
horizonPolygon = allskyRegion2.getSubtraction(horizonPolygon);
}
}
void Landscape::drawHorizonLine(StelCore* core, StelPainter& painter)
{
if (!horizonPolygon || horizonPolygonLineColor == Vec3f(-1.f,0.f,0.f))
return;
StelProjector::ModelViewTranformP transfo = core->getAltAzModelViewTransform(StelCore::RefractionOff);
transfo->combine(Mat4d::zrotation(static_cast<double>(-angleRotateZOffset)));
const StelProjectorP prj = core->getProjection(transfo);
painter.setProjector(prj);
painter.setLineSmooth(true);
painter.setBlending(true);
painter.setColor(horizonPolygonLineColor, landFader.getInterstate());
const float lineWidth=painter.getLineWidth();
const float ppx = static_cast<float>(prj->getDevicePixelsPerPixel());
painter.setLineWidth(GETSTELMODULE(LandscapeMgr)->getPolyLineThickness()*ppx);
painter.drawSphericalRegion(horizonPolygon.data(), StelPainter::SphericalPolygonDrawModeBoundary);
painter.setLineWidth(lineWidth);
painter.setLineSmooth(false);
}
#include <iostream>
const QString Landscape::getTexturePath(const QString& basename, const QString& landscapeId)
{
// look in the landscape directory first, and if not found default to global textures directory
QString path = StelFileMgr::findFile("landscapes/" + landscapeId + "/" + basename);
if (path.isEmpty())
path = StelFileMgr::findFile("textures/" + basename);
if (path.isEmpty())
qWarning() << "Warning: Landscape" << landscapeId << ": File" << basename << "does not exist.";
return path;
}
// find optional file and fill landscapeLabels list.
void Landscape::loadLabels(const QString& landscapeId)
{
// in case we have labels and this is called for a retranslation, clean list first.
landscapeLabels.clear();
QString lang, descFileName, locLabelFileName, engLabelFileName;
lang = StelApp::getInstance().getLocaleMgr().getAppLanguage();
locLabelFileName = StelFileMgr::findFile("landscapes/" + landscapeId,
StelFileMgr::Directory) + "/gazetteer." + lang + ".utf8";
engLabelFileName = StelFileMgr::findFile("landscapes/" + landscapeId,
StelFileMgr::Directory) + "/gazetteer.en.utf8";
// Check the file with full name of locale
if (!QFileInfo::exists(locLabelFileName))
{
// File not found. What about short name of locale?
lang = lang.split("_").at(0);
locLabelFileName = StelFileMgr::findFile("landscapes/" + landscapeId,
StelFileMgr::Directory) + "/gazetteer." + lang + ".utf8";
}
// Get localized or at least English description for landscape
if (QFileInfo::exists(locLabelFileName))
descFileName = locLabelFileName;
else if (QFileInfo::exists(engLabelFileName))
descFileName = engLabelFileName;
else
return;
// We have found some file now.
QFile file(descFileName);
if(file.open(QIODevice::ReadOnly | QIODevice::Text))
{
QTextStream in(&file);
#if (QT_VERSION>=QT_VERSION_CHECK(6,0,0))
in.setEncoding(QStringConverter::Utf8);
#else
in.setCodec("UTF-8");
#endif
while (!in.atEnd())
{
QString line=in.readLine();
// Skip comments and all-empty lines (space allowed and ignored)
if (line.startsWith('#') || line.trimmed().isEmpty() )
continue;
// Read entries, construct vectors, put in list.
const QStringList parts=line.split('|');
if (parts.count() != 5)
{
qWarning() << "Invalid line in landscape gazetteer" << descFileName << ":" << line;
continue;
}
LandscapeLabel newLabel;
newLabel.name=parts.at(4).trimmed();
StelUtils::spheToRect((180.0f-parts.at(0).toFloat()) *M_PI_180f,
parts.at(1).toFloat()*M_PI_180f, newLabel.featurePoint);
StelUtils::spheToRect((180.0f-parts.at(0).toFloat() - parts.at(3).toFloat())*M_PI_180f,
(parts.at(1).toFloat() + parts.at(2).toFloat())*M_PI_180f, newLabel.labelPoint);
landscapeLabels.append(newLabel);
//qDebug() << "Added landscape label " << newLabel.name;
}
file.close();
}
}
void Landscape::drawLabels(StelCore* core, StelPainter *painter)
{
if (landscapeLabels.length()==0) // no labels
return;
if (labelFader.getInterstate() < 0.0001f) // switched off
return;
// We must reset painter to pure altaz coordinates without pano-based rotation
const StelProjectorP prj = core->getProjection(StelCore::FrameAltAz, StelCore::RefractionOff);
painter->setProjector(prj);
QFont font;
font.setPixelSize(fontSize);
painter->setFont(font);
QFontMetrics fm(font);
painter->setColor(labelColor, labelFader.getInterstate()*landFader.getInterstate());
painter->setBlending(true);
painter->setLineSmooth(true);
for (int i = 0; i < landscapeLabels.size(); ++i)
{
// in case of gravityLabels, we cannot shift-adjust centered placename, sorry!
if (prj->getFlagGravityLabels())
{
painter->drawText(landscapeLabels.at(i).labelPoint, landscapeLabels.at(i).name, 0, 0, 0, false);
}
else
{
int textWidth=fm.boundingRect(landscapeLabels.at(i).name).width();
painter->drawText(landscapeLabels.at(i).labelPoint, landscapeLabels.at(i).name, 0, -textWidth/2, 2, true);
}
painter->drawGreatCircleArc(landscapeLabels.at(i).featurePoint, landscapeLabels.at(i).labelPoint, Q_NULLPTR);
}
painter->setLineSmooth(false);
painter->setBlending(false);
}
LandscapeOldStyle::LandscapeOldStyle(float _radius)
: Landscape(_radius)
, sideTexs(Q_NULLPTR)
, nbSideTexs(0)
, nbSide(0)
, sides(Q_NULLPTR)
, nbDecorRepeat(0)
, fogAltAngle(0.)
, fogAngleShift(0.)
, decorAltAngle(0.)
, decorAngleShift(0.)
, groundAngleShift(0.)
, groundAngleRotateZ(0.)
, drawGroundFirst(false)
, tanMode(false)
, calibrated(false) // start with just the known entries.
{
memorySize=sizeof(LandscapeOldStyle);
}
LandscapeOldStyle::~LandscapeOldStyle()
{
if (sideTexs)
{
delete [] sideTexs;
sideTexs = Q_NULLPTR;
}
if (sides) delete [] sides;
if (!sidesImages.isEmpty())
{
qDeleteAll(sidesImages);
sidesImages.clear();
}
landscapeLabels.clear();
}
void LandscapeOldStyle::load(const QSettings& landscapeIni, const QString& landscapeId)
{
// TODO: put values into hash and call create() method to consolidate code
loadCommon(landscapeIni, landscapeId);
// rows, cols have been loaded already, but with different defaults.
// GZ Hey, they are not used altogether! Resolution is constant, below!
//rows = landscapeIni.value("landscape/tesselate_rows", 8).toInt();
//cols = landscapeIni.value("landscape/tesselate_cols", 16).toInt();
QString type = landscapeIni.value("landscape/type").toString();
if(type != "old_style")
{
qWarning() << "Landscape type mismatch for landscape " << landscapeId
<< ", expected old_style, found " << type << ". No landscape in use.";
validLandscape = false;
return;
}
nbDecorRepeat = static_cast<unsigned short>(landscapeIni.value("landscape/nb_decor_repeat", 1).toUInt());
fogAltAngle = landscapeIni.value("landscape/fog_alt_angle", 0.).toFloat();
fogAngleShift = landscapeIni.value("landscape/fog_angle_shift", 0.).toFloat();
decorAltAngle = landscapeIni.value("landscape/decor_alt_angle", 0.).toFloat();
decorAngleShift = landscapeIni.value("landscape/decor_angle_shift", 0.).toFloat();
angleRotateZ = landscapeIni.value("landscape/decor_angle_rotatez", 0.).toFloat() * M_PI_180f;
groundAngleShift = landscapeIni.value("landscape/ground_angle_shift", 0.).toFloat() * M_PI_180f;
groundAngleRotateZ = landscapeIni.value("landscape/ground_angle_rotatez", 0.).toDouble() * M_PI_180;
drawGroundFirst = landscapeIni.value("landscape/draw_ground_first", false).toBool();
tanMode = landscapeIni.value("landscape/tan_mode", false).toBool();
calibrated = landscapeIni.value("landscape/calibrated", false).toBool();
auto& texMan = StelApp::getInstance().getTextureManager();
// Load sides textures
nbSideTexs = static_cast<unsigned short>(landscapeIni.value("landscape/nbsidetex", 0).toUInt());
sideTexs = new StelTextureSP[static_cast<size_t>(nbSideTexs)*2]; // 0.14: allow upper half for light textures!
const auto texParams = StelTexture::StelTextureParams(true, GL_LINEAR, GL_CLAMP_TO_EDGE, true);
for (unsigned int i=0; i<nbSideTexs; ++i)
{
QString textureKey = QString("landscape/tex%1").arg(i);
QString textureName = landscapeIni.value(textureKey).toString();
const QString texturePath = getTexturePath(textureName, landscapeId);
sideTexs[i] = texMan.createTexture(texturePath, texParams);
// GZ: To query the textures, also keep an array of QImage*, but only
// if that query is not going to be prevented by the polygon that already has been loaded at that point...
if ( (!horizonPolygon) && calibrated ) { // for uncalibrated landscapes the texture is currently never queried, so no need to store.
QImage *image = new QImage(texturePath);
if (image->isNull())
qWarning() << "Null image (out of memory!) in Landscape!";
sidesImages.append(image); // indices identical to those in sideTexs
memorySize+=(image->sizeInBytes());
}
// Also allow light textures. The light textures must cover the same geometry as the sides. It is allowed that not all or even any light textures are present!
textureKey = QString("landscape/light%1").arg(i);
textureName = landscapeIni.value(textureKey).toString();
if (textureName.length())
{
const QString lightTexturePath = getTexturePath(textureName, landscapeId);
sideTexs[nbSideTexs+i] = texMan.createTexture(lightTexturePath, texParams);
if(sideTexs[nbSideTexs+i])
memorySize+=sideTexs[nbSideTexs+i]->getGlSize();
}
else
sideTexs[nbSideTexs+i].clear();
}
if ( (!horizonPolygon) && calibrated )
{
Q_ASSERT(sidesImages.size()==nbSideTexs);
}
QMap<unsigned int, unsigned int> texToSide;
// Init sides parameters
nbSide = static_cast<unsigned short>(landscapeIni.value("landscape/nbside", 0).toUInt());
sides = new landscapeTexCoord[static_cast<size_t>(nbSide)];
unsigned int texnum;
for (unsigned int i=0;i<nbSide;++i)
{
const QString key = QString("landscape/side%1").arg(i); // e.g. side0
//sscanf(s.toLocal8Bit(),"tex%d:%f:%f:%f:%f",&texnum,&a,&b,&c,&d);
const QStringList parameters = landscapeIni.value(key).toString().split(':'); // e.g. tex0:0:0:1:1
//TODO: How should be handled an invalid texture description?
QString textureName = parameters.value(0); // tex0
texnum = textureName.right(textureName.length() - 3).toUInt(); // 0
sides[i].tex = sideTexs[texnum];
sides[i].tex_illum = sideTexs[nbSide+texnum];
sides[i].texCoords[0] = parameters.at(1).toFloat();
sides[i].texCoords[1] = parameters.at(2).toFloat();
sides[i].texCoords[2] = parameters.at(3).toFloat();
sides[i].texCoords[3] = parameters.at(4).toFloat();
//qDebug() << i << texnum << sides[i].texCoords[0] << sides[i].texCoords[1] << sides[i].texCoords[2] << sides[i].texCoords[3];
// Prior to precomputing the sides, we used to match E to side0.
// In r4598 the precomputing was put in place and caused a problem for
// old_style landscapes which had a z rotation on the side textures
// and where side0 did not map to tex0
// texToSide is a nasty hack to replace the old behaviour.
// GZ for V0.13: I put the zrotation to the draw call (like for all other landscapes).
// Maybe this can be again simplified?
texToSide[i] = texnum;
}
const QString groundTexName = landscapeIni.value("landscape/groundtex").toString();
const QString groundTexPath = getTexturePath(groundTexName, landscapeId);
groundTex = texMan.createTexture(groundTexPath, texParams);
if (groundTex)
memorySize+=groundTex->getGlSize();
const QString fogTexName = landscapeIni.value("landscape/fogtex").toString();
const QString fogTexPath = getTexturePath(fogTexName, landscapeId);
fogTex = texMan.createTexture(fogTexPath, StelTexture::StelTextureParams(true, GL_LINEAR, GL_REPEAT));
if (fogTex)
memorySize+=fogTex->getGlSize();
// Precompute the vertex arrays for ground display
// Make slices_per_side=(3<<K) so that the innermost polygon of the fandisk becomes a triangle:
//const int slices_per_side = 3*64/(nbDecorRepeat*nbSide);
//if (slices_per_side<=0) // GZ: How can negative ever happen?
// slices_per_side = 1;
const auto slices_per_side = static_cast<unsigned short>(qMax(3u*64u/(nbDecorRepeat*nbSide), 1u));
// draw a fan disk instead of a ordinary disk to that the inner slices
// are not so slender. When they are too slender, culling errors occur
// in cylinder projection mode.
unsigned short int slices_inside = nbSide*slices_per_side*nbDecorRepeat;
uint level = 0;
while ((slices_inside&1)==0 && slices_inside > 4)
{
++level;
slices_inside>>=1;
}
StelPainter::computeFanDisk(static_cast<float>(radius), slices_inside, level, groundVertexArr, groundTexCoordArr); //comaVertexArr, comaTexCoordArr);
// Precompute the vertex arrays for side display. The geometry of the sides is always a cylinder.
// The texture is split into regular quads.
// GZ: the original code for vertical placement makes unfortunately no sense. There are many approximately-fitted landscapes, though.
// I added a switch "calibrated" for the ini file. If true, it works as this landscape apparently was originally intended,
// if false (or missing) it uses the original code.
// I corrected the texture coordinates so that decorAltAngle is the total vertical angle, decorAngleShift the lower angle,
// and the texture in between is correctly stretched.
// I located an undocumented switch tan_mode, maybe tan_mode=true means cylindrical panorama projection instead of equirectangular.
// Since V0.13, calibrated&&tanMode also works!
// In calibrated && !tan_mode, the vertical position is computed correctly, so that quads off the horizon are larger.
// in calibrated && tan_mode, d_z can become a constant because the texture is already predistorted in cylindrical projection.
const unsigned short int stacks = (calibrated ? 16u : 8u); // GZ: 8->16, I need better precision.
float z0, d_z;
if (calibrated)
{
if (tanMode) // cylindrical pano: linear in d_z, simpler.
{
z0= static_cast<float>(radius)*std::tan(decorAngleShift*M_PI_180f);
d_z=(static_cast<float>(radius)*std::tan((decorAltAngle+decorAngleShift)*M_PI_180f) - z0)/stacks;
}
else // equirectangular pano: angular z, requires more work in the loop below!
{
z0=decorAngleShift;
d_z=decorAltAngle/stacks;
}
}
else // buggy code, but legacy.
{
z0 =static_cast<float>(radius)*(tanMode ? std::tan(decorAngleShift*M_PI_180f)
: std::sin(decorAngleShift*M_PI_180f));
d_z=static_cast<float>(radius)*(tanMode ? std::tan(decorAltAngle *M_PI_180f)/stacks
: std::sin(decorAltAngle *M_PI_180f)/stacks);
}
const float alpha = 2.f*static_cast<float>(M_PI)/(nbDecorRepeat*nbSide*slices_per_side); //delta_azimuth
const float ca = std::cos(alpha);
const float sa = std::sin(alpha);
float y0 = static_cast<float>(radius);
float x0 = 0.0f;
unsigned short int limit;
LOSSide precompSide;
precompSide.arr.primitiveType=StelVertexArray::Triangles;
for (unsigned int n=0;n<nbDecorRepeat;n++)
{
for (unsigned int i=0;i<nbSide;i++)
{
unsigned int ti;
if (texToSide.contains(i))
ti = texToSide[i];
else
{
qDebug() << QString("LandscapeOldStyle::load ERROR: found no "
"corresponding tex value for side%1").arg(i);
break;
}
precompSide.arr.vertex.resize(0);
precompSide.arr.texCoords.resize(0);
precompSide.arr.indices.resize(0);
precompSide.tex=sideTexs[ti];
precompSide.light=false;
float tx0 = sides[ti].texCoords[0];
const float d_tx = (sides[ti].texCoords[2]-sides[ti].texCoords[0]) / slices_per_side;
const float d_ty = (sides[ti].texCoords[3]-sides[ti].texCoords[1]) / stacks;
for (unsigned short int j=0;j<slices_per_side;j++)
{
const float y1 = y0*ca - x0*sa;
const float x1 = y0*sa + x0*ca;
const float tx1 = tx0 + d_tx;
float z = z0;
float ty0 = sides[ti].texCoords[1];
limit = static_cast<unsigned short int>(stacks*2u);
for (unsigned short int k=0u;k<=limit;k+=2u)
{
precompSide.arr.texCoords << Vec2f(tx0, ty0) << Vec2f(tx1, ty0);
if (calibrated && !tanMode)
{
double tanZ=radius * static_cast<double>(std::tan(z*M_PI_180f));
precompSide.arr.vertex << Vec3d(static_cast<double>(x0),
static_cast<double>(y0), tanZ)
<< Vec3d(static_cast<double>(x1),
static_cast<double>(y1), tanZ);
} else
{
precompSide.arr.vertex << Vec3d(static_cast<double>(x0),
static_cast<double>(y0), static_cast<double>(z))
<< Vec3d(static_cast<double>(x1),
static_cast<double>(y1), static_cast<double>(z));
}
z += d_z;
ty0 += d_ty;
}
unsigned short int offset = j*(stacks+1u)*2u;
limit = static_cast<unsigned short int>(stacks*2u+2u);
for (unsigned short int k = 2;k<limit;k+=2u)
{
precompSide.arr.indices << offset+k-2 << offset+k-1 << offset+k;
precompSide.arr.indices << offset+k << offset+k-1 << offset+k+1;
}
y0 = y1;
x0 = x1;
tx0 = tx1;
}
precomputedSides.append(precompSide);
if (sideTexs[ti+nbSide])
{
precompSide.light=true;
precompSide.tex=sideTexs[ti+nbSide];
precomputedSides.append(precompSide); // These sides are not called by strict index!
// May be 9 for 8 sidetexs plus 1-only light panel
}
}
}
//qDebug() << "OldStyleLandscape" << landscapeId << "loaded, mem size:" << memorySize;
}
void LandscapeOldStyle::draw(StelCore* core, bool onlyPolygon)
{
if(!StelOpenGL::globalShaderPrefix(StelOpenGL::FRAGMENT_SHADER).contains("textureGrad_SUPPORTED"))
{
drawLowGL(core, onlyPolygon);
return;
}
if(!initialized) initGL();
if(!validLandscape) return;
if(landFader.getInterstate()==0.f) return;
StelProjector::ModelViewTranformP transfo = core->getAltAzModelViewTransform(StelCore::RefractionOff);
transfo->combine(Mat4d::zrotation(-static_cast<double>(angleRotateZ+angleRotateZOffset)));
const StelProjectorP prj = core->getProjection(transfo);
if(!renderProgram || !prevProjector || !prj->isSameProjection(*prevProjector))
{
renderProgram.reset(new QOpenGLShaderProgram);
prevProjector = prj;
const auto vert =
StelOpenGL::globalShaderPrefix(StelOpenGL::VERTEX_SHADER) +
R"(
ATTRIBUTE highp vec3 vertex;
VARYING highp vec3 ndcPos;
void main()
{
gl_Position = vec4(vertex, 1.);
ndcPos = vertex;
}
)";
bool ok = renderProgram->addShaderFromSourceCode(QOpenGLShader::Vertex, vert);
if(!renderProgram->log().isEmpty())
qWarning().noquote() << "LandscapeSpherical: Warnings while compiling vertex shader:\n"
<< renderProgram->log();
if(!ok) return;
const auto frag =
StelOpenGL::globalShaderPrefix(StelOpenGL::FRAGMENT_SHADER) +
prj->getUnProjectShader() +
R"(
VARYING highp vec3 ndcPos;
uniform int whatToRender;
uniform int totalNumberOfSides;
uniform int firstSideInBatch;
uniform int numberOfSidesInBatch;
uniform int sidePresenceMask;
uniform vec4 perSideTexCoords[8];
uniform sampler2D sideTex0;
uniform sampler2D sideTex1;
uniform sampler2D sideTex2;
uniform sampler2D sideTex3;
uniform sampler2D sideTex4;
uniform sampler2D sideTex5;
uniform sampler2D sideTex6;
uniform sampler2D sideTex7;
uniform sampler2D mapTex;
uniform mat4 projectionMatrixInverse;
uniform float vshift; // tan (or sin) of {ground,fog}_angle_shift
uniform float decorAngleShift;
uniform float sideAngularHeight;
uniform float fogCylinderHeight;
uniform bool calibrated;
uniform bool tanMode;
uniform vec4 brightness;
vec4 sampleSideTexture(int sideIndex, const vec2 texc, const vec2 texDx, const vec2 texDy)
{
sideIndex -= firstSideInBatch;
if(sideIndex==0 && (sidePresenceMask& 1)!=0) return textureGrad(sideTex0, texc, texDx, texDy);
if(sideIndex==1 && (sidePresenceMask& 2)!=0) return textureGrad(sideTex1, texc, texDx, texDy);
if(sideIndex==2 && (sidePresenceMask& 4)!=0) return textureGrad(sideTex2, texc, texDx, texDy);
if(sideIndex==3 && (sidePresenceMask& 8)!=0) return textureGrad(sideTex3, texc, texDx, texDy);
if(sideIndex==4 && (sidePresenceMask& 16)!=0) return textureGrad(sideTex4, texc, texDx, texDy);
if(sideIndex==5 && (sidePresenceMask& 32)!=0) return textureGrad(sideTex5, texc, texDx, texDy);
if(sideIndex==6 && (sidePresenceMask& 64)!=0) return textureGrad(sideTex6, texc, texDx, texDy);
if(sideIndex==7 && (sidePresenceMask&128)!=0) return textureGrad(sideTex7, texc, texDx, texDy);
return vec4(0);
}
void main(void)
{
const float PI = 3.14159265;
vec4 winPos = projectionMatrixInverse * vec4(ndcPos, 1);
bool unprojectSuccess = false;
vec3 modelPos = unProject(winPos.x, winPos.y, unprojectSuccess).xyz;
// First we must compute the derivatives of texture coordinates, and only
// then decide whether we want to display the !unprojectSuccess case.
vec3 viewDir = normalize(modelPos);
vec4 color;
if(whatToRender == -1) // ground
{
vec2 centeredTexCoords = viewDir.z!=0. ? vshift / viewDir.z * viewDir.xy
: vec2(0);
vec2 texc = (centeredTexCoords + 1.) / 2.;
vec2 texDx = dFdx(texc);
vec2 texDy = dFdy(texc);
// Now that all dFdx/dFdy are computed, we can early return if needed.
if(!unprojectSuccess)
{
FRAG_COLOR = vec4(0);
return;
}
if(viewDir.z > 0. || length(centeredTexCoords) > 1.)
{
FRAG_COLOR = vec4(0);
return;
}
color = textureGrad(mapTex, texc, texDx, texDy);
}
else if(whatToRender == -2) // fog
{
float azimuth = atan(viewDir.x, viewDir.y);
if(azimuth<0.) azimuth += 2.*PI;
float s = azimuth/(2.*PI);
float tanElevation = viewDir.z / sqrt(1. - viewDir.z*viewDir.z);
float t = (tanElevation - vshift) / fogCylinderHeight;
vec2 texc = vec2(s,t);
vec2 texDx = dFdx(texc);
vec2 texDy = dFdy(texc);
// Now that all dFdx/dFdy are computed, we can early return if needed.
if(!unprojectSuccess)
{
FRAG_COLOR = vec4(0);
return;
}
if(t<0. || t>1.)
{
FRAG_COLOR = vec4(0);
return;
}
color = textureGrad(mapTex, texc, texDx, texDy);
}
else
{
float azimuth = atan(viewDir.x, viewDir.y);
if(azimuth<0.) azimuth += 2.*PI;
float sideAngularWidth = 2.*PI/float(totalNumberOfSides);
int currentSide = int(azimuth/sideAngularWidth);
int currentSideInBatch = currentSide%numberOfSidesInBatch;
float leftBorderAzimuth = float(currentSide)*sideAngularWidth;
float texCoordLeft = perSideTexCoords[currentSideInBatch][0];
float texCoordRight = perSideTexCoords[currentSideInBatch][2];
float deltaS = texCoordRight - texCoordLeft;
float s = texCoordLeft + (azimuth-leftBorderAzimuth)/sideAngularWidth * deltaS;
float elevation = asin(viewDir.z);
float texCoordBottom = perSideTexCoords[currentSideInBatch][1];
float texCoordTop = perSideTexCoords[currentSideInBatch][3];
float deltaT = texCoordTop - texCoordBottom;
float texCoordInUnitRange;
if(calibrated)
{
if(tanMode)
{
float tanShift = tan(decorAngleShift);
texCoordInUnitRange = (tan(elevation)-tanShift)/(tan(decorAngleShift+sideAngularHeight)-tanShift);
}
else
{
texCoordInUnitRange = (elevation-decorAngleShift)/sideAngularHeight;
}
}
else
{
if(tanMode)
{
texCoordInUnitRange = (tan(elevation)-tan(decorAngleShift))/tan(sideAngularHeight);
}
else
{
texCoordInUnitRange = (tan(elevation)-sin(decorAngleShift))/sin(sideAngularHeight);
}
}
float t = texCoordBottom + texCoordInUnitRange * deltaT;
// The usual automatic computation of derivatives of texture coordinates
// breaks down at the discontinuity of atan, resulting in choosing the most
// minified mip level instead of the correct one, which looks as a seam on
// the screen. Thus, we need to compute them in a custom way, treating atan
// as a (continuous) multivalued function. We differentiate
// atan(modelPosX(x,y), modelPosY(x,y)) with respect to x and y and yield
// gradAzimuth vector.
vec2 gradModelPosX = vec2(dFdx(modelPos.x), dFdy(modelPos.x));
vec2 gradModelPosY = vec2(dFdx(modelPos.y), dFdy(modelPos.y));
float texTdx = dFdx(t);
float texTdy = dFdy(t);
// Now that all dFdx/dFdy are computed, we can early return if needed.
int lastSideInBatch = firstSideInBatch+numberOfSidesInBatch-1;
if(currentSide < firstSideInBatch || currentSide > lastSideInBatch)
{
FRAG_COLOR = vec4(0);
return;
}
if(s<texCoordLeft || s>texCoordRight || t<texCoordBottom || t>texCoordTop)
{
FRAG_COLOR = vec4(0);
return;
}
if(!unprojectSuccess)
{
FRAG_COLOR = vec4(0);
return;
}
vec2 gradAzimuth = vec2(modelPos.y*gradModelPosX.s-modelPos.x*gradModelPosY.s,
modelPos.y*gradModelPosX.t-modelPos.x*gradModelPosY.t)
/
dot(modelPos, modelPos);
vec2 texDx = vec2(gradAzimuth.s/sideAngularWidth*deltaS, texTdx);
vec2 texDy = vec2(gradAzimuth.t/sideAngularWidth*deltaS, texTdy);
color = sampleSideTexture(currentSide, vec2(s,t), texDx, texDy);
}
FRAG_COLOR = color * brightness;
}
)";
ok = renderProgram->addShaderFromSourceCode(QOpenGLShader::Fragment, frag);
if(!renderProgram->log().isEmpty())
qWarning().noquote() << "LandscapeSpherical: Warnings while compiling fragment shader:\n"
<< renderProgram->log();
if(!ok) return;
renderProgram->bindAttributeLocation("vertex", SKY_VERTEX_ATTRIB_INDEX);
if(!StelPainter::linkProg(renderProgram.get(), "Spherical landscape render program"))
return;
renderProgram->bind();
shaderVars.mapTex = renderProgram->uniformLocation("mapTex");
shaderVars.vshift = renderProgram->uniformLocation("vshift");
shaderVars.tanMode = renderProgram->uniformLocation("tanMode");
shaderVars.calibrated = renderProgram->uniformLocation("calibrated");
shaderVars.brightness = renderProgram->uniformLocation("brightness");
shaderVars.whatToRender = renderProgram->uniformLocation("whatToRender");
shaderVars.decorAngleShift = renderProgram->uniformLocation("decorAngleShift");