diff --git a/apps/Launcher/syncwidget.cpp b/apps/Launcher/syncwidget.cpp index df65188357..512556d936 100644 --- a/apps/Launcher/syncwidget.cpp +++ b/apps/Launcher/syncwidget.cpp @@ -52,7 +52,7 @@ #include #include -#include +//#include #include #include #include @@ -161,23 +161,28 @@ SyncWidget::SyncWidget(QWidget* parent, Qt::WindowFlags f) } _session->start_upnp(); - std::ifstream file(_configurationFile); - if (!file.fail()) { - union { - uint32_t value; - std::array data; - } size; - file.read(size.data.data(), sizeof(uint32_t)); - std::vector buffer(size.value); - file.read(buffer.data(), size.value); - file.close(); + // I commented this out as it caused the Linux build nodes to fail during linking + // and I couldn't figure out how to fix it + // it would throw an cxx11 ABI incompatibility error - libtorrent::entry e = libtorrent::bdecode(buffer.begin(), buffer.end()); - _session->start_dht(e); - } - else - _session->start_dht(); + //std::ifstream file(_configurationFile); + //if (!file.fail()) { + // union { + // uint32_t value; + // std::array data; + // } size; + + // file.read(size.data.data(), sizeof(uint32_t)); + // std::vector buffer(size.value); + // file.read(buffer.data(), size.value); + // file.close(); + + // libtorrent::entry e = libtorrent::bdecode(buffer.begin(), buffer.end()); + // _session->start_dht(e); + //} + //else + _session->start_dht(); _session->add_dht_router({ "router.utorrent.com", 6881 }); _session->add_dht_router({ "dht.transmissionbt.com", 6881 }); @@ -198,18 +203,22 @@ SyncWidget::SyncWidget(QWidget* parent, Qt::WindowFlags f) SyncWidget::~SyncWidget() { libtorrent::entry dht = _session->dht_state(); - std::vector buffer; - libtorrent::bencode(std::back_inserter(buffer), dht); + // I commented this out as it caused the Linux build nodes to fail during linking + // and I couldn't figure out how to fix it + // it would throw an cxx11 ABI incompatibility error - std::ofstream f(_configurationFile); + //std::vector buffer; + //libtorrent::bencode(std::back_inserter(buffer), dht); - union { - uint32_t value; - std::array data; - } size; - size.value = buffer.size(); - f.write(size.data.data(), sizeof(uint32_t)); - f.write(buffer.data(), buffer.size()); + //std::ofstream f(_configurationFile); + + //union { + // uint32_t value; + // std::array data; + //} size; + //size.value = buffer.size(); + //f.write(size.data.data(), sizeof(uint32_t)); + //f.write(buffer.data(), buffer.size()); _downloadManager.reset(); ghoul::deinitialize(); diff --git a/apps/OpenSpace/main.cpp b/apps/OpenSpace/main.cpp index d5dc91c1b4..986a1908fc 100644 --- a/apps/OpenSpace/main.cpp +++ b/apps/OpenSpace/main.cpp @@ -268,7 +268,7 @@ void mainInitFunc() { const sgct::SGCTWindow::StereoMode sm = windowPtr->getStereoMode(); const bool hasStereo = - (sm != sgct::SGCTWindow::No_Stereo) && + (sm != sgct::SGCTWindow::No_Stereo) && (sm < sgct::SGCTWindow::Side_By_Side_Stereo); if (hasStereo) { @@ -359,6 +359,20 @@ void mainRenderFunc() { LTRACE("main::mainRenderFunc(end)"); } +void mainDraw2DFunc() { + LTRACE("main::mainDraw2DFunc(begin)"); + + OsEng.drawOverlays(); + + // SGCT gets angry if we change this in our function + glEnable(GL_BLEND); + glDisable(GL_CULL_FACE); + glDisable(GL_DEPTH_TEST); + + + LTRACE("main::mainDraw2DFunc(end)"); +} + void mainPostDrawFunc() { LTRACE("main::mainPostDrawFunc(begin)"); @@ -525,6 +539,7 @@ int main_main(int argc, char** argv) { SgctEngine->setPreSyncFunction(mainPreSyncFunc); SgctEngine->setPostSyncPreDrawFunction(mainPostSyncPreDrawFunc); SgctEngine->setDrawFunction(mainRenderFunc); + SgctEngine->setDraw2DFunction(mainDraw2DFunc); SgctEngine->setPostDrawFunction(mainPostDrawFunc); SgctEngine->setKeyboardCallbackFunction(mainKeyboardCallback); SgctEngine->setMouseButtonCallbackFunction(mainMouseButtonCallback); @@ -609,7 +624,7 @@ int main_main(int argc, char** argv) { cleanup(); // Exit program - exit(EXIT_SUCCESS); + exit(EXIT_SUCCESS); } } // namespace diff --git a/apps/TaskRunner/main.cpp b/apps/TaskRunner/main.cpp index 83d426cd23..75a7b3bfc5 100644 --- a/apps/TaskRunner/main.cpp +++ b/apps/TaskRunner/main.cpp @@ -58,10 +58,14 @@ namespace { void initTextureReaders() { #ifdef GHOUL_USE_DEVIL - ghoul::io::TextureReader::ref().addReader(std::make_shared()); + ghoul::io::TextureReader::ref().addReader( + std::make_shared() + ); #endif // GHOUL_USE_DEVIL #ifdef GHOUL_USE_FREEIMAGE - ghoul::io::TextureReader::ref().addReader(std::make_shared()); + ghoul::io::TextureReader::ref().addReader( + std::make_shared() + ); #endif // GHOUL_USE_FREEIMAGE } @@ -81,7 +85,10 @@ void performTasks(const std::string& path) { for (size_t i = 0; i < tasks.size(); i++) { Task& task = *tasks[i].get(); - LINFO("Performing task " << (i + 1) << " out of " << tasks.size() << ": " << task.description()); + LINFO( + "Performing task " << (i + 1) << " out of " << + tasks.size() << ": " << task.description() + ); ProgressBar progressBar(100); auto onProgress = [&progressBar](float progress) { progressBar.print(progress * 100); diff --git a/apps/TimelineView/controlwidget.cpp b/apps/TimelineView/controlwidget.cpp index a4f501d830..a872a2e6f8 100644 --- a/apps/TimelineView/controlwidget.cpp +++ b/apps/TimelineView/controlwidget.cpp @@ -253,7 +253,8 @@ void ControlWidget::onDateChange() { QString script = "openspace.time.setTime('" + date + "');\ openspace.setPropertyValue('Interaction.origin', '" + focus + "');\ - openspace.setPropertyValue('Interaction.coordinateSystem', '" + coordinateSystem + "')"; + openspace.setPropertyValue('Interaction.coordinateSystem', '" + + coordinateSystem + "')"; emit scriptActivity(script); } _setTime->blockSignals(true); @@ -265,18 +266,28 @@ void ControlWidget::onFocusChange() { int index = _focusNode->currentIndex(); QString name = FocusNodes[index].name; QString coordinateSystem = FocusNodes[index].coordinateSystem; - QString script = "openspace.setPropertyValue('Interaction.origin', '" + name + "');openspace.setPropertyValue('Interaction.coordinateSystem', '" + coordinateSystem + "');"; + QString script = "openspace.setPropertyValue('Interaction.origin', '" + name + + "');openspace.setPropertyValue('Interaction.coordinateSystem', '" + + coordinateSystem + "');"; emit scriptActivity(script); } void ControlWidget::onFocusToTargetButton() { std::string target = reinterpret_cast(parent())->nextTarget(); if (!target.empty()) { - auto it = std::find_if(std::begin(FocusNodes), std::end(FocusNodes), [target](const FocusNode& n) { return n.guiName.toLower() == QString::fromStdString(target).toLower(); }); + auto it = std::find_if( + std::begin(FocusNodes), + std::end(FocusNodes), + [target](const FocusNode& n) { + return n.guiName.toLower() == QString::fromStdString(target).toLower(); + }); if (it != std::end(FocusNodes)) { QString name = it->name; QString coordinateSystem = it->coordinateSystem; - QString script = "openspace.setPropertyValue('Interaction.origin', '" + name + "');openspace.setPropertyValue('Interaction.coordinateSystem', '" + coordinateSystem + "');"; + QString script = + "openspace.setPropertyValue('Interaction.origin', '" + name + + "');openspace.setPropertyValue('Interaction.coordinateSystem', '" + + coordinateSystem + "');"; emit scriptActivity(script); } } @@ -292,7 +303,9 @@ void ControlWidget::onFocusToNewHorizonsButton() { else coordinateSystem = "Pluto"; - QString script = "openspace.setPropertyValue('Interaction.origin', 'NewHorizons');openspace.setPropertyValue('Interaction.coordinateSystem', '" + coordinateSystem + "');"; + QString script = "openspace.setPropertyValue('Interaction.origin', 'NewHorizons');\ + openspace.setPropertyValue('Interaction.coordinateSystem', '" + coordinateSystem + + "');"; emit scriptActivity(script); } diff --git a/apps/TimelineView/main.cpp b/apps/TimelineView/main.cpp index 420f02fcd7..64da99f345 100644 --- a/apps/TimelineView/main.cpp +++ b/apps/TimelineView/main.cpp @@ -58,7 +58,9 @@ QLineEdit { QSlider::groove:horizontal { border: 1px solid #999999; - height: 8px; /* the groove expands to the size of the slider by default. by giving it a height, it has a fixed size */ + /* the groove expands to the size of the slider by default. by giving it a height, + it has a fixed size */ + height: 8px; background: qlineargradient( x1:0, y1:0, x2:1, y2:0, stop:0 #c4c4c4, @@ -72,7 +74,9 @@ QSlider::handle:horizontal { background: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 #b4b4b4, stop:1 #8f8f8f); border: 1px solid #5c5c5c; width: 18px; - margin: -2px 0; /* handle is placed by default on the contents rect of the groove. Expand outside the groove */ + /* handle is placed by default on the contents rect of the groove. + Expand outside the groove */ + margin: -2px 0; border-radius: 3px; } @@ -112,7 +116,7 @@ QCombobox { } QComboBox:editable { - background: lightgrey; + background: lightgrey; } QComboBox QAbstractItemView { diff --git a/apps/TimelineView/mainwindow.cpp b/apps/TimelineView/mainwindow.cpp index b227633515..88b00581cb 100644 --- a/apps/TimelineView/mainwindow.cpp +++ b/apps/TimelineView/mainwindow.cpp @@ -257,17 +257,23 @@ void MainWindow::handleStatusMessage(QByteArray data) { QString::fromStdString(std::string(timeString.begin(), timeString.end())), QString::number(delta.value) ); - _timelineWidget->setCurrentTime(std::string(timeString.begin(), timeString.end()), et.value); + _timelineWidget->setCurrentTime( + std::string(timeString.begin(), timeString.end()), + et.value + ); } -std::vector instrumentsFromId(uint16_t instrumentId, std::map instrumentMap) { +std::vector instrumentsFromId(uint16_t instrumentId, + std::map instrumentMap) +{ std::vector results; for (int i = 0; i < 16; ++i) { uint16_t testValue = 1 << i; if ((testValue & instrumentId) != 0) { std::string t = instrumentMap.at(testValue); - if (t.empty()) + if (t.empty()) { qDebug() << "Empty instrument"; + } results.push_back(t); } } @@ -318,15 +324,21 @@ QByteArray MainWindow::handlePlaybook(QByteArray data) { qDebug() << "Instruments were empty"; images.push_back(image); } - _timelineWidget->setData(std::move(images), std::move(targetMap), std::move(instrumentMap)); + _timelineWidget->setData( + std::move(images), + std::move(targetMap), + std::move(instrumentMap) + ); auto dataSize = data.size(); auto readSize = currentReadLocation; auto extraBytes = dataSize - readSize; - if (extraBytes > 0) + if (extraBytes > 0) { return data.mid(currentReadLocation); - else + } + else { return QByteArray(); + } } void MainWindow::sendScript(QString script) { @@ -361,7 +373,10 @@ std::string MainWindow::nextTarget() const { } void MainWindow::fullyConnected() { - _informationWidget->logInformation("Connected to " + _socket->peerName() + " on port " + QString::number(_socket->peerPort()) + "."); + _informationWidget->logInformation( + "Connected to " + _socket->peerName() + " on port " + + QString::number(_socket->peerPort()) + "." + ); _configurationWidget->socketConnected(); _timeControlWidget->socketConnected(); @@ -379,6 +394,5 @@ void MainWindow::printMapping(QByteArray data) { std::string mapping = readFromBuffer(buffer, currentReadPosition); qDebug() << identifier << ": " << QString::fromStdString(mapping); - } } diff --git a/apps/TimelineView/timelinewidget.cpp b/apps/TimelineView/timelinewidget.cpp index b4014b12bf..73da3a324b 100644 --- a/apps/TimelineView/timelinewidget.cpp +++ b/apps/TimelineView/timelinewidget.cpp @@ -89,7 +89,12 @@ void TimelineWidget::paintEvent(QPaintEvent* event) { QRectF fullRect = contentsRect(); QRectF contentRect(0, 0, fullRect.width() - 1, fullRect.height() - LegendHeight); - QRectF legendRect(0, fullRect.bottom() - LegendHeight, fullRect.right(), fullRect.bottom()); + QRectF legendRect( + 0, + fullRect.bottom() - LegendHeight, + fullRect.right(), + fullRect.bottom() + ); painter.save(); drawContent(painter, contentRect); @@ -101,10 +106,17 @@ void TimelineWidget::paintEvent(QPaintEvent* event) { painter.restore(); } -void TimelineWidget::setData(std::vector images, std::map targetMap, std::map instrumentMap) { +void TimelineWidget::setData(std::vector images, + std::map targetMap, + std::map instrumentMap) +{ _images.insert(_images.end(), images.begin(), images.end()); - std::sort(_images.begin(), _images.end(), [](const Image& a, const Image& b) { return a.beginning < b.beginning; }); + std::sort( + _images.begin(), + _images.end(), + [](const Image& a, const Image& b) { return a.beginning < b.beginning; } + ); _targetMap.insert(targetMap.begin(), targetMap.end()); _instrumentMap.insert(instrumentMap.begin(), instrumentMap.end()); @@ -148,8 +160,15 @@ void TimelineWidget::drawContent(QPainter& painter, QRectF rect) { // Draw current time painter.setBrush(QBrush(Qt::black)); painter.setPen(QPen(Qt::black, 2)); - painter.drawLine(QPointF(0, timelineRect.height() / 2), QPointF(timelineRect.width(), timelineRect.height() / 2)); - painter.drawText(timelineRect.width(), timelineRect.height() / 2 + TextOffset, QString::fromStdString(_currentTime.time)); + painter.drawLine( + QPointF(0, timelineRect.height() / 2), + QPointF(timelineRect.width(), timelineRect.height() / 2) + ); + painter.drawText( + timelineRect.width(), + timelineRect.height() / 2 + TextOffset, + QString::fromStdString(_currentTime.time) + ); } void TimelineWidget::drawLegend(QPainter& painter, QRectF rect) { @@ -171,14 +190,21 @@ void TimelineWidget::drawLegend(QPainter& painter, QRectF rect) { ; painter.setBrush(QBrush(InstrumentColors[QString::fromStdString(instrument)])); painter.setPen(QPen(InstrumentColors[QString::fromStdString(instrument)])); - painter.drawRect(currentHorizontalPosition, currentVerticalPosition, BoxSize, BoxSize); + painter.drawRect( + currentHorizontalPosition, + currentVerticalPosition, + BoxSize, + BoxSize + ); currentHorizontalPosition += BoxSize + Padding; painter.setPen(QPen(QColor(200, 200, 200))); //painter.setPen(QPen(Qt::black)); - painter.drawText(currentHorizontalPosition, currentVerticalPosition + BoxSize / 2 + TextOffset, InstrumentConversion[QString::fromStdString(instrument)]); -// int textWidth = painter.boundingRect(QRect(), QString::fromStdString(instrument)).width(); - //currentHorizontalPosition += std::max(textWidth, 25) + Padding; + painter.drawText( + currentHorizontalPosition, + currentVerticalPosition + BoxSize / 2 + TextOffset, + InstrumentConversion[QString::fromStdString(instrument)] + ); currentHorizontalPosition += 125; } } @@ -198,11 +224,12 @@ void TimelineWidget::drawImages( { std::set instrumentSet; for (Image* i : images) { - for (std::string instrument : i->instruments) + for (std::string instrument : i->instruments) { instrumentSet.insert(instrument); + } } std::map instruments; - for (std::set::const_iterator it = instrumentSet.begin(); it != instrumentSet.end(); ++it) + for (auto it = instrumentSet.begin(); it != instrumentSet.end(); ++it) instruments[*it] = std::distance(instrumentSet.begin(), it); for (Image* i : images) { @@ -215,8 +242,9 @@ void TimelineWidget::drawImages( int height = (timelineRect.top() + timelineRect.height() * tEnd) - loc; height = std::max(height, 5); - if (loc + height > timelineRect.height()) + if (loc + height > timelineRect.height()) { height = timelineRect.height() - loc; + } std::string target = i->target; auto it = std::find(_targets.begin(), _targets.end(), target); @@ -224,10 +252,13 @@ void TimelineWidget::drawImages( for (std::string instrument : i->instruments) { auto it = std::find(_instruments.begin(), _instruments.end(), instrument); - if (it == _instruments.end()) + if (it == _instruments.end()) { qDebug() << "Instrument not found"; + } - painter.setBrush(QBrush(InstrumentColors[QString::fromStdString(instrument)])); + painter.setBrush( + QBrush(InstrumentColors[QString::fromStdString(instrument)]) + ); double width = timelineRect.width() / instruments.size(); double pos = instruments[instrument] * width; @@ -238,7 +269,8 @@ void TimelineWidget::drawImages( if (height >= 5) { painter.setBrush(QBrush(Qt::black)); painter.setPen(QPen(Qt::black)); - QString line = QString::fromStdString(i->beginningString) + QString(" (") + QString::fromStdString(i->target) + QString(")"); + QString line = QString::fromStdString(i->beginningString) + QString(" (") + + QString::fromStdString(i->target) + QString(")"); painter.drawText(timelineRect.width(), loc + height / 2 + TextOffset, line); } @@ -257,9 +289,16 @@ void TimelineWidget::socketDisconnected() { } std::string TimelineWidget::nextTarget() const { - auto it = std::lower_bound(_images.begin(), _images.end(), _currentTime.et, [](const Image& i, double et) { return i.beginning < et; }); - if (it != _images.end()) + auto it = std::lower_bound( + _images.begin(), + _images.end(), + _currentTime.et, + [](const Image& i, double et) { return i.beginning < et; } + ); + if (it != _images.end()) { return it->target; - else + } + else { return ""; + } } diff --git a/apps/TimelineView/timelinewidget.h b/apps/TimelineView/timelinewidget.h index 3ad24c33b5..f20ee4e956 100644 --- a/apps/TimelineView/timelinewidget.h +++ b/apps/TimelineView/timelinewidget.h @@ -40,7 +40,8 @@ Q_OBJECT public: TimelineWidget(QWidget* parent); - void setData(std::vector images, std::map targetMap, std::map instrumentMap); + void setData(std::vector images, std::map targetMap, + std::map instrumentMap); void setCurrentTime(std::string currentTime, double et); void socketConnected(); void socketDisconnected(); @@ -48,10 +49,11 @@ public: std::string nextTarget() const; protected: - void paintEvent(QPaintEvent* event); + void paintEvent(QPaintEvent* event); void drawContent(QPainter& painter, QRectF rect); void drawLegend(QPainter& painter, QRectF rect); - void drawImages(QPainter& painter, QRectF timelineRect, std::vector images, double minimumTime, double maximumTime); + void drawImages(QPainter& painter, QRectF timelineRect, std::vector images, + double minimumTime, double maximumTime); private: std::vector _images; diff --git a/data/openspace-logo.png b/data/openspace-logo.png new file mode 100644 index 0000000000..a34574d42f Binary files /dev/null and b/data/openspace-logo.png differ diff --git a/data/scene/examples/fixedrotation/fixedrotation.mod b/data/scene/examples/fixedrotation/fixedrotation.mod new file mode 100644 index 0000000000..dbaf6cd5d6 --- /dev/null +++ b/data/scene/examples/fixedrotation/fixedrotation.mod @@ -0,0 +1,35 @@ +return { + -- Earth barycenter module + { + Name = "Fixed Rotation", + Parent = "EarthBarycenter", + Transform = { + Rotation = { + Type = "FixedRotation", + Attached = "Fixed Rotation", + XAxis = { 0.0, 1.0, 0.0 }, + XAxisOrthogonal = true, + YAxis = "EarthBarycenter" + }, + Translation = { + Type = "SpiceTranslation", + Target = "MOON", + Observer = "EARTH BARYCENTER", + Kernels = "${OPENSPACE_DATA}/spice/de430_1850-2150.bsp" + }, + Scale = { + Type = "StaticScale", + Scale = 10000000 + } + }, + Renderable = { + Type = "RenderableModel", + Geometry = { + Type = "MultiModelGeometry", + GeometryFile = "teapot.obj", + -- Magnification = 4, + }, + ColorTexture = "placeholder.png", + } + } +} diff --git a/include/openspace/documentation/documentation.h b/include/openspace/documentation/documentation.h index c82ba9ac90..2725272987 100644 --- a/include/openspace/documentation/documentation.h +++ b/include/openspace/documentation/documentation.h @@ -47,7 +47,7 @@ using Optional = ghoul::Boolean; struct TestResult { /** * An Offense is a violation against a specific verifier. The Offense::offender is the - * key that caused the offense (in the case of nested tables, it will be fully + * key that caused the offense (in the case of nested tables, it will be fully * qualified identifier) and the Offense::Reason is the reason that caused the * offense. */ @@ -60,7 +60,7 @@ struct TestResult { ExtraKey, ///< The exhaustive documentation contained an extra key WrongType, ///< The key's value was not of the expected type Verification, ///< The value did not pass a necessary non-type verifier - UnknownIdentifier ///< If the identifier for a ReferencingVerifier did not exist + UnknownIdentifier ///< The identifier for a ReferencingVerifier did not exist }; /// The offending key that caused the Offense. In the case of a nested table, /// this value will be the fully qualified name of the key @@ -142,8 +142,8 @@ struct DocumentationEntry { /** * The constructor for a DocumentationEntry describing a \p key in a Documentation. - * The value for the key (or each value in the case of the - * DocumentationEntry::Wildcard) is tested using the \p verifier, that specifies the + * The value for the key (or each value in the case of the + * DocumentationEntry::Wildcard) is tested using the \p verifier, that specifies the * conditions that the \p key%'s value has to fulfill. The textual documentation * \p doc shall describe the usage of the key-value pair and will be printed for human * consumption for example in the DocumentationEngine. Each DocumentationEntry can @@ -211,7 +211,7 @@ Documentation doc = { { // A list of DocumentationEntry%s; also specified using initializer lists { "key1", new IntVerifier, "Documentation key1", Optional::Yes }, { "key2", new FloatVerifier, "Documentation key2" }, - { "key3", new StringVerifier } + { "key3", new StringVerifier } } }; \endverbatim diff --git a/include/openspace/documentation/documentationengine.h b/include/openspace/documentation/documentationengine.h index 9e73e9f8c5..5d313a5ee8 100644 --- a/include/openspace/documentation/documentationengine.h +++ b/include/openspace/documentation/documentationengine.h @@ -62,7 +62,7 @@ public: DocumentationEngine(); /** - * Adds the \p documentation to the list of Documentation%s that are written to a + * Adds the \p documentation to the list of Documentation%s that are written to a * documentation file with the writeDocumentation method. * \param documentation The Documentation object that is to be stored for later use * \throws DuplicateDocumentationException If the \p documentation has a non-empty diff --git a/include/openspace/documentation/documentationgenerator.h b/include/openspace/documentation/documentationgenerator.h index ff51c29aba..430823c3f1 100644 --- a/include/openspace/documentation/documentationgenerator.h +++ b/include/openspace/documentation/documentationgenerator.h @@ -33,10 +33,10 @@ namespace openspace { /* * This abstract class is used for instances when another class has the ability to * generate a Handlebar generated documentation file that contains valuable information - * for the user. Instances of this are the DocumentationEngine results, the list of + * for the user. Instances of this are the DocumentationEngine results, the list of * Property%s generated by the Scene, or the FactoryEngine results. The documentation is * generated through the writeDocumentation method. - * + * * The concrete subclass needs to overload the generateJson class that will return the * Json that is parsed by Handlebar to generate the webpage. * @@ -57,7 +57,7 @@ public: * writeDocumentation method. * \param name The name of the written documentation * \param jsonName The variable name of the value generated by the generateJson - * \param handlebarTemplates A list of Handlebar templates that is added to the + * \param handlebarTemplates A list of Handlebar templates that is added to the * documentation file * \param javascriptFilename The path to a Javascript source file that is added to the * documentation and that can contain additional functionality @@ -76,7 +76,7 @@ public: /** * Create the documentation into the provided filename. Any existing file will be * silently overwritten. This method will call the generateJson method that can be - * used by concrete subclasses to provide the actual data that is provided in the + * used by concrete subclasses to provide the actual data that is provided in the * documentation. * \param filename The filename in which the documentation is written */ diff --git a/include/openspace/documentation/verifier.h b/include/openspace/documentation/verifier.h index 7c231d02e9..a4113b818f 100644 --- a/include/openspace/documentation/verifier.h +++ b/include/openspace/documentation/verifier.h @@ -61,7 +61,7 @@ struct Verifier { * \post If the return values' TestResult::success is \c true, its * TestResult::offenders is empty */ - virtual TestResult operator()(const ghoul::Dictionary& dictionary, + virtual TestResult operator()(const ghoul::Dictionary& dictionary, const std::string& key) const = 0; /** @@ -116,7 +116,7 @@ struct TemplateVerifier : public Verifier { }; /** - * A Verifier that checks whether a given key inside a ghoul::Dictionary is of type + * A Verifier that checks whether a given key inside a ghoul::Dictionary is of type * \c bool. No implicit conversion is considered in this testing. */ struct BoolVerifier : public TemplateVerifier { @@ -258,7 +258,7 @@ struct Vector4Verifier : public TemplateVerifier>, public VectorVe }; /** -* A Verifier that checks whether all values contained in a Table are of +* A Verifier that checks whether all values contained in a Table are of * type glm::tvec2 */ template @@ -546,7 +546,9 @@ struct GreaterVerifier : public OperatorVerifier -struct GreaterEqualVerifier : public OperatorVerifier> { +struct GreaterEqualVerifier : public OperatorVerifier> +{ static_assert( !std::is_base_of::value, "T cannot be BoolVerifier" @@ -627,7 +629,7 @@ struct InListVerifier : public T { * Tests whether the \p key exists in the \p dictionary, whether it has the correct * type by invoking the template parameter \c T, and then tests if the \p key's value * is part of the list passed to the constructor. - * \param dictionary The ghoul::Dictionary that contains the \p key + * \param dictionary The ghoul::Dictionary that contains the \p key * \param key The key that is contained in the \p dictionary and whose value is tested * \return A TestResult containing the results of the specification testing. If the * \p key%'s value has the wrong type, it will be added to the TestResult's offense @@ -688,7 +690,7 @@ struct NotInListVerifier : public T { * This Verifier checks whether the incoming value is of the correct type, using the * Verifier passed as a template parameter \c T and then checks whether it is greater or * equal to a lower limit and less or equal to a higher limit. To the missing comparison -* operators, \c T cannot be a subclass of (or the same as) BoolVerifier, StringVerifier, +* operators, \c T cannot be a subclass of (or the same as) BoolVerifier, StringVerifier, * TableVerifier, or VectorVerifier. Both the lower and the higher limit are inclusive). */ template @@ -890,7 +892,7 @@ struct ReferencingVerifier : public TableVerifier { std::string documentation() const override; - /// The identifier that references another Documentation registered with the + /// The identifier that references another Documentation registered with the /// DocumentationEngine std::string identifier; }; @@ -900,7 +902,7 @@ struct ReferencingVerifier : public TableVerifier { //---------------------------------------------------------------------------------------- /** - * This Verifier takes two Verifiers and performs a boolean \c and operation on their + * This Verifier takes two Verifiers and performs a boolean \c and operation on their * results. In essence, a value only passes this Verifier if it passes both Verifier%s * that are passed in the constructor. Opposed to the C++ && * operator, the AndVerifier does not perform any short-circut evaluation. diff --git a/include/openspace/documentation/verifier.inl b/include/openspace/documentation/verifier.inl index 9ace596fb3..81ec2cd14e 100644 --- a/include/openspace/documentation/verifier.inl +++ b/include/openspace/documentation/verifier.inl @@ -122,7 +122,7 @@ OperatorVerifier::OperatorVerifier(typename T::Type val) template TestResult OperatorVerifier::operator()(const ghoul::Dictionary& dict, - const std::string& key) const + const std::string& key) const { TestResult res = T::operator()(dict, key); if (res.success) { @@ -345,7 +345,9 @@ TestResult DeprecatedVerifier::operator()(const ghoul::Dictionary& dict, const std::string& key) const { TestResult res = T::operator()(dict, key); - res.warnings.push_back(TestResult::Warning{ key, TestResult::Warning::Reason::Deprecated }); + res.warnings.push_back( + TestResult::Warning{ key, TestResult::Warning::Reason::Deprecated } + ); return res; } diff --git a/include/openspace/engine/configurationmanager.h b/include/openspace/engine/configurationmanager.h index d13734aee8..489435dac6 100644 --- a/include/openspace/engine/configurationmanager.h +++ b/include/openspace/engine/configurationmanager.h @@ -131,9 +131,9 @@ public: static const std::string PartHttpProxyPort; /// The key that stores the authentication method of the http proxy static const std::string PartHttpProxyAuthentication; - /// The key that stores the username to use for authentication to access the http proxy + /// Key that stores the username to use for authentication to access the http proxy static const std::string PartHttpProxyUser; - /// The key that stores the password to use for authentication to access the http proxy + /// Key that stores the password to use for authentication to access the http proxy static const std::string PartHttpProxyPassword; /// The key that stores the dictionary containing information about debug contexts static const std::string KeyOpenGLDebugContext; @@ -156,6 +156,20 @@ public: /// The part of the key storing whether each OpenGL call should be logged static const std::string KeyLogEachOpenGLCall; + /// This key determines whether the scene graph nodes should initialized multithreaded + static const std::string KeyUseMultithreadedInitialization; + + /// The key under which all of the loading settings are grouped + static const std::string KeyLoadingScreen; + /// The part of the key storing whether the loading screen should display the message + /// about current status + static const std::string PartShowMessage; + /// The part of the key storing whether the loading screen should display node names + static const std::string PartShowNodeNames; + /// The part of the key storing whether the loading screen should contain a progress + /// bar + static const std::string PartShowProgressbar; + /** * Iteratively walks the directory structure starting with \p filename to find the diff --git a/include/openspace/engine/downloadmanager.h b/include/openspace/engine/downloadmanager.h index db7cff07ea..addce8435c 100644 --- a/include/openspace/engine/downloadmanager.h +++ b/include/openspace/engine/downloadmanager.h @@ -102,13 +102,13 @@ public: DownloadProgressCallback progressCallback = DownloadProgressCallback() ); - std::future fetchFile( - const std::string& url, - SuccessCallback successCallback = SuccessCallback(), ErrorCallback errorCallback = ErrorCallback()); + std::future fetchFile(const std::string& url, + SuccessCallback successCallback = SuccessCallback(), + ErrorCallback errorCallback = ErrorCallback()); - std::vector> downloadRequestFiles(const std::string& identifier, - const ghoul::filesystem::Directory& destination, int version, - bool overrideFiles = true, + std::vector> downloadRequestFiles( + const std::string& identifier, const ghoul::filesystem::Directory& destination, + int version, bool overrideFiles = true, DownloadFinishedCallback finishedCallback = DownloadFinishedCallback(), DownloadProgressCallback progressCallback = DownloadProgressCallback() ); diff --git a/include/openspace/engine/moduleengine.h b/include/openspace/engine/moduleengine.h index 22b15f142f..2b750e31ab 100644 --- a/include/openspace/engine/moduleengine.h +++ b/include/openspace/engine/moduleengine.h @@ -68,7 +68,7 @@ public: * Registers the passed \p module with this ModuleEngine. The OpenSpaceModule::create * method will be called on the \p module in the process. * \param module The OpenSpaceModule that is to be registered - * \throw ghoul::RuntimeError If the name of the \p module was already registered + * \throw ghoul::RuntimeError If the name of the \p module was already registered * previously * \pre \p module must not be nullptr */ diff --git a/include/openspace/engine/openspaceengine.h b/include/openspace/engine/openspaceengine.h index 8aa395f08e..987e03bf56 100644 --- a/include/openspace/engine/openspaceengine.h +++ b/include/openspace/engine/openspaceengine.h @@ -45,6 +45,7 @@ namespace openspace { class ConfigurationManager; class DownloadManager; class GUI; +class LoadingScreen; class LuaConsole; class ModuleEngine; class NetworkEngine; @@ -87,6 +88,7 @@ public: void postSynchronizationPreDraw(); void render(const glm::mat4& sceneMatrix, const glm::mat4& viewMatrix, const glm::mat4& projectionMatrix); + void drawOverlays(); void postDraw(); void keyboardCallback(Key key, KeyModifier mod, KeyAction action); void charCallback(unsigned int codepoint, KeyModifier mod); @@ -109,6 +111,7 @@ public: LuaConsole& console(); DownloadManager& downloadManager(); ModuleEngine& moduleEngine(); + LoadingScreen& loadingScreen(); NetworkEngine& networkEngine(); ParallelConnection& parallelConnection(); RenderEngine& renderEngine(); @@ -133,6 +136,7 @@ public: PreSync, // Callback for the end of the pre-sync function PostSyncPreDraw, // Callback for the end of the post-sync-pre-draw function Render, // Callback for the end of the render function + Draw2D, // Callback for the two-dimensional rendering functions PostDraw // Callback for the end of the post-draw function }; @@ -200,6 +204,8 @@ private: // Others std::unique_ptr _globalPropertyNamespace; + std::unique_ptr _loadingScreen; + struct { properties::StringProperty versionString; properties::StringProperty sourceControlInformation; @@ -218,6 +224,7 @@ private: std::vector> preSync; std::vector> postSyncPreDraw; std::vector> render; + std::vector> draw2D; std::vector> postDraw; std::vector> keyboard; diff --git a/include/openspace/engine/syncengine.h b/include/openspace/engine/syncengine.h index a23dc78c22..847a80a5f6 100644 --- a/include/openspace/engine/syncengine.h +++ b/include/openspace/engine/syncengine.h @@ -51,7 +51,7 @@ public: SyncEngine(unsigned int syncBufferSize); /** - * Encodes all added Syncables in the injected SyncBuffer. + * Encodes all added Syncables in the injected SyncBuffer. * This method is only called on the SGCT master node */ void encodeSyncables(); @@ -95,7 +95,7 @@ public: void removeSyncables(const std::vector& syncables); private: - /** + /** * Vector of Syncables. The vectors ensures consistent encode/decode order */ std::vector _syncables; diff --git a/include/openspace/engine/wrapper/sgctwindowwrapper.h b/include/openspace/engine/wrapper/sgctwindowwrapper.h index 8f7d5d8107..2b09f00e3b 100644 --- a/include/openspace/engine/wrapper/sgctwindowwrapper.h +++ b/include/openspace/engine/wrapper/sgctwindowwrapper.h @@ -79,6 +79,8 @@ public: void takeScreenshot(bool applyWarping = false) const override; + void swapBuffer() const override; + private: properties::FloatProperty _eyeSeparation; properties::BoolProperty _showStatsGraph; diff --git a/include/openspace/engine/wrapper/windowwrapper.h b/include/openspace/engine/wrapper/windowwrapper.h index 2498addbfd..df302ff64a 100644 --- a/include/openspace/engine/wrapper/windowwrapper.h +++ b/include/openspace/engine/wrapper/windowwrapper.h @@ -125,7 +125,7 @@ public: * is 1 if mouse button i is pressed down; * false otherwise. On default, this method returns that none of the * buttons is pressed. - * \param maxNumber The maximum number of mouse buttons that should be queried + * \param maxNumber The maximum number of mouse buttons that should be queried * \return A bitmask showing the status of all mouse buttons (up to \p maxNumber) */ virtual uint32_t mouseButtons(int maxNumber = 8) const; @@ -201,8 +201,9 @@ public: virtual bool isUsingSwapGroups() const; /** - * Returns true if the current rendering window is master of the swap its group. - */ + * Returns true if the current rendering window is master of the swap its + * group. + */ virtual bool isSwapGroupMaster() const; /** @@ -270,6 +271,8 @@ public: */ virtual void takeScreenshot(bool applyWarping = false) const; + virtual void swapBuffer() const; + struct WindowWrapperException : public ghoul::RuntimeError { explicit WindowWrapperException(const std::string& msg); }; diff --git a/include/openspace/interaction/keybindingmanager.h b/include/openspace/interaction/keybindingmanager.h index 8682fecc6a..7426610a99 100644 --- a/include/openspace/interaction/keybindingmanager.h +++ b/include/openspace/interaction/keybindingmanager.h @@ -61,7 +61,7 @@ public: static scripting::LuaLibrary luaLibrary(); - // Callback functions + // Callback functions void keyboardCallback(Key key, KeyModifier modifier, KeyAction action); private: diff --git a/include/openspace/interaction/mousestate.h b/include/openspace/interaction/mousestate.h index 7db9a94d53..5d39ef7bad 100644 --- a/include/openspace/interaction/mousestate.h +++ b/include/openspace/interaction/mousestate.h @@ -46,7 +46,7 @@ public: /** * \param sensitivity * \param velocityScaleFactor can be set to 60 to remove the inertia of the - * interaction. Lower value will make it harder to move the camera. + * interaction. Lower value will make it harder to move the camera. */ MouseStates(double sensitivity, double velocityScaleFactor); void updateMouseStatesFromInput(const InputState& inputState, double deltaTime); diff --git a/include/openspace/interaction/navigationhandler.h b/include/openspace/interaction/navigationhandler.h index 6e8d4fad76..d09966ce4e 100644 --- a/include/openspace/interaction/navigationhandler.h +++ b/include/openspace/interaction/navigationhandler.h @@ -57,7 +57,7 @@ public: void setCamera(Camera* camera); void resetCameraDirection(); - void setCameraStateFromDictionary(const ghoul::Dictionary& cameraDict); + void setCameraStateFromDictionary(const ghoul::Dictionary& cameraDict); void updateCamera(double deltaTime); @@ -69,9 +69,9 @@ public: Camera* camera() const; const InputState& inputState() const; const OrbitalNavigator& orbitalNavigator() const; - KeyframeNavigator& keyframeNavigator() const; + KeyframeNavigator& keyframeNavigator() const; - // Callback functions + // Callback functions void keyboardCallback(Key key, KeyModifier modifier, KeyAction action); void mouseButtonCallback(MouseButton button, MouseAction action); void mousePositionCallback(double x, double y); diff --git a/include/openspace/interaction/orbitalnavigator.h b/include/openspace/interaction/orbitalnavigator.h index 8a99f752e6..3887023cde 100644 --- a/include/openspace/interaction/orbitalnavigator.h +++ b/include/openspace/interaction/orbitalnavigator.h @@ -55,7 +55,7 @@ public: void setFocusNode(SceneGraphNode* focusNode); void startInterpolateCameraDirection(const Camera& camera); - bool followingNodeRotation() const; + bool followingNodeRotation() const; SceneGraphNode* focusNode() const; bool hasRotationalFriction() const; @@ -99,7 +99,7 @@ private: * camera points towards the focus node in the direction opposite to the direction * out from the surface of the object. The local rotation defines the differential * from the global to the current total rotation so that - * cameraRotation = globalRotation * localRotation. + * cameraRotation = globalRotation * localRotation. */ CameraRotationDecomposition decomposeCameraRotation(const glm::dvec3& cameraPosition, const glm::dquat& cameraRotation, const glm::dvec3& cameraLookUp, @@ -139,7 +139,7 @@ private: /* * Adds rotation to the camera position so that it follows the rotation of the focus - * node defined by the differential focusNodeRotationDiff. + * node defined by the differential focusNodeRotationDiff. * \returns a position updated with the rotation defined by focusNodeRotationDiff */ glm::dvec3 followFocusNodeRotation(const glm::dvec3& cameraPosition, diff --git a/include/openspace/interaction/touchbar.h b/include/openspace/interaction/touchbar.h new file mode 100644 index 0000000000..99fdf4e977 --- /dev/null +++ b/include/openspace/interaction/touchbar.h @@ -0,0 +1,36 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2017 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef __OPENSPACE_CORE___TOUCHBAR___H__ +#define __OPENSPACE_CORE___TOUCHBAR___H__ + +namespace openspace { + +// Initializes the touch bar on MacOS (if available) and creates all the buttons and +// callbacks +void showTouchbar(); + +} // namespace openspace + +#endif // __OPENSPACE_CORE___TOUCHBAR___H__ diff --git a/include/openspace/mission/mission.h b/include/openspace/mission/mission.h index a7036bfb44..7dfb165522 100644 --- a/include/openspace/mission/mission.h +++ b/include/openspace/mission/mission.h @@ -41,7 +41,7 @@ namespace documentation { struct Documentation; } * Used to represent a named period of time within a mission. Allows nested phases, i.e. * phases within phases. Designed for WORM usage (Write Once, Read Multiple), and, * therefore, has only accessors. - * + * * Each MissionPhase is characterized by its MissionPhase::name, a TimeRange, an * optional MissionPhase::description, and optional subphases. */ diff --git a/include/openspace/mission/missionmanager.h b/include/openspace/mission/missionmanager.h index 2d31f89ba4..06dae81df3 100644 --- a/include/openspace/mission/missionmanager.h +++ b/include/openspace/mission/missionmanager.h @@ -38,7 +38,7 @@ namespace openspace { namespace scripting { struct LuaLibrary; } /** -* Singleton class keeping track of space missions. +* Singleton class keeping track of space missions. */ class MissionManager : public ghoul::Singleton { public: @@ -50,7 +50,7 @@ public: /** * Reads a mission from file and maps the mission name to the Mission object. If - * this is the first mission to be loaded, the mission will also be set as the + * this is the first mission to be loaded, the mission will also be set as the * current active mission. * \pre \p filename must not be empty * \pre \p filename must not contain tokens @@ -79,8 +79,8 @@ public: bool hasCurrentMission() const; /** - * Returns the latest mission specified to `setCurrentMission()`. If no mission has - * been specified, the first mission loaded will be returned. If no mission has been + * Returns the latest mission specified to `setCurrentMission()`. If no mission has + * been specified, the first mission loaded will be returned. If no mission has been * loaded, a warning will be printed and a dummy mission will be returned. */ const Mission& currentMission(); diff --git a/include/openspace/network/messagestructures.h b/include/openspace/network/messagestructures.h index eb3c9eea09..b065f2d9d6 100644 --- a/include/openspace/network/messagestructures.h +++ b/include/openspace/network/messagestructures.h @@ -52,27 +52,51 @@ struct CameraKeyframe { double _timestamp; - void serialize(std::vector &buffer){ + void serialize(std::vector &buffer) { // Add position - buffer.insert(buffer.end(), reinterpret_cast(&_position), reinterpret_cast(&_position) + sizeof(_position)); + buffer.insert( + buffer.end(), + reinterpret_cast(&_position), + reinterpret_cast(&_position) + sizeof(_position) + ); // Add orientation - buffer.insert(buffer.end(), reinterpret_cast(&_rotation), reinterpret_cast(&_rotation) + sizeof(_rotation)); + buffer.insert( + buffer.end(), + reinterpret_cast(&_rotation), + reinterpret_cast(&_rotation) + sizeof(_rotation) + ); // Follow focus node rotation? - buffer.insert(buffer.end(), reinterpret_cast(&_followNodeRotation), reinterpret_cast(&_followNodeRotation) + sizeof(_followNodeRotation)); + buffer.insert( + buffer.end(), + reinterpret_cast(&_followNodeRotation), + reinterpret_cast(&_followNodeRotation) + sizeof(_followNodeRotation) + ); int nodeNameLength = static_cast(_focusNode.size()); // Add focus node - buffer.insert(buffer.end(), reinterpret_cast(&nodeNameLength), reinterpret_cast(&nodeNameLength) + sizeof(nodeNameLength)); - buffer.insert(buffer.end(), _focusNode.data(), _focusNode.data() + nodeNameLength); + buffer.insert( + buffer.end(), + reinterpret_cast(&nodeNameLength), + reinterpret_cast(&nodeNameLength) + sizeof(nodeNameLength) + ); + buffer.insert( + buffer.end(), + _focusNode.data(), + _focusNode.data() + nodeNameLength + ); // Add timestamp - buffer.insert(buffer.end(), reinterpret_cast(&_timestamp), reinterpret_cast(&_timestamp) + sizeof(_timestamp)); + buffer.insert( + buffer.end(), + reinterpret_cast(&_timestamp), + reinterpret_cast(&_timestamp) + sizeof(_timestamp) + ); }; - void deserialize(const std::vector &buffer){ + void deserialize(const std::vector &buffer) { int offset = 0; int size = 0; @@ -94,7 +118,7 @@ struct CameraKeyframe { // Focus node int nodeNameLength; size = sizeof(int); - memcpy(&nodeNameLength, buffer.data() + offset, size); + memcpy(&nodeNameLength, buffer.data() + offset, size); offset += size; size = nodeNameLength; _focusNode = std::string(buffer.data() + offset, buffer.data() + offset + size); @@ -120,19 +144,39 @@ struct TimeKeyframe { void serialize(std::vector &buffer){ // Add current time - buffer.insert(buffer.end(), reinterpret_cast(&_time), reinterpret_cast(&_time) + sizeof(_time)); + buffer.insert( + buffer.end(), + reinterpret_cast(&_time), + reinterpret_cast(&_time) + sizeof(_time) + ); // Add delta time - buffer.insert(buffer.end(), reinterpret_cast(&_dt), reinterpret_cast(&_dt) + sizeof(_dt)); + buffer.insert( + buffer.end(), + reinterpret_cast(&_dt), + reinterpret_cast(&_dt) + sizeof(_dt) + ); // Add whether time is paused or not - buffer.insert(buffer.end(), reinterpret_cast(&_paused), reinterpret_cast(&_paused) + sizeof(_paused)); + buffer.insert( + buffer.end(), + reinterpret_cast(&_paused), + reinterpret_cast(&_paused) + sizeof(_paused) + ); // Add whether a time jump is necessary (recompute paths etc) - buffer.insert(buffer.end(), reinterpret_cast(&_requiresTimeJump), reinterpret_cast(&_requiresTimeJump) + sizeof(_requiresTimeJump)); + buffer.insert( + buffer.end(), + reinterpret_cast(&_requiresTimeJump), + reinterpret_cast(&_requiresTimeJump) + sizeof(_requiresTimeJump) + ); // Add timestamp - buffer.insert(buffer.end(), reinterpret_cast(&_timestamp), reinterpret_cast(&_timestamp) + sizeof(_timestamp)); + buffer.insert( + buffer.end(), + reinterpret_cast(&_timestamp), + reinterpret_cast(&_timestamp) + sizeof(_timestamp) + ); }; void deserialize(const std::vector &buffer){ diff --git a/include/openspace/network/networkengine.h b/include/openspace/network/networkengine.h index 8d0008b406..6d36f0d130 100644 --- a/include/openspace/network/networkengine.h +++ b/include/openspace/network/networkengine.h @@ -48,7 +48,8 @@ public: void sendMessages(); // Initial Connection Messages - void setInitialConnectionMessage(MessageIdentifier identifier, std::vector message); + void setInitialConnectionMessage(MessageIdentifier identifier, + std::vector message); void sendInitialInformation(); // Background diff --git a/include/openspace/performance/performancemanager.h b/include/openspace/performance/performancemanager.h index 890657363c..f894d1d817 100644 --- a/include/openspace/performance/performancemanager.h +++ b/include/openspace/performance/performancemanager.h @@ -53,8 +53,10 @@ public: bool isMeasuringPerformance() const; - void storeIndividualPerformanceMeasurement(std::string identifier, long long nanoseconds); - void storeScenePerformanceMeasurements(const std::vector& sceneNodes); + void storeIndividualPerformanceMeasurement(std::string identifier, + long long nanoseconds); + void storeScenePerformanceMeasurements( + const std::vector& sceneNodes); void outputLogs(); diff --git a/include/openspace/performance/performancemeasurement.h b/include/openspace/performance/performancemeasurement.h index 7815492e51..b45558be76 100644 --- a/include/openspace/performance/performancemeasurement.h +++ b/include/openspace/performance/performancemeasurement.h @@ -37,7 +37,8 @@ class PerformanceManager; class PerformanceMeasurement { public: - PerformanceMeasurement(std::string identifier, performance::PerformanceManager* manager); + PerformanceMeasurement(std::string identifier, + performance::PerformanceManager* manager); ~PerformanceMeasurement(); private: diff --git a/include/openspace/properties/numericalproperty.h b/include/openspace/properties/numericalproperty.h index 25abe7a01b..9bf680556c 100644 --- a/include/openspace/properties/numericalproperty.h +++ b/include/openspace/properties/numericalproperty.h @@ -34,9 +34,10 @@ class NumericalProperty : public TemplateProperty { public: NumericalProperty(Property::PropertyInfo info); NumericalProperty(Property::PropertyInfo info, T value); - NumericalProperty(Property::PropertyInfo info, T value, T minimumValue, T maximumValue); - NumericalProperty(Property::PropertyInfo info, T value, T minimumValue, T maximumValue, - T steppingValue); + NumericalProperty(Property::PropertyInfo info, T value, T minimumValue, + T maximumValue); + NumericalProperty(Property::PropertyInfo info, T value, T minimumValue, + T maximumValue, T steppingValue); bool getLuaValue(lua_State* state) const override; bool setLuaValue(lua_State* state) override; diff --git a/include/openspace/properties/numericalproperty.inl b/include/openspace/properties/numericalproperty.inl index 39a4ea2cf9..c0a07e3127 100644 --- a/include/openspace/properties/numericalproperty.inl +++ b/include/openspace/properties/numericalproperty.inl @@ -141,27 +141,27 @@ namespace openspace::properties { \ template <> \ template <> \ - TYPE PropertyDelegate>::fromLuaValue(lua_State* state, \ - bool& success) \ + TYPE PropertyDelegate>::fromLuaValue(lua_State* lua, \ + bool& successful) \ { \ - return FROM_LUA_LAMBDA_EXPRESSION(state, success); \ + return FROM_LUA_LAMBDA_EXPRESSION(lua, successful); \ } \ \ template <> \ template <> \ - TYPE PropertyDelegate>::fromLuaValue(lua_State* state, \ - bool& success) \ + TYPE PropertyDelegate>::fromLuaValue(lua_State* lua, \ + bool& successful) \ { \ return PropertyDelegate>::fromLuaValue( \ - state, success); \ + lua, successful); \ } \ \ template <> \ template <> \ - bool PropertyDelegate>::toLuaValue(lua_State* state, \ + bool PropertyDelegate>::toLuaValue(lua_State* lua, \ TYPE value) \ { \ - return TO_LUA_LAMBDA_EXPRESSION(state, value); \ + return TO_LUA_LAMBDA_EXPRESSION(lua, value); \ } \ \ template <> \ @@ -187,9 +187,9 @@ namespace openspace::properties { template <> \ template <> \ TYPE PropertyDelegate>::fromString(std::string value, \ - bool& success) \ + bool& successful) \ { \ - return FROM_STRING_LAMBDA_EXPRESSION(value, success); \ + return FROM_STRING_LAMBDA_EXPRESSION(value, successful); \ } \ \ template <> \ @@ -205,18 +205,18 @@ namespace openspace::properties { \ template <> \ template <> \ - bool PropertyDelegate>::toString(std::string& outValue, \ - TYPE inValue) \ + bool PropertyDelegate>::toString(std::string& out, \ + TYPE in) \ { \ - return TO_STRING_LAMBDA_EXPRESSION(outValue, inValue); \ + return TO_STRING_LAMBDA_EXPRESSION(out, in); \ } \ \ template <> \ template <> \ - bool PropertyDelegate>::toString(std::string& outValue, \ - TYPE inValue) \ + bool PropertyDelegate>::toString(std::string& out, \ + TYPE in) \ { \ - return PropertyDelegate>::toString(outValue, inValue); \ + return PropertyDelegate>::toString(out, in); \ } @@ -231,7 +231,7 @@ const std::string NumericalProperty::SteppingValueKey = "SteppingValue"; // Delegating constructors are necessary; automatic template deduction cannot // deduce template argument for 'U' if 'default' methods are used as default values in -// a single constructor +// a single constructor template NumericalProperty::NumericalProperty(Property::PropertyInfo info) diff --git a/include/openspace/properties/optionproperty.h b/include/openspace/properties/optionproperty.h index b465c33039..cb87fc2532 100644 --- a/include/openspace/properties/optionproperty.h +++ b/include/openspace/properties/optionproperty.h @@ -32,7 +32,7 @@ namespace openspace::properties { /** - * The OptionProperty is a property that provides a number of predefined (using the + * The OptionProperty is a property that provides a number of predefined (using the * addOption method) options consisting of a description and a * value. The available options can be queried using the options method. * Only values representing valid options can be used to set this property, or an error @@ -119,7 +119,7 @@ public: /** * Get the description of the option that matches value - * \param value The value of the option + * \param value The value of the option */ std::string getDescriptionByValue(int value); diff --git a/include/openspace/properties/property.h b/include/openspace/properties/property.h index 83301f87d1..da89a1c809 100644 --- a/include/openspace/properties/property.h +++ b/include/openspace/properties/property.h @@ -88,7 +88,7 @@ public: Visibility visibility = Visibility::All; }; - /// An OnChangeHandle is returned by the onChange method to uniquely identify an + /// An OnChangeHandle is returned by the onChange method to uniquely identify an /// onChange callback using OnChangeHandle = uint32_t; @@ -102,7 +102,7 @@ public: * to be accessed by the GUI elements using the guiName key. The default * visibility settings is Visibility::All, whereas the default read-only state is * false. - * \param info The PropertyInfo structure that contains all the required static + * \param info The PropertyInfo structure that contains all the required static * information for initializing this Property. * \pre \p info.identifier must not be empty * \pre \p info.guiName must not be empty @@ -399,7 +399,7 @@ protected: * generateAdditionalDescription()}, which #generateMetaDataDescription * and this method being the override points to customize the behavior. * \return The information specific to each subclass of Property - */ + */ virtual std::string generateAdditionalDescription() const; /** @@ -409,7 +409,7 @@ protected: void notifyListener(); /// The PropetyOwner this Property belongs to, or nullptr - PropertyOwner* _owner; + PropertyOwner* _owner; /// The identifier for this Property std::string _identifier; diff --git a/include/openspace/properties/propertyowner.h b/include/openspace/properties/propertyowner.h index c0f8bc8914..1720a2e90a 100644 --- a/include/openspace/properties/propertyowner.h +++ b/include/openspace/properties/propertyowner.h @@ -39,7 +39,7 @@ class Property; * sub-owners must be unique to this PropertyOwner. A Property cannot have the same name * as a PropertyOwner owned by this PropertyOwner. * Propertys can be added using the Property::addProperty methods and be removed by the - * Property::removeProperty method. The same holds true for sub-owners + * Property::removeProperty method. The same holds true for sub-owners * (Property::addPropertySubOwner, Property::removePropertySubOwner). These methods will * inform the passed object about the new ownership automatically. * Stored properties can be accessed using the Property::properties method or the @@ -231,7 +231,7 @@ public: void addTag(std::string tag); /** - * Removes a tag from this PropertyOwner. No error is reported if the tag does not + * Removes a tag from this PropertyOwner. No error is reported if the tag does not * exist * @param tag The tag is that is to be removed from this PropertyOwner */ diff --git a/include/openspace/properties/scalar/boolproperty.h b/include/openspace/properties/scalar/boolproperty.h index ee74bbfcf8..d38576b698 100644 --- a/include/openspace/properties/scalar/boolproperty.h +++ b/include/openspace/properties/scalar/boolproperty.h @@ -28,9 +28,9 @@ /** * \file boolproperty.h * - * \addtogroup openspace + * \addtogroup openspace * @{ - * \addtogroup properties + * \addtogroup properties * @{ * \class BoolProperty diff --git a/include/openspace/properties/scalar/charproperty.h b/include/openspace/properties/scalar/charproperty.h index 3151c53ebe..f1178e42a1 100644 --- a/include/openspace/properties/scalar/charproperty.h +++ b/include/openspace/properties/scalar/charproperty.h @@ -28,9 +28,9 @@ /** * \file charproperty.h * - * \addtogroup openspace + * \addtogroup openspace * @{ - * \addtogroup properties + * \addtogroup properties * @{ * \class CharProperty diff --git a/include/openspace/properties/scalar/doubleproperty.h b/include/openspace/properties/scalar/doubleproperty.h index 0ef4ed259c..4ac78f8602 100644 --- a/include/openspace/properties/scalar/doubleproperty.h +++ b/include/openspace/properties/scalar/doubleproperty.h @@ -28,9 +28,9 @@ /** * \file doubleproperty.h * - * \addtogroup openspace + * \addtogroup openspace * @{ - * \addtogroup properties + * \addtogroup properties * @{ * \class DoubleProperty diff --git a/include/openspace/properties/scalar/floatproperty.h b/include/openspace/properties/scalar/floatproperty.h index bf7957d4f0..838521aa3f 100644 --- a/include/openspace/properties/scalar/floatproperty.h +++ b/include/openspace/properties/scalar/floatproperty.h @@ -28,9 +28,9 @@ /** * \file floatproperty.h * - * \addtogroup openspace + * \addtogroup openspace * @{ - * \addtogroup properties + * \addtogroup properties * @{ * \class FloatProperty diff --git a/include/openspace/properties/scalar/intproperty.h b/include/openspace/properties/scalar/intproperty.h index b0fbdd9acb..43214ce1c8 100644 --- a/include/openspace/properties/scalar/intproperty.h +++ b/include/openspace/properties/scalar/intproperty.h @@ -28,9 +28,9 @@ /** * \file intproperty.h * - * \addtogroup openspace + * \addtogroup openspace * @{ - * \addtogroup properties + * \addtogroup properties * @{ * \class IntProperty diff --git a/include/openspace/properties/scalar/longdoubleproperty.h b/include/openspace/properties/scalar/longdoubleproperty.h index f02ac8f44f..72455378ee 100644 --- a/include/openspace/properties/scalar/longdoubleproperty.h +++ b/include/openspace/properties/scalar/longdoubleproperty.h @@ -28,9 +28,9 @@ /** * \file longdoubleproperty.h * - * \addtogroup openspace + * \addtogroup openspace * @{ - * \addtogroup properties + * \addtogroup properties * @{ * \class LongDoubleProperty diff --git a/include/openspace/properties/scalar/longlongproperty.h b/include/openspace/properties/scalar/longlongproperty.h index d8f86f3351..645c0cd54d 100644 --- a/include/openspace/properties/scalar/longlongproperty.h +++ b/include/openspace/properties/scalar/longlongproperty.h @@ -28,9 +28,9 @@ /** * \file longlongproperty.h * - * \addtogroup openspace + * \addtogroup openspace * @{ - * \addtogroup properties + * \addtogroup properties * @{ * \class LongLongProperty diff --git a/include/openspace/properties/scalar/longproperty.h b/include/openspace/properties/scalar/longproperty.h index 85576f258c..0adfbf881c 100644 --- a/include/openspace/properties/scalar/longproperty.h +++ b/include/openspace/properties/scalar/longproperty.h @@ -28,9 +28,9 @@ /** * \file longproperty.h * - * \addtogroup openspace + * \addtogroup openspace * @{ - * \addtogroup properties + * \addtogroup properties * @{ * \class LongProperty diff --git a/include/openspace/properties/scalar/shortproperty.h b/include/openspace/properties/scalar/shortproperty.h index 90cb81af0c..93cae8a937 100644 --- a/include/openspace/properties/scalar/shortproperty.h +++ b/include/openspace/properties/scalar/shortproperty.h @@ -28,9 +28,9 @@ /** * \file shortproperty.h * - * \addtogroup openspace + * \addtogroup openspace * @{ - * \addtogroup properties + * \addtogroup properties * @{ * \class ShortProperty diff --git a/include/openspace/properties/scalar/signedcharproperty.h b/include/openspace/properties/scalar/signedcharproperty.h index fae4a5e2ed..3b45631b6d 100644 --- a/include/openspace/properties/scalar/signedcharproperty.h +++ b/include/openspace/properties/scalar/signedcharproperty.h @@ -28,9 +28,9 @@ /** * \file signedcharproperty.h * - * \addtogroup openspace + * \addtogroup openspace * @{ - * \addtogroup properties + * \addtogroup properties * @{ * \class SignedCharProperty diff --git a/include/openspace/properties/scalar/ucharproperty.h b/include/openspace/properties/scalar/ucharproperty.h index 04f799179a..55f3cc5da3 100644 --- a/include/openspace/properties/scalar/ucharproperty.h +++ b/include/openspace/properties/scalar/ucharproperty.h @@ -28,9 +28,9 @@ /** * \file ucharproperty.h * - * \addtogroup openspace + * \addtogroup openspace * @{ - * \addtogroup properties + * \addtogroup properties * @{ * \class UCharProperty diff --git a/include/openspace/properties/scalar/uintproperty.h b/include/openspace/properties/scalar/uintproperty.h index bb3b346a40..43b3debcbc 100644 --- a/include/openspace/properties/scalar/uintproperty.h +++ b/include/openspace/properties/scalar/uintproperty.h @@ -28,9 +28,9 @@ /** * \file uintproperty.h * - * \addtogroup openspace + * \addtogroup openspace * @{ - * \addtogroup properties + * \addtogroup properties * @{ * \class UIntProperty diff --git a/include/openspace/properties/scalar/ulonglongproperty.h b/include/openspace/properties/scalar/ulonglongproperty.h index b0b36b5eb3..e571fcf1f9 100644 --- a/include/openspace/properties/scalar/ulonglongproperty.h +++ b/include/openspace/properties/scalar/ulonglongproperty.h @@ -28,9 +28,9 @@ /** * \file ulonglongproperty.h * - * \addtogroup openspace + * \addtogroup openspace * @{ - * \addtogroup properties + * \addtogroup properties * @{ * \class ULongLongProperty diff --git a/include/openspace/properties/scalar/ulongproperty.h b/include/openspace/properties/scalar/ulongproperty.h index 8372f62938..e27839dc75 100644 --- a/include/openspace/properties/scalar/ulongproperty.h +++ b/include/openspace/properties/scalar/ulongproperty.h @@ -28,9 +28,9 @@ /** * \file ulongproperty.h * - * \addtogroup openspace + * \addtogroup openspace * @{ - * \addtogroup properties + * \addtogroup properties * @{ * \class ULongProperty diff --git a/include/openspace/properties/scalar/ushortproperty.h b/include/openspace/properties/scalar/ushortproperty.h index 10fac45e29..15a0acb3c8 100644 --- a/include/openspace/properties/scalar/ushortproperty.h +++ b/include/openspace/properties/scalar/ushortproperty.h @@ -28,9 +28,9 @@ /** * \file ushortproperty.h * - * \addtogroup openspace + * \addtogroup openspace * @{ - * \addtogroup properties + * \addtogroup properties * @{ * \class UShortProperty diff --git a/include/openspace/properties/scalar/wcharproperty.h b/include/openspace/properties/scalar/wcharproperty.h index d9b2ca546a..73683b857d 100644 --- a/include/openspace/properties/scalar/wcharproperty.h +++ b/include/openspace/properties/scalar/wcharproperty.h @@ -28,9 +28,9 @@ /** * \file wcharproperty.h * - * \addtogroup openspace + * \addtogroup openspace * @{ - * \addtogroup properties + * \addtogroup properties * @{ * \class WCharProperty diff --git a/include/openspace/properties/selectionproperty.h b/include/openspace/properties/selectionproperty.h index f60d7b5217..81b6bd9973 100644 --- a/include/openspace/properties/selectionproperty.h +++ b/include/openspace/properties/selectionproperty.h @@ -63,22 +63,26 @@ std::string PropertyDelegate>>::className(); template <> template <> -std::vector PropertyDelegate>>::fromLuaValue(lua_State* state, bool& success); +std::vector PropertyDelegate>>::fromLuaValue( + lua_State* state, bool& success); template <> template <> -bool PropertyDelegate>>::toLuaValue(lua_State* state, std::vector value); +bool PropertyDelegate>>::toLuaValue( + lua_State* state, std::vector value); template <> int PropertyDelegate>>::typeLua(); template <> template <> -std::vector PropertyDelegate>>::fromString(std::string value, bool& success); +std::vector PropertyDelegate>>::fromString( + std::string value, bool& success); template <> template <> -bool PropertyDelegate>>::toString(std::string& outValue, std::vector inValue); +bool PropertyDelegate>>::toString( + std::string& outValue, std::vector inValue); } // namespace openspace::properties diff --git a/include/openspace/properties/templateproperty.inl b/include/openspace/properties/templateproperty.inl index 9569ecad35..32ecffb1ab 100644 --- a/include/openspace/properties/templateproperty.inl +++ b/include/openspace/properties/templateproperty.inl @@ -29,8 +29,8 @@ namespace openspace::properties { // The following macros can be used to quickly generate the necessary PropertyDelegate // specializations required by the TemplateProperty class. Use the // REGISTER_TEMPLATEPROPERTY_HEADER macro in the header file and the - // REGISTER_TEMPLATEPROPERTY_SOURCE macro in the source file of your new specialization of - // a TemplateProperty + // REGISTER_TEMPLATEPROPERTY_SOURCE macro in the source file of your new + // specialization of a TemplateProperty // CLASS_NAME = The string that the Property::className() should return as well as the diff --git a/include/openspace/properties/triggerproperty.h b/include/openspace/properties/triggerproperty.h index 3ddb7619c4..089f579536 100644 --- a/include/openspace/properties/triggerproperty.h +++ b/include/openspace/properties/triggerproperty.h @@ -54,7 +54,7 @@ public: /** * Accepts only the LUA_TNIL type and will notify all the listeners * that the event has been triggered. - * \param state The unused Lua state + * \param state The unused Lua state * \return Returns always true */ bool setLuaValue(lua_State* state) override; diff --git a/include/openspace/rendering/abufferrenderer.h b/include/openspace/rendering/abufferrenderer.h index e2e0da026d..a4374bba70 100644 --- a/include/openspace/rendering/abufferrenderer.h +++ b/include/openspace/rendering/abufferrenderer.h @@ -119,9 +119,11 @@ private: * The _volumes map keeps track of which volumes that can * be rendered using the current resolve program, along with their raycast data * (id, namespace, etc) - */ + */ std::map _raycastData; - std::map> _boundsPrograms; + std::map< + VolumeRaycaster*, std::unique_ptr + > _boundsPrograms; std::vector _helperPaths; ghoul::Dictionary _resolveDictionary; diff --git a/include/openspace/rendering/framebufferrenderer.h b/include/openspace/rendering/framebufferrenderer.h index 4dbfa6eeef..70e0c0cea5 100644 --- a/include/openspace/rendering/framebufferrenderer.h +++ b/include/openspace/rendering/framebufferrenderer.h @@ -90,9 +90,15 @@ public: private: std::map _raycastData; - std::map> _exitPrograms; - std::map> _raycastPrograms; - std::map> _insideRaycastPrograms; + std::map< + VolumeRaycaster*, std::unique_ptr + > _exitPrograms; + std::map< + VolumeRaycaster*, std::unique_ptr + > _raycastPrograms; + std::map< + VolumeRaycaster*, std::unique_ptr + > _insideRaycastPrograms; std::map _deferredcastData; std::map> _deferredcastPrograms; diff --git a/include/openspace/rendering/loadingscreen.h b/include/openspace/rendering/loadingscreen.h new file mode 100644 index 0000000000..1b6ca397c8 --- /dev/null +++ b/include/openspace/rendering/loadingscreen.h @@ -0,0 +1,138 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2017 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef __OPENSPACE_CORE___LOADINGSCREEN___H__ +#define __OPENSPACE_CORE___LOADINGSCREEN___H__ + +#include +#include +#include + +#include +#include +#include + +// #define LOADINGSCREEN_DEBUGGING + +namespace ghoul::fontrendering { + class Font; +} // namespace ghoul::fontrendering + +namespace ghoul::opengl { + class ProgramObject; + class Texture; +} // namespace ghoul::opengl + +namespace openspace { + +class LoadingScreen { +public: + using ShowMessage = ghoul::Boolean; + using ShowNodeNames = ghoul::Boolean; + using ShowProgressbar = ghoul::Boolean; + + LoadingScreen(ShowMessage showMessage, ShowNodeNames showNodeNames, + ShowProgressbar showProgressbar); + ~LoadingScreen(); + + void render(); + + void postMessage(std::string message); + + void finalize(); + + void setItemNumber(int nItems); + void tickItem(); + + enum class Phase { + Construction, + Initialization + }; + void setPhase(Phase phase); + + + enum class ItemStatus { + Started, + Initializing, + Finished, + Failed + }; + + void updateItem(const std::string& itemName, ItemStatus newStatus); + +private: + bool _showMessage; + bool _showNodeNames; + bool _showProgressbar; + + Phase _phase; + int _iProgress; + int _nItems; + + std::unique_ptr _program; + std::unique_ptr _logoTexture; + + std::shared_ptr _loadingFont; + std::shared_ptr _messageFont; + std::shared_ptr _itemFont; + + struct { + GLuint vao; + GLuint vbo; + } _logo; + + struct { + GLuint vaoFill; + GLuint vboFill; + + GLuint vaoBox; + GLuint vboBox; + } _progressbar; + + std::string _message; + std::mutex _messageMutex; + + struct Item { + std::string name; + ItemStatus status; + + bool hasLocation; +#ifdef LOADINGSCREEN_DEBUGGING + bool exhaustedSearch; +#endif // LOADINGSCREEN_DEBUGGING + glm::vec2 ll; + glm::vec2 ur; + + std::chrono::system_clock::time_point finishedTime; + }; + std::vector _items; + std::mutex _itemsMutex; + + std::random_device _randomDevice; + std::default_random_engine _randomEngine; +}; + +} // namespace openspace + +#endif // __OPENSPACE_CORE___LOADINGSCREEN___H__ diff --git a/include/openspace/rendering/renderable.h b/include/openspace/rendering/renderable.h index 57b89d29e2..fb1bf30751 100644 --- a/include/openspace/rendering/renderable.h +++ b/include/openspace/rendering/renderable.h @@ -42,7 +42,7 @@ struct UpdateData; struct RendererTasks; struct SurfacePositionHandle; -namespace documentation { struct Documentation; } +namespace documentation { struct Documentation; } // Forward declare to minimize dependencies @@ -58,14 +58,17 @@ public: Overlay = 8 }; - static std::unique_ptr createFromDictionary(const ghoul::Dictionary& dictionary); + static std::unique_ptr createFromDictionary( + const ghoul::Dictionary& dictionary); // constructors & destructor Renderable(const ghoul::Dictionary& dictionary); virtual ~Renderable(); virtual void initialize(); + virtual void initializeGL(); virtual void deinitialize(); + virtual void deinitializeGL(); virtual bool isReady() const = 0; bool isEnabled() const; @@ -89,7 +92,8 @@ public: void onEnabledChange(std::function callback); - static void setPscUniforms(ghoul::opengl::ProgramObject& program, const Camera& camera, const PowerScaledCoordinate& position); + static void setPscUniforms(ghoul::opengl::ProgramObject& program, + const Camera& camera, const PowerScaledCoordinate& position); static documentation::Documentation Documentation(); diff --git a/include/openspace/rendering/renderengine.h b/include/openspace/rendering/renderengine.h index f3ad634384..f3064d00d0 100644 --- a/include/openspace/rendering/renderengine.h +++ b/include/openspace/rendering/renderengine.h @@ -130,7 +130,8 @@ public: std::string progressToStr(int size, double t); - void removeRenderProgram(const std::unique_ptr& program); + void removeRenderProgram( + const std::unique_ptr& program); /** * Set raycasting uniforms on the program object, and setup raycasting. diff --git a/include/openspace/rendering/screenspacerenderable.h b/include/openspace/rendering/screenspacerenderable.h index 7db38d281e..24d301d2a0 100644 --- a/include/openspace/rendering/screenspacerenderable.h +++ b/include/openspace/rendering/screenspacerenderable.h @@ -44,7 +44,7 @@ namespace documentation { struct Documentation; } /** * The base class for screen space images and screen space framebuffers. - * This base class handles general functionality specific to planes that are rendered in + * This base class handles general functionality specific to planes that are rendered in * front of the camera. It implements protected methods and properties for converting * the planes from Spherical to Euclidean coordinates and back. It also specifies the * interface that its children need to implement. @@ -60,7 +60,10 @@ public: virtual void render(); virtual bool initialize(); + virtual bool initializeGL(); virtual bool deinitialize(); + virtual bool deinitializeGL(); + virtual void update() = 0; virtual bool isReady() const; bool isEnabled() const; @@ -79,7 +82,7 @@ protected: * Converts Spherical coordinates to Euclidean. * \param spherical The coordinates theta and phi * \param radius The radius position value of the plane - * \return The x and y position value of the plane + * \return The x and y position value of the plane */ glm::vec2 toEuclidean(const glm::vec2& spherical, float radius); diff --git a/include/openspace/rendering/transferfunction.h b/include/openspace/rendering/transferfunction.h index 2c462f7845..f317c1485f 100644 --- a/include/openspace/rendering/transferfunction.h +++ b/include/openspace/rendering/transferfunction.h @@ -38,7 +38,8 @@ class TransferFunction { public: typedef std::function TfChangedCallback; - TransferFunction(const std::string& filepath, TfChangedCallback tfChangedCallback = TfChangedCallback()); + TransferFunction(const std::string& filepath, + TfChangedCallback tfChangedCallback = TfChangedCallback()); void setPath(const std::string& filepath); ghoul::opengl::Texture& getTexture(); void bind(); diff --git a/include/openspace/rendering/volume.h b/include/openspace/rendering/volume.h index 8d954ab531..4e7eaa105c 100644 --- a/include/openspace/rendering/volume.h +++ b/include/openspace/rendering/volume.h @@ -40,7 +40,7 @@ public: /** * Constructor */ - Volume() {}; + Volume() {}; /** * Destructor @@ -50,16 +50,19 @@ public: /** * Render the volume's entry points (front face of the bounding geometry) */ - //virtual void renderEntryPoints(const RenderData& data, ghoul::opengl::ProgramObject* program) = 0; + //virtual void renderEntryPoints(const RenderData& data, + // ghoul::opengl::ProgramObject* program) = 0; /** * Render the volume's exit points (back face of the bounding geometry) */ - //virtual void renderExitPoints(const RenderData& data, ghoul::opengl::ProgramObject* program) = 0; + //virtual void renderExitPoints(const RenderData& data, + // ghoul::opengl::ProgramObject* program) = 0; /** * Prepare the volume for the ABuffer's resolve step. - * Make sure textures are up to date, bind them to texture units, set program uniforms etc. + * Make sure textures are up to date, bind them to texture units, set program uniforms + * etc. */ //virtual void preRayCast(ghoul::opengl::ProgramObject* program) {}; @@ -76,22 +79,22 @@ public: * * The shader preprocessor will have acceess to * A #{namespace} variable (unique per helper file) - * + * * Should define the function: * vec4 getVertex() */ //virtual std::string getBoundsVsPath() = 0; /* - * Return a path to a file with the functions, uniforms and fragment shader in variables - * required to generate the fragment color and depth. + * Return a path to a file with the functions, uniforms and fragment shader in + * variables required to generate the fragment color and depth. * * Should define the function: * Fragment getFragment() - * + * * The shader preprocessor will have acceess to * A #{namespace} variable (unique per helper file) - */ + */ //virtual std::string getBoundsFsPath() = 0; /** @@ -99,7 +102,8 @@ public: * required to perform ray casting through this volume. * * The header should define the following two functions: - * vec4 sampler#{id}(vec3 samplePos, vec3 dir, float occludingAlpha, inout float maxStepSize) + * vec4 sampler#{id}(vec3 samplePos, vec3 dir, float occludingAlpha, + * inout float maxStepSize) * (return color of sample) * float stepSize#{id}(vec3 samplePos, vec3 dir) * (return the preferred step size at this sample position) @@ -116,9 +120,9 @@ public: * This file will be included once per shader program generated, * regardless of how many volumes say they require the file. * Ideal to avoid redefinitions of helper functions. - * - * The shader preprocessor will have access to the #{namespace} variable (unique per helper file) - * which should be a prefix to all symbols defined by the helper + * + * The shader preprocessor will have access to the #{namespace} variable (unique per + * helper file) which should be a prefix to all symbols defined by the helper */ //virtual std::string getHelperPath() = 0; diff --git a/include/openspace/rendering/volumeraycaster.h b/include/openspace/rendering/volumeraycaster.h index 14db9e5eab..7e1e60bfa0 100644 --- a/include/openspace/rendering/volumeraycaster.h +++ b/include/openspace/rendering/volumeraycaster.h @@ -49,30 +49,37 @@ public: /** * Render the volume's entry points (front face of the bounding geometry) */ - virtual void renderEntryPoints(const RenderData& /*data*/, ghoul::opengl::ProgramObject& /*program*/) = 0; + virtual void renderEntryPoints(const RenderData& /*data*/, + ghoul::opengl::ProgramObject& /*program*/) = 0; /** * Render the volume's exit points (back face of the bounding geometry) */ - virtual void renderExitPoints(const RenderData& /*data*/, ghoul::opengl::ProgramObject& /*program*/) = 0; + virtual void renderExitPoints(const RenderData& /*data*/, + ghoul::opengl::ProgramObject& /*program*/) = 0; /** * Prepare the volume for the ABuffer's resolve step. - * Make sure textures are up to date, bind them to texture units, set program uniforms etc. + * Make sure textures are up to date, bind them to texture units, set program uniforms + * etc. */ - virtual void preRaycast(const RaycastData& /*data*/, ghoul::opengl::ProgramObject& /*program*/) {}; + virtual void preRaycast(const RaycastData& /*data*/, + ghoul::opengl::ProgramObject& /*program*/) {}; /** * Clean up for the volume after the ABuffer's resolve step. * Make sure texture units are deinitialized, etc. */ - virtual void postRaycast(const RaycastData& /*data*/, ghoul::opengl::ProgramObject& /*program*/) {}; + virtual void postRaycast(const RaycastData& /*data*/, + ghoul::opengl::ProgramObject& /*program*/) {}; /** * Return true if the camera is inside the volume. - * Also set localPosition to the camera position in the volume's local coordainte system. + * Also set localPosition to the camera position in the volume's local coordinate + * system. */ - virtual bool cameraIsInside(const RenderData& /*data*/, glm::vec3& /*localPosition*/) { return false; }; + virtual bool cameraIsInside(const RenderData& /*data*/, + glm::vec3& /*localPosition*/) { return false; }; /** * Return a path the file to use as vertex shader @@ -83,15 +90,15 @@ public: virtual std::string getBoundsVsPath() const = 0; /* - * Return a path to a file with the functions, uniforms and fragment shader in variables - * required to generate the fragment color and depth. + * Return a path to a file with the functions, uniforms and fragment shader in + * variables required to generate the fragment color and depth. * * Should define the function: * Fragment getFragment() - * + * * The shader preprocessor will have acceess to * A #{namespace} variable (unique per helper file) - */ + */ virtual std::string getBoundsFsPath() const = 0 ; /** @@ -99,7 +106,8 @@ public: * required to perform ray casting through this volume. * * The header should define the following two functions: - * vec4 sample#{id}(vec3 samplePos, vec3 dir, float occludingAlpha, inout float maxStepSize) + * vec4 sample#{id}(vec3 samplePos, vec3 dir, float occludingAlpha, + * inout float maxStepSize) * (return color of sample) * float stepSize#{id}(vec3 samplePos, vec3 dir) * (return the preferred step size at this sample position) @@ -116,13 +124,13 @@ public: * This file will be included once per shader program generated, * regardless of how many volumes say they require the file. * Ideal to avoid redefinitions of helper functions. - * - * The shader preprocessor will have access to the #{namespace} variable (unique per helper file) - * which should be a prefix to all symbols defined by the helper + * + * The shader preprocessor will have access to the #{namespace} variable (unique per + * helper file) which should be a prefix to all symbols defined by the helper */ virtual std::string getHelperPath() const = 0; }; } // namespace openspace -#endif // __OPENSPACE_CORE___VOLUMERAYCASTER___H__ +#endif // __OPENSPACE_CORE___VOLUMERAYCASTER___H__ diff --git a/include/openspace/scene/rotation.h b/include/openspace/scene/rotation.h index 18d1f0a7c1..9566e50ef6 100644 --- a/include/openspace/scene/rotation.h +++ b/include/openspace/scene/rotation.h @@ -41,7 +41,8 @@ namespace documentation { struct Documentation; } class Rotation : public properties::PropertyOwner { public: - static std::unique_ptr createFromDictionary(const ghoul::Dictionary& dictionary); + static std::unique_ptr createFromDictionary( + const ghoul::Dictionary& dictionary); Rotation(const ghoul::Dictionary& dictionary); virtual ~Rotation() = default; diff --git a/include/openspace/scene/scale.h b/include/openspace/scene/scale.h index a9f8cbd856..13948adcee 100644 --- a/include/openspace/scene/scale.h +++ b/include/openspace/scene/scale.h @@ -41,7 +41,8 @@ namespace documentation { struct Documentation; } class Scale : public properties::PropertyOwner { public: - static std::unique_ptr createFromDictionary(const ghoul::Dictionary& dictionary); + static std::unique_ptr createFromDictionary( + const ghoul::Dictionary& dictionary); Scale(); virtual ~Scale() = default; diff --git a/include/openspace/scene/scene.h b/include/openspace/scene/scene.h index f4d132cc15..2f61a0675a 100644 --- a/include/openspace/scene/scene.h +++ b/include/openspace/scene/scene.h @@ -61,7 +61,8 @@ public: * \param component The optional compoment that caused this exception to be thrown * \pre message may not be empty */ - explicit InvalidSceneError(const std::string& message, const std::string& component = ""); + explicit InvalidSceneError(const std::string& message, + const std::string& component = ""); }; // constructors & destructor @@ -72,6 +73,12 @@ public: * Initalizes the SceneGraph */ void initialize(); + + /** + * Initializes the OpenGL part of the SceneGraph + */ + void initializeGL(); + /** * Clear the scene graph, @@ -118,12 +125,14 @@ public: /** * Add a node and all its children to the scene. */ - void addNode(SceneGraphNode* node, UpdateDependencies updateDeps = UpdateDependencies::Yes); + void addNode(SceneGraphNode* node, + UpdateDependencies updateDeps = UpdateDependencies::Yes); /** * Remove a node and all its children from the scene. */ - void removeNode(SceneGraphNode* node, UpdateDependencies updateDeps = UpdateDependencies::Yes); + void removeNode(SceneGraphNode* node, + UpdateDependencies updateDeps = UpdateDependencies::Yes); void addSceneLicense(SceneLicense license); diff --git a/include/openspace/scene/scenegraphnode.h b/include/openspace/scene/scenegraphnode.h index 0261328d6a..89398d504a 100644 --- a/include/openspace/scene/scenegraphnode.h +++ b/include/openspace/scene/scenegraphnode.h @@ -73,10 +73,13 @@ public: SceneGraphNode(); ~SceneGraphNode(); - static std::unique_ptr createFromDictionary(const ghoul::Dictionary& dictionary); + static std::unique_ptr createFromDictionary( + const ghoul::Dictionary& dictionary); void initialize(); + void initializeGL(); void deinitialize(); + void deinitializeGL(); void traversePreOrder(std::function fn); void traversePostOrder(std::function fn); @@ -84,16 +87,21 @@ public: void render(const RenderData& data, RendererTasks& tasks); void updateCamera(Camera* camera) const; - void attachChild(std::unique_ptr child, UpdateScene updateScene = UpdateScene::Yes); - std::unique_ptr detachChild(SceneGraphNode& child, UpdateScene updateScene = UpdateScene::Yes); + void attachChild(std::unique_ptr child, + UpdateScene updateScene = UpdateScene::Yes); + std::unique_ptr detachChild(SceneGraphNode& child, + UpdateScene updateScene = UpdateScene::Yes); void setParent(SceneGraphNode& parent, UpdateScene updateScene = UpdateScene::Yes); - void addDependency(SceneGraphNode& dependency, UpdateScene updateScene = UpdateScene::Yes); - void removeDependency(SceneGraphNode& dependency, UpdateScene updateScene = UpdateScene::Yes); + void addDependency(SceneGraphNode& dependency, + UpdateScene updateScene = UpdateScene::Yes); + void removeDependency(SceneGraphNode& dependency, + UpdateScene updateScene = UpdateScene::Yes); void clearDependencies(UpdateScene updateScene = UpdateScene::Yes); - void setDependencies(const std::vector& dependencies, UpdateScene updateScene = UpdateScene::Yes); + void setDependencies(const std::vector& dependencies, + UpdateScene updateScene = UpdateScene::Yes); SurfacePositionHandle calculateSurfacePositionHandle( - const glm::dvec3& targetModelSpace); + const glm::dvec3& targetModelSpace); const std::vector& dependencies() const; const std::vector& dependentNodes() const; diff --git a/include/openspace/scene/sceneloader.h b/include/openspace/scene/sceneloader.h index 140bbc0f29..a605e4d8d0 100644 --- a/include/openspace/scene/sceneloader.h +++ b/include/openspace/scene/sceneloader.h @@ -59,7 +59,8 @@ public: /** * Import a scene graph node from a dictionary into an existing scene. */ - SceneGraphNode* importNodeDictionary(Scene& scene, const ghoul::Dictionary& dictionary); + SceneGraphNode* importNodeDictionary(Scene& scene, + const ghoul::Dictionary& dictionary); private: struct LoadedNode { @@ -99,7 +100,8 @@ private: /** * Load a mod file. */ - std::vector loadModule(const std::string& path, lua_State* luaState); + std::vector loadModule(const std::string& path, + lua_State* luaState); /** * Loads an existing license file @@ -120,7 +122,8 @@ private: /** * Add loaded nodes to an existing scene */ - std::vector addLoadedNodes(Scene& scene, std::vector&& nodes); + std::vector addLoadedNodes(Scene& scene, + std::vector&& nodes); }; } // namespace openspace diff --git a/include/openspace/scene/translation.h b/include/openspace/scene/translation.h index bcd7597c68..f685c55182 100644 --- a/include/openspace/scene/translation.h +++ b/include/openspace/scene/translation.h @@ -42,7 +42,8 @@ namespace documentation { struct Documentation; } class Translation : public properties::PropertyOwner { public: - static std::unique_ptr createFromDictionary(const ghoul::Dictionary& dictionary); + static std::unique_ptr createFromDictionary( + const ghoul::Dictionary& dictionary); Translation(); virtual ~Translation() = default; diff --git a/include/openspace/scripting/scriptengine.h b/include/openspace/scripting/scriptengine.h index 793e07f21d..0c5e120beb 100644 --- a/include/openspace/scripting/scriptengine.h +++ b/include/openspace/scripting/scriptengine.h @@ -91,11 +91,6 @@ public: std::vector allLuaFunctions() const; - //parallel functions - //bool parseLibraryAndFunctionNames(std::string &library, std::string &function, const std::string &script); - //bool shouldScriptBeSent(const std::string &library, const std::string &function); - //void cacheScript(const std::string &library, const std::string &function, const std::string &script); - static std::string OpenSpaceLibraryName; private: diff --git a/include/openspace/scripting/scriptscheduler.h b/include/openspace/scripting/scriptscheduler.h index 6641e47f3f..67e66948cc 100644 --- a/include/openspace/scripting/scriptscheduler.h +++ b/include/openspace/scripting/scriptscheduler.h @@ -37,7 +37,7 @@ namespace openspace::documentation { struct Documentation; } namespace openspace::scripting { /** - * Maintains an ordered list of ScheduledScripts and provides a simple + * Maintains an ordered list of ScheduledScripts and provides a simple * interface for retrieveing scheduled scripts */ class ScriptScheduler { @@ -72,8 +72,8 @@ public: void clearSchedule(); /** - * Progresses the script schedulers time and returns all scripts that has been - * scheduled to run between \param newTime and the time provided in the last invocation + * Progresses the script schedulers time and returns all scripts that has been + * scheduled to run between \param newTime and the time provided in the last invocation * of this method. * * \param newTime A j2000 time value specifying the new time stamp that @@ -96,7 +96,7 @@ public: > progressTo(double newTime); /** - * Returns the the j2000 time value that the script scheduler is currently at + * Returns the the j2000 time value that the script scheduler is currently at */ double currentTime() const; diff --git a/include/openspace/util/concurrentjobmanager.h b/include/openspace/util/concurrentjobmanager.h index a0c446a2e6..72f66312c1 100644 --- a/include/openspace/util/concurrentjobmanager.h +++ b/include/openspace/util/concurrentjobmanager.h @@ -43,7 +43,7 @@ struct Job { virtual std::shared_ptr

product() = 0; }; -/* +/* * Templated Concurrent Job Manager * This class is used execute specific jobs on one (1) parallell thread */ diff --git a/include/openspace/util/gpudata.h b/include/openspace/util/gpudata.h index bf030e3c7d..b5189cbd65 100644 --- a/include/openspace/util/gpudata.h +++ b/include/openspace/util/gpudata.h @@ -41,7 +41,7 @@ class UniformLocation { public: /** - * Updates the uniform location of the uniform variable named + * Updates the uniform location of the uniform variable named * in the provided shader program. */ void bind(ghoul::opengl::ProgramObject* program, const std::string& name); @@ -53,7 +53,7 @@ protected: /** * Manages a GPU representation of the templated data type T. - * This class provides a simple interface setting the value of + * This class provides a simple interface setting the value of * the binded GLSL variable. */ template @@ -71,13 +71,13 @@ public: /** * Manages a Texture on the GPU. - * This class provides a simple interface binding texture to the + * This class provides a simple interface binding texture to the * named uniform. */ class GPUTexture : public UniformLocation{ public: /** - * Sets and assignes a texture unit within the provided shader + * Sets and assignes a texture unit within the provided shader * program. * OBS! Users must ensure bind has been called before using this method. */ diff --git a/include/openspace/util/histogram.h b/include/openspace/util/histogram.h index 408cc2222c..8029951bf6 100644 --- a/include/openspace/util/histogram.h +++ b/include/openspace/util/histogram.h @@ -49,10 +49,10 @@ public: * Enter value into the histogram. The add method takes the given * value, works out which bin this corresponds to, and increments * this bin by 'repeat'. - * + * * @param value The Value to insert into the histogram * @param repeat How many times you want to insert it - * + * * @return Returns true if succesful insertion, otherwise return false */ bool add(float value, float repeat = 1.0f); diff --git a/include/openspace/util/openspacemodule.h b/include/openspace/util/openspacemodule.h index 791c6cfef3..97eaf3c9d0 100644 --- a/include/openspace/util/openspacemodule.h +++ b/include/openspace/util/openspacemodule.h @@ -45,7 +45,7 @@ namespace documentation { struct Documentation; } class OpenSpaceModule : public properties::PropertyOwner { public: /** - * Constructs the OpenSpaceModule with a specific \p name. The uniqueness of the + * Constructs the OpenSpaceModule with a specific \p name. The uniqueness of the * \p name will be checked at a later stage. * \param name The name of this OpenSpace module * \pre \p name must not be empty diff --git a/include/openspace/util/spicemanager.h b/include/openspace/util/spicemanager.h index e40d0509a9..ac0693bf68 100644 --- a/include/openspace/util/spicemanager.h +++ b/include/openspace/util/spicemanager.h @@ -64,7 +64,7 @@ public: LightTime, ///< One-way light time (LT) LightTimeStellar, ///< One-way light time and stellar (LT+S) ConvergedNewtonian, ///< Converged newtonian light time (CN) - ConvergedNewtonianStellar ///< Converged newtonian + stellar (CN+S) + ConvergedNewtonianStellar ///< Converged newtonian+stellar (CN+S) }; /// The direction of the aberration correct enum class Direction { @@ -630,7 +630,7 @@ public: }; /** - * Returns the state vector (position and velocity) of a \p target body relative to an + * Returns the state vector (position and velocity) of a \p target body relative to an * \p observer in a specific \p referenceFrame, optionally corrected for aberration * (\p aberrationCorrection). * \param target The target body name or the target body's NAIF ID @@ -660,7 +660,7 @@ public: const std::string& observer, const std::string& referenceFrame, AberrationCorrection aberrationCorrection, double ephemerisTime) const; - /** + /** * Returns the state transformation matrix used to convert from the \p sourceFrame to * the \p destinationFrame at a specific \p ephemerisTime. * \param sourceFrame The name of the source reference frame @@ -824,7 +824,7 @@ public: bool addFrame(std::string body, std::string frame); /** - * This function returns the frame of a body if defined, otherwise it returns + * This function returns the frame of a body if defined, otherwise it returns * IAU_ + body (most frames are known by the International Astronomical Union) * \param body - the name of the body * \return the frame of the body @@ -833,7 +833,7 @@ public: std::string frameFromBody(const std::string& body) const; /** - * Sets the SpiceManager's exception handling. If UseException::No is passed to this + * Sets the SpiceManager's exception handling. If UseException::No is passed to this * function, all subsequent calls will not throw an error, but fail silently instead. * If set to UseException::Yes, a SpiceException is thrown whenever an error occurs. * \param useException The new exeception handling method that the SpiceManager should @@ -896,7 +896,8 @@ private: * position will be retrieved. If the coverage has ended, the last position will be * retrieved. If \p time is in a coverage gap, the position will be interpolated. * \param target The body which is missing SPK data for this time - * \param observer The observer. The position will be retrieved in relation to this body + * \param observer The observer. The position will be retrieved in relation to this + * body * \param referenceFrame The reference frame of the output position vector * \param aberrationCorrection The aberration correction used for the position * calculation diff --git a/include/openspace/util/syncbuffer.h b/include/openspace/util/syncbuffer.h index a64ee9191e..e3954d5202 100644 --- a/include/openspace/util/syncbuffer.h +++ b/include/openspace/util/syncbuffer.h @@ -52,7 +52,11 @@ public: ghoul_assert(_encodeOffset + size < _n, ""); int32_t length = static_cast(s.length()); - memcpy(_dataStream.data() + _encodeOffset, reinterpret_cast(&length), sizeof(int32_t)); + memcpy( + _dataStream.data() + _encodeOffset, + reinterpret_cast(&length), + sizeof(int32_t) + ); _encodeOffset += sizeof(int32_t); memcpy(_dataStream.data() + _encodeOffset, s.c_str(), length); _encodeOffset += length; @@ -69,7 +73,11 @@ public: std::string decode() { int32_t length; - memcpy(reinterpret_cast(&length), _dataStream.data() + _decodeOffset, sizeof(int32_t)); + memcpy( + reinterpret_cast(&length), + _dataStream.data() + _decodeOffset, + sizeof(int32_t) + ); char* tmp = new char[length + 1]; _decodeOffset += sizeof(int32_t); memcpy(tmp, _dataStream.data() + _decodeOffset, length); diff --git a/include/openspace/util/syncdata.h b/include/openspace/util/syncdata.h index ec22cea74a..6b688ac068 100644 --- a/include/openspace/util/syncdata.h +++ b/include/openspace/util/syncdata.h @@ -53,13 +53,13 @@ protected: }; /** - * A double buffered implementation of the Syncable interface. - * Users are encouraged to used this class as a default way to synchronize different + * A double buffered implementation of the Syncable interface. + * Users are encouraged to used this class as a default way to synchronize different * C++ data types using the SyncEngine * - * This class aims to handle the synchronization parts and yet act like a regular - * instance of T. Implicit casts are supported, however, when accessing member functions or - * or variables, user may have to do explicit casts. + * This class aims to handle the synchronization parts and yet act like a regular + * instance of T. Implicit casts are supported, however, when accessing member functions + * or variables, user may have to do explicit casts. * * ((T&) t).method(); * @@ -71,7 +71,7 @@ public: SyncData() {}; SyncData(const T& val) : data(val) {}; SyncData(const SyncData& o) : data(o.data) { - // Should not have to be copied! + // Should not have to be copied! }; /** diff --git a/include/openspace/util/taskloader.h b/include/openspace/util/taskloader.h index 4081523c7d..63672bff0f 100644 --- a/include/openspace/util/taskloader.h +++ b/include/openspace/util/taskloader.h @@ -33,7 +33,8 @@ namespace openspace { class TaskLoader { public: - std::vector> tasksFromDictionary(const ghoul::Dictionary& dictionary); + std::vector> tasksFromDictionary( + const ghoul::Dictionary& dictionary); std::vector> tasksFromFile(const std::string& path); }; diff --git a/include/openspace/util/threadpool.h b/include/openspace/util/threadpool.h index f83b622b2f..556d0cba1f 100644 --- a/include/openspace/util/threadpool.h +++ b/include/openspace/util/threadpool.h @@ -40,7 +40,7 @@ namespace openspace { class ThreadPool; class Worker { -public: +public: Worker(ThreadPool& pool); void operator()(); private: diff --git a/include/openspace/util/time.h b/include/openspace/util/time.h index 06a4a629b2..a3f23059e5 100644 --- a/include/openspace/util/time.h +++ b/include/openspace/util/time.h @@ -36,7 +36,7 @@ namespace openspace { /** * This singleton class represents the current simulation time in OpenSpace. It * internally stores the time and provides methods to set the time directly - * (setTime(double), setTime(std::string)) using a double value using the + * (setTime(double), setTime(std::string)) using a double value using the * number of seconds passed since the J2000 epoch or a string that denotes * a valid date string in accordance to the Spice library * (http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/str2et_c.html). The time can @@ -47,12 +47,12 @@ namespace openspace { * the number of seconds that pass for each real-time second. This value is set with * setDeltaTime(double), retrieved with deltaTime() and solely used in the * advanceTime(double), which takes a tickTime parameter. The value of the - * parameter is dependent on the usage of the class and must be equal to the real-world + * parameter is dependent on the usage of the class and must be equal to the real-world * time that has passed since the last call to the method. For example, if the * advanceTime(double) method is called each frame, the tickTime has to be * equal to the frame time. * - * The synchronization of the simulation time requires + * The synchronization of the simulation time requires */ class Time { public: @@ -144,7 +144,7 @@ public: double deltaTime() const; /** - * Sets the pause function, i.e. setting the deltaTime to 0 (pause = + * Sets the pause function, i.e. setting the deltaTime to 0 (pause = * true) and restoring it when the function is called with a parameter of * false. * \param pause If true, the simulation time stops; diff --git a/include/openspace/util/timeline.h b/include/openspace/util/timeline.h index 9c96f0b582..0798580e62 100644 --- a/include/openspace/util/timeline.h +++ b/include/openspace/util/timeline.h @@ -64,7 +64,8 @@ public: void removeKeyframe(size_t id); void removeKeyframesBefore(double timestamp, bool inclusive = false); void removeKeyframesAfter(double timestamp, bool inclusive = false); - void removeKeyframesBetween(double begin, double end, bool inclusiveBegin = false, bool inclusiveEnd = false); + void removeKeyframesBetween(double begin, double end, bool inclusiveBegin = false, + bool inclusiveEnd = false); size_t nKeyframes() const; const Keyframe* firstKeyframeAfter(double timestamp, bool inclusive = false) const; const Keyframe* lastKeyframeBefore(double timestamp, bool inclusive = false) const; diff --git a/include/openspace/util/timeline.inl b/include/openspace/util/timeline.inl index f3b4a3774f..1ed2d1d45a 100644 --- a/include/openspace/util/timeline.inl +++ b/include/openspace/util/timeline.inl @@ -35,15 +35,30 @@ Timeline::~Timeline() {} template void Timeline::addKeyframe(double timestamp, T data) { Keyframe keyframe(++_nextKeyframeId, timestamp, data); - auto iter = std::upper_bound(_keyframes.begin(), _keyframes.end(), keyframe, &compareKeyframeTimes); + auto iter = std::upper_bound( + _keyframes.begin(), + _keyframes.end(), + keyframe, + &compareKeyframeTimes + ); _keyframes.insert(iter, keyframe); } template void Timeline::removeKeyframesAfter(double timestamp, bool inclusive) { auto iter = inclusive - ? std::lower_bound(_keyframes.begin(), _keyframes.end(), timestamp, &compareKeyframeTimeWithTime) - : std::upper_bound(_keyframes.begin(), _keyframes.end(), timestamp, &compareTimeWithKeyframeTime); + ? std::lower_bound( + _keyframes.begin(), + _keyframes.end(), + timestamp, + &compareKeyframeTimeWithTime + ) + : std::upper_bound( + _keyframes.begin(), + _keyframes.end(), + timestamp, + &compareTimeWithKeyframeTime + ); _keyframes.erase(iter, _keyframes.end()); } @@ -51,21 +66,53 @@ void Timeline::removeKeyframesAfter(double timestamp, bool inclusive) { template void Timeline::removeKeyframesBefore(double timestamp, bool inclusive) { auto iter = inclusive - ? std::upper_bound(_keyframes.begin(), _keyframes.end(), timestamp, &compareTimeWithKeyframeTime) - : std::lower_bound(_keyframes.begin(), _keyframes.end(), timestamp, &compareKeyframeTimeWithTime); + ? std::upper_bound( + _keyframes.begin(), + _keyframes.end(), + timestamp, + &compareTimeWithKeyframeTime + ) + : std::lower_bound( + _keyframes.begin(), + _keyframes.end(), + timestamp, + &compareKeyframeTimeWithTime) + ; _keyframes.erase(_keyframes.begin(), iter); } template -void Timeline::removeKeyframesBetween(double begin, double end, bool inclusiveBegin, bool inclusiveEnd) { +void Timeline::removeKeyframesBetween(double begin, double end, bool inclusiveBegin, + bool inclusiveEnd) +{ auto beginIter = inclusiveBegin - ? std::lower_bound(_keyframes.begin(), _keyframes.end(), begin, &compareKeyframeTimeWithTime) - : std::upper_bound(_keyframes.begin(), _keyframes.end(), begin, &compareTimeWithKeyframeTime); + ? std::lower_bound( + _keyframes.begin(), + _keyframes.end(), + begin, + &compareKeyframeTimeWithTime + ) + : std::upper_bound( + _keyframes.begin(), + _keyframes.end(), + begin, + &compareTimeWithKeyframeTime + ); auto endIter = inclusiveEnd - ? std::upper_bound(beginIter, _keyframes.end(), end, &compareTimeWithKeyframeTime) - : std::lower_bound(beginIter, _keyframes.end(), end, &compareKeyframeTimeWithTime); + ? std::upper_bound( + beginIter, + _keyframes.end(), + end, + &compareTimeWithKeyframeTime + ) + : std::lower_bound( + beginIter, + _keyframes.end(), + end, + &compareKeyframeTimeWithTime + ); _keyframes.erase(beginIter, endIter); } @@ -77,9 +124,14 @@ void Timeline::clearKeyframes() { template void Timeline::removeKeyframe(size_t id) { - _keyframes.erase(std::remove_if(_keyframes.begin(), _keyframes.end(), [id] (Keyframe keyframe) { - return keyframe.id == id; - }), _keyframes.end()); + _keyframes.erase( + std::remove_if( + _keyframes.begin(), + _keyframes.end(), + [id] (Keyframe keyframe) { return keyframe.id == id; } + ), + _keyframes.end() + ); } template @@ -88,10 +140,23 @@ size_t Timeline::nKeyframes() const { } template -const Keyframe* Timeline::firstKeyframeAfter(double timestamp, bool inclusive) const { +const Keyframe* Timeline::firstKeyframeAfter(double timestamp, + bool inclusive) const +{ auto it = inclusive - ? std::lower_bound(_keyframes.begin(), _keyframes.end(), timestamp, &compareKeyframeTimeWithTime) - : std::upper_bound(_keyframes.begin(), _keyframes.end(), timestamp, &compareTimeWithKeyframeTime); + ? std::lower_bound( + _keyframes.begin(), + _keyframes.end(), + timestamp, + &compareKeyframeTimeWithTime + ) + : std::upper_bound( + _keyframes.begin(), + _keyframes.end(), + timestamp, + &compareTimeWithKeyframeTime + ); + if (it == _keyframes.end()) { return nullptr; } @@ -99,10 +164,23 @@ const Keyframe* Timeline::firstKeyframeAfter(double timestamp, bool inclus } template -const Keyframe* Timeline::lastKeyframeBefore(double timestamp, bool inclusive) const { +const Keyframe* Timeline::lastKeyframeBefore(double timestamp, + bool inclusive) const +{ auto it = inclusive - ? std::upper_bound(_keyframes.begin(), _keyframes.end(), timestamp, &compareTimeWithKeyframeTime) - : std::lower_bound(_keyframes.begin(), _keyframes.end(), timestamp, &compareKeyframeTimeWithTime); + ? std::upper_bound( + _keyframes.begin(), + _keyframes.end(), + timestamp, + &compareTimeWithKeyframeTime + ) + : std::lower_bound( + _keyframes.begin(), + _keyframes.end(), + timestamp, + &compareKeyframeTimeWithTime + ); + if (it == _keyframes.begin()) { return nullptr; } @@ -116,6 +194,4 @@ const std::deque>& Timeline::keyframes() const { return _keyframes; } - -} - +} // namespace openspace diff --git a/include/openspace/util/timerange.h b/include/openspace/util/timerange.h index 4b2e567249..14da40957d 100644 --- a/include/openspace/util/timerange.h +++ b/include/openspace/util/timerange.h @@ -38,7 +38,7 @@ struct TimeRange { TimeRange(); /** - * Initializes a TimeRange with both start and end time. Initializing empty timeranges + * Initializes a TimeRange with both start and end time. Initializing empty timeranges * is OK. */ TimeRange(double startTime, double endTime); @@ -49,9 +49,11 @@ struct TimeRange { TimeRange(const ghoul::Dictionary& dict); /** - * \returns true if timeRange could be initialized from the dictionary, false otherwise. + * \returns true if timeRange could be initialized from the dictionary, + * false otherwise. */ - static bool initializeFromDictionary(const ghoul::Dictionary& dict, TimeRange& timeRange); + static bool initializeFromDictionary(const ghoul::Dictionary& dict, + TimeRange& timeRange); void include(double val); diff --git a/include/openspace/util/transformationmanager.h b/include/openspace/util/transformationmanager.h index 054933a67d..642aa182ad 100644 --- a/include/openspace/util/transformationmanager.h +++ b/include/openspace/util/transformationmanager.h @@ -59,10 +59,12 @@ public: TransformationManager(); ~TransformationManager(); - glm::dmat3 frameTransformationMatrix(const std::string& from, const std::string& to, double ephemerisTime) const; + glm::dmat3 frameTransformationMatrix(const std::string& from, const std::string& to, + double ephemerisTime) const; private: - glm::dmat3 kameleonTransformationMatrix(const std::string& from, const std::string& to, double ephemerisTime) const; + glm::dmat3 kameleonTransformationMatrix(const std::string& from, + const std::string& to, double ephemerisTime) const; #ifdef OPENSPACE_MODULE_KAMELEON_ENABLED std::shared_ptr _kameleon; diff --git a/modules/atmosphere/rendering/renderableatmosphere.cpp b/modules/atmosphere/rendering/renderableatmosphere.cpp index 9e1ceff815..d1733c1459 100644 --- a/modules/atmosphere/rendering/renderableatmosphere.cpp +++ b/modules/atmosphere/rendering/renderableatmosphere.cpp @@ -611,6 +611,57 @@ namespace openspace { } void RenderableAtmosphere::initialize() { + //RenderEngine& renderEngine = OsEng.renderEngine(); + + //if (_atmosphereEnabled) { + // _deferredcaster = std::make_unique(); + // if (_deferredcaster) { + // _deferredcaster->setAtmosphereRadius(_atmosphereRadius); + // _deferredcaster->setPlanetRadius(_atmospherePlanetRadius); + // _deferredcaster->setPlanetAverageGroundReflectance(_planetAverageGroundReflectance); + // _deferredcaster->setPlanetGroundRadianceEmittion(_planetGroundRadianceEmittion); + // _deferredcaster->setRayleighHeightScale(_rayleighHeightScale); + // _deferredcaster->enableOzone(_ozoneLayerEnabled); + // _deferredcaster->setOzoneHeightScale(_ozoneHeightScale); + // _deferredcaster->setMieHeightScale(_mieHeightScale); + // _deferredcaster->setMiePhaseConstant(_miePhaseConstant); + // _deferredcaster->setSunRadianceIntensity(_sunRadianceIntensity); + // _deferredcaster->setRayleighScatteringCoefficients(_rayleighScatteringCoeff); + // _deferredcaster->setOzoneExtinctionCoefficients(_ozoneExtinctionCoeff); + // _deferredcaster->setMieScatteringCoefficients(_mieScatteringCoeff); + // _deferredcaster->setMieExtinctionCoefficients(_mieExtinctionCoeff); + // // TODO: Fix the ellipsoid nature of the renderable globe (JCC) + // //_deferredcaster->setEllipsoidRadii(_ellipsoid.radii()); + // _deferredcaster->enableSunFollowing(_sunFollowingCameraEnabled); + + // _deferredcaster->setPrecalculationTextureScale(_preCalculatedTexturesScale); + // if (_saveCalculationsToTexture) + // _deferredcaster->enablePrecalculationTexturesSaving(); + + // if (_shadowEnabled) { + // _deferredcaster->setShadowConfigArray(_shadowConfArray); + // _deferredcaster->setHardShadows(_hardShadows); + // } + + // //_deferredcaster->initialize(); + // } + + // OsEng.renderEngine().deferredcasterManager().attachDeferredcaster(*_deferredcaster.get()); + //} + + return; + } + + void RenderableAtmosphere::deinitialize() { + if (_deferredcaster) { + OsEng.renderEngine().deferredcasterManager().detachDeferredcaster(*_deferredcaster.get()); + _deferredcaster = nullptr; + } + + return; + } + + void RenderableAtmosphere::initializeGL() { RenderEngine& renderEngine = OsEng.renderEngine(); if (_atmosphereEnabled) { @@ -652,13 +703,7 @@ namespace openspace { return; } - void RenderableAtmosphere::deinitialize() { - if (_deferredcaster) { - OsEng.renderEngine().deferredcasterManager().detachDeferredcaster(*_deferredcaster.get()); - _deferredcaster = nullptr; - } - - return; + void RenderableAtmosphere::deinitializeGL() { } bool RenderableAtmosphere::isReady() const { diff --git a/modules/atmosphere/rendering/renderableatmosphere.h b/modules/atmosphere/rendering/renderableatmosphere.h index 169fc7dbf4..0f4db2cedd 100644 --- a/modules/atmosphere/rendering/renderableatmosphere.h +++ b/modules/atmosphere/rendering/renderableatmosphere.h @@ -82,6 +82,8 @@ public: void initialize() override; void deinitialize() override; + void initializeGL() override; + void deinitializeGL() override; bool isReady() const override; void render(const RenderData& data, RendererTasks& rendererTask) override; diff --git a/modules/base/CMakeLists.txt b/modules/base/CMakeLists.txt index 5ac1aa21a3..5d49dc687f 100644 --- a/modules/base/CMakeLists.txt +++ b/modules/base/CMakeLists.txt @@ -39,6 +39,7 @@ set(HEADER_FILES ${CMAKE_CURRENT_SOURCE_DIR}/rendering/screenspaceimageonline.h ${CMAKE_CURRENT_SOURCE_DIR}/translation/luatranslation.h ${CMAKE_CURRENT_SOURCE_DIR}/translation/statictranslation.h + ${CMAKE_CURRENT_SOURCE_DIR}/rotation/fixedrotation.h ${CMAKE_CURRENT_SOURCE_DIR}/rotation/luarotation.h ${CMAKE_CURRENT_SOURCE_DIR}/rotation/staticrotation.h ${CMAKE_CURRENT_SOURCE_DIR}/scale/luascale.h @@ -61,6 +62,7 @@ set(SOURCE_FILES ${CMAKE_CURRENT_SOURCE_DIR}/rendering/screenspaceimageonline.cpp ${CMAKE_CURRENT_SOURCE_DIR}/translation/luatranslation.cpp ${CMAKE_CURRENT_SOURCE_DIR}/translation/statictranslation.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/rotation/fixedrotation.cpp ${CMAKE_CURRENT_SOURCE_DIR}/rotation/luarotation.cpp ${CMAKE_CURRENT_SOURCE_DIR}/rotation/staticrotation.cpp ${CMAKE_CURRENT_SOURCE_DIR}/scale/luascale.cpp diff --git a/modules/base/basemodule.cpp b/modules/base/basemodule.cpp index a389592e5a..c228629622 100644 --- a/modules/base/basemodule.cpp +++ b/modules/base/basemodule.cpp @@ -46,6 +46,7 @@ #include #include +#include #include #include @@ -94,6 +95,7 @@ void BaseModule::internalInitialize() { auto fRotation = FactoryManager::ref().factory(); ghoul_assert(fRotation, "Rotation factory was not created"); + fRotation->registerClass("FixedRotation"); fRotation->registerClass("LuaRotation"); fRotation->registerClass("StaticRotation"); @@ -118,6 +120,7 @@ std::vector BaseModule::documentations() const { ScreenSpaceFramebuffer::Documentation(), ScreenSpaceImageLocal::Documentation(), ScreenSpaceImageOnline::Documentation(), + FixedRotation::Documentation(), LuaRotation::Documentation(), StaticRotation::Documentation(), LuaScale::Documentation(), diff --git a/modules/base/rendering/multimodelgeometry.cpp b/modules/base/rendering/multimodelgeometry.cpp index 94638e5cd5..bb18d0663d 100644 --- a/modules/base/rendering/multimodelgeometry.cpp +++ b/modules/base/rendering/multimodelgeometry.cpp @@ -52,7 +52,7 @@ bool MultiModelGeometry::loadModel(const std::string& filename) { _vertices.push_back(vv); } - _indices.resize(indices.size()); + _indices.resize(indices.size()); std::copy(indices.begin(), indices.end(), _indices.begin()); return true; diff --git a/modules/base/rendering/multimodelgeometry.h b/modules/base/rendering/multimodelgeometry.h index d062cda355..a276bdc342 100644 --- a/modules/base/rendering/multimodelgeometry.h +++ b/modules/base/rendering/multimodelgeometry.h @@ -39,7 +39,7 @@ public: MultiModelGeometry(const ghoul::Dictionary& dictionary); private: - bool loadModel(const std::string& filename); + virtual bool loadModel(const std::string& filename) override; }; } // namespace openspace::modelgeometry diff --git a/modules/base/rendering/renderablemodel.cpp b/modules/base/rendering/renderablemodel.cpp index faf34d5477..1c5a5a5b8a 100644 --- a/modules/base/rendering/renderablemodel.cpp +++ b/modules/base/rendering/renderablemodel.cpp @@ -156,7 +156,7 @@ bool RenderableModel::isReady() const { return _programObject && _texture; } -void RenderableModel::initialize() { +void RenderableModel::initializeGL() { _programObject = OsEng.renderEngine().buildRenderProgram( "ModelProgram", "${MODULE_BASE}/shaders/model_vs.glsl", @@ -165,10 +165,10 @@ void RenderableModel::initialize() { loadTexture(); - _geometry->initialize(this); + _geometry->initialize(this); } -void RenderableModel::deinitialize() { +void RenderableModel::deinitializeGL() { if (_geometry) { _geometry->deinitialize(); _geometry = nullptr; diff --git a/modules/base/rendering/renderablemodel.h b/modules/base/rendering/renderablemodel.h index 86b8d1c35f..d7c92b77d0 100644 --- a/modules/base/rendering/renderablemodel.h +++ b/modules/base/rendering/renderablemodel.h @@ -35,7 +35,7 @@ #include namespace ghoul::opengl { - class ProgramObject; + class ProgramObject; class Texture; } // namespace ghoul::opengl @@ -51,8 +51,8 @@ class RenderableModel : public Renderable { public: RenderableModel(const ghoul::Dictionary& dictionary); - void initialize() override; - void deinitialize() override; + void initializeGL() override; + void deinitializeGL() override; bool isReady() const override; diff --git a/modules/base/rendering/renderableplane.cpp b/modules/base/rendering/renderableplane.cpp index 95e5629f7d..e28a923812 100644 --- a/modules/base/rendering/renderableplane.cpp +++ b/modules/base/rendering/renderableplane.cpp @@ -178,7 +178,7 @@ bool RenderablePlane::isReady() const { return _shader && _texture; } -void RenderablePlane::initialize() { +void RenderablePlane::initializeGL() { glGenVertexArrays(1, &_quad); // generate array glGenBuffers(1, &_vertexPositionBuffer); // generate buffer createPlane(); @@ -191,7 +191,7 @@ void RenderablePlane::initialize() { loadTexture(); } -void RenderablePlane::deinitialize() { +void RenderablePlane::deinitializeGL() { glDeleteVertexArrays(1, &_quad); _quad = 0; @@ -210,7 +210,7 @@ void RenderablePlane::deinitialize() { void RenderablePlane::render(const RenderData& data, RendererTasks&) { _shader->activate(); //if (_projectionListener){ - // //get parent node-texture and set with correct dimensions + // //get parent node-texture and set with correct dimensions // SceneGraphNode* textureNode = OsEng.renderEngine().scene()->sceneGraphNode( // _nodeName // )->parent(); @@ -345,7 +345,7 @@ void RenderablePlane::createPlane() { glEnableVertexAttribArray(1); glVertexAttribPointer( - 1, + 1, 2, GL_FLOAT, GL_FALSE, diff --git a/modules/base/rendering/renderableplane.h b/modules/base/rendering/renderableplane.h index a18659d6b1..81800f97c1 100644 --- a/modules/base/rendering/renderableplane.h +++ b/modules/base/rendering/renderableplane.h @@ -54,8 +54,8 @@ class RenderablePlane : public Renderable { public: RenderablePlane(const ghoul::Dictionary& dictionary); - void initialize() override; - void deinitialize() override; + void initializeGL() override; + void deinitializeGL() override; bool isReady() const override; diff --git a/modules/base/rendering/renderablesphere.cpp b/modules/base/rendering/renderablesphere.cpp index 1795e4dec8..7f2681159d 100644 --- a/modules/base/rendering/renderablesphere.cpp +++ b/modules/base/rendering/renderablesphere.cpp @@ -255,7 +255,7 @@ bool RenderableSphere::isReady() const { return _shader && _texture; } -void RenderableSphere::initialize() { +void RenderableSphere::initializeGL() { _sphere = std::make_unique( PowerScaledScalar::CreatePSS(_size), _segments ); @@ -269,7 +269,7 @@ void RenderableSphere::initialize() { loadTexture(); } -void RenderableSphere::deinitialize() { +void RenderableSphere::deinitializeGL() { _texture = nullptr; if (_shader) { diff --git a/modules/base/rendering/renderablesphere.h b/modules/base/rendering/renderablesphere.h index 75939cc3e6..3da5a5c6de 100644 --- a/modules/base/rendering/renderablesphere.h +++ b/modules/base/rendering/renderablesphere.h @@ -49,8 +49,8 @@ class RenderableSphere : public Renderable { public: RenderableSphere(const ghoul::Dictionary& dictionary); - void initialize() override; - void deinitialize() override; + void initializeGL() override; + void deinitializeGL() override; bool isReady() const override; diff --git a/modules/base/rendering/renderablesphericalgrid.cpp b/modules/base/rendering/renderablesphericalgrid.cpp index 1824fc6d8c..f9478e4f91 100644 --- a/modules/base/rendering/renderablesphericalgrid.cpp +++ b/modules/base/rendering/renderablesphericalgrid.cpp @@ -177,18 +177,7 @@ bool RenderableSphericalGrid::isReady() const { return ready; } -void RenderableSphericalGrid::deinitialize() { - glDeleteVertexArrays(1,&_vaoID); - _vaoID = 0; - - glDeleteBuffers(1,&_vBufferID); - _vBufferID = 0; - - glDeleteBuffers(1,&_iBufferID); - _iBufferID = 0; -} - -void RenderableSphericalGrid::initialize() { +void RenderableSphericalGrid::initializeGL() { _gridProgram = OsEng.renderEngine().buildRenderProgram( "GridProgram", "${MODULE_BASE}/shaders/grid_vs.glsl", @@ -206,6 +195,17 @@ void RenderableSphericalGrid::initialize() { glBindVertexArray(0); } +void RenderableSphericalGrid::deinitializeGL() { + glDeleteVertexArrays(1, &_vaoID); + _vaoID = 0; + + glDeleteBuffers(1, &_vBufferID); + _vBufferID = 0; + + glDeleteBuffers(1, &_iBufferID); + _iBufferID = 0; +} + void RenderableSphericalGrid::render(const RenderData& data, RendererTasks&){ _gridProgram->activate(); diff --git a/modules/base/rendering/renderablesphericalgrid.h b/modules/base/rendering/renderablesphericalgrid.h index 66a042c58a..9fff6708fd 100644 --- a/modules/base/rendering/renderablesphericalgrid.h +++ b/modules/base/rendering/renderablesphericalgrid.h @@ -48,8 +48,8 @@ public: RenderableSphericalGrid(const ghoul::Dictionary& dictionary); ~RenderableSphericalGrid(); - void initialize() override; - void deinitialize() override; + void initializeGL() override; + void deinitializeGL() override; bool isReady() const override; diff --git a/modules/base/rendering/renderabletrail.cpp b/modules/base/rendering/renderabletrail.cpp index ed07333be3..416f71b0c1 100644 --- a/modules/base/rendering/renderabletrail.cpp +++ b/modules/base/rendering/renderabletrail.cpp @@ -217,7 +217,7 @@ RenderableTrail::RenderableTrail(const ghoul::Dictionary& dictionary) addProperty(_renderingModes); } -void RenderableTrail::initialize() { +void RenderableTrail::initializeGL() { RenderEngine& renderEngine = OsEng.renderEngine(); _programObject = renderEngine.buildRenderProgram( "EphemerisProgram", @@ -228,7 +228,7 @@ void RenderableTrail::initialize() { setRenderBin(Renderable::RenderBin::Overlay); } -void RenderableTrail::deinitialize() { +void RenderableTrail::deinitializeGL() { RenderEngine& renderEngine = OsEng.renderEngine(); if (_programObject) { renderEngine.removeRenderProgram(_programObject); diff --git a/modules/base/rendering/renderabletrail.h b/modules/base/rendering/renderabletrail.h index 8dd51a5c78..447c083f40 100644 --- a/modules/base/rendering/renderabletrail.h +++ b/modules/base/rendering/renderabletrail.h @@ -60,7 +60,7 @@ class Translation; * * Trails can be rendered either as lines, as points, or a combination of both with * varying colors, line thicknesses, or fading settings. If trails are rendered as points, - * the RenderInformation's \c stride parameter determines the number of points between + * the RenderInformation's \c stride parameter determines the number of points between * larger points. A potential use case for this is showing the passage of time along a * trail by using a point separation of one hour and a subsampling of 4, you would get a * point every 15 minutes with every hourly point being bigger. @@ -73,8 +73,8 @@ class RenderableTrail : public Renderable { public: ~RenderableTrail() = default; - void initialize() override; - void deinitialize() override; + void initializeGL() override; + void deinitializeGL() override; bool isReady() const override; @@ -109,7 +109,7 @@ protected: std::unique_ptr _translation; /// The RenderInformation contains information filled in by the concrete subclasses to - /// be used by this class. + /// be used by this class. struct RenderInformation { enum class VertexSorting { NewestFirst = 0, ///< Newer vertices have a lower index than older ones @@ -117,13 +117,13 @@ protected: NoSorting ///< No ordering in the vertices; no fading applied }; /// The first element in the vertex buffer to be rendered - GLint first = 0; + GLint first = 0; /// The number of values to be rendered GLsizei count = 0; /// The stride between 'major' points in the array int stride = 1; /// Sorting of the vertices; required for correct fading - VertexSorting sorting = VertexSorting::NoSorting; + VertexSorting sorting = VertexSorting::NoSorting; /// Local model matrix transformation, used for rendering in camera space glm::dmat4 _localTransform = glm::dmat4(1.0); @@ -156,7 +156,7 @@ private: /// The option determining which rendering method to use properties::OptionProperty _renderingModes; - /// Program object used to render the data stored in RenderInformation + /// Program object used to render the data stored in RenderInformation std::unique_ptr _programObject; }; diff --git a/modules/base/rendering/renderabletrailorbit.cpp b/modules/base/rendering/renderabletrailorbit.cpp index 3818d7f965..3d6fcf0b1d 100644 --- a/modules/base/rendering/renderabletrailorbit.cpp +++ b/modules/base/rendering/renderabletrailorbit.cpp @@ -39,11 +39,11 @@ // --------------------------------------------------------------------------------- // | FF | | | | | | | | | | | | | | | | // --------------------------------------------------------------------------------- -// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 +// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 // <------ newer in time oldest // // In the begining the floating value starts at 0; this means that array element 0 is -// updated and uploaded to the GPU at every frame. The FF+1 element is the newest fixed +// updated and uploaded to the GPU at every frame. The FF+1 element is the newest fixed // location and FF-1 element is the oldest fixed location (including wrapping around the // array) with the times of _lastPointTime and _firstPointTime. // @@ -53,7 +53,7 @@ // --------------------------------------------------------------------------------- // | | | | | | | | | | | | | | | | FF | // --------------------------------------------------------------------------------- -// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 +// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 // <------ newer in time oldest // // Thus making the floating point traverse backwards through the array and element 0 being @@ -169,20 +169,20 @@ RenderableTrailOrbit::RenderableTrailOrbit(const ghoul::Dictionary& dictionary) _primaryRenderInformation.sorting = RenderInformation::VertexSorting::NewestFirst; } -void RenderableTrailOrbit::initialize() { - RenderableTrail::initialize(); +void RenderableTrailOrbit::initializeGL() { + RenderableTrail::initializeGL(); glGenVertexArrays(1, &_primaryRenderInformation._vaoID); glGenBuffers(1, &_primaryRenderInformation._vBufferID); glGenBuffers(1, &_primaryRenderInformation._iBufferID); } -void RenderableTrailOrbit::deinitialize() { +void RenderableTrailOrbit::deinitializeGL() { glDeleteVertexArrays(1, &_primaryRenderInformation._vaoID); glDeleteBuffers(1, &_primaryRenderInformation._vBufferID); glDeleteBuffers(1, &_primaryRenderInformation._iBufferID); - RenderableTrail::deinitialize(); + RenderableTrail::deinitializeGL(); } void RenderableTrailOrbit::update(const UpdateData& data) { @@ -257,7 +257,7 @@ void RenderableTrailOrbit::update(const UpdateData& data) { // Only update the changed ones // Since we are using a ring buffer, the number of updated needed might be // bigger than our current points, which means we have to split the upload - // into two calls. + // into two calls. if (report.nUpdated > 0) { // deltaT is positive, so the pointer is moving backwards and update has // to happen towards the front @@ -277,7 +277,7 @@ void RenderableTrailOrbit::update(const UpdateData& data) { // The current index is too close to the wrap around part, so we need // to split the upload into two parts: // 1. from the current index to the end of the array - // 2. the rest starting from the beginning of the array + // 2. the rest starting from the beginning of the array int first = s - i; int second = n - first; upload(i, first); // 1 diff --git a/modules/base/rendering/renderabletrailorbit.h b/modules/base/rendering/renderabletrailorbit.h index 1c74839b23..a76caf4edc 100644 --- a/modules/base/rendering/renderabletrailorbit.h +++ b/modules/base/rendering/renderabletrailorbit.h @@ -47,12 +47,12 @@ namespace documentation { struct Documentation; } class RenderableTrailOrbit : public RenderableTrail { public: explicit RenderableTrailOrbit(const ghoul::Dictionary& dictionary); - - void initialize() override; - void deinitialize() override; + + void initializeGL() override; + void deinitializeGL() override; void update(const UpdateData& data) override; - + static documentation::Documentation Documentation(); private: @@ -68,7 +68,7 @@ private: static const int All = 0; ///< The entire array was touched in the update /// If \c true at least one point was touched - bool needsUpdate; + bool needsUpdate; /// Returns the number of fixed points that were touched in the update method /// If this value is negative, the newest values were replaced, if positive the /// oldest diff --git a/modules/base/rendering/renderabletrailtrajectory.cpp b/modules/base/rendering/renderabletrailtrajectory.cpp index f8438ccf58..a3117122ff 100644 --- a/modules/base/rendering/renderabletrailtrajectory.cpp +++ b/modules/base/rendering/renderabletrailtrajectory.cpp @@ -187,8 +187,8 @@ RenderableTrailTrajectory::RenderableTrailTrajectory(const ghoul::Dictionary& di _primaryRenderInformation.sorting = RenderInformation::VertexSorting::OldestFirst; } -void RenderableTrailTrajectory::initialize() { - RenderableTrail::initialize(); +void RenderableTrailTrajectory::initializeGL() { + RenderableTrail::initializeGL(); // We don't need an index buffer, so we keep it at the default value of 0 glGenVertexArrays(1, &_primaryRenderInformation._vaoID); @@ -201,14 +201,14 @@ void RenderableTrailTrajectory::initialize() { _floatingRenderInformation.sorting = RenderInformation::VertexSorting::OldestFirst; } -void RenderableTrailTrajectory::deinitialize() { +void RenderableTrailTrajectory::deinitializeGL() { glDeleteVertexArrays(1, &_primaryRenderInformation._vaoID); glDeleteBuffers(1, &_primaryRenderInformation._vBufferID); glDeleteVertexArrays(1, &_floatingRenderInformation._vaoID); glDeleteBuffers(1, &_floatingRenderInformation._vBufferID); - RenderableTrail::deinitialize(); + RenderableTrail::deinitializeGL(); } void RenderableTrailTrajectory::update(const UpdateData& data) { diff --git a/modules/base/rendering/renderabletrailtrajectory.h b/modules/base/rendering/renderabletrailtrajectory.h index 5f68bdfe01..0f56d48221 100644 --- a/modules/base/rendering/renderabletrailtrajectory.h +++ b/modules/base/rendering/renderabletrailtrajectory.h @@ -53,8 +53,8 @@ class RenderableTrailTrajectory : public RenderableTrail { public: explicit RenderableTrailTrajectory(const ghoul::Dictionary& dictionary); - void initialize() override; - void deinitialize() override; + void initializeGL() override; + void deinitializeGL() override; void update(const UpdateData& data) override; diff --git a/modules/base/rendering/screenspaceframebuffer.cpp b/modules/base/rendering/screenspaceframebuffer.cpp index 25d11833ee..d6d9803957 100644 --- a/modules/base/rendering/screenspaceframebuffer.cpp +++ b/modules/base/rendering/screenspaceframebuffer.cpp @@ -54,7 +54,7 @@ documentation::Documentation ScreenSpaceFramebuffer::Documentation() { }; } -ScreenSpaceFramebuffer::ScreenSpaceFramebuffer(const ghoul::Dictionary& dictionary) +ScreenSpaceFramebuffer::ScreenSpaceFramebuffer(const ghoul::Dictionary& dictionary) : ScreenSpaceRenderable(dictionary) , _size(SizeInfo, glm::vec4(0), glm::vec4(0), glm::vec4(16384)) , _framebuffer(nullptr) @@ -75,15 +75,15 @@ ScreenSpaceFramebuffer::ScreenSpaceFramebuffer(const ghoul::Dictionary& dictiona ScreenSpaceFramebuffer::~ScreenSpaceFramebuffer() {} -bool ScreenSpaceFramebuffer::initialize() { - ScreenSpaceRenderable::initialize(); +bool ScreenSpaceFramebuffer::initializeGL() { + ScreenSpaceRenderable::initializeGL(); createFragmentbuffer(); return isReady(); } -bool ScreenSpaceFramebuffer::deinitialize() { - ScreenSpaceRenderable::deinitialize(); +bool ScreenSpaceFramebuffer::deinitializeGL() { + ScreenSpaceRenderable::deinitializeGL(); _framebuffer->detachAll(); removeAllRenderFunctions(); diff --git a/modules/base/rendering/screenspaceframebuffer.h b/modules/base/rendering/screenspaceframebuffer.h index 2b76d1ea09..a4cc947f51 100644 --- a/modules/base/rendering/screenspaceframebuffer.h +++ b/modules/base/rendering/screenspaceframebuffer.h @@ -36,17 +36,20 @@ namespace openspace { namespace documentation { struct Documentation; } /** - * @brief Creates a texture by rendering to a framebuffer, this is then used on a screen space plane. - * @details This class lets you ass renderfunctions that should render to a framebuffer with an attached texture. - * The texture is then used on a screen space plane that works both in fisheye and flat screens. + * @brief Creates a texture by rendering to a framebuffer, this is then used on a screen + * space plane. + * @details This class lets you ass renderfunctions that should render to a framebuffer + * with an attached texture. + * The texture is then used on a screen space plane that works both in fisheye and flat + * screens. */ class ScreenSpaceFramebuffer : public ScreenSpaceRenderable { public: ScreenSpaceFramebuffer(const ghoul::Dictionary& dictionary = ghoul::Dictionary()); ~ScreenSpaceFramebuffer(); - bool initialize() override; - bool deinitialize() override; + bool initializeGL() override; + bool deinitializeGL() override; void render() override; void update() override; bool isReady() const override; diff --git a/modules/base/rendering/wavefrontgeometry.cpp b/modules/base/rendering/wavefrontgeometry.cpp index bbf4f25ba8..853c1e1d00 100644 --- a/modules/base/rendering/wavefrontgeometry.cpp +++ b/modules/base/rendering/wavefrontgeometry.cpp @@ -35,7 +35,7 @@ namespace openspace { namespace modelgeometry { WavefrontGeometry::WavefrontGeometry(const ghoul::Dictionary& dictionary) - : ModelGeometry(dictionary) + : ModelGeometry(dictionary) { loadObj(_file); } diff --git a/modules/base/rotation/fixedrotation.cpp b/modules/base/rotation/fixedrotation.cpp new file mode 100644 index 0000000000..df05dbb397 --- /dev/null +++ b/modules/base/rotation/fixedrotation.cpp @@ -0,0 +1,734 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2017 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#include + +#include +#include +#include +#include + +#include + +namespace { + const char* KeyXAxis = "XAxis"; + const char* KeyYAxis = "YAxis"; + const char* KeyZAxis = "ZAxis"; + + static const openspace::properties::Property::PropertyInfo EnableInfo = { + "Enable", + "Enabled", + "If this value is 'true', all the machinery of this rotation is used, of it is " + "'false', it provides the ability to change its attributes without risking some " + "undefined behavior." + }; + + static const openspace::properties::Property::PropertyInfo TypeInfo = { + "Type", + "Specification Type", + "This value specifies how this axis is being specified, that is whether it is " + "referencing another object, specifying an absolute vector, or whether it is " + "using the right handed coordinate system completion based off the other two " + "vectors." + }; + + static const openspace::properties::Property::PropertyInfo ObjectInfo = { + "Object", + "Focus Object", + "This is the object that the axis will focus on. This object must name an " + "existing scene graph node in the currently loaded scene and the rotation will " + "stay fixed to the current position of that object." + }; + + static const openspace::properties::Property::PropertyInfo InvertObjectInfo = { + "InvertObject", + "Invert Object Point Direction", + "If this value is set to 'true', and the type is set to 'Object', the inverse of " + "the pointing direction is used, causing the object to point away from the " + "referenced object." + }; + + static const openspace::properties::Property::PropertyInfo VectorInfo = { + "Vector", + "Direction vector", + "This value specifies a static direction vector that is used for a fixed " + "rotation." + }; + + static const openspace::properties::Property::PropertyInfo OrthogonalVectorInfo = { + "Orthogonal", + "Vector is orthogonal", + "This value determines whether the vector specified is used directly, or whether " + "it is used together with another non-coordinate system completion vector to " + "construct an orthogonal vector instead." + }; + + static const openspace::properties::Property::PropertyInfo AttachedInfo = { + "Attached", + "Attached Node", + "This is the name of the node that this rotation is attached to, this value is " + "only needed if any of the three axis uses the Object type. In this case, the " + "location of the attached node is required to compute the relative direction." + }; +} // namespace + +namespace openspace { + +documentation::Documentation FixedRotation::Documentation() { + using namespace openspace::documentation; + return { + "Fixed Rotation", + "base_transform_rotation_fixed", + { + { + "Type", + new StringEqualVerifier("FixedRotation"), + Optional::No + }, + { + KeyXAxis, + new OrVerifier( + new StringVerifier, + new DoubleVector3Verifier + ), + Optional::Yes, + "This value specifies the direction of the new X axis. If this value is " + "not specified, it will be computed by completing a right handed " + "coordinate system from the Y and Z axis, which must be specified " + "instead." + }, + { + KeyXAxis + OrthogonalVectorInfo.identifier, + new BoolVerifier, + Optional::Yes, + OrthogonalVectorInfo.description + }, + { + KeyYAxis, + new OrVerifier( + new StringVerifier, + new DoubleVector3Verifier + ), + Optional::Yes, + "This value specifies the direction of the new Y axis. If this value is " + "not specified, it will be computed by completing a right handed " + "coordinate system from the X and Z axis, which must be specified " + "instead." + }, + { + KeyYAxis + OrthogonalVectorInfo.identifier, + new BoolVerifier, + Optional::Yes, + OrthogonalVectorInfo.description + }, + { + KeyZAxis, + new OrVerifier( + new StringVerifier, + new DoubleVector3Verifier + ), + Optional::Yes, + "This value specifies the direction of the new Z axis. If this value is " + "not specified, it will be computed by completing a right handed " + "coordinate system from the X and Y axis, which must be specified " + "instead." + }, + { + KeyZAxis + OrthogonalVectorInfo.identifier, + new BoolVerifier, + Optional::Yes, + OrthogonalVectorInfo.description + }, + { + AttachedInfo.identifier, + new StringVerifier, + Optional::Yes, + AttachedInfo.description + } + } + }; +} + +FixedRotation::FixedRotation(const ghoul::Dictionary& dictionary) + : _enabled(EnableInfo, true) + , _xAxis{ + properties::OptionProperty( + { + "xAxis-" + TypeInfo.identifier, + "xAxis:" + TypeInfo.guiName, + TypeInfo.description + }, + properties::OptionProperty::DisplayType::Dropdown + ), + properties::StringProperty( + { + "xAxis-" + ObjectInfo.identifier, + "xAxis:" + ObjectInfo.guiName, + ObjectInfo.description + }, + "" + ), + properties::BoolProperty( + { + "xAxis-" + InvertObjectInfo.identifier, + "xAxis:" + InvertObjectInfo.guiName, + InvertObjectInfo.description + }, + false + ), + properties::Vec3Property( + { + "xAxis-" + VectorInfo.identifier, + "xAxis:" + VectorInfo.guiName, + VectorInfo.description + }, + glm::vec3(1.f, 0.f, 0.f), + glm::vec3(0.f), + glm::vec3(1.f) + ), + properties::BoolProperty( + { + "xAxis-" + OrthogonalVectorInfo.identifier, + "xAxis:" + OrthogonalVectorInfo.guiName, + OrthogonalVectorInfo.description + }, + false + ), + nullptr + } + , _yAxis{ + properties::OptionProperty( + { + "yAxis-" + TypeInfo.identifier, + "yAxis:" + TypeInfo.guiName, + "yAxis:" + TypeInfo.description + }, + properties::OptionProperty::DisplayType::Dropdown + ), + properties::StringProperty( + { + "yAxis-" + ObjectInfo.identifier, + "yAxis:" + ObjectInfo.guiName, + "yAxis:" + ObjectInfo.description + }, + "" + ), + properties::BoolProperty( + { + "yAxis-" + InvertObjectInfo.identifier, + "yAxis:" + InvertObjectInfo.guiName, + InvertObjectInfo.description + }, + false + ), + properties::Vec3Property( + { + "yAxis-" + VectorInfo.identifier, + "yAxis:" + VectorInfo.guiName, + "yAxis:" + VectorInfo.description + }, + glm::vec3(0.f, 1.f, 0.f), + glm::vec3(0.f), + glm::vec3(1.f) + ), + properties::BoolProperty( + { + "yAxis-" + OrthogonalVectorInfo.identifier, + "yAxis:" + OrthogonalVectorInfo.guiName, + OrthogonalVectorInfo.description + }, + false + ), + nullptr + } + , _zAxis{ + properties::OptionProperty( + { + "zAxis-" + TypeInfo.identifier, + "zAxis:" + TypeInfo.guiName, + "zAxis:" + TypeInfo.description + }, + properties::OptionProperty::DisplayType::Dropdown + ), + properties::StringProperty( + { + "zAxis-" + ObjectInfo.identifier, + "zAxis:" + ObjectInfo.guiName, + "zAxis:" + ObjectInfo.description + }, + "" + ), + properties::BoolProperty( + { + "zAxis-" + InvertObjectInfo.identifier, + "zAxis:" + InvertObjectInfo.guiName, + InvertObjectInfo.description + }, + false + ), + properties::Vec3Property( + { + "zAxis-" + VectorInfo.identifier, + "zAxis:" + VectorInfo.guiName, + "zAxis:" + VectorInfo.description + }, + glm::vec3(0.f, 0.f, 1.f), + glm::vec3(0.f), + glm::vec3(1.f) + ), + properties::BoolProperty( + { + "zAxis-" + OrthogonalVectorInfo.identifier, + "zAxis:" + OrthogonalVectorInfo.guiName, + OrthogonalVectorInfo.description + }, + false + ), + nullptr + } + , _attachedObject(AttachedInfo, "") + , _attachedNode(nullptr) +{ + documentation::testSpecificationAndThrow( + Documentation(), + dictionary, + "FixedRotation" + ); + + _constructorDictionary = dictionary; + + setPropertyGroupName("global", "Global"); + setPropertyGroupName("xAxis", "X Axis"); + setPropertyGroupName("yAxis", "Y Axis"); + setPropertyGroupName("zAxis", "Z Axis"); + + + + _enabled.setGroupIdentifier("global"); + addProperty(_enabled); + + _attachedObject.setGroupIdentifier("global"); + addProperty(_attachedObject); + _attachedObject.onChange([this](){ + _attachedNode = sceneGraphNode(_attachedObject); + }); + + auto setPropertyVisibility = [this](Axis& axis) { + using Visibility = properties::Property::Visibility; + switch (axis.type) { + case Axis::Type::Object: + axis.object.setVisibility(Visibility::User); + axis.invertObject.setVisibility(Visibility::User); + axis.vector.setVisibility(Visibility::Hidden); + break; + case Axis::Type::Vector: + case Axis::Type::OrthogonalVector: + axis.object.setVisibility(Visibility::Hidden); + axis.invertObject.setVisibility(Visibility::Hidden); + axis.vector.setVisibility(Visibility::User); + break; + case Axis::Type::CoordinateSystemCompletion: + axis.object.setVisibility(Visibility::Hidden); + axis.invertObject.setVisibility(Visibility::Hidden); + axis.vector.setVisibility(Visibility::Hidden); + break; + } + }; + + + _xAxis.type.addOptions({ + { Axis::Type::Object, "Object" }, + { Axis::Type::Vector, "Vector" }, + { Axis::Type::OrthogonalVector, "Orthogonal Vector" }, + { Axis::Type::CoordinateSystemCompletion, "Coordinate System Completion" } + }); + _xAxis.type.setGroupIdentifier("xAxis"); + _xAxis.type.onChange([&]() { + setPropertyVisibility(_xAxis); + }); + addProperty(_xAxis.type); + + _xAxis.object.setGroupIdentifier("xAxis"); + addProperty(_xAxis.object); + _xAxis.object.onChange([this](){ + _xAxis.node = sceneGraphNode(_xAxis.object); + }); + + _xAxis.invertObject.setGroupIdentifier("xAxis"); + addProperty(_xAxis.invertObject); + + _xAxis.vector.setGroupIdentifier("xAxis"); + addProperty(_xAxis.vector); + + + _yAxis.type.addOptions({ + { Axis::Type::Object, "Object" }, + { Axis::Type::Vector, "Vector" }, + { Axis::Type::OrthogonalVector, "Orthogonal Vector" }, + { Axis::Type::CoordinateSystemCompletion, "Coordinate System Completion" } + }); + _yAxis.type.setGroupIdentifier("yAxis"); + _yAxis.type.onChange([&]() { + setPropertyVisibility(_yAxis); + }); + addProperty(_yAxis.type); + + _yAxis.object.setGroupIdentifier("yAxis"); + addProperty(_yAxis.object); + _yAxis.object.onChange([this](){ + _yAxis.node = sceneGraphNode(_yAxis.object); + }); + + _yAxis.invertObject.setGroupIdentifier("yAxis"); + addProperty(_yAxis.invertObject); + + _yAxis.vector.setGroupIdentifier("yAxis"); + addProperty(_yAxis.vector); + + + _zAxis.type.addOptions({ + { Axis::Type::Object, "Object" }, + { Axis::Type::Vector, "Vector" }, + { Axis::Type::OrthogonalVector, "Orthogonal Vector" }, + { Axis::Type::CoordinateSystemCompletion, "Coordinate System Completion" } + }); + _zAxis.type.setGroupIdentifier("zAxis"); + _zAxis.type.onChange([&]() { + setPropertyVisibility(_zAxis); + }); + addProperty(_zAxis.type); + + _zAxis.object.setGroupIdentifier("zAxis"); + addProperty(_zAxis.object); + _zAxis.object.onChange([this](){ + _zAxis.node = sceneGraphNode(_zAxis.object); + }); + + _zAxis.invertObject.setGroupIdentifier("zAxis"); + addProperty(_zAxis.invertObject); + + _zAxis.vector.setGroupIdentifier("zAxis"); + addProperty(_zAxis.vector); + + setPropertyVisibility(_xAxis); + setPropertyVisibility(_yAxis); + setPropertyVisibility(_zAxis); +} + +bool FixedRotation::initialize() { + // We need to do this in the initialize and not the constructor as the scene graph + // nodes referenced in the dictionary might not exist yet at construction time. At + // initialization time, however, we know that they already have been created + + bool res = Rotation::initialize(); + + if (_constructorDictionary.hasKey(AttachedInfo.identifier)) { + _attachedObject = _constructorDictionary.value( + AttachedInfo.identifier + ); + } + + bool hasXAxis = _constructorDictionary.hasKey(KeyXAxis); + if (hasXAxis) { + if (_constructorDictionary.hasKeyAndValue(KeyXAxis)) { + _xAxis.type = Axis::Type::Object; + _xAxis.object = _constructorDictionary.value(KeyXAxis); + } + else { + // We know it has to be a vector now + _xAxis.type = Axis::Type::Vector; + _xAxis.vector = _constructorDictionary.value(KeyXAxis); + } + } + + if (_constructorDictionary.hasKey(KeyXAxis + OrthogonalVectorInfo.identifier)) { + _xAxis.isOrthogonal = _constructorDictionary.value( + KeyXAxis + OrthogonalVectorInfo.identifier + ); + } + if (_xAxis.isOrthogonal) { + _xAxis.type = Axis::Type::OrthogonalVector; + } + + bool hasYAxis = _constructorDictionary.hasKey(KeyYAxis); + if (hasYAxis) { + if (_constructorDictionary.hasKeyAndValue(KeyYAxis)) { + _yAxis.type = Axis::Type::Object; + _yAxis.object = _constructorDictionary.value(KeyYAxis); + } + else { + // We know it has to be a vector now + _yAxis.type = Axis::Type::Vector; + _yAxis.vector = _constructorDictionary.value(KeyYAxis); + } + } + + if (_constructorDictionary.hasKey(KeyYAxis + OrthogonalVectorInfo.identifier)) { + _yAxis.isOrthogonal = _constructorDictionary.value( + KeyYAxis + OrthogonalVectorInfo.identifier + ); + } + if (_yAxis.isOrthogonal) { + _yAxis.type = Axis::Type::OrthogonalVector; + } + + bool hasZAxis = _constructorDictionary.hasKey(KeyZAxis); + if (hasZAxis) { + if (_constructorDictionary.hasKeyAndValue(KeyZAxis)) { + _zAxis.type = Axis::Type::Object; + _zAxis.object = _constructorDictionary.value(KeyZAxis); + } + else { + // We know it has to be a vector now + _zAxis.type = Axis::Type::Vector; + _zAxis.vector = _constructorDictionary.value(KeyZAxis); + } + } + + if (_constructorDictionary.hasKey(KeyZAxis + OrthogonalVectorInfo.identifier)) { + _zAxis.isOrthogonal = _constructorDictionary.value( + KeyZAxis + OrthogonalVectorInfo.identifier + ); + } + if (_zAxis.isOrthogonal) { + _zAxis.type = Axis::Type::OrthogonalVector; + } + + + + if (!hasXAxis && hasYAxis && hasZAxis) { + _xAxis.type = Axis::Type::CoordinateSystemCompletion; + } + + if (hasXAxis && !hasYAxis && hasZAxis) { + _yAxis.type = Axis::Type::CoordinateSystemCompletion; + } + + if (hasXAxis && hasYAxis && !hasZAxis) { + _zAxis.type = Axis::Type::CoordinateSystemCompletion; + } + + // No need to hold on to the data + _constructorDictionary = {}; + return res; +} + +void FixedRotation::update(const UpdateData&) { + if (!_enabled) { + _matrix = glm::dmat3(); + return; + } + + glm::vec3 x = xAxis(); + glm::vec3 y = yAxis(); + glm::vec3 z = zAxis(); + + static const float Epsilon = 1e-3; + + if (glm::dot(x, y) > 1.f - Epsilon || + glm::dot(y, z) > 1.f - Epsilon || + glm::dot(x, z) > 1.f - Epsilon) + { + LWARNINGC( + "FixedRotation", + "Dangerously collinear vectors detected: " << + "x: " << x << " y: " << y << " z: " << z + ); + _matrix = glm::dmat3(); + } + else { + _matrix = { + x.x, x.y, x.z, + y.x, y.y, y.z, + z.x, z.y, z.z + }; + } +} + +glm::vec3 FixedRotation::xAxis() const { + switch (_xAxis.type) { + case Axis::Type::Unspecified: + LWARNINGC("FixedRotation", "Unspecified axis type for X axis"); + return glm::vec3(1.f, 0.f, 0.f); + case Axis::Type::Object: + if (_xAxis.node && _attachedNode) { + glm::vec3 dir = glm::vec3(glm::normalize( + _xAxis.node->worldPosition() - + _attachedNode->worldPosition() + )); + return _xAxis.invertObject ? -dir : dir; + } + else { + if (_xAxis.node) { + LWARNINGC("FixedRotation", "Missing attachment node"); + return glm::vec3(1.f, 0.f, 0.f); + } + else { + LWARNINGC("FixedRotation", "Missing node for X axis"); + return glm::vec3(1.f, 0.f, 0.f); + } + } + case Axis::Type::Vector: + if (_xAxis.vector.value() == glm::vec3(0.f)) { + LWARNINGC("FixedRotation", "Zero vector detected for X Axis"); + return glm::vec3(1.f, 0.f, 0.f); + } + else { + return glm::normalize(_xAxis.vector.value()); + } + case Axis::Type::OrthogonalVector: + if (_xAxis.vector.value() == glm::vec3(0.f)) { + LWARNINGC("FixedRotation", "Zero vector detected for X Axis"); + return glm::vec3(1.f, 0.f, 0.f); + } + else { + if (_yAxis.type != Axis::Type::CoordinateSystemCompletion) { + return glm::normalize( + glm::cross(_xAxis.vector.value(), yAxis()) + ); + } + else { + return glm::normalize( + glm::cross(_xAxis.vector.value(), zAxis()) + ); + } + } + case Axis::Type::CoordinateSystemCompletion: + return glm::normalize(-glm::cross(yAxis(), zAxis())); + default: + throw ghoul::MissingCaseException(); + } +} + +glm::vec3 FixedRotation::yAxis() const { + switch (_yAxis.type) { + case Axis::Type::Unspecified: + LWARNINGC("FixedRotation", "Unspecified axis type for Y axis"); + return glm::vec3(0.f, 1.f, 0.f); + case Axis::Type::Object: + if (_yAxis.node && _attachedNode) { + glm::vec3 dir = glm::vec3(glm::normalize( + _yAxis.node->worldPosition() - + _attachedNode->worldPosition() + )); + return _yAxis.invertObject ? -dir : dir; + } + else { + if (_yAxis.node) { + LWARNINGC("FixedRotation", "Missing attachment node"); + return glm::vec3(0.f, 1.f, 0.f); + } + else { + LWARNINGC("FixedRotation", "Missing node for Y axis"); + return glm::vec3(0.f, 1.f, 0.f); + } + } + case Axis::Type::Vector: + if (_yAxis.vector.value() == glm::vec3(0.f)) { + LWARNINGC("FixedRotation", "Zero vector detected for Y Axis"); + return glm::vec3(0.f, 1.f, 0.f); + } + else { + return glm::normalize(_yAxis.vector.value()); + } + case Axis::Type::OrthogonalVector: + if (_yAxis.vector.value() == glm::vec3(0.f)) { + LWARNINGC("FixedRotation", "Zero vector detected for Y Axis"); + return glm::vec3(0.f, 1.f, 0.f); + } + else { + if (_zAxis.type != Axis::Type::CoordinateSystemCompletion) { + return glm::normalize( + glm::cross(_yAxis.vector.value(), zAxis()) + ); + } + else { + return glm::normalize( + glm::cross(_yAxis.vector.value(), xAxis()) + ); + } + } + case Axis::Type::CoordinateSystemCompletion: + return glm::normalize(glm::cross(xAxis(), -zAxis())); + default: + throw ghoul::MissingCaseException(); + } +} + +glm::vec3 FixedRotation::zAxis() const { + switch (_zAxis.type) { + case Axis::Type::Unspecified: + LWARNINGC("FixedRotation", "Unspecified axis type for Z axis"); + return glm::vec3(0.f, 0.f, 1.f); + case Axis::Type::Object: + if (_zAxis.node && _attachedNode) { + glm::vec3 dir = glm::vec3(glm::normalize( + _zAxis.node->worldPosition() - + _attachedNode->worldPosition() + )); + return _zAxis.invertObject ? -dir : dir; + } + else { + if (_zAxis.node) { + LWARNINGC("FixedRotation", "Missing attachment node"); + return glm::vec3(0.f, 0.f, 1.f); + } + else { + LWARNINGC("FixedRotation", "Missing node for Z axis"); + return glm::vec3(0.f, 0.f, 1.f); + } + } + case Axis::Type::Vector: + if (_zAxis.vector.value() == glm::vec3(0.f)) { + LWARNINGC("FixedRotation", "Zero vector detected for Z Axis"); + return glm::vec3(0.f, 0.f, 1.f); + } + else { + return glm::normalize(_zAxis.vector.value()); + } + case Axis::Type::OrthogonalVector: + if (_zAxis.vector.value() == glm::vec3(0.f)) { + LWARNINGC("FixedRotation", "Zero vector detected for Z Axis"); + return glm::vec3(0.f, 0.f, 1.f); + } + else { + if (_xAxis.type != Axis::Type::CoordinateSystemCompletion) { + return glm::normalize( + glm::cross(_zAxis.vector.value(), xAxis()) + ); + } + else { + return glm::normalize( + glm::cross(_zAxis.vector.value(), yAxis()) + ); + } + } + case Axis::Type::CoordinateSystemCompletion: + return glm::normalize(glm::cross(xAxis(), yAxis())); + default: + throw ghoul::MissingCaseException(); + } +} + +} // namespace openspace diff --git a/modules/base/rotation/fixedrotation.h b/modules/base/rotation/fixedrotation.h new file mode 100644 index 0000000000..94f6148c3a --- /dev/null +++ b/modules/base/rotation/fixedrotation.h @@ -0,0 +1,90 @@ +/***************************************************************************************** + * * + * OpenSpace * + * * + * Copyright (c) 2014-2017 * + * * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this * + * software and associated documentation files (the "Software"), to deal in the Software * + * without restriction, including without limitation the rights to use, copy, modify, * + * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * + * permit persons to whom the Software is furnished to do so, subject to the following * + * conditions: * + * * + * The above copyright notice and this permission notice shall be included in all copies * + * or substantial portions of the Software. * + * * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * + * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * + * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * + * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * + ****************************************************************************************/ + +#ifndef __OPENSPACE_MODULE_BASE___FIXEDROTATION___H__ +#define __OPENSPACE_MODULE_BASE___FIXEDROTATION___H__ + +#include + +#include +#include +#include +#include + +#include + +namespace openspace { + +class SceneGraphNode; + +namespace documentation { struct Documentation; } + +class FixedRotation : public Rotation { +public: + FixedRotation(const ghoul::Dictionary& dictionary); + + bool initialize() override; + + static documentation::Documentation Documentation(); + + void update(const UpdateData& data) override; + +private: + glm::vec3 xAxis() const; + glm::vec3 yAxis() const; + glm::vec3 zAxis() const; + + struct Axis { + enum Type { + Unspecified = 0, + Object, + Vector, + OrthogonalVector, + CoordinateSystemCompletion + }; + + properties::OptionProperty type; + properties::StringProperty object; + properties::BoolProperty invertObject; + properties::Vec3Property vector; + properties::BoolProperty isOrthogonal; + + SceneGraphNode* node; + }; + + properties::BoolProperty _enabled; + + Axis _xAxis; + Axis _yAxis; + Axis _zAxis; + + properties::StringProperty _attachedObject; + SceneGraphNode* _attachedNode; + + ghoul::Dictionary _constructorDictionary; +}; + +} // namespace openspace + +#endif // __OPENSPACE_MODULE_BASE___FIXEDROTATION___H__ diff --git a/modules/base/translation/luatranslation.cpp b/modules/base/translation/luatranslation.cpp index 139fa48cf8..7dd8353d9e 100644 --- a/modules/base/translation/luatranslation.cpp +++ b/modules/base/translation/luatranslation.cpp @@ -78,8 +78,8 @@ LuaTranslation::LuaTranslation() _luaScriptFile.onChange([&](){ _fileHandle = std::make_unique(_luaScriptFile); - _fileHandle->setCallback([&](const ghoul::filesystem::File&){ - notifyObservers(); + _fileHandle->setCallback([&](const ghoul::filesystem::File&) { + notifyObservers(); }); }); } diff --git a/modules/debugging/debuggingmodule.cpp b/modules/debugging/debuggingmodule.cpp index 4b009b91d4..ff873e22e0 100644 --- a/modules/debugging/debuggingmodule.cpp +++ b/modules/debugging/debuggingmodule.cpp @@ -43,7 +43,7 @@ void DebuggingModule::internalInitialize() { fRenderable->registerClass("RenderableDebugPlane"); } -std::vector DebuggingModule::documentations() const { +std::vector DebuggingModule::documentations() const { return { RenderableDebugPlane::Documentation() }; diff --git a/modules/debugging/rendering/debugrenderer.cpp b/modules/debugging/rendering/debugrenderer.cpp index c6f348857a..5f6ebcc8ac 100644 --- a/modules/debugging/rendering/debugrenderer.cpp +++ b/modules/debugging/rendering/debugrenderer.cpp @@ -44,15 +44,15 @@ DebugRenderer* DebugRenderer::_reference = nullptr; DebugRenderer::DebugRenderer() { _programObject = OsEng.renderEngine().buildRenderProgram( - "BasicDebugShader", + "BasicDebugShader", "${MODULE_DEBUGGING}/rendering/debugshader_vs.glsl", "${MODULE_DEBUGGING}/rendering/debugshader_fs.glsl" ); } DebugRenderer::DebugRenderer(std::unique_ptr programObject) - : _programObject(std::move(programObject)) -{ + : _programObject(std::move(programObject)) +{ // nothing to do } @@ -107,7 +107,14 @@ void DebugRenderer::renderVertices(const Vertices& clippingSpacePoints, GLenum m glEnableVertexAttribArray(0); - glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(clippingSpacePoints[0]), 0); + glVertexAttribPointer( + 0, + 4, + GL_FLOAT, + GL_FALSE, + sizeof(clippingSpacePoints[0]), + nullptr + ); // Draw the vertices glDrawArrays(mode, 0, static_cast(clippingSpacePoints.size())); diff --git a/modules/debugging/rendering/debugrenderer.h b/modules/debugging/rendering/debugrenderer.h index 1d86ecf8c0..da6b87af56 100644 --- a/modules/debugging/rendering/debugrenderer.h +++ b/modules/debugging/rendering/debugrenderer.h @@ -40,7 +40,7 @@ namespace openspace { /** - * A helper class for quick rendering of vertices IN clipping space. + * A helper class for quick rendering of vertices IN clipping space. * The class is practically stateless. It only stores a ghoul::opengl::ProgramObject * which can be reused despite the fact that rendering calls are invoked from different * callers. Therefore a static reference is provided for convenience which is accessed @@ -77,7 +77,7 @@ public: /** * Takes a vector of exactly 8 vertices, i.e. corner points in a box. * The box corners should be ordered from smaller to larger, - * first by x, the, y and finally z. + * first by x, the, y and finally z. * * 6-------7 * |\ |\ @@ -93,7 +93,7 @@ public: /** * Takes a vector of exactly 8 vertices, i.e. corner points in a box. * The box corners should be ordered from smaller to larger, - * first by x, the, y and finally z. + * first by x, the, y and finally z. * * 6-------7 * |\ |\ @@ -124,7 +124,7 @@ public: /** * Input arguments: - * 1. const RenderData& data: defines position and camera that we will see the + * 1. const RenderData& data: defines position and camera that we will see the * other cameras view frustum from * 2. const Camera& otherCamera: The camera who's view frustum is to be rendered * 3. RGBA rgba Color to draw the view frustum with @@ -143,7 +143,7 @@ public: #ifdef OPENSPACE_MODULE_GLOBEBROWSING_ENABLED /** - * Takes a AABB3 in screen space and returns vertices representing the corner points + * Takes a AABB3 in screen space and returns vertices representing the corner points * of the AABB. The ordering of the corner points is compatible with the box * rendering methods in this class. */ diff --git a/modules/debugging/rendering/renderabledebugplane.cpp b/modules/debugging/rendering/renderabledebugplane.cpp index dc381c172a..1e1847ae38 100644 --- a/modules/debugging/rendering/renderabledebugplane.cpp +++ b/modules/debugging/rendering/renderabledebugplane.cpp @@ -190,7 +190,7 @@ bool RenderableDebugPlane::isReady() const { return ready; } -void RenderableDebugPlane::initialize() { +void RenderableDebugPlane::initializeGL() { glGenVertexArrays(1, &_quad); // generate array glGenBuffers(1, &_vertexPositionBuffer); // generate buffer createPlane(); @@ -204,7 +204,7 @@ void RenderableDebugPlane::initialize() { } } -void RenderableDebugPlane::deinitialize() { +void RenderableDebugPlane::deinitializeGL() { glDeleteVertexArrays(1, &_quad); _quad = 0; diff --git a/modules/debugging/rendering/renderabledebugplane.h b/modules/debugging/rendering/renderabledebugplane.h index 91fa8914b2..62bbe4d2f0 100644 --- a/modules/debugging/rendering/renderabledebugplane.h +++ b/modules/debugging/rendering/renderabledebugplane.h @@ -49,8 +49,8 @@ public: RenderableDebugPlane(const ghoul::Dictionary& dictionary); ~RenderableDebugPlane(); - void initialize() override; - void deinitialize() override; + void initializeGL() override; + void deinitializeGL() override; bool isReady() const override; diff --git a/modules/digitaluniverse/digitaluniversemodule.cpp b/modules/digitaluniverse/digitaluniversemodule.cpp index 72fa1b0406..3d47edb9d9 100644 --- a/modules/digitaluniverse/digitaluniversemodule.cpp +++ b/modules/digitaluniverse/digitaluniversemodule.cpp @@ -40,7 +40,9 @@ namespace openspace { -DigitalUniverseModule::DigitalUniverseModule() : OpenSpaceModule(DigitalUniverseModule::Name) {} +DigitalUniverseModule::DigitalUniverseModule() + : OpenSpaceModule(DigitalUniverseModule::Name) +{} void DigitalUniverseModule::internalInitialize() { auto fRenderable = FactoryManager::ref().factory(); diff --git a/modules/digitaluniverse/rendering/renderablebillboardscloud.cpp b/modules/digitaluniverse/rendering/renderablebillboardscloud.cpp index e744e47ae0..fc73ba0e48 100644 --- a/modules/digitaluniverse/rendering/renderablebillboardscloud.cpp +++ b/modules/digitaluniverse/rendering/renderablebillboardscloud.cpp @@ -40,7 +40,7 @@ #include #include -#include +#include #include #include @@ -69,7 +69,7 @@ namespace { "Point Sprite Texture", "The path to the texture that should be used as the point sprite." }; - + static const openspace::properties::Property::PropertyInfo TransparencyInfo = { "Transparency", "Transparency", @@ -378,7 +378,7 @@ RenderableBillboardsCloud::RenderableBillboardsCloud(const ghoul::Dictionary& di _hasSpeckFile = _hasSpeckFile == true? false : true; }); addProperty(_drawElements); } - + // DEBUG: _renderOption.addOption(0, "Camera View Direction"); _renderOption.addOption(1, "Camera Position Normal"); @@ -441,7 +441,7 @@ RenderableBillboardsCloud::RenderableBillboardsCloud(const ghoul::Dictionary& di ghoul::Dictionary colorOptionDataDic = dictionary.value( ColorOptionInfo.identifier ); - for (int i = 0; i < static_cast(colorOptionDataDic.size()); ++i) { + for (int i = 0; i < colorOptionDataDic.size(); ++i) { std::string colorMapInUseName( colorOptionDataDic.value(std::to_string(i + 1))); _colorOption.addOption(i, colorMapInUseName); @@ -460,17 +460,17 @@ RenderableBillboardsCloud::RenderableBillboardsCloud(const ghoul::Dictionary& di ghoul::Dictionary rangeDataDic = dictionary.value( ColorRangeInfo.identifier ); - for (int i = 0; i < static_cast(rangeDataDic.size()); ++i) { + for (int i = 0; i < rangeDataDic.size(); ++i) { _colorRangeData.push_back( rangeDataDic.value(std::to_string(i+1))); } - + } } else if (dictionary.hasKey(keyColor)) { _pointColor = dictionary.value(keyColor); addProperty(_pointColor); - } + } if (dictionary.hasKey(TransparencyInfo.identifier)) { _alphaValue = static_cast( @@ -501,7 +501,7 @@ RenderableBillboardsCloud::RenderableBillboardsCloud(const ghoul::Dictionary& di _labelFile = absPath(dictionary.value( LabelFileInfo.identifier - )); + )); _hasLabel = true; if (dictionary.hasKey(TextColorInfo.identifier)) { @@ -520,7 +520,7 @@ RenderableBillboardsCloud::RenderableBillboardsCloud(const ghoul::Dictionary& di if (dictionary.hasKey(LabelMinSizeInfo.identifier)) { _textMinSize = static_cast(dictionary.value(LabelMinSizeInfo.identifier)); - } + } addProperty(_textMinSize); } @@ -547,13 +547,6 @@ bool RenderableBillboardsCloud::isReady() const { } void RenderableBillboardsCloud::initialize() { - RenderEngine& renderEngine = OsEng.renderEngine(); - - _program = renderEngine.buildRenderProgram("RenderableBillboardsCloud", - "${MODULE_DIGITALUNIVERSE}/shaders/billboard2_vs.glsl", - "${MODULE_DIGITALUNIVERSE}/shaders/billboard2_fs.glsl", - "${MODULE_DIGITALUNIVERSE}/shaders/billboard2_gs.glsl"); - bool success = loadData(); if (!success) { throw ghoul::RuntimeError("Error loading data"); @@ -562,8 +555,17 @@ void RenderableBillboardsCloud::initialize() { if (!_colorOptionString.empty()) { // Following DU behavior here. The last colormap variable // entry is the one selected by default. - _colorOption = static_cast(_colorRangeData.size() - 1); + _colorOption.setValue(_colorRangeData.size() - 1); } +} + +void RenderableBillboardsCloud::initializeGL() { + RenderEngine& renderEngine = OsEng.renderEngine(); + + _program = renderEngine.buildRenderProgram("RenderableBillboardsCloud", + "${MODULE_DIGITALUNIVERSE}/shaders/billboard2_vs.glsl", + "${MODULE_DIGITALUNIVERSE}/shaders/billboard2_fs.glsl", + "${MODULE_DIGITALUNIVERSE}/shaders/billboard2_gs.glsl"); if (_hasPolygon) { createPolygonTexture(); @@ -576,14 +578,12 @@ void RenderableBillboardsCloud::initialize() { if (_font == nullptr) { size_t _fontSize = 30; _font = OsEng.fontManager().font("Mono", static_cast(_fontSize), - ghoul::fontrendering::FontManager::Outline::Yes, - ghoul::fontrendering::FontManager::LoadGlyphs::No - ); + ghoul::fontrendering::FontManager::Outline::Yes, ghoul::fontrendering::FontManager::LoadGlyphs::No); } } } -void RenderableBillboardsCloud::deinitialize() { +void RenderableBillboardsCloud::deinitializeGL() { glDeleteBuffers(1, &_vbo); _vbo = 0; glDeleteVertexArrays(1, &_vao); @@ -652,7 +652,7 @@ void RenderableBillboardsCloud::renderBillboards(const RenderData& data, const g glm::dvec4 centerScreenWorld = glm::inverse(data.camera.combinedViewMatrix()) * glm::dvec4(0.0, 0.0, 0.0, 1.0); _program->setUniform("centerScreenInWorldPosition", centerScreenWorld); - + _program->setUniform("minBillboardSize", 1.f); // in pixels _program->setUniform("maxBillboardSize", _billboardMaxSize); // in pixels _program->setUniform("color", _pointColor); @@ -717,7 +717,7 @@ void RenderableBillboardsCloud::renderLabels(const RenderData& data, const glm:: RenderEngine& renderEngine = OsEng.renderEngine(); _fontRenderer->setFramebufferSize(renderEngine.renderingResolution()); - + float scale = 0.0; switch (_unit) { case Meter: @@ -828,12 +828,12 @@ void RenderableBillboardsCloud::render(const RenderData& data, RendererTasks&) { glm::mat4 viewMatrix = data.camera.viewMatrix(); glm::mat4 projectionMatrix = data.camera.projectionMatrix(); glm::dmat4 modelViewProjectionMatrix = glm::dmat4(projectionMatrix) * - modelViewMatrix; - - glm::vec3 lookup = data.camera.lookUpVectorWorldSpace(); + modelViewMatrix; glm::dmat4 worldToModelTransform = glm::inverse(modelMatrix); - glm::vec3 viewDirection = data.camera.viewDirectionWorldSpace(); + + //glm::vec3 lookup = data.camera.lookUpVectorWorldSpace(); + //glm::vec3 viewDirection = data.camera.viewDirectionWorldSpace(); //glm::vec3 right = glm::cross(viewDirection, lookup); //glm::vec3 up = glm::cross(right, viewDirection); //glm::vec3 orthoRight = glm::normalize(glm::vec3(worldToModelTransform * glm::vec4(right, 0.0))); @@ -880,13 +880,13 @@ void RenderableBillboardsCloud::update(const UpdateData&) { GL_STATIC_DRAW ); GLint positionAttrib = _program->attributeLocation("in_position"); - + if (_hasColorMapFile) { - + /*const size_t nAstronomicalObjects = _fullData.size() / _nValuesPerAstronomicalObject; const size_t nValues = _slicedData.size() / nAstronomicalObjects; GLsizei stride = static_cast(sizeof(float) * nValues);*/ - + glEnableVertexAttribArray(positionAttrib); glVertexAttribPointer( positionAttrib, @@ -908,7 +908,7 @@ void RenderableBillboardsCloud::update(const UpdateData&) { reinterpret_cast(sizeof(float)*4) ); } - else { + else { glEnableVertexAttribArray(positionAttrib); glVertexAttribPointer( positionAttrib, @@ -942,10 +942,11 @@ void RenderableBillboardsCloud::update(const UpdateData&) { [&](const ghoul::filesystem::File&) { _spriteTextureIsDirty = true; } ); } - _spriteTextureIsDirty = false; + _spriteTextureIsDirty = false; } if (_hasLabel && _labelDataIsDirty) { + _labelDataIsDirty = false; } } @@ -1025,7 +1026,7 @@ bool RenderableBillboardsCloud::loadData() { // } } - + return success; } @@ -1086,7 +1087,7 @@ bool RenderableBillboardsCloud::readSpeckFile() { _variableDataPositionMap.insert({ dummy, _nValuesPerAstronomicalObject }); _nValuesPerAstronomicalObject += 1; // We want the number, but the index is 0 based - } + } } _nValuesPerAstronomicalObject += 3; // X Y Z are not counted in the Speck file indices @@ -1109,7 +1110,7 @@ bool RenderableBillboardsCloud::readSpeckFile() { std::stringstream str(line); for (int i = 0; i < _nValuesPerAstronomicalObject; ++i) { - str >> values[i]; + str >> values[i]; } _fullData.insert(_fullData.end(), values.begin(), values.end()); @@ -1125,15 +1126,15 @@ bool RenderableBillboardsCloud::readColorMapFile() { LERROR("Failed to open Color Map file '" << _file << "'"); return false; } - - int numberOfColors = 0; + + std::size_t numberOfColors = 0; // The beginning of the speck file has a header that either contains comments // (signaled by a preceding '#') or information about the structure of the file // (signaled by the keywords 'datavar', 'texturevar', and 'texture') std::string line = ""; while (true) { - // std::streampos position = file.tellg(); + std::streampos position = file.tellg(); std::getline(file, line); if (line[0] == '#' || line.empty()) { @@ -1144,18 +1145,18 @@ bool RenderableBillboardsCloud::readColorMapFile() { std::locale loc; if (std::isdigit(line[0], loc)) { std::string::size_type sz; - numberOfColors = static_cast(std::stoi(line, &sz)); + numberOfColors = std::stoi(line, &sz); break; } else if (file.eof()) { return false; - } + } } - - for (int i = 0; i < numberOfColors; ++i) { + + for (auto i = 0; i < numberOfColors; ++i) { std::getline(file, line); std::stringstream str(line); - + glm::vec4 color; for (auto j = 0; j < 4; ++j) { str >> color[j]; @@ -1163,7 +1164,7 @@ bool RenderableBillboardsCloud::readColorMapFile() { _colorMapData.push_back(color); } - + return true; } @@ -1174,7 +1175,7 @@ bool RenderableBillboardsCloud::readLabelFile() { LERROR("Failed to open Label file '" << _file << "'"); return false; } - + // The beginning of the speck file has a header that either contains comments // (signaled by a preceding '#') or information about the structure of the file // (signaled by the keywords 'datavar', 'texturevar', and 'texture') @@ -1236,7 +1237,7 @@ bool RenderableBillboardsCloud::readLabelFile() { std::string dummy; str >> dummy; // text keyword - + std::string label; str >> label; dummy.clear(); @@ -1284,7 +1285,7 @@ bool RenderableBillboardsCloud::loadCachedFile(const std::string& file) { for (int i = 0; i < nItems; ++i) { int32_t keySize = 0; fileStream.read(reinterpret_cast(&keySize), sizeof(int32_t)); - std::string key; + std::string key; for (int c = 0; c < keySize; ++c) { char t[2]; t[1] = '\0'; @@ -1322,7 +1323,7 @@ bool RenderableBillboardsCloud::saveCachedFile(const std::string& file) const { int32_t nValuesPerAstronomicalObject = static_cast(_nValuesPerAstronomicalObject); fileStream.write(reinterpret_cast(&nValuesPerAstronomicalObject), sizeof(int32_t)); - + size_t nBytes = nValues * sizeof(_fullData[0]); fileStream.write(reinterpret_cast(&_fullData[0]), nBytes); @@ -1333,7 +1334,7 @@ bool RenderableBillboardsCloud::saveCachedFile(const std::string& file) const { for (auto pair : _variableDataPositionMap) { int32_t keySize = static_cast(pair.first.size()); fileStream.write(reinterpret_cast(&keySize), sizeof(int32_t)); - for (int c = 0; c < static_cast(pair.first.size()); ++c) { + for (int c = 0; c < pair.first.size(); ++c) { int32_t keyChar = static_cast(pair.first[c]); fileStream.write(reinterpret_cast(&keyChar), sizeof(int32_t)); } @@ -1350,7 +1351,7 @@ bool RenderableBillboardsCloud::saveCachedFile(const std::string& file) const { return false; } } - + void RenderableBillboardsCloud::createDataSlice() { _slicedData.clear(); if (_hasColorMapFile) { @@ -1368,38 +1369,34 @@ void RenderableBillboardsCloud::createDataSlice() { glm::vec2 currentColorRange = _colorRangeData[_colorOption.value()]; float colorMapBinSize = (currentColorRange.y - currentColorRange.x) / static_cast(_colorMapData.size()); float bin = colorMapBinSize; - for (int i = 0; i < static_cast(_colorMapData.size()); ++i) { + for (int i = 0; i < _colorMapData.size(); ++i) { colorBins.push_back(bin); bin += colorMapBinSize; } - } + } for (size_t i = 0; i < _fullData.size(); i += _nValuesPerAstronomicalObject) { glm::dvec4 transformedPos = _transformationMatrix * glm::dvec4(_fullData[i + 0], _fullData[i + 1], _fullData[i + 2], 1.0); glm::vec4 position(glm::vec3(transformedPos), static_cast(_unit)); - + if (_hasColorMapFile) { - for (int j = 0; j < 4; ++j) { + for (auto j = 0; j < 4; ++j) { _slicedData.push_back(position[j]); } // Finds from which bin to get the color. // Note: the first color in the colormap file // is the outliers color. - glm::vec4 itemColor; + glm::vec4 itemColor; float variableColor = _fullData[i + 3 + colorMapInUse]; - int c = static_cast(colorBins.size() - 1); - // Float vs int comparison? + int c = colorBins.size()-1; while (variableColor < colorBins[c]) { --c; if (c == 0) break; } - - int colorIndex = 0; - if (c != static_cast(colorBins.size() - 1)) { - colorIndex = c + 1; - } - + + int colorIndex = c == colorBins.size() - 1 ? 0 : c + 1; + for (auto j = 0; j < 4; ++j) { _slicedData.push_back(_colorMapData[colorIndex][j]); } @@ -1408,7 +1405,7 @@ void RenderableBillboardsCloud::createDataSlice() { for (auto j = 0; j < 4; ++j) { _slicedData.push_back(position[j]); } - } + } } } @@ -1430,7 +1427,7 @@ void RenderableBillboardsCloud::createPolygonTexture() { this), std::bind(&openspace::RenderableBillboardsCloud::renderPolygonGeometry, this, std::placeholders::_1), - _pTexture, 256, 256); + _pTexture, 256, 256); } void RenderableBillboardsCloud::renderToTexture( @@ -1438,7 +1435,7 @@ void RenderableBillboardsCloud::renderToTexture( std::function renderFunction, GLuint textureToRenderTo, GLuint textureWidth, GLuint textureHeight) { LDEBUG("Rendering to Texture"); - + // Saves initial Application's OpenGL State GLint defaultFBO; GLint viewport[4]; @@ -1452,12 +1449,12 @@ void RenderableBillboardsCloud::renderToTexture( glDrawBuffers(1, drawBuffers); glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, textureToRenderTo, 0); - + glViewport(0, 0, textureWidth, textureHeight); - + geometryLoadingFunction(); renderFunction(_polygonVao); - + // Restores Applications' OpenGL State glBindFramebuffer(GL_FRAMEBUFFER, defaultFBO); glViewport(viewport[0], viewport[1], viewport[2], viewport[3]); @@ -1469,7 +1466,7 @@ void RenderableBillboardsCloud::renderToTexture( if (_polygonVao) { glDeleteVertexArrays(1, &_polygonVao); } - glDeleteFramebuffers(1, &textureFBO); + glDeleteFramebuffers(1, &textureFBO); } void RenderableBillboardsCloud::loadPolygonGeometryForRendering() { diff --git a/modules/digitaluniverse/rendering/renderablebillboardscloud.h b/modules/digitaluniverse/rendering/renderablebillboardscloud.h index 48f1fdbc63..f735db860a 100644 --- a/modules/digitaluniverse/rendering/renderablebillboardscloud.h +++ b/modules/digitaluniverse/rendering/renderablebillboardscloud.h @@ -59,7 +59,8 @@ public: ~RenderableBillboardsCloud() = default; void initialize() override; - void deinitialize() override; + void initializeGL() override; + void deinitializeGL() override; bool isReady() const override; diff --git a/modules/digitaluniverse/rendering/renderabledumeshes.cpp b/modules/digitaluniverse/rendering/renderabledumeshes.cpp index 4d4c33b121..02f843a193 100644 --- a/modules/digitaluniverse/rendering/renderabledumeshes.cpp +++ b/modules/digitaluniverse/rendering/renderabledumeshes.cpp @@ -371,7 +371,7 @@ bool RenderableDUMeshes::isReady() const { return (_program != nullptr) && (!_renderingMeshesMap.empty() || (!_labelData.empty())); } -void RenderableDUMeshes::initialize() { +void RenderableDUMeshes::initializeGL() { RenderEngine& renderEngine = OsEng.renderEngine(); _program = renderEngine.buildRenderProgram("RenderableDUMeshes", "${MODULE_DIGITALUNIVERSE}/shaders/dumesh_vs.glsl", @@ -396,7 +396,7 @@ void RenderableDUMeshes::initialize() { } } -void RenderableDUMeshes::deinitialize() { +void RenderableDUMeshes::deinitializeGL() { for (const std::pair& pair : _renderingMeshesMap) { for (int i = 0; i < pair.second.numU; ++i) { glDeleteVertexArrays(1, &pair.second.vaoArray[i]); diff --git a/modules/digitaluniverse/rendering/renderabledumeshes.h b/modules/digitaluniverse/rendering/renderabledumeshes.h index 989d7dd0e7..c246e0f002 100644 --- a/modules/digitaluniverse/rendering/renderabledumeshes.h +++ b/modules/digitaluniverse/rendering/renderabledumeshes.h @@ -56,8 +56,8 @@ public: explicit RenderableDUMeshes(const ghoul::Dictionary& dictionary); ~RenderableDUMeshes() = default; - void initialize() override; - void deinitialize() override; + void initializeGL() override; + void deinitializeGL() override; bool isReady() const override; diff --git a/modules/digitaluniverse/rendering/renderableplanescloud.cpp b/modules/digitaluniverse/rendering/renderableplanescloud.cpp index 964963ffee..e39b520e26 100644 --- a/modules/digitaluniverse/rendering/renderableplanescloud.cpp +++ b/modules/digitaluniverse/rendering/renderableplanescloud.cpp @@ -40,7 +40,7 @@ #include #include -#include +#include #include #include @@ -317,7 +317,7 @@ RenderablePlanesCloud::RenderablePlanesCloud(const ghoul::Dictionary& dictionary _hasSpeckFile = _hasSpeckFile == true? false : true; }); addProperty(_drawElements); } - + // DEBUG: _renderOption.addOption(0, "Camera View Direction"); _renderOption.addOption(1, "Camera Position Normal"); @@ -374,11 +374,11 @@ RenderablePlanesCloud::RenderablePlanesCloud(const ghoul::Dictionary& dictionary _scaleFactor.onChange([&]() { _dataIsDirty = true; }); - + if (dictionary.hasKey(LabelFileInfo.identifier)) { _labelFile = absPath(dictionary.value( LabelFileInfo.identifier - )); + )); _hasLabel = true; if (dictionary.hasKey(TextColorInfo.identifier)) { @@ -397,7 +397,7 @@ RenderablePlanesCloud::RenderablePlanesCloud(const ghoul::Dictionary& dictionary if (dictionary.hasKey(LabelMinSizeInfo.identifier)) { _textMinSize = static_cast(dictionary.value(LabelMinSizeInfo.identifier)); - } + } } if (dictionary.hasKey(TransformationMatrixInfo.identifier)) { @@ -455,17 +455,19 @@ bool RenderablePlanesCloud::isReady() const { } void RenderablePlanesCloud::initialize() { - RenderEngine& renderEngine = OsEng.renderEngine(); - - _program = renderEngine.buildRenderProgram("RenderablePlanesCloud", - "${MODULE_DIGITALUNIVERSE}/shaders/plane2_vs.glsl", - "${MODULE_DIGITALUNIVERSE}/shaders/plane2_fs.glsl"); - bool success = loadData(); if (!success) { throw ghoul::RuntimeError("Error loading data"); } +} +void RenderablePlanesCloud::initializeGL() { + RenderEngine& renderEngine = OsEng.renderEngine(); + + _program = renderEngine.buildRenderProgram("RenderablePlanesCloud", + "${MODULE_DIGITALUNIVERSE}/shaders/plane2_vs.glsl", + "${MODULE_DIGITALUNIVERSE}/shaders/plane2_fs.glsl"); + createPlanes(); loadTextures(); @@ -490,14 +492,14 @@ void RenderablePlanesCloud::deleteDataGPU() { } } -void RenderablePlanesCloud::deinitialize() { +void RenderablePlanesCloud::deinitializeGL() { deleteDataGPU(); - + RenderEngine& renderEngine = OsEng.renderEngine(); if (_program) { renderEngine.removeRenderProgram(_program); _program = nullptr; - } + } } void RenderablePlanesCloud::renderPlanes(const RenderData&, @@ -536,7 +538,7 @@ void RenderablePlanesCloud::renderPlanes(const RenderData&, _program->setUniform("scaleFactor", _scaleFactor); _program->setUniform("fadeInValue", fadeInVariable); //_program->setUniform("minPlaneSize", 1.f); // in pixels - + //bool usingFramebufferRenderer = // OsEng.renderEngine().rendererImplementation() == RenderEngine::RendererImplementation::Framebuffer; @@ -552,7 +554,7 @@ void RenderablePlanesCloud::renderPlanes(const RenderData&, // //glDepthMask(false); // glBlendFunc(GL_SRC_ALPHA, GL_ONE); //} - + for (auto pair : _renderingPlanesMap) { ghoul::opengl::TextureUnit unit; unit.activate(); @@ -560,14 +562,14 @@ void RenderablePlanesCloud::renderPlanes(const RenderData&, _program->setUniform("galaxyTexture", unit); glBindVertexArray(pair.second.vao); - glDrawArrays(GL_TRIANGLES, 0, 6); - } - + glDrawArrays(GL_TRIANGLES, 0, 6); + } + //if (additiveBlending) { // glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // //glDepthMask(true); //} - + glBindVertexArray(0); using IgnoreError = ghoul::opengl::ProgramObject::IgnoreError; @@ -582,7 +584,7 @@ void RenderablePlanesCloud::renderPlanes(const RenderData&, if (!blendEnabled) { glDisable(GL_BLEND); - } + } } void RenderablePlanesCloud::renderLabels(const RenderData& data, const glm::dmat4& modelViewProjectionMatrix, @@ -590,7 +592,7 @@ void RenderablePlanesCloud::renderLabels(const RenderData& data, const glm::dmat RenderEngine& renderEngine = OsEng.renderEngine(); _fontRenderer->setFramebufferSize(renderEngine.renderingResolution()); - + float scale = 0.0; switch (_unit) { case Meter: @@ -637,7 +639,8 @@ void RenderablePlanesCloud::renderLabels(const RenderData& data, const glm::dmat _renderOption.value(), "%s", pair.second.c_str()); - } + } + } void RenderablePlanesCloud::render(const RenderData& data, RendererTasks&) { @@ -706,7 +709,7 @@ void RenderablePlanesCloud::render(const RenderData& data, RendererTasks&) { if (_hasSpeckFile) { renderPlanes(data, modelViewMatrix, projectionMatrix, fadeInVariable); } - + if (_hasLabel) { renderLabels(data, modelViewProjectionMatrix, orthoRight, orthoUp, fadeInVariable); } @@ -721,7 +724,7 @@ void RenderablePlanesCloud::update(const UpdateData&) { } bool RenderablePlanesCloud::loadData() { - bool success = false; + bool success = false; if (_hasSpeckFile) { std::string _file = _speckFile; // I disabled the cache as it didn't work on Mac --- abock @@ -755,7 +758,7 @@ bool RenderablePlanesCloud::loadData() { //success &= saveCachedFile(cachedFile); // } } - + std::string labelFile = _labelFile; if (!labelFile.empty()) { // I disabled the cache as it didn't work on Mac --- abock @@ -786,7 +789,7 @@ bool RenderablePlanesCloud::loadData() { // } } - + return success; } @@ -804,7 +807,7 @@ bool RenderablePlanesCloud::loadTextures() { it->second->uploadTexture(); it->second->setFilter(ghoul::opengl::Texture::FilterMode::Linear); } - } + } } else { return false; @@ -874,7 +877,7 @@ bool RenderablePlanesCloud::readSpeckFile() { } else { _nValuesPerAstronomicalObject += 1; // We want the number, but the index is 0 based - } + } } if (line.substr(0, 10) == "polyorivar") { @@ -899,9 +902,9 @@ bool RenderablePlanesCloud::readSpeckFile() { if (line.substr(0, 8) == "texture ") { std::stringstream str(line); - + int textureIndex = 0; - + std::string dummy; str >> dummy; // command str >> textureIndex; @@ -929,7 +932,7 @@ bool RenderablePlanesCloud::readSpeckFile() { if (line.empty()) { continue; } - + std::stringstream str(line); glm::vec3 u(0.0f), v(0.0f); @@ -980,7 +983,7 @@ bool RenderablePlanesCloud::readLabelFile() { LERROR("Failed to open Label file '" << _file << "'"); return false; } - + // The beginning of the speck file has a header that either contains comments // (signaled by a preceding '#') or information about the structure of the file // (signaled by the keywords 'datavar', 'texturevar', and 'texture') @@ -1017,7 +1020,7 @@ bool RenderablePlanesCloud::readLabelFile() { } } - + do { std::vector values(_nValuesPerAstronomicalObject); @@ -1042,7 +1045,7 @@ bool RenderablePlanesCloud::readLabelFile() { std::string dummy; str >> dummy; // text keyword - + std::string label; str >> label; dummy.clear(); @@ -1122,9 +1125,9 @@ void RenderablePlanesCloud::createPlanes() { LDEBUG("Creating planes"); int planeNumber = 0; - for (int p = 0; p < static_cast(_fullData.size()); p += _nValuesPerAstronomicalObject) { + for (int p = 0; p < _fullData.size(); p += _nValuesPerAstronomicalObject) { glm::vec4 transformedPos = glm::vec4(_transformationMatrix * - glm::dvec4(_fullData[p + 0], _fullData[p + 1], _fullData[p + 2], 1.0)); + glm::dvec4(_fullData[p + 0], _fullData[p + 1], _fullData[p + 2], 1.0)); // Plane vectors u and v glm::vec4 u = glm::vec4(_transformationMatrix * @@ -1155,21 +1158,21 @@ void RenderablePlanesCloud::createPlanes() { RenderingPlane plane; plane.planeIndex = _fullData[p + _textureVariableIndex]; - + // JCC: Ask Abbott about these points refeering to a non-existing texture. if (plane.planeIndex == 30) { //std::cout << "--- Creating planes - index: " << plane.planeIndex << std::endl; plane.planeIndex = 0; } - + glGenVertexArrays(1, &plane.vao); glGenBuffers(1, &plane.vbo); - + glm::vec4 vertex0 = transformedPos - u - v; // same as 3 glm::vec4 vertex1 = transformedPos + u + v; // same as 5 glm::vec4 vertex2 = transformedPos - u + v; glm::vec4 vertex4 = transformedPos + u - v; - + float scale = 0.0; switch (_unit) { case Meter: @@ -1225,7 +1228,7 @@ void RenderablePlanesCloud::createPlanes() { sizeof(GLfloat) * 6, nullptr ); - + // texture coords glEnableVertexAttribArray(1); glVertexAttribPointer( @@ -1235,7 +1238,7 @@ void RenderablePlanesCloud::createPlanes() { GL_FALSE, sizeof(GLfloat) * 6, reinterpret_cast(sizeof(GLfloat) * 4) - ); + ); _renderingPlanesMap.insert({planeNumber++, plane}); } @@ -1246,6 +1249,7 @@ void RenderablePlanesCloud::createPlanes() { } if (_hasLabel && _labelDataIsDirty) { + _labelDataIsDirty = false; } } diff --git a/modules/digitaluniverse/rendering/renderableplanescloud.h b/modules/digitaluniverse/rendering/renderableplanescloud.h index 3f273c01d1..aba5317dff 100644 --- a/modules/digitaluniverse/rendering/renderableplanescloud.h +++ b/modules/digitaluniverse/rendering/renderableplanescloud.h @@ -61,7 +61,8 @@ namespace openspace { ~RenderablePlanesCloud() = default; void initialize() override; - void deinitialize() override; + void initializeGL() override; + void deinitializeGL() override; bool isReady() const override; diff --git a/modules/digitaluniverse/rendering/renderablepoints.cpp b/modules/digitaluniverse/rendering/renderablepoints.cpp index d5147a7c0a..0724b35305 100644 --- a/modules/digitaluniverse/rendering/renderablepoints.cpp +++ b/modules/digitaluniverse/rendering/renderablepoints.cpp @@ -62,9 +62,9 @@ namespace { static const openspace::properties::Property::PropertyInfo SpriteTextureInfo = { "Texture", "Point Sprite Texture", - "The path to the texture that should be used as the point sprite." + "The path to the texture that should be used as the point sprite." }; - + static const openspace::properties::Property::PropertyInfo TransparencyInfo = { "Transparency", "Transparency", @@ -112,7 +112,7 @@ namespace openspace { "The path to the SPECK file that contains information about the astronomical " "object being rendered." }, - { + { keyColor, new Vector3Verifier, Optional::No, @@ -174,9 +174,9 @@ namespace openspace { dictionary, "RenderablePoints" ); - + _speckFile = absPath(dictionary.value(KeyFile)); - + if (dictionary.hasKey(keyUnit)) { std::string unit = dictionary.value(keyUnit); if (unit == MeterUnit) { @@ -184,7 +184,7 @@ namespace openspace { } else if (unit == KilometerUnit) { _unit = Kilometer; - } + } else if (unit == ParsecUnit) { _unit = Parsec; } @@ -254,6 +254,13 @@ namespace openspace { } void RenderablePoints::initialize() { + bool success = loadData(); + if (!success) { + throw ghoul::RuntimeError("Error loading data"); + } + } + + void RenderablePoints::initializeGL() { RenderEngine& renderEngine = OsEng.renderEngine(); if (_hasSpriteTexture) { _program = renderEngine.buildRenderProgram("RenderablePoints", @@ -266,14 +273,9 @@ namespace openspace { "${MODULE_DIGITALUNIVERSE}/shaders/points_fs.glsl");// , //"${MODULE_DIGITALUNIVERSE}/shaders/points_gs.glsl"); } - - bool success = loadData(); - if (!success) { - throw ghoul::RuntimeError("Error loading data"); - } } - void RenderablePoints::deinitialize() { + void RenderablePoints::deinitializeGL() { glDeleteBuffers(1, &_vbo); _vbo = 0; glDeleteVertexArrays(1, &_vao); @@ -295,17 +297,17 @@ namespace openspace { _program->activate(); glm::dmat4 modelMatrix = glm::dmat4(1.0); - + using IgnoreError = ghoul::opengl::ProgramObject::IgnoreError; _program->setIgnoreUniformLocationError(IgnoreError::Yes); - _program->setUniform("modelViewProjectionTransform", glm::dmat4(data.camera.projectionMatrix()) * + _program->setUniform("modelViewProjectionTransform", glm::dmat4(data.camera.projectionMatrix()) * data.camera.combinedViewMatrix() * modelMatrix); _program->setUniform("color", _pointColor); _program->setUniform("sides", 4); _program->setUniform("alphaValue", _alphaValue); _program->setUniform("scaleFactor", _scaleFactor); - + if (_hasSpriteTexture) { ghoul::opengl::TextureUnit spriteTextureUnit; spriteTextureUnit.activate(); @@ -319,12 +321,12 @@ namespace openspace { else { _program->setUniform("hasColorMap", false); } - + glEnable(GL_PROGRAM_POINT_SIZE); glBindVertexArray(_vao); const GLsizei nAstronomicalObjects = static_cast(_fullData.size() / _nValuesPerAstronomicalObject); glDrawArrays(GL_POINTS, 0, nAstronomicalObjects); - + glDisable(GL_PROGRAM_POINT_SIZE); glBindVertexArray(0); using IgnoreError = ghoul::opengl::ProgramObject::IgnoreError; @@ -334,7 +336,7 @@ namespace openspace { glDepthMask(true); } - void RenderablePoints::update(const UpdateData&) { + void RenderablePoints::update(const UpdateData&) { if (_dataIsDirty) { LDEBUG("Regenerating data"); @@ -362,10 +364,11 @@ namespace openspace { GLint positionAttrib = _program->attributeLocation("in_position"); if (_hasColorMapFile) { + const size_t nAstronomicalObjects = _fullData.size() / _nValuesPerAstronomicalObject; - // const size_t nValues = _slicedData.size() / nAstronomicalObjects; - // GLsizei stride = static_cast(sizeof(double) * nValues); - + const size_t nValues = _slicedData.size() / nAstronomicalObjects; + GLsizei stride = static_cast(sizeof(double) * nValues); + glEnableVertexAttribArray(positionAttrib); glVertexAttribLPointer( positionAttrib, @@ -385,7 +388,7 @@ namespace openspace { reinterpret_cast(sizeof(double)*4) ); } - else { + else { glEnableVertexAttribArray(positionAttrib); glVertexAttribLPointer( positionAttrib, @@ -418,7 +421,7 @@ namespace openspace { [&](const ghoul::filesystem::File&) { _spriteTextureIsDirty = true; } ); } - _spriteTextureIsDirty = false; + _spriteTextureIsDirty = false; } } @@ -483,7 +486,7 @@ namespace openspace { while (true) { std::streampos position = file.tellg(); std::getline(file, line); - + if (line[0] == '#' || line.empty()) { continue; } @@ -538,15 +541,15 @@ namespace openspace { LERROR("Failed to open Color Map file '" << _file << "'"); return false; } - - int numberOfColors = 0; + + std::size_t numberOfColors = 0; // The beginning of the speck file has a header that either contains comments // (signaled by a preceding '#') or information about the structure of the file // (signaled by the keywords 'datavar', 'texturevar', and 'texture') std::string line = ""; while (true) { - // std::streampos position = file.tellg(); + std::streampos position = file.tellg(); std::getline(file, line); if (line[0] == '#' || line.empty()) { @@ -557,18 +560,18 @@ namespace openspace { std::locale loc; if (std::isdigit(line[0], loc)) { std::string::size_type sz; - numberOfColors = static_cast(std::stoi(line, &sz)); + numberOfColors = std::stoi(line, &sz); break; } else if (file.eof()) { return false; - } + } } - - for (int i = 0; i < numberOfColors; ++i) { + + for (auto i = 0; i < numberOfColors; ++i) { std::getline(file, line); std::stringstream str(line); - + glm::vec4 color; for (auto j = 0; j < 4; ++j) { str >> color[j]; @@ -576,7 +579,7 @@ namespace openspace { _colorMapData.push_back(color); } - + return true; } @@ -636,7 +639,7 @@ namespace openspace { return false; } } - + void RenderablePoints::createDataSlice() { _slicedData.clear(); if (_hasColorMapFile) { @@ -653,7 +656,7 @@ namespace openspace { // Converting untis if (_unit == Kilometer) { p *= 1E3; - } + } else if (_unit == Parsec) { p *= PARSEC; } @@ -673,24 +676,22 @@ namespace openspace { glm::dvec4 position(p, 1.0); if (_hasColorMapFile) { - for (int j = 0; j < 4; ++j) { + for (auto j = 0; j < 4; ++j) { _slicedData.push_back(position[j]); } - for (int j = 0; j < 4; ++j) { + for (auto j = 0; j < 4; ++j) { _slicedData.push_back(_colorMapData[colorIndex][j]); } } else { - for (int j = 0; j < 4; ++j) { + for (auto j = 0; j < 4; ++j) { _slicedData.push_back(position[j]); } } - - colorIndex = - (colorIndex == (static_cast(_colorMapData.size()) - 1)) ? - 0 : - colorIndex + 1; + + colorIndex = (colorIndex == (_colorMapData.size() - 1)) ? 0 : colorIndex + 1; } } + } // namespace openspace diff --git a/modules/digitaluniverse/rendering/renderablepoints.h b/modules/digitaluniverse/rendering/renderablepoints.h index 51cb4b819e..5d5cb88159 100644 --- a/modules/digitaluniverse/rendering/renderablepoints.h +++ b/modules/digitaluniverse/rendering/renderablepoints.h @@ -35,8 +35,8 @@ #include -namespace ghoul::filesystem { - class File; +namespace ghoul::filesystem { + class File; } namespace ghoul::opengl { @@ -54,7 +54,8 @@ namespace openspace { ~RenderablePoints() = default; void initialize() override; - void deinitialize() override; + void initializeGL() override; + void deinitializeGL() override; bool isReady() const override; diff --git a/modules/fieldlines/rendering/renderablefieldlines.cpp b/modules/fieldlines/rendering/renderablefieldlines.cpp index 7253e7ff86..c038b13891 100644 --- a/modules/fieldlines/rendering/renderablefieldlines.cpp +++ b/modules/fieldlines/rendering/renderablefieldlines.cpp @@ -104,7 +104,7 @@ namespace { namespace openspace { -RenderableFieldlines::RenderableFieldlines(const ghoul::Dictionary& dictionary) +RenderableFieldlines::RenderableFieldlines(const ghoul::Dictionary& dictionary) : Renderable(dictionary) , _stepSize(StepSizeInfo, defaultFieldlineStepSize, 0.f, 10.f) , _classification(Classification, true) @@ -235,7 +235,7 @@ bool RenderableFieldlines::isReady() const { return programReady && vectorFieldReady && fieldlineReady && seedPointsReady; } -void RenderableFieldlines::initialize() { +void RenderableFieldlines::initializeGL() { if (_vectorFieldInfo.empty() || _fieldlineInfo.empty() || _seedPointsInfo.empty()) { throw ghoul::RuntimeError("Error initializing"); } @@ -248,7 +248,7 @@ void RenderableFieldlines::initialize() { ); } -void RenderableFieldlines::deinitialize() { +void RenderableFieldlines::deinitializeGL() { glDeleteVertexArrays(1, &_fieldlineVAO); _fieldlineVAO = 0; glDeleteBuffers(1, &_vertexPositionBuffer); @@ -265,7 +265,10 @@ void RenderableFieldlines::render(const RenderData& data, RendererTasks&) { _program->activate(); _program->setUniform("modelViewProjection", data.camera.viewProjectionMatrix()); _program->setUniform("modelTransform", glm::mat4(1.0)); - _program->setUniform("cameraViewDir", glm::vec3(data.camera.viewDirectionWorldSpace())); + _program->setUniform( + "cameraViewDir", + glm::vec3(data.camera.viewDirectionWorldSpace()) + ); glDisable(GL_CULL_FACE); setPscUniforms(*_program, data.camera, data.position); @@ -310,7 +313,11 @@ void RenderableFieldlines::update(const UpdateData&) { _lineStart.push_back(prevEnd); _lineCount.push_back(static_cast(fieldlines[j].size())); prevEnd = prevEnd + static_cast(fieldlines[j].size()); - vertexData.insert(vertexData.end(), fieldlines[j].begin(), fieldlines[j].end()); + vertexData.insert( + vertexData.end(), + fieldlines[j].begin(), + fieldlines[j].end() + ); } LDEBUG("Number of vertices : " << vertexData.size()); @@ -324,15 +331,34 @@ void RenderableFieldlines::update(const UpdateData&) { } glBindBuffer(GL_ARRAY_BUFFER, _vertexPositionBuffer); - glBufferData(GL_ARRAY_BUFFER, vertexData.size()*sizeof(LinePoint), &vertexData.front(), GL_STATIC_DRAW); + glBufferData( + GL_ARRAY_BUFFER, + vertexData.size() * sizeof(LinePoint), + &vertexData.front(), + GL_STATIC_DRAW + ); GLuint vertexLocation = 0; glEnableVertexAttribArray(vertexLocation); - glVertexAttribPointer(vertexLocation, 3, GL_FLOAT, GL_FALSE, sizeof(LinePoint), reinterpret_cast(0)); + glVertexAttribPointer( + vertexLocation, + 3, + GL_FLOAT, + GL_FALSE, + sizeof(LinePoint), + reinterpret_cast(0) + ); GLuint colorLocation = 1; glEnableVertexAttribArray(colorLocation); - glVertexAttribPointer(colorLocation, 4, GL_FLOAT, GL_FALSE, sizeof(LinePoint), (void*)(sizeof(glm::vec3))); + glVertexAttribPointer( + colorLocation, + 4, + GL_FLOAT, + GL_FALSE, + sizeof(LinePoint), + (void*)(sizeof(glm::vec3)) + ); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); @@ -360,7 +386,9 @@ void RenderableFieldlines::loadSeedPointsFromFile() { std::ifstream seedFile(_seedPointSourceFile); if (!seedFile.good()) - LERROR("Could not open seed points file '" << _seedPointSourceFile.value() << "'"); + LERROR( + "Could not open seed points file '" << _seedPointSourceFile.value() << "'" + ); else { std::string line; glm::vec3 point; @@ -427,7 +455,7 @@ RenderableFieldlines::generateFieldlinesVolumeKameleon() if (model != vectorFieldKameleonModelBATSRUS) { //modelType = KameleonWrapper::Model::BATSRUS; //else { - LERROR(keyVectorField << "." << keyVectorFieldVolumeModel << " model '" << + LERROR(keyVectorField << "." << keyVectorFieldVolumeModel << " model '" << model << "' not supported"); return {}; } @@ -457,7 +485,13 @@ RenderableFieldlines::generateFieldlinesVolumeKameleon() _vectorFieldInfo.getValue(v3, zVariable); KameleonWrapper kw(fileName); - return kw.getClassifiedFieldLines(xVariable, yVariable, zVariable, _seedPoints, _stepSize); + return kw.getClassifiedFieldLines( + xVariable, + yVariable, + zVariable, + _seedPoints, + _stepSize + ); } if (lorentzForce) { diff --git a/modules/fieldlines/rendering/renderablefieldlines.h b/modules/fieldlines/rendering/renderablefieldlines.h index 1fc72680e4..5dc5dacbda 100644 --- a/modules/fieldlines/rendering/renderablefieldlines.h +++ b/modules/fieldlines/rendering/renderablefieldlines.h @@ -45,8 +45,8 @@ class RenderableFieldlines : public Renderable { public: RenderableFieldlines(const ghoul::Dictionary& dictionary); - void initialize() override; - void deinitialize() override; + void initializeGL() override; + void deinitializeGL() override; bool isReady() const override; @@ -57,7 +57,6 @@ private: typedef std::vector Line; void initializeDefaultPropertyValues(); - //std::vector > getFieldlinesData(std::string filename, ghoul::Dictionary hintsDictionary); std::vector getFieldlinesData(); void loadSeedPoints(); void loadSeedPointsFromFile(); diff --git a/modules/fieldlinessequence/fieldlinessequencemodule.cpp b/modules/fieldlinessequence/fieldlinessequencemodule.cpp index 040625f1f9..fa9109c060 100644 --- a/modules/fieldlinessequence/fieldlinessequencemodule.cpp +++ b/modules/fieldlinessequence/fieldlinessequencemodule.cpp @@ -38,10 +38,10 @@ FieldlinesSequenceModule::FieldlinesSequenceModule() : OpenSpaceModule("FieldlinesSequence") {} void FieldlinesSequenceModule::internalInitialize() { - auto fRenderable = FactoryManager::ref().factory(); - ghoul_assert(fRenderable, "No renderable factory existed"); + auto factory = FactoryManager::ref().factory(); + ghoul_assert(factory, "No renderable factory existed"); - fRenderable->registerClass("RenderableFieldlinesSequence"); + factory->registerClass("RenderableFieldlinesSequence"); } } // namespace openspace diff --git a/modules/fieldlinessequence/rendering/renderablefieldlinessequence.cpp b/modules/fieldlinessequence/rendering/renderablefieldlinessequence.cpp index ac0ec033a7..65914800e0 100644 --- a/modules/fieldlinessequence/rendering/renderablefieldlinessequence.cpp +++ b/modules/fieldlinessequence/rendering/renderablefieldlinessequence.cpp @@ -25,6 +25,7 @@ #include #include +#include #include #include @@ -77,9 +78,9 @@ void RenderableFieldlinesSequence::render(const RenderData& data, RendererTasks& // Calculate Model View MatrixProjection const glm::dmat4 rotMat = glm::dmat4(data.modelTransform.rotation); const glm::dmat4 modelMat = - glm::translate(glm::dmat4(1.0), data.modelTransform.translation) * - rotMat * - glm::dmat4(glm::scale(glm::dmat4(1), glm::dvec3(data.modelTransform.scale))); + glm::translate(glm::dmat4(1.0), data.modelTransform.translation) * + rotMat * + glm::dmat4(glm::scale(glm::dmat4(1), glm::dvec3(data.modelTransform.scale))); const glm::dmat4 modelViewMat = data.camera.combinedViewMatrix() * modelMat; _shaderProgram->setUniform("modelViewProjection", @@ -114,7 +115,10 @@ void RenderableFieldlinesSequence::render(const RenderData& data, RendererTasks& _shaderProgram->setUniform("particleSize", _pFlowParticleSize); _shaderProgram->setUniform("particleSpacing", _pFlowParticleSpacing); _shaderProgram->setUniform("particleSpeed", _pFlowSpeed); - _shaderProgram->setUniform("time", OsEng.runTime() * (_pFlowReversed ? -1 : 1)); + _shaderProgram->setUniform( + "time", + OsEng.windowWrapper().applicationTime() * (_pFlowReversed ? -1 : 1) + ); bool additiveBlending = false; if (_pColorABlendEnabled) { @@ -228,12 +232,15 @@ void RenderableFieldlinesSequence::update(const UpdateData& data) { } } -inline bool RenderableFieldlinesSequence::isWithinSequenceInterval(const double currentTime) const { +inline bool RenderableFieldlinesSequence::isWithinSequenceInterval( + const double currentTime) const +{ return (currentTime >= _startTimes[0]) && (currentTime < _sequenceEndTime); } // Assumes we already know that currentTime is within the sequence interval -void RenderableFieldlinesSequence::updateActiveTriggerTimeIndex(const double currentTime) { +void RenderableFieldlinesSequence::updateActiveTriggerTimeIndex(const double currentTime) +{ auto iter = std::upper_bound(_startTimes.begin(), _startTimes.end(), currentTime); if (iter != _startTimes.end()) { if ( iter != _startTimes.begin()) { diff --git a/modules/fieldlinessequence/rendering/renderablefieldlinessequence.h b/modules/fieldlinessequence/rendering/renderablefieldlinessequence.h index 54f666b660..3c13d6d588 100644 --- a/modules/fieldlinessequence/rendering/renderablefieldlinessequence.h +++ b/modules/fieldlinessequence/rendering/renderablefieldlinessequence.h @@ -58,7 +58,8 @@ public: void update(const UpdateData& data) override; private: // ------------------------------------- ENUMS -------------------------------------// - enum ColorMethod : int { // Used to determine if lines should be colored UNIFORMLY or by an extraQuantity + // Used to determine if lines should be colored UNIFORMLY or by an extraQuantity + enum ColorMethod : int { Uniform = 0, ByQuantity }; @@ -67,73 +68,139 @@ private: std::string _name; // Name of the Node! // ------------------------------------- FLAGS -------------------------------------// - std::atomic _isLoadingStateFromDisk { false}; // Used for 'runtime-states'. True when loading a new state from disk on another thread. - bool _isReady = false; // If initialization proved successful - bool _loadingStatesDynamically = false; // False => states are stored in RAM (using 'in-RAM-states'), True => states are loaded from disk during runtime (using 'runtime-states') - bool _mustLoadNewStateFromDisk = false; // Used for 'runtime-states': True if new 'runtime-state' must be loaded from disk. False => the previous frame's state should still be shown - bool _needsUpdate = false; // Used for 'in-RAM-states' : True if new 'in-RAM-state' must be loaded. False => the previous frame's state should still be shown - std::atomic _newStateIsReady { false}; // Used for 'runtime-states'. True when finished loading a new state from disk on another thread. - bool _shouldUpdateColorBuffer = false; // True when new state is loaded or user change which quantity to color the lines by - bool _shouldUpdateMaskingBuffer = false; // True when new state is loaded or user change which quantity used for masking out line segments + // Used for 'runtime-states'. True when loading a new state from disk on another + // thread. + std::atomic _isLoadingStateFromDisk { false}; + // If initialization proved successful + bool _isReady = false; + // False => states are stored in RAM (using 'in-RAM-states'), True => states are + // loaded from disk during runtime (using 'runtime-states') + bool _loadingStatesDynamically = false; + // Used for 'runtime-states': True if new 'runtime-state' must be loaded from disk. + // False => the previous frame's state should still be shown + bool _mustLoadNewStateFromDisk = false; + // Used for 'in-RAM-states' : True if new 'in-RAM-state' must be loaded. + // False => the previous frame's state should still be shown + bool _needsUpdate = false; + // Used for 'runtime-states'. True when finished loading a new state from disk on + // another thread. + std::atomic _newStateIsReady = false; + // True when new state is loaded or user change which quantity to color the lines by + bool _shouldUpdateColorBuffer = false; + // True when new state is loaded or user change which quantity used for masking out + // line segments + bool _shouldUpdateMaskingBuffer = false; // --------------------------------- NUMERICALS ----------------------------------- // - int _activeStateIndex = -1; // Active index of _states. If(==-1)=>no state available for current time. Always the same as _activeTriggerTimeIndex if(_loadingStatesDynamically==true), else always = 0 - int _activeTriggerTimeIndex = -1; // Active index of _startTimes - size_t _nStates = 0; // Number of states in the sequence - float _scalingFactor = 1.f; // In setup it is used to scale JSON coordinates. During runtime it is used to scale domain limits. - double _sequenceEndTime; // Estimated end of sequence. - GLuint _vertexArrayObject = 0; // OpenGL Vertex Array Object - GLuint _vertexColorBuffer = 0; // OpenGL Vertex Buffer Object containing the extraQuantity values used for coloring the lines - GLuint _vertexMaskingBuffer = 0; // OpenGL Vertex Buffer Object containing the extraQuantity values used for masking out segments of the lines - GLuint _vertexPositionBuffer = 0; // OpenGL Vertex Buffer Object containing the vertex positions + // Active index of _states. If(==-1)=>no state available for current time. Always the + // same as _activeTriggerTimeIndex if(_loadingStatesDynamically==true), else + // always = 0 + int _activeStateIndex = -1; + // Active index of _startTimes + int _activeTriggerTimeIndex = -1; + // Number of states in the sequence + size_t _nStates = 0; + // In setup it is used to scale JSON coordinates. During runtime it is used to scale + // domain limits. + float _scalingFactor = 1.f; + // Estimated end of sequence. + double _sequenceEndTime; + // OpenGL Vertex Array Object + GLuint _vertexArrayObject = 0; + // OpenGL Vertex Buffer Object containing the extraQuantity values used for coloring + // the lines + GLuint _vertexColorBuffer = 0; + // OpenGL Vertex Buffer Object containing the extraQuantity values used for masking + // out segments of the lines + GLuint _vertexMaskingBuffer = 0; + // OpenGL Vertex Buffer Object containing the vertex positions + GLuint _vertexPositionBuffer = 0; // ----------------------------------- POINTERS ------------------------------------// - std::unique_ptr _dictionary; // The Lua-Modfile-Dictionary used during initialization - std::unique_ptr _newState; // Used for 'runtime-states' when switching out current state to a new state + // The Lua-Modfile-Dictionary used during initialization + std::unique_ptr _dictionary; + // Used for 'runtime-states' when switching out current state to a new state + std::unique_ptr _newState; std::unique_ptr _shaderProgram; - std::shared_ptr _transferFunction; // Transfer function used to color lines when _pColorMethod is set to BY_QUANTITY + // Transfer function used to color lines when _pColorMethod is set to BY_QUANTITY + std::shared_ptr _transferFunction; // ------------------------------------ VECTORS ----------------------------------- // - std::vector _colorTablePaths; // Paths to color tables. One for each 'extraQuantity' - std::vector _colorTableRanges; // Values represents min & max values represented in the color table - std::vector _maskingRanges; // Values represents min & max limits for valid masking range - std::vector _sourceFiles; // Stores the provided source file paths if using 'runtime-states', else emptied after initialization - std::vector _startTimes; // Contains the _triggerTimes for all FieldlineStates in the sequence - std::vector _states; // Stores the FieldlineStates + // Paths to color tables. One for each 'extraQuantity' + std::vector _colorTablePaths; + // Values represents min & max values represented in the color table + std::vector _colorTableRanges; + // Values represents min & max limits for valid masking range + std::vector _maskingRanges; + // Stores the provided source file paths if using 'runtime-states', else emptied after + // initialization + std::vector _sourceFiles; + // Contains the _triggerTimes for all FieldlineStates in the sequence + std::vector _startTimes; + // Stores the FieldlineStates + std::vector _states; // ---------------------------------- Properties ---------------------------------- // - properties::PropertyOwner _pColorGroup; // Group to hold the color properties - properties::OptionProperty _pColorMethod; // Uniform/transfer function/topology? - properties::OptionProperty _pColorQuantity; // Index of the extra quantity to color lines by - properties::StringProperty _pColorQuantityMin; // Color table/transfer function min - properties::StringProperty _pColorQuantityMax; // Color table/transfer function max - properties::StringProperty _pColorTablePath; // Color table/transfer function for "By Quantity" coloring - properties::Vec4Property _pColorUniform; // Uniform Field Line Color - properties::BoolProperty _pColorABlendEnabled; // Whether or not to use additive blending + // Group to hold the color properties + properties::PropertyOwner _pColorGroup; + // Uniform/transfer function/topology? + properties::OptionProperty _pColorMethod; + // Index of the extra quantity to color lines by + properties::OptionProperty _pColorQuantity; + // Color table/transfer function min + properties::StringProperty _pColorQuantityMin; + // Color table/transfer function max + properties::StringProperty _pColorQuantityMax; + // Color table/transfer function for "By Quantity" coloring + properties::StringProperty _pColorTablePath; + // Uniform Field Line Color + properties::Vec4Property _pColorUniform; + // Whether or not to use additive blending + properties::BoolProperty _pColorABlendEnabled; - properties::BoolProperty _pDomainEnabled; // Whether or not to use Domain - properties::PropertyOwner _pDomainGroup; // Group to hold the Domain properties - properties::Vec2Property _pDomainX; // Domain Limits along x-axis - properties::Vec2Property _pDomainY; // Domain Limits along y-axis - properties::Vec2Property _pDomainZ; // Domain Limits along z-axis - properties::Vec2Property _pDomainR; // Domain Limits radially +// Whether or not to use Domain + properties::BoolProperty _pDomainEnabled; + // Group to hold the Domain properties + properties::PropertyOwner _pDomainGroup; + // Domain Limits along x-axis + properties::Vec2Property _pDomainX; + // Domain Limits along y-axis + properties::Vec2Property _pDomainY; + // Domain Limits along z-axis + properties::Vec2Property _pDomainZ; + // Domain Limits radially + properties::Vec2Property _pDomainR; - properties::Vec4Property _pFlowColor; // Simulated particles' color - properties::BoolProperty _pFlowEnabled; // Toggle flow [ON/OFF] - properties::PropertyOwner _pFlowGroup; // Group to hold the flow/particle properties - properties::IntProperty _pFlowParticleSize; // Size of simulated flow particles - properties::IntProperty _pFlowParticleSpacing; // Size of simulated flow particles - properties::BoolProperty _pFlowReversed; // Toggle flow direction [FORWARDS/BACKWARDS] - properties::IntProperty _pFlowSpeed; // Speed of simulated flow +// Simulated particles' color + properties::Vec4Property _pFlowColor; + // Toggle flow [ON/OFF] + properties::BoolProperty _pFlowEnabled; + // Group to hold the flow/particle properties + properties::PropertyOwner _pFlowGroup; + // Size of simulated flow particles + properties::IntProperty _pFlowParticleSize; + // Size of simulated flow particles + properties::IntProperty _pFlowParticleSpacing; + // Toggle flow direction [FORWARDS/BACKWARDS] + properties::BoolProperty _pFlowReversed; + // Speed of simulated flow + properties::IntProperty _pFlowSpeed; - properties::BoolProperty _pMaskingEnabled; // Whether or not to use masking - properties::PropertyOwner _pMaskingGroup; // Group to hold the masking properties - properties::StringProperty _pMaskingMin; // Lower limit for allowed values - properties::StringProperty _pMaskingMax; // Upper limit for allowed values - properties::OptionProperty _pMaskingQuantity; // Index of the extra quantity to use for masking +// Whether or not to use masking + properties::BoolProperty _pMaskingEnabled; + // Group to hold the masking properties + properties::PropertyOwner _pMaskingGroup; + // Lower limit for allowed values + properties::StringProperty _pMaskingMin; + // Upper limit for allowed values + properties::StringProperty _pMaskingMax; + // Index of the extra quantity to use for masking + properties::OptionProperty _pMaskingQuantity; - properties::TriggerProperty _pFocusOnOriginBtn; // Button which sets camera focus to parent node of the renderable - properties::TriggerProperty _pJumpToStartBtn; // Button which executes a time jump to start of sequence +// Button which sets camera focus to parent node of the renderable + properties::TriggerProperty _pFocusOnOriginBtn; + // Button which executes a time jump to start of sequence + properties::TriggerProperty _pJumpToStartBtn; // --------------------- FUNCTIONS USED DURING INITIALIZATION --------------------- // void addStateToSequence(FieldlinesState& STATE); @@ -147,7 +214,8 @@ private: bool extractMandatoryInfoFromDictionary(SourceFileType& sourceFileType); void extractOptionalInfoFromDictionary(std::string& outputFolderPath); void extractOsflsInfoFromDictionary(); - bool extractSeedPointsFromFile(const std::string& path, std::vector& outVec); + bool extractSeedPointsFromFile(const std::string& path, + std::vector& outVec); void extractTriggerTimesFromFileNames(); bool loadJsonStatesIntoRAM(const std::string& outputFolder); void loadOsflsStatesIntoRAM(const std::string& outputFolder); diff --git a/modules/fieldlinessequence/util/commons.cpp b/modules/fieldlinessequence/util/commons.cpp index df3f76978f..cf006a4abc 100644 --- a/modules/fieldlinessequence/util/commons.cpp +++ b/modules/fieldlinessequence/util/commons.cpp @@ -39,4 +39,4 @@ Model stringToModel(const std::string s) { } } // namespace fls -} // namespace openspace \ No newline at end of file +} // namespace openspace diff --git a/modules/fieldlinessequence/util/fieldlinesstate.cpp b/modules/fieldlinessequence/util/fieldlinesstate.cpp index 3d61f1c384..51c8b7b0d9 100644 --- a/modules/fieldlinessequence/util/fieldlinesstate.cpp +++ b/modules/fieldlinessequence/util/fieldlinesstate.cpp @@ -33,7 +33,7 @@ #include namespace { - std::string _loggerCat = "FieldlinesState"; + const char* _loggerCat = "FieldlinesState"; const int CurrentVersion = 0; using json = nlohmann::json; } @@ -99,7 +99,8 @@ bool FieldlinesState::loadStateFromOsfls(const std::string& pathToOsflsFile) { ifs.read( reinterpret_cast(&byteSizeAllNames), sizeof(size_t)); // RESERVE/RESIZE vectors - // TODO: Do this without initializing values? Resize is slower than just using reserve, due to initialization of all values + // TODO: Do this without initializing values? Resize is slower than just using + // reserve, due to initialization of all values _lineStart.resize(nLines); _lineCount.resize(nLines); _vertexPositions.resize(nPoints); @@ -107,9 +108,12 @@ bool FieldlinesState::loadStateFromOsfls(const std::string& pathToOsflsFile) { _extraQuantityNames.reserve(nExtras); // Read vertex position data - ifs.read( reinterpret_cast(_lineStart.data()), sizeof(GLint)*nLines); - ifs.read( reinterpret_cast(_lineCount.data()), sizeof(GLsizei)*nLines); - ifs.read( reinterpret_cast(_vertexPositions.data()), sizeof(glm::vec3)*nPoints); + ifs.read( reinterpret_cast(_lineStart.data()), sizeof(GLint) * nLines); + ifs.read( reinterpret_cast(_lineCount.data()), sizeof(GLsizei) * nLines); + ifs.read( + reinterpret_cast(_vertexPositions.data()), + sizeof(glm::vec3) * nPoints + ); // Read all extra quantities for (std::vector& vec : _extraQuantities) { @@ -168,8 +172,10 @@ bool FieldlinesState::loadStateFromJson(const std::string& pathToJsonFile, const size_t nPosComponents = 3; // x,y,z if (nVariables < nPosComponents) { - LERROR(pathToJsonFile + ": Each field '" + sColumns + - "' must contain the variables: 'x', 'y' and 'z' (order is important)."); + LERROR( + pathToJsonFile + ": Each field '" + sColumns + + "' must contain the variables: 'x', 'y' and 'z' (order is important)." + ); return false; } @@ -215,19 +221,27 @@ bool FieldlinesState::loadStateFromJson(const std::string& pathToJsonFile, * @param absPath must be the path to the file (incl. filename but excl. extension!) * Directory must exist! File is created (or overwritten if already existing). * File is structured like this: (for version 0) - * 0. int - version number of binary state file! (in case something needs to be altered in the future, then increase CurrentVersion) + * 0. int - version number of binary state file! (in case something + * needs to be altered in the future, then increase + * CurrentVersion) * 1. double - _triggerTime * 2. int - _model * 3. bool - _isMorphable - * 4. size_t - Number of lines in the state == _lineStart.size() == _lineCount.size() - * 5. size_t - Total number of vertex points == _vertexPositions.size() == _extraQuantities[i].size() - * 6. size_t - Number of extra quantites == _extraQuantities.size() == _extraQuantityNames.size() - * 7. site_t - Number of total bytes that ALL _extraQuantityNames consists of (Each such name is stored as a c_str which means it ends with the null char '\0' ) + * 4. size_t - Number of lines in the state == _lineStart.size() + * == _lineCount.size() + * 5. size_t - Total number of vertex points == _vertexPositions.size() + * == _extraQuantities[i].size() + * 6. size_t - Number of extra quantites == _extraQuantities.size() + * == _extraQuantityNames.size() + * 7. site_t - Number of total bytes that ALL _extraQuantityNames + * consists of (Each such name is stored as a c_str which + * means it ends with the null char '\0' ) * 7. std::vector - _lineStart * 8. std::vector - _lineCount * 9. std::vector - _vertexPositions * 10. std::vector - _extraQuantities - * 11. array of c_str - Strings naming the extra quantities (elements of _extraQuantityNames). Each string ends with null char '\0' + * 11. array of c_str - Strings naming the extra quantities (elements of + * _extraQuantityNames). Each string ends with null char '\0' */ void FieldlinesState::saveStateToOsfls(const std::string& absPath) { // ------------------------------- Create the file ------------------------------- // @@ -246,7 +260,7 @@ void FieldlinesState::saveStateToOsfls(const std::string& absPath) { // --------- Add each string of _extraQuantityNames into one long string --------- // std::string allExtraQuantityNamesInOne = ""; for (std::string str : _extraQuantityNames) { - allExtraQuantityNamesInOne += str + '\0'; // Add the null char '\0' for easier reading + allExtraQuantityNamesInOne += str + '\0'; // Add null char '\0' for easier reading } const size_t nLines = _lineStart.size(); @@ -254,24 +268,27 @@ void FieldlinesState::saveStateToOsfls(const std::string& absPath) { const size_t nExtras = _extraQuantities.size(); const size_t nStringBytes = allExtraQuantityNamesInOne.size(); - //------------------------------ WRITE EVERYTHING TO FILE ------------------------------ - // WHICH VERSION OF BINARY FIELDLINES STATE FILE - IN CASE STRUCTURE CHANGES IN THE FUTURE + //----------------------------- WRITE EVERYTHING TO FILE ----------------------------- + // VERSION OF BINARY FIELDLINES STATE FILE - IN CASE STRUCTURE CHANGES IN THE FUTURE ofs.write( (char*)(&CurrentVersion), sizeof( int ) ); //-------------------- WRITE META DATA FOR STATE -------------------------------- - ofs.write( reinterpret_cast(&_triggerTime), sizeof( _triggerTime ) ); - ofs.write( reinterpret_cast(&_model), sizeof( int ) ); - ofs.write( reinterpret_cast(&_isMorphable), sizeof( bool ) ); + ofs.write(reinterpret_cast(&_triggerTime), sizeof( _triggerTime )); + ofs.write(reinterpret_cast(&_model), sizeof( int )); + ofs.write(reinterpret_cast(&_isMorphable), sizeof( bool )); - ofs.write( reinterpret_cast(&nLines), sizeof( size_t ) ); - ofs.write( reinterpret_cast(&nPoints), sizeof( size_t ) ); - ofs.write( reinterpret_cast(&nExtras), sizeof( size_t ) ); - ofs.write( reinterpret_cast(&nStringBytes), sizeof( size_t ) ); + ofs.write(reinterpret_cast(&nLines), sizeof( size_t )); + ofs.write(reinterpret_cast(&nPoints), sizeof( size_t )); + ofs.write(reinterpret_cast(&nExtras), sizeof( size_t )); + ofs.write(reinterpret_cast(&nStringBytes), sizeof( size_t )); //---------------------- WRITE ALL ARRAYS OF DATA -------------------------------- - ofs.write( reinterpret_cast(_lineStart.data()), sizeof(GLint) * nLines); - ofs.write( reinterpret_cast(_lineCount.data()), sizeof(GLsizei) * nLines); - ofs.write( reinterpret_cast(_vertexPositions.data()), sizeof(glm::vec3) * nPoints); + ofs.write(reinterpret_cast(_lineStart.data()), sizeof(GLint) * nLines); + ofs.write(reinterpret_cast(_lineCount.data()), sizeof(GLsizei) * nLines); + ofs.write( + reinterpret_cast(_vertexPositions.data()), + sizeof(glm::vec3) * nPoints + ); // Write the data for each vector in _extraQuantities for (std::vector& vec : _extraQuantities) { ofs.write( reinterpret_cast(vec.data()), sizeof(float) * nPoints); @@ -279,23 +296,27 @@ void FieldlinesState::saveStateToOsfls(const std::string& absPath) { ofs.write( allExtraQuantityNamesInOne.c_str(), nStringBytes); } -// TODO: This should probably be rewritten, but this is the way the files were structured by CCMC +// TODO: This should probably be rewritten, but this is the way the files were structured +// by CCMC // Structure of File! NO TRAILING COMMAS ALLOWED! -// Additional info can be stored within each line as the code only extracts the keys it needs (time, trace & data) +// Additional info can be stored within each line as the code only extracts the keys it +// needs (time, trace & data) // The key/name of each line ("0" & "1" in the example below) is arbitrary // { // "0":{ // "time": "YYYY-MM-DDTHH:MM:SS.XXX", // "trace": { // "columns": ["x","y","z","s","temperature","rho","j_para"], -// "data": [[8.694,127.853,115.304,0.0,0.047,9.249,-5e-10],...,[8.698,127.253,114.768,0.800,0.0,9.244,-5e-10]] +// "data": [[8.694,127.853,115.304,0.0,0.047,9.249,-5e-10],..., +// [8.698,127.253,114.768,0.800,0.0,9.244,-5e-10]] // }, // }, // "1":{ // "time": "YYYY-MM-DDTHH:MM:SS.XXX // "trace": { // "columns": ["x","y","z","s","temperature","rho","j_para"], -// "data": [[8.694,127.853,115.304,0.0,0.047,9.249,-5e-10],...,[8.698,127.253,114.768,0.800,0.0,9.244,-5e-10]] +// "data": [[8.694,127.853,115.304,0.0,0.047,9.249,-5e-10],..., +// [8.698,127.253,114.768,0.800,0.0,9.244,-5e-10]] // }, // } // } @@ -343,7 +364,7 @@ void FieldlinesState::saveStateToJson(const std::string& absPath) { }; } - //------------------------------ WRITE EVERYTHING TO FILE ------------------------------ + //----------------------------- WRITE EVERYTHING TO FILE ----------------------------- const int indentationSpaces = 2; ofs << std::setw(indentationSpaces) << jFile << std::endl; @@ -351,7 +372,7 @@ void FieldlinesState::saveStateToJson(const std::string& absPath) { } // Returns one of the extra quantity vectors, _extraQuantities[index]. -// If index is out of scope an empty vector is returned and the referenced bool will be false. +// If index is out of scope an empty vector is returned and the referenced bool is false. const std::vector& FieldlinesState::extraQuantity(const size_t index, bool& isSuccessful) const { if (index < _extraQuantities.size()) { @@ -364,16 +385,20 @@ const std::vector& FieldlinesState::extraQuantity(const size_t index, return std::vector(); } -/** Moves the points in @param line over to _vertexPositions and updates _lineStart & _lineCount accordingly. - */ +// Moves the points in @param line over to _vertexPositions and updates +// _lineStart & _lineCount accordingly. + void FieldlinesState::addLine(std::vector& line) { const size_t nNewPoints = line.size(); const size_t nOldPoints = _vertexPositions.size(); _lineStart.push_back(static_cast(nOldPoints)); _lineCount.push_back(static_cast(nNewPoints)); _vertexPositions.reserve(nOldPoints + nNewPoints); - _vertexPositions.insert(_vertexPositions.end(), std::make_move_iterator(line.begin()), - std::make_move_iterator(line.end())); + _vertexPositions.insert( + _vertexPositions.end(), + std::make_move_iterator(line.begin()), + std::make_move_iterator(line.end()) + ); line.clear(); } @@ -382,4 +407,37 @@ void FieldlinesState::setExtraQuantityNames(std::vector& names) { names.clear(); _extraQuantities.resize(_extraQuantityNames.size()); } + +const std::vector>& FieldlinesState::extraQuantities() const { + return _extraQuantities; +} + +const std::vector& FieldlinesState::extraQuantityNames() const { + return _extraQuantityNames; +} + +const std::vector& FieldlinesState::lineCount() const { + return _lineCount; +} + +const std::vector& FieldlinesState::lineStart() const { + return _lineStart; +} + +fls::Model FieldlinesState::FieldlinesState::model() const { + return _model; +} + +size_t FieldlinesState::nExtraQuantities() const { + return _extraQuantities.size(); +} + +double FieldlinesState::triggerTime() const { + return _triggerTime; +} + +const std::vector& FieldlinesState::vertexPositions() const { + return _vertexPositions; +} + } // namespace openspace diff --git a/modules/fieldlinessequence/util/fieldlinesstate.h b/modules/fieldlinessequence/util/fieldlinesstate.h index 35b1fb9db3..66d417deff 100644 --- a/modules/fieldlinessequence/util/fieldlinesstate.h +++ b/modules/fieldlinessequence/util/fieldlinesstate.h @@ -54,14 +54,14 @@ public: void saveStateToJson(const std::string& pathToJsonFile); // ----------------------------------- GETTERS ----------------------------------- // - const std::vector>& extraQuantities() const { return _extraQuantities; } - const std::vector& extraQuantityNames() const { return _extraQuantityNames; } - const std::vector& lineCount() const { return _lineCount; } - const std::vector& lineStart() const { return _lineStart; } - fls::Model model() const { return _model; } - size_t nExtraQuantities() const { return _extraQuantities.size(); } - double triggerTime() const { return _triggerTime; } - const std::vector& vertexPositions() const { return _vertexPositions; } + const std::vector>& extraQuantities() const; + const std::vector& extraQuantityNames() const; + const std::vector& lineCount() const; + const std::vector& lineStart() const; + fls::Model model() const; + size_t nExtraQuantities() const; + double triggerTime() const; + const std::vector& vertexPositions() const; // Special getter. Returns extraQuantities[INDEX]. const std::vector& extraQuantity(const size_t INDEX, bool& isSuccesful) const; diff --git a/modules/fieldlinessequence/util/kameleonfieldlinehelper.cpp b/modules/fieldlinessequence/util/kameleonfieldlinehelper.cpp index 283207ec1c..be5a64d975 100644 --- a/modules/fieldlinessequence/util/kameleonfieldlinehelper.cpp +++ b/modules/fieldlinessequence/util/kameleonfieldlinehelper.cpp @@ -42,7 +42,8 @@ namespace { const std::string TAsPOverRho = "T = p/rho"; const std::string JParallelB = "Current: mag(J||B)"; - const float ToKelvin = 72429735.6984f; // <-- [nPa]/[amu/cm^3] * ToKelvin => Temperature in Kelvin + // [nPa]/[amu/cm^3] * ToKelvin => Temperature in Kelvin + const float ToKelvin = 72429735.6984f; } namespace openspace { @@ -63,14 +64,20 @@ namespace fls { #endif // OPENSPACE_MODULE_KAMELEON_ENABLED // ----------------------------------------------------------------------------------- // -/** Traces field lines from the provided cdf file using kameleon and stores the data in the provided FieldlinesState. - * Returns `false` if it fails to create a valid state. Requires the kameleon module to be activated! +/** Traces field lines from the provided cdf file using kameleon and stores the data in + * the provided FieldlinesState. + * Returns `false` if it fails to create a valid state. Requires the kameleon module to be + * activated! * @param state, FieldlineState which should hold the extracted data * @param cdfPath, std::string of the absolute path to a .cdf file * @param seedPoints, vector of seed points from which to trace field lines - * @param tracingVar, which quantity to trace lines from. Typically "b" for magnetic field lines and "u" for velocity flow lines - * @param extraVars, extra scalar quantities to be stored in the FieldlinesState; e.g. "T" for temperature, "rho" for density or "P" for pressure - * @param extraMagVars, variables which should be used for extracting magnitudes, must be a multiple of 3; e.g. "ux", "uy" & "uz" to get the magnitude of the velocity vector at each line vertex + * @param tracingVar, which quantity to trace lines from. Typically "b" for magnetic field + * lines and "u" for velocity flow lines + * @param extraVars, extra scalar quantities to be stored in the FieldlinesState; e.g. "T" + * for temperature, "rho" for density or "P" for pressure + * @param extraMagVars, variables which should be used for extracting magnitudes, must be + * a multiple of 3; e.g. "ux", "uy" & "uz" to get the magnitude of the velocity + * vector at each line vertex */ bool convertCdfToFieldlinesState(FieldlinesState& state, const std::string cdfPath, const std::vector& seedPoints, @@ -118,7 +125,8 @@ bool convertCdfToFieldlinesState(FieldlinesState& state, const std::string cdfPa #ifdef OPENSPACE_MODULE_KAMELEON_ENABLED /** * Traces and adds line vertices to state. - * Vertices are not scaled to meters nor converted from spherical into cartesian coordinates. + * Vertices are not scaled to meters nor converted from spherical into cartesian + * coordinates. * Note that extraQuantities will NOT be set! */ bool addLinesToState(ccmc::Kameleon* kameleon, const std::vector& seedPoints, @@ -184,8 +192,9 @@ bool addLinesToState(ccmc::Kameleon* kameleon, const std::vector& see * coordinate system)! * * @param kameleon raw pointer to an already opened Kameleon object - * @param extraScalarVars vector of strings. Strings should be names of a scalar quantities - * to load into _extraQuantites; such as: "T" for temperature or "rho" for density. + * @param extraScalarVars vector of strings. Strings should be names of a scalar + * quantities to load into _extraQuantites; such as: "T" for temperature or "rho" for + * density. * @param extraMagVars vector of strings. Size must be multiple of 3. Strings should be * names of the components needed to calculate magnitude. E.g. {"ux", "uy", "uz"} will * calculate: sqrt(ux*ux + uy*uy + uz*uz). Magnitude will be stored in _extraQuantities @@ -256,8 +265,10 @@ void addExtraQuantities(ccmc::Kameleon* kameleon, * _extraQuantityNames vector. * * @param kameleon, raw pointer to an already opened kameleon object - * @param extraScalarVars, names of scalar quantities to add to state; e.g "rho" for density - * @param extraMagVars, names of the variables used for calculating magnitudes. Must be multiple of 3. + * @param extraScalarVars, names of scalar quantities to add to state; e.g "rho" for + * density + * @param extraMagVars, names of the variables used for calculating magnitudes. Must be + * multiple of 3. */ #ifdef OPENSPACE_MODULE_KAMELEON_ENABLED void prepareStateAndKameleonForExtras(ccmc::Kameleon* kameleon, @@ -271,7 +282,8 @@ void prepareStateAndKameleonForExtras(ccmc::Kameleon* kameleon, // Remove non-existing variables from vector for (int i = 0; i < extraScalarVars.size(); i++) { std::string& str = extraScalarVars[i]; - bool isSuccesful = kameleon->doesVariableExist(str) && kameleon->loadVariable(str); + bool isSuccesful = kameleon->doesVariableExist(str) && + kameleon->loadVariable(str); if (!isSuccesful && (model == fls::Model::Batsrus && (str == TAsPOverRho || str == "T" ))) { LDEBUG("BATSRUS doesn't contain variable T for temperature. Trying to " @@ -321,7 +333,10 @@ void prepareStateAndKameleonForExtras(ccmc::Kameleon* kameleon, LWARNING("FAILED TO LOAD AT LEAST ONE OF THE MAGNITUDE VARIABLES: " << s1 << ", " << s2 << " & " << s3 << ". Removing ability to store corresponding magnitude!"); - extraMagVars.erase(extraMagVars.begin() + i, extraMagVars.begin() + i + 3); + extraMagVars.erase( + extraMagVars.begin() + i, + extraMagVars.begin() + i + 3 + ); i -= 3; } else { extraQuantityNames.push_back(name); diff --git a/modules/fieldlinessequence/util/kameleonfieldlinehelper.h b/modules/fieldlinessequence/util/kameleonfieldlinehelper.h index f6f898a5ed..e496dcd258 100644 --- a/modules/fieldlinessequence/util/kameleonfieldlinehelper.h +++ b/modules/fieldlinessequence/util/kameleonfieldlinehelper.h @@ -45,4 +45,4 @@ bool convertCdfToFieldlinesState(FieldlinesState& state, const std::string cdfPa } // namespace fls } // namespace openspace -#endif // __OPENSPACE_MODULE_FIELDLINESSEQUENCE___KAMELEONFIELDLINEHELPER___H__ \ No newline at end of file +#endif // __OPENSPACE_MODULE_FIELDLINESSEQUENCE___KAMELEONFIELDLINEHELPER___H__ diff --git a/modules/galaxy/rendering/galaxyraycaster.h b/modules/galaxy/rendering/galaxyraycaster.h index f3ea1a32e2..1e70c70b4b 100644 --- a/modules/galaxy/rendering/galaxyraycaster.h +++ b/modules/galaxy/rendering/galaxyraycaster.h @@ -52,11 +52,16 @@ public: virtual ~GalaxyRaycaster(); void initialize(); void deinitialize(); - void renderEntryPoints(const RenderData& data, ghoul::opengl::ProgramObject& program) override; - void renderExitPoints(const RenderData& data, ghoul::opengl::ProgramObject& program) override; - void preRaycast(const RaycastData& data, ghoul::opengl::ProgramObject& program) override; - void postRaycast(const RaycastData& data, ghoul::opengl::ProgramObject& program) override; - bool cameraIsInside(const RenderData& data, glm::vec3& localPosition) override; + void renderEntryPoints(const RenderData& data, + ghoul::opengl::ProgramObject& program) override; + void renderExitPoints(const RenderData& data, + ghoul::opengl::ProgramObject& program) override; + void preRaycast(const RaycastData& data, + ghoul::opengl::ProgramObject& program) override; + void postRaycast(const RaycastData& data, + ghoul::opengl::ProgramObject& program) override; + bool cameraIsInside(const RenderData& data, + glm::vec3& localPosition) override; std::string getBoundsVsPath() const override; diff --git a/modules/galaxy/rendering/renderablegalaxy.cpp b/modules/galaxy/rendering/renderablegalaxy.cpp index 2c62310399..6ef4b4c635 100644 --- a/modules/galaxy/rendering/renderablegalaxy.cpp +++ b/modules/galaxy/rendering/renderablegalaxy.cpp @@ -150,10 +150,10 @@ namespace openspace { } } - + RenderableGalaxy::~RenderableGalaxy() {} -void RenderableGalaxy::initialize() { +void RenderableGalaxy::initializeGL() { // Aspect is currently hardcoded to cubic voxels. _aspect = static_cast(_volumeDimensions); _aspect = _aspect / std::max(std::max(_aspect.x, _aspect.y), _aspect.z); @@ -163,7 +163,7 @@ void RenderableGalaxy::initialize() { _volumeDimensions ); _volume = reader.read(); - + _texture = std::make_unique( _volumeDimensions, ghoul::opengl::Texture::Format::RGBA, @@ -176,6 +176,7 @@ void RenderableGalaxy::initialize() { _volume->data()), ghoul::opengl::Texture::TakeOwnership::No ); + _texture->setDimensions(_volume->dimensions()); _texture->uploadTexture(); @@ -200,7 +201,7 @@ void RenderableGalaxy::initialize() { addProperty(_translation); addProperty(_rotation); addProperty(_enabledPointsRatio); - + // initialize points. std::ifstream pointFile(_pointsFilename, std::ios::in | std::ios::binary); @@ -221,7 +222,7 @@ void RenderableGalaxy::initialize() { pointFile.close(); float maxdist = 0; - + for (size_t i = 0; i < _nPoints; ++i) { float x = pointData[i * 7 + 0]; float y = pointData[i * 7 + 1]; @@ -231,9 +232,9 @@ void RenderableGalaxy::initialize() { float b = pointData[i * 7 + 5]; maxdist = std::max(maxdist, glm::length(glm::vec3(x, y, z))); //float a = pointData[i * 7 + 6]; alpha is not used. - + pointPositions.push_back(glm::vec3(x, y, z)); - pointColors.push_back(glm::vec3(r, g, b)); + pointColors.push_back(glm::vec3(r, g, b)); } std::cout << maxdist << std::endl; @@ -272,28 +273,28 @@ void RenderableGalaxy::initialize() { GLint colorAttrib = _pointsProgram->attributeLocation("inColor"); glBindBuffer(GL_ARRAY_BUFFER, _positionVbo); - glEnableVertexAttribArray(positionAttrib); + glEnableVertexAttribArray(positionAttrib); glVertexAttribPointer(positionAttrib, 3, GL_FLOAT, GL_FALSE, 0, 0); glBindBuffer(GL_ARRAY_BUFFER, _colorVbo); glEnableVertexAttribArray(colorAttrib); glVertexAttribPointer(colorAttrib, 3, GL_FLOAT, GL_FALSE, 0, 0); - + glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); } - -void RenderableGalaxy::deinitialize() { + +void RenderableGalaxy::deinitializeGL() { if (_raycaster) { OsEng.renderEngine().raycasterManager().detachRaycaster(*_raycaster.get()); _raycaster = nullptr; } } - + bool RenderableGalaxy::isReady() const { return true; } - + void RenderableGalaxy::update(const UpdateData& data) { if (_raycaster) { @@ -312,7 +313,7 @@ void RenderableGalaxy::update(const UpdateData& data) { static_cast(_volumeSize) ); _pointTransform = glm::scale(transform, static_cast(_pointScaling)); - + glm::vec4 translation = glm::vec4(static_cast(_translation), 0.0); // Todo: handle floating point overflow, to actually support translation. @@ -337,6 +338,7 @@ void RenderableGalaxy::render(const RenderData& data, RendererTasks& tasks) { glm::vec3 galaxySize = static_cast(_volumeSize); float maxDim = std::max(std::max(galaxySize.x, galaxySize.y), galaxySize.z); + float lowerRampStart = maxDim * 0.02; float lowerRampEnd = maxDim * 0.5; @@ -409,5 +411,5 @@ float RenderableGalaxy::safeLength(const glm::vec3& vector) { OsEng.ref().renderEngine().postRaycast(*_pointsProgram); }*/ - + } diff --git a/modules/galaxy/rendering/renderablegalaxy.h b/modules/galaxy/rendering/renderablegalaxy.h index 9bc543bdc1..d910be4650 100644 --- a/modules/galaxy/rendering/renderablegalaxy.h +++ b/modules/galaxy/rendering/renderablegalaxy.h @@ -35,14 +35,14 @@ namespace openspace { struct RenderData; - + class RenderableGalaxy : public Renderable { public: RenderableGalaxy(const ghoul::Dictionary& dictionary); ~RenderableGalaxy(); - - void initialize() override; - void deinitialize() override; + + void initializeGL() override; + void deinitializeGL() override; bool isReady() const override; void render(const RenderData& data, RendererTasks& tasks) override; void update(const UpdateData& data) override; diff --git a/modules/galaxy/tasks/milkywayconversiontask.cpp b/modules/galaxy/tasks/milkywayconversiontask.cpp index 4002251bb9..6b623b1b92 100644 --- a/modules/galaxy/tasks/milkywayconversiontask.cpp +++ b/modules/galaxy/tasks/milkywayconversiontask.cpp @@ -39,7 +39,7 @@ namespace { const char* KeyInNSlices = "InNSlices"; const char* KeyOutFilename = "OutFilename"; const char* KeyOutDimensions = "OutDimensions"; -} // namespace +} // namespace namespace openspace { diff --git a/modules/galaxy/tasks/milkywaypointsconversiontask.cpp b/modules/galaxy/tasks/milkywaypointsconversiontask.cpp index eb8b61c0be..9428186f62 100644 --- a/modules/galaxy/tasks/milkywaypointsconversiontask.cpp +++ b/modules/galaxy/tasks/milkywaypointsconversiontask.cpp @@ -51,7 +51,8 @@ std::string MilkywayPointsConversionTask::description() return std::string(); } -void MilkywayPointsConversionTask::perform(const Task::ProgressCallback & progressCallback) { +void MilkywayPointsConversionTask::perform(const Task::ProgressCallback& progressCallback) +{ std::ifstream in(_inFilename, std::ios::in); std::ofstream out(_outFilename, std::ios::out | std::ios::binary); diff --git a/modules/globebrowsing/cache/texturecontainer.cpp b/modules/globebrowsing/cache/texturecontainer.cpp index a1006be9a5..a6bdd9cb9e 100644 --- a/modules/globebrowsing/cache/texturecontainer.cpp +++ b/modules/globebrowsing/cache/texturecontainer.cpp @@ -75,7 +75,9 @@ ghoul::opengl::Texture* TextureContainer::getTextureIfFree() { return texture; } -const openspace::globebrowsing::TileTextureInitData& TextureContainer::tileTextureInitData() const { +const openspace::globebrowsing::TileTextureInitData& +TextureContainer::tileTextureInitData() const +{ return _initData; } diff --git a/modules/globebrowsing/chunk/chunk.cpp b/modules/globebrowsing/chunk/chunk.cpp index 6e10fde6f6..215283b33a 100644 --- a/modules/globebrowsing/chunk/chunk.cpp +++ b/modules/globebrowsing/chunk/chunk.cpp @@ -40,7 +40,7 @@ Chunk::Chunk(const RenderableGlobe& owner, const TileIndex& tileIndex, bool init : _owner(owner) , _tileIndex(tileIndex) , _isVisible(initVisible) - , _surfacePatch(tileIndex) + , _surfacePatch(tileIndex) {} const GeodeticPatch& Chunk::surfacePatch() const { @@ -62,7 +62,14 @@ bool Chunk::isVisible() const { Chunk::Status Chunk::update(const RenderData& data) { const auto& savedCamera = _owner.savedCamera(); const Camera& camRef = savedCamera != nullptr ? *savedCamera : data.camera; - RenderData myRenderData = { camRef, data.position, data.time, data.doPerformanceMeasurement, data.renderBinMask, data.modelTransform }; + RenderData myRenderData = { + camRef, + data.position, + data.time, + data.doPerformanceMeasurement, + data.renderBinMask, + data.modelTransform + }; _isVisible = true; if (_owner.chunkedLodGlobe()->testIfCullable(*this, myRenderData)) { @@ -100,7 +107,9 @@ Chunk::BoundingHeights Chunk::getBoundingHeights() const { // a single raster image. If it is not we will just use the first raster // (that is channel 0). const size_t HeightChannel = 0; - const LayerGroup& heightmaps = layerManager->layerGroup(layergroupid::GroupID::HeightLayers); + const LayerGroup& heightmaps = layerManager->layerGroup( + layergroupid::GroupID::HeightLayers + ); std::vector chunkTileSettingPairs = tileselector::getTilesAndSettingsUnsorted( heightmaps, _tileIndex); @@ -171,8 +180,8 @@ std::vector Chunk::getBoundingPolyhedronCorners() const { double maxCenterRadius = patchCenterRadius + boundingHeight.max; Geodetic2 halfSize = patch.halfSize(); - // As the patch is curved, the maximum height offsets at the corners must be long - // enough to cover large enough to cover a boundingHeight.max at the center of the + // As the patch is curved, the maximum height offsets at the corners must be long + // enough to cover large enough to cover a boundingHeight.max at the center of the // patch. // Approximating scaleToCoverCenter by assuming the latitude and longitude angles // of "halfSize" are equal to the angles they create from the center of the @@ -189,7 +198,7 @@ std::vector Chunk::getBoundingPolyhedronCorners() const { bool chunkIsNorthOfEquator = patch.isNorthern(); - // The minimum height offset, however, we can simply + // The minimum height offset, however, we can simply double minCornerHeight = boundingHeight.min; std::vector corners(8); diff --git a/modules/globebrowsing/chunk/chunk.h b/modules/globebrowsing/chunk/chunk.h index c3c676adab..fc3af610e5 100644 --- a/modules/globebrowsing/chunk/chunk.h +++ b/modules/globebrowsing/chunk/chunk.h @@ -66,7 +66,7 @@ public: * return Status::WANT_MERGE, if it is larger it will return Status::WANT_SPLIT, * otherwise Status::DO_NOTHING. * - * \returns The Status of the chunk. + * \returns The Status of the chunk. */ Status update(const RenderData& data); diff --git a/modules/globebrowsing/chunk/chunklevelevaluator/projectedareaevaluator.cpp b/modules/globebrowsing/chunk/chunklevelevaluator/projectedareaevaluator.cpp index c31e1d5818..d8abd70f72 100644 --- a/modules/globebrowsing/chunk/chunklevelevaluator/projectedareaevaluator.cpp +++ b/modules/globebrowsing/chunk/chunklevelevaluator/projectedareaevaluator.cpp @@ -46,12 +46,12 @@ int ProjectedArea::getDesiredLevel(const Chunk& chunk, const RenderData& data) c glm::dvec3(inverseModelTransform * cameraPositionModelSpace); glm::dvec3 cameraToEllipsoidCenter = -cameraPosition; - Geodetic2 cameraGeodeticPos = ellipsoid.cartesianToGeodetic2(cameraPosition); + Geodetic2 cameraGeodeticPos = ellipsoid.cartesianToGeodetic2(cameraPosition); // Approach: // The projected area of the chunk will be calculated based on a small area that // is close to the camera, and the scaled up to represent the full area. - // The advantage of doing this is that it will better handle the cases where the + // The advantage of doing this is that it will better handle the cases where the // full patch is very curved (e.g. stretches from latitude 0 to 90 deg). const Geodetic2 center = chunk.surfacePatch().center(); @@ -61,11 +61,11 @@ int ProjectedArea::getDesiredLevel(const Chunk& chunk, const RenderData& data) c // | // V // - // oo + // oo // [ ]< // *geodetic space* - // - // closestCorner + // + // closestCorner // +-----------------+ <-- north east corner // | | // | center | @@ -81,7 +81,7 @@ int ProjectedArea::getDesiredLevel(const Chunk& chunk, const RenderData& data) c // | // V // - // oo + // oo // [ ]< // *geodetic space* // @@ -103,7 +103,7 @@ int ProjectedArea::getDesiredLevel(const Chunk& chunk, const RenderData& data) c C = glm::normalize(C); // Camera *cartesian space* - // | +--------+---+ + // | +--------+---+ // V __--'' __--'' / // C-------A--------- + // oo / / / diff --git a/modules/globebrowsing/chunk/chunklevelevaluator/projectedareaevaluator.h b/modules/globebrowsing/chunk/chunklevelevaluator/projectedareaevaluator.h index 8211848627..70aecee378 100644 --- a/modules/globebrowsing/chunk/chunklevelevaluator/projectedareaevaluator.h +++ b/modules/globebrowsing/chunk/chunklevelevaluator/projectedareaevaluator.h @@ -38,7 +38,8 @@ namespace openspace::globebrowsing::chunklevelevaluator { */ class ProjectedArea : public Evaluator { public: - virtual int getDesiredLevel(const Chunk& chunk, const RenderData& data) const; + virtual int getDesiredLevel( + const Chunk& chunk, const RenderData& data) const override; }; } // namespace openspace::globebrowsing::chunklevelevaluator diff --git a/modules/globebrowsing/chunk/chunknode.cpp b/modules/globebrowsing/chunk/chunknode.cpp index bbe9392605..1ef8c7694b 100644 --- a/modules/globebrowsing/chunk/chunknode.cpp +++ b/modules/globebrowsing/chunk/chunknode.cpp @@ -109,7 +109,7 @@ void ChunkNode::reverseBreadthFirst(const std::function& // Loop through nodes in breadths first order Q.push(this); while (Q.size() > 0) { - const ChunkNode* node = Q.front(); + const ChunkNode* node = Q.front(); Q.pop(); // Add node to future stack @@ -126,7 +126,7 @@ void ChunkNode::reverseBreadthFirst(const std::function& } } - // Loop through all nodes in stack, this will be reversed breadth first + // Loop through all nodes in stack, this will be reversed breadth first while (S.size() > 0) { f(*S.top()); S.pop(); diff --git a/modules/globebrowsing/chunk/culling/frustumculler.cpp b/modules/globebrowsing/chunk/culling/frustumculler.cpp index 3d23475162..8c9eeab47a 100644 --- a/modules/globebrowsing/chunk/culling/frustumculler.cpp +++ b/modules/globebrowsing/chunk/culling/frustumculler.cpp @@ -38,8 +38,9 @@ bool FrustumCuller::isCullable(const Chunk& chunk, const RenderData& data) { // Calculate the MVP matrix glm::dmat4 modelTransform = chunk.owner().modelTransform(); glm::dmat4 viewTransform = glm::dmat4(data.camera.combinedViewMatrix()); - glm::dmat4 modelViewProjectionTransform = glm::dmat4(data.camera.sgctInternal.projectionMatrix()) - * viewTransform * modelTransform; + glm::dmat4 modelViewProjectionTransform = glm::dmat4( + data.camera.sgctInternal.projectionMatrix() + ) * viewTransform * modelTransform; const std::vector& corners = chunk.getBoundingPolyhedronCorners(); @@ -50,7 +51,9 @@ bool FrustumCuller::isCullable(const Chunk& chunk, const RenderData& data) { glm::dvec4 cornerClippingSpace = modelViewProjectionTransform * corners[i]; clippingSpaceCorners[i] = cornerClippingSpace; - glm::dvec3 ndc = glm::dvec3((1.0f / glm::abs(cornerClippingSpace.w)) * cornerClippingSpace); + glm::dvec3 ndc = glm::dvec3( + (1.f / glm::abs(cornerClippingSpace.w)) * cornerClippingSpace + ); bounds.expand(ndc); } diff --git a/modules/globebrowsing/chunk/culling/horizonculler.cpp b/modules/globebrowsing/chunk/culling/horizonculler.cpp index 84edb71c90..4919490c4f 100644 --- a/modules/globebrowsing/chunk/culling/horizonculler.cpp +++ b/modules/globebrowsing/chunk/culling/horizonculler.cpp @@ -79,7 +79,7 @@ bool HorizonCuller::isCullable(const Chunk& chunk, const RenderData& data) { maxHeight, minimumGlobeRadius); } -bool HorizonCuller::isCullable(const glm::dvec3& cameraPosition, +bool HorizonCuller::isCullable(const glm::dvec3& cameraPosition, const glm::dvec3& globePosition, const glm::dvec3& objectPosition, double objectBoundingSphereRadius, diff --git a/modules/globebrowsing/geometry/angle.h b/modules/globebrowsing/geometry/angle.h index 9ad16bfa41..68cb1f4cd7 100644 --- a/modules/globebrowsing/geometry/angle.h +++ b/modules/globebrowsing/geometry/angle.h @@ -96,8 +96,8 @@ public: Angle& normalizeAround(const Angle& center); /** - * Clamps the angle to the interval [min, max]. - * Default arguments are [0, 2pi]. + * Clamps the angle to the interval [min, max]. + * Default arguments are [0, 2pi]. */ Angle& clamp(const Angle& min = ZERO, const Angle& max = FULL); diff --git a/modules/globebrowsing/geometry/angle.inl b/modules/globebrowsing/geometry/angle.inl index 0ef33336cb..d6b763885d 100644 --- a/modules/globebrowsing/geometry/angle.inl +++ b/modules/globebrowsing/geometry/angle.inl @@ -30,7 +30,7 @@ template const T Angle::PI = T(3.14159265358979323846264338327950); template -const T Angle::EPSILON = 1e-10; // Should depend on the typedef /eb +const T Angle::EPSILON = 1e-10; // Should depend on the typedef /eb ////////////////////////////////////////////////////////////////////////////////////////// // STATIC CONSTANTS // diff --git a/modules/globebrowsing/geometry/ellipsoid.cpp b/modules/globebrowsing/geometry/ellipsoid.cpp index dfee03010d..183cc1b28d 100644 --- a/modules/globebrowsing/geometry/ellipsoid.cpp +++ b/modules/globebrowsing/geometry/ellipsoid.cpp @@ -81,7 +81,9 @@ glm::dvec3 Ellipsoid::geodeticSurfaceProjection(const glm::dvec3& p) const { return p / d; } -glm::dvec3 Ellipsoid::geodeticSurfaceNormalForGeocentricallyProjectedPoint(const glm::dvec3& p) const { +glm::dvec3 Ellipsoid::geodeticSurfaceNormalForGeocentricallyProjectedPoint( + const glm::dvec3& p) const +{ glm::dvec3 normal = p * _cached._oneOverRadiiSquared; return glm::normalize(normal); } @@ -91,7 +93,7 @@ glm::dvec3 Ellipsoid::geodeticSurfaceNormal(Geodetic2 geodetic2) const { //geodetic2.lon = geodetic2.lon > M_PI ? geodetic2.lon - M_PI * 2 : geodetic2.lon; return glm::dvec3( cosLat * cos(geodetic2.lon), - cosLat * sin(geodetic2.lon), + cosLat * sin(geodetic2.lon), sin(geodetic2.lat)); } diff --git a/modules/globebrowsing/geometry/ellipsoid.h b/modules/globebrowsing/geometry/ellipsoid.h index f68bb38b48..1cf222a786 100644 --- a/modules/globebrowsing/geometry/ellipsoid.h +++ b/modules/globebrowsing/geometry/ellipsoid.h @@ -38,8 +38,8 @@ namespace openspace::globebrowsing { * This class is based largely on the Ellipsoid class defined in the book * "3D Engine Design for Virtual Globes". Most planets or planetary objects are better * described using ellipsoids than spheres. All inputs and outputs to this class is - * based on the WGS84 standard coordinate system where the x-axis points towards geographic - * (lat = 0, lon = 0), the y-axis points towards (lat = 0, lon = 90deg) and the + * based on the WGS84 standard coordinate system where the x-axis points towards + * geographic (lat = 0, lon = 0), the y-axis points towards (lat = 0, lon = 90deg) and the * z-axis points towards the north pole. For other globes than earth of course the radii * can differ. */ @@ -72,7 +72,8 @@ public: */ glm::dvec3 geodeticSurfaceProjection(const glm::dvec3& p) const; - glm::dvec3 geodeticSurfaceNormalForGeocentricallyProjectedPoint(const glm::dvec3& p) const; + glm::dvec3 geodeticSurfaceNormalForGeocentricallyProjectedPoint( + const glm::dvec3& p) const; glm::dvec3 geodeticSurfaceNormal(Geodetic2 geodetic2) const; const glm::dvec3& radii() const; diff --git a/modules/globebrowsing/geometry/geodeticpatch.cpp b/modules/globebrowsing/geometry/geodeticpatch.cpp index 3171225df4..28a9d891b4 100644 --- a/modules/globebrowsing/geometry/geodeticpatch.cpp +++ b/modules/globebrowsing/geometry/geodeticpatch.cpp @@ -48,9 +48,14 @@ GeodeticPatch::GeodeticPatch(const GeodeticPatch& patch) {} GeodeticPatch::GeodeticPatch(const TileIndex& tileIndex) { - double deltaLat = (2 * glm::pi()) / (static_cast(1 << tileIndex.level)); - double deltaLon = (2 * glm::pi()) / (static_cast(1 << tileIndex.level)); - Geodetic2 nwCorner(glm::pi() / 2 - deltaLat * tileIndex.y, -glm::pi() + deltaLon * tileIndex.x); + double deltaLat = (2 * glm::pi()) / + (static_cast(1 << tileIndex.level)); + double deltaLon = (2 * glm::pi()) / + (static_cast(1 << tileIndex.level)); + Geodetic2 nwCorner( + glm::pi() / 2 - deltaLat * tileIndex.y, + -glm::pi() + deltaLon * tileIndex.x + ); _halfSize = Geodetic2(deltaLat / 2, deltaLon / 2); _center = Geodetic2(nwCorner.lat - _halfSize.lat, nwCorner.lon + _halfSize.lon); } @@ -139,7 +144,7 @@ Geodetic2 GeodeticPatch::clamp(const Geodetic2& p) const { // Normalize w.r.t. the center in order for the clamping to done correctly // - // Example: + // Example: // centerLat = 0 deg, halfSize.lat = 10 deg, pointLat = 330 deg // --> Just clamping pointLat would be clamp(330, -10, 10) = 10 // WRONG! // Instead, if we first normalize 330 deg around 0, we get -30 deg @@ -163,11 +168,11 @@ Geodetic2 GeodeticPatch::closestCorner(const Geodetic2& p) const { Ang latDiff = Ang::fromRadians(centerToPoint.lat).normalizeAround(Ang::ZERO); Ang lonDiff = Ang::fromRadians(centerToPoint.lon).normalizeAround(Ang::ZERO); - // If latDiff > 0 - // --> point p is north of the patch center + // If latDiff > 0 + // --> point p is north of the patch center // --> the closest corner to the point must be a northern one // --> set the corner's latitude coordinate to center.lat + halfSize.lat - // else + // else // --> set corner's latidude coordinate to center.lat - halfSize.lat double cornerLat = _center.lat + _halfSize.lat * (latDiff > Ang::ZERO ? 1 : -1); @@ -179,31 +184,31 @@ Geodetic2 GeodeticPatch::closestCorner(const Geodetic2& p) const { Geodetic2 GeodeticPatch::closestPoint(const Geodetic2& p) const { // This method finds the closest point on the patch, to the provided - // point p. As we are deali ng with latitude-longitude patches, distance in this + // point p. As we are deali ng with latitude-longitude patches, distance in this // context refers to great-circle distance. // (https://en.wikipedia.org/wiki/Great-circle_distance) // - // This uses a simple clamping approach to find the closest point on the - // patch. A naive castesian clamp is not sufficient for this purpose, + // This uses a simple clamping approach to find the closest point on the + // patch. A naive castesian clamp is not sufficient for this purpose, // as illustrated with an example below. // Example: (degrees are used for latidude, longitude) // patchCenter = (0,0), patchHalfSize = (45,45), point = (5, 170) // Note, the point and the patch are on opposite sides of the sphere // - // cartesian clamp: + // cartesian clamp: // --> clampedPointLat = clamp(5, -45, 45) = 5 // --> clampedPointLon = clamp(170, -45, 45) = 45 // --> result: (5, 45) - // --> closest point is actually (45, 45) + // --> closest point is actually (45, 45) // --> The error is significant - // - // This method simply adds an extra clamp on the latitude in these cases. In the + // + // This method simply adds an extra clamp on the latitude in these cases. In the // above example, that would be the following: // --> clampedPointLat = clamp(180 - 5, -45, 45) = 45 - // + // // Just doing this actually makes points returned from this methods being the - // true closest point, great-circle distance-wise. + // true closest point, great-circle distance-wise. using Ang = Angle; @@ -213,25 +218,30 @@ Geodetic2 GeodeticPatch::closestPoint(const Geodetic2& p) const { Ang pointLat = Ang::fromRadians(p.lat); Ang pointLon = Ang::fromRadians(p.lon); - // Normalize point with respect to center. This is done because the point + // Normalize point with respect to center. This is done because the point // will later be clamped. See LatLonPatch::clamp(const LatLon&) for explanation pointLat.normalizeAround(centerLat); pointLon.normalizeAround(centerLon); - // Calculate the longitud difference between center and point. We normalize around - // zero because we want the "shortest distance" difference, i.e the difference + // Calculate the longitud difference between center and point. We normalize around + // zero because we want the "shortest distance" difference, i.e the difference // should be in the interval [-180 deg, 180 deg] Ang centerToPointLon = (centerLon - pointLon).normalizeAround(Ang::ZERO); - // Calculate the longitudinal distance to the closest patch edge - Ang longitudeDistanceToClosestPatchEdge = centerToPointLon.abs() - Ang::fromRadians(_halfSize.lon); + // Calculate the longitudinal distance to the closest patch edge + Ang longitudeDistanceToClosestPatchEdge = + centerToPointLon.abs() - Ang::fromRadians(_halfSize.lon); // If the longitude distance to the closest patch edge is larger than 90 deg // the latitude will have to be clamped to its closest corner, as explained in // the example above. - double clampedLat = longitudeDistanceToClosestPatchEdge > Ang::QUARTER ? - clampedLat = glm::clamp((Ang::HALF - pointLat).normalizeAround(centerLat).asRadians(), minLat(), maxLat()) : - clampedLat = glm::clamp(pointLat.asRadians(), minLat(), maxLat()); + double clampedLat = + longitudeDistanceToClosestPatchEdge > Ang::QUARTER ? + glm::clamp( + (Ang::HALF - pointLat).normalizeAround(centerLat).asRadians(), + minLat(), + maxLat()) : + glm::clamp(pointLat.asRadians(), minLat(), maxLat()); // Longitude is just clamped normally double clampedLon = glm::clamp(pointLon.asRadians(), minLon(), maxLon()); diff --git a/modules/globebrowsing/geometry/geodeticpatch.h b/modules/globebrowsing/geometry/geodeticpatch.h index fda307db1f..a67a84dc71 100644 --- a/modules/globebrowsing/geometry/geodeticpatch.h +++ b/modules/globebrowsing/geometry/geodeticpatch.h @@ -48,7 +48,7 @@ public: GeodeticPatch(const TileIndex& tileIndex); void setCenter(const Geodetic2&); - void setHalfSize(const Geodetic2&); + void setHalfSize(const Geodetic2&); /** * Returns the latitude boundary which is closest to the equator diff --git a/modules/globebrowsing/globebrowsingmodule.cpp b/modules/globebrowsing/globebrowsingmodule.cpp index 2b62d3b820..b8fd5a5626 100644 --- a/modules/globebrowsing/globebrowsingmodule.cpp +++ b/modules/globebrowsing/globebrowsingmodule.cpp @@ -66,8 +66,9 @@ namespace { openspace::GlobeBrowsingModule::Capabilities parseSubDatasets(char** subDatasets, int nSubdatasets) { - // Idea: Iterate over the list of sublayers keeping a current layer and identify it - // by its number. If this number changes, we know that we have a new layer + // Idea: Iterate over the list of sublayers keeping a current layer and identify + // it by its number. If this number changes, we know that we have a new + // layer using Layer = openspace::GlobeBrowsingModule::Layer; std::vector result; @@ -104,7 +105,9 @@ namespace { currentLayer.url = value; } else { - LINFOC("GlobeBrowsingGUI", "Unknown subdataset identifier: " + identifier); + LINFOC( + "GlobeBrowsingGUI", "Unknown subdataset identifier: " + identifier + ); } } @@ -139,18 +142,18 @@ void GlobeBrowsingModule::internalInitialize() { // Convert from MB to Bytes GdalWrapper::create( 16ULL * 1024ULL * 1024ULL, // 16 MB - static_cast(CpuCap.installedMainMemory() * 0.25 * 1024 * 1024)); // 25% of total RAM + static_cast(CpuCap.installedMainMemory() * 0.25 * 1024 * 1024));// 25% addPropertySubOwner(GdalWrapper::ref()); #endif // GLOBEBROWSING_USE_GDAL }); // Render - OsEng.registerModuleCallback(OpenSpaceEngine::CallbackOption::Render, [&]{ + OsEng.registerModuleCallback(OpenSpaceEngine::CallbackOption::Render, [&] { _tileCache->update(); }); // Deinitialize - OsEng.registerModuleCallback(OpenSpaceEngine::CallbackOption::Deinitialize, [&]{ + OsEng.registerModuleCallback(OpenSpaceEngine::CallbackOption::Deinitialize, [&] { #ifdef GLOBEBROWSING_USE_GDAL GdalWrapper::ref().destroy(); #endif // GLOBEBROWSING_USE_GDAL @@ -169,21 +172,35 @@ void GlobeBrowsingModule::internalInitialize() { // Register TileProvider classes fTileProvider->registerClass( - layergroupid::LAYER_TYPE_NAMES[static_cast(layergroupid::TypeID::DefaultTileLayer)]); + layergroupid::LAYER_TYPE_NAMES[static_cast( + layergroupid::TypeID::DefaultTileLayer + )]); fTileProvider->registerClass( - layergroupid::LAYER_TYPE_NAMES[static_cast(layergroupid::TypeID::SingleImageTileLayer)]); + layergroupid::LAYER_TYPE_NAMES[static_cast( + layergroupid::TypeID::SingleImageTileLayer + )]); #ifdef GLOBEBROWSING_USE_GDAL fTileProvider->registerClass( - layergroupid::LAYER_TYPE_NAMES[static_cast(layergroupid::TypeID::TemporalTileLayer)]); + layergroupid::LAYER_TYPE_NAMES[static_cast( + layergroupid::TypeID::TemporalTileLayer + )]); #endif // GLOBEBROWSING_USE_GDAL fTileProvider->registerClass( - layergroupid::LAYER_TYPE_NAMES[static_cast(layergroupid::TypeID::TileIndexTileLayer)]); + layergroupid::LAYER_TYPE_NAMES[static_cast( + layergroupid::TypeID::TileIndexTileLayer + )]); fTileProvider->registerClass( - layergroupid::LAYER_TYPE_NAMES[static_cast(layergroupid::TypeID::SizeReferenceTileLayer)]); + layergroupid::LAYER_TYPE_NAMES[static_cast( + layergroupid::TypeID::SizeReferenceTileLayer + )]); fTileProvider->registerClass( - layergroupid::LAYER_TYPE_NAMES[static_cast(layergroupid::TypeID::ByLevelTileLayer)]); + layergroupid::LAYER_TYPE_NAMES[static_cast( + layergroupid::TypeID::ByLevelTileLayer + )]); fTileProvider->registerClass( - layergroupid::LAYER_TYPE_NAMES[static_cast(layergroupid::TypeID::ByIndexTileLayer)]); + layergroupid::LAYER_TYPE_NAMES[static_cast( + layergroupid::TypeID::ByIndexTileLayer + )]); FactoryManager::ref().addFactory(std::move(fTileProvider)); } @@ -381,7 +398,8 @@ void GlobeBrowsingModule::goToGeodetic3(Camera& camera, globebrowsing::Geodetic3 glm::dvec3 positionModelSpace = globe->ellipsoid().cartesianPosition(geo3); glm::dmat4 modelTransform = globe->modelTransform(); - glm::dvec3 positionWorldSpace = glm::dvec3(modelTransform * glm::dvec4(positionModelSpace, 1.0)); + glm::dvec3 positionWorldSpace = glm::dvec3(modelTransform * + glm::dvec4(positionModelSpace, 1.0)); camera.setPositionVec3(positionWorldSpace); if (resetCameraDirection) { @@ -389,7 +407,8 @@ void GlobeBrowsingModule::goToGeodetic3(Camera& camera, globebrowsing::Geodetic3 } } -void GlobeBrowsingModule::resetCameraDirection(Camera& camera, globebrowsing::Geodetic2 geo2) +void GlobeBrowsingModule::resetCameraDirection(Camera& camera, + globebrowsing::Geodetic2 geo2) { using namespace globebrowsing; @@ -410,7 +429,8 @@ void GlobeBrowsingModule::resetCameraDirection(Camera& camera, globebrowsing::Ge glm::dvec3 lookUpWorldSpace = glm::dmat3(modelTransform) * lookUpModelSpace; // Lookat vector - glm::dvec3 lookAtWorldSpace = glm::dvec3(modelTransform * glm::dvec4(positionModelSpace, 1.0)); + glm::dvec3 lookAtWorldSpace = glm::dvec3(modelTransform * + glm::dvec4(positionModelSpace, 1.0)); // Eye position glm::dvec3 eye = camera.positionVec3(); @@ -459,10 +479,13 @@ std::string GlobeBrowsingModule::layerGroupNamesList() { std::string GlobeBrowsingModule::layerTypeNamesList() { std::string listLayerTypes; for (int i = 0; i < globebrowsing::layergroupid::NUM_LAYER_TYPES - 1; ++i) { - listLayerTypes += std::string(globebrowsing::layergroupid::LAYER_TYPE_NAMES[i]) + ", "; + listLayerTypes += std::string(globebrowsing::layergroupid::LAYER_TYPE_NAMES[i]) + + ", "; } - listLayerTypes += - " and " + std::string(globebrowsing::layergroupid::LAYER_TYPE_NAMES[globebrowsing::layergroupid::NUM_LAYER_TYPES - 1]); + listLayerTypes += " and " + + std::string(globebrowsing::layergroupid::LAYER_TYPE_NAMES[ + globebrowsing::layergroupid::NUM_LAYER_TYPES - 1 + ]); return listLayerTypes; } @@ -471,16 +494,11 @@ std::string GlobeBrowsingModule::layerTypeNamesList() { void GlobeBrowsingModule::loadWMSCapabilities(std::string name, std::string globe, std::string url) { - auto downloadFunction = [](const std::string& url) { + auto downloadFunction = [](const std::string& downloadUrl) { GDALDatasetH dataset = GDALOpen( - url.c_str(), + downloadUrl.c_str(), GA_ReadOnly ); - // GDAL_OF_READONLY | GDAL_OF_RASTER | GDAL_OF_VERBOSE_ERROR, - // nullptr, - // nullptr, - // nullptr - //); char** subDatasets = GDALGetMetadata(dataset, "SUBDATASETS"); int nSubdatasets = CSLCount(subDatasets); @@ -489,7 +507,11 @@ void GlobeBrowsingModule::loadWMSCapabilities(std::string name, std::string glob return cap; }; - _inFlightCapabilitiesMap[name] = std::async(std::launch::async, downloadFunction, url); + _inFlightCapabilitiesMap[name] = std::async( + std::launch::async, + downloadFunction, + url + ); _urlList.emplace(std::move(globe), UrlInfo{ std::move(name), std::move(url) }); } diff --git a/modules/globebrowsing/globebrowsingmodule_lua.inl b/modules/globebrowsing/globebrowsingmodule_lua.inl index 7900c3f72e..85c6e6d040 100644 --- a/modules/globebrowsing/globebrowsingmodule_lua.inl +++ b/modules/globebrowsing/globebrowsingmodule_lua.inl @@ -84,7 +84,10 @@ int addLayer(lua_State* L) { return 0; } - globe->layerManager()->addLayer(groupID, d); + std::shared_ptr layer = globe->layerManager()->addLayer(groupID, d); + if (layer) { + layer->initialize(); + } return 0; } @@ -179,9 +182,8 @@ int getGeoPosition(lua_State* L) { if (nArguments != 0) { return luaL_error(L, "Expected %i arguments, got %i", 0, nArguments); } - - RenderableGlobe* globe = - OsEng.moduleEngine().module()->castFocusNodeRenderableToGlobe(); + GlobeBrowsingModule* module = OsEng.moduleEngine().module(); + RenderableGlobe* globe = module->castFocusNodeRenderableToGlobe(); if (!globe) { return luaL_error(L, "Focus node must be a RenderableGlobe"); } @@ -194,8 +196,11 @@ int getGeoPosition(lua_State* L) { SurfacePositionHandle posHandle = globe->calculateSurfacePositionHandle( cameraPositionModelSpace); - Geodetic2 geo2 = globe->ellipsoid().cartesianToGeodetic2(posHandle.centerToReferenceSurface); - double altitude = glm::length(cameraPositionModelSpace - posHandle.centerToReferenceSurface); + Geodetic2 geo2 = globe->ellipsoid().cartesianToGeodetic2( + posHandle.centerToReferenceSurface + ); + double altitude = glm::length(cameraPositionModelSpace - + posHandle.centerToReferenceSurface); lua_pushnumber(L, Angle::fromRadians(geo2.lat).asDegrees()); lua_pushnumber(L, Angle::fromRadians(geo2.lon).asDegrees()); diff --git a/modules/globebrowsing/globes/chunkedlodglobe.cpp b/modules/globebrowsing/globes/chunkedlodglobe.cpp index 681263155b..a6ed62ceeb 100644 --- a/modules/globebrowsing/globes/chunkedlodglobe.cpp +++ b/modules/globebrowsing/globes/chunkedlodglobe.cpp @@ -80,7 +80,7 @@ ChunkedLodGlobe::ChunkedLodGlobe(const RenderableGlobe& owner, size_t segmentsPe AABB3(glm::vec3(-1, -1, 0), glm::vec3(1, 1, 1e35))) ); - _chunkEvaluatorByAvailableTiles = + _chunkEvaluatorByAvailableTiles = std::make_unique(); _chunkEvaluatorByProjectedArea = std::make_unique(); @@ -133,12 +133,13 @@ int ChunkedLodGlobe::getDesiredLevel( desiredLevel = _chunkEvaluatorByDistance->getDesiredLevel(chunk, renderData); } - int desiredLevelByAvailableData = _chunkEvaluatorByAvailableTiles->getDesiredLevel( + int levelByAvailableData = _chunkEvaluatorByAvailableTiles->getDesiredLevel( chunk, renderData ); - if (desiredLevelByAvailableData != chunklevelevaluator::Evaluator::UnknownDesiredLevel && - _owner.debugProperties().limitLevelByAvailableData) { - desiredLevel = glm::min(desiredLevel, desiredLevelByAvailableData); + if (levelByAvailableData != chunklevelevaluator::Evaluator::UnknownDesiredLevel && + _owner.debugProperties().limitLevelByAvailableData) + { + desiredLevel = glm::min(desiredLevel, levelByAvailableData); } desiredLevel = glm::clamp(desiredLevel, minSplitDepth, maxSplitDepth); @@ -291,7 +292,8 @@ void ChunkedLodGlobe::render(const RenderData& data, RendererTasks&) { // Calculate the MVP matrix glm::dmat4 viewTransform = glm::dmat4(data.camera.combinedViewMatrix()); - glm::dmat4 vp = glm::dmat4(data.camera.sgctInternal.projectionMatrix()) * viewTransform; + glm::dmat4 vp = glm::dmat4(data.camera.sgctInternal.projectionMatrix()) * + viewTransform; glm::dmat4 mvp = vp * _owner.modelTransform(); // Render function @@ -315,8 +317,8 @@ void ChunkedLodGlobe::render(const RenderData& data, RendererTasks&) { //_rightRoot->reverseBreadthFirst(renderJob); auto duration2 = std::chrono::system_clock::now().time_since_epoch(); - auto millis2 = std::chrono::duration_cast(duration2).count(); - stats.i["chunk globe render time"] = millis2 - millis; + auto ms2 = std::chrono::duration_cast(duration2).count(); + stats.i["chunk globe render time"] = ms2 - millis; } void ChunkedLodGlobe::debugRenderChunk(const Chunk& chunk, const glm::dmat4& mvp) const { diff --git a/modules/globebrowsing/globes/chunkedlodglobe.h b/modules/globebrowsing/globes/chunkedlodglobe.h index 3ccad36387..872659ae9c 100644 --- a/modules/globebrowsing/globes/chunkedlodglobe.h +++ b/modules/globebrowsing/globes/chunkedlodglobe.h @@ -83,7 +83,7 @@ public: * lower than the current level of the Chunkss * TileIndex. If the desired level is higher than that of the * Chunk, it wants to split. If it is lower, it wants to merge with - * its siblings. + * its siblings. */ int getDesiredLevel(const Chunk& chunk, const RenderData& renderData) const; diff --git a/modules/globebrowsing/globes/pointglobe.cpp b/modules/globebrowsing/globes/pointglobe.cpp index 581f0345de..630cbd300c 100644 --- a/modules/globebrowsing/globes/pointglobe.cpp +++ b/modules/globebrowsing/globes/pointglobe.cpp @@ -37,7 +37,7 @@ namespace { static const openspace::properties::Property::PropertyInfo IntensityClampInfo = { "IntensityClamp", "Intensity clamp", - "" + "" }; static const openspace::properties::Property::PropertyInfo LightIntensityInfo = { @@ -95,7 +95,7 @@ void PointGlobe::initialize() { // Position at location 0 glEnableVertexAttribArray(0); - glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(glm::vec2), 0); + glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(glm::vec2), nullptr); glBindVertexArray(0); } @@ -138,18 +138,19 @@ void PointGlobe::render(const RenderData& data, RendererTasks&) { // Model transform and view transform needs to be in double precision glm::dmat4 modelTransform = glm::translate(glm::dmat4(1.0), bodyPosition) * // Translation - glm::inverse(rotationTransform) * + glm::inverse(rotationTransform) * scaleTransform; // Scale glm::dmat4 modelViewTransform = data.camera.combinedViewMatrix() * modelTransform; - //glm::vec3 directionToSun = glm::normalize(glm::vec3(0) - glm::vec3(bodyPosition)); - //glm::vec3 directionToSunViewSpace = glm::mat3(data.camera.combinedViewMatrix()) * directionToSun; _programObject->setUniform("lightIntensityClamped", lightIntensityClamped); //_programObject->setUniform("lightOverflow", lightOverflow); //_programObject->setUniform("directionToSunViewSpace", directionToSunViewSpace); _programObject->setUniform("modelViewTransform", glm::mat4(modelViewTransform)); - _programObject->setUniform("projectionTransform", data.camera.sgctInternal.projectionMatrix()); + _programObject->setUniform( + "projectionTransform", + data.camera.sgctInternal.projectionMatrix() + ); glBlendFunc(GL_SRC_ALPHA, GL_ONE); diff --git a/modules/globebrowsing/globes/renderableglobe.cpp b/modules/globebrowsing/globes/renderableglobe.cpp index 1b5ff30d84..68ea6e4d88 100644 --- a/modules/globebrowsing/globes/renderableglobe.cpp +++ b/modules/globebrowsing/globes/renderableglobe.cpp @@ -173,11 +173,11 @@ namespace openspace::globebrowsing { RenderableGlobe::RenderableGlobe(const ghoul::Dictionary& dictionary) : Renderable(dictionary) , _debugProperties({ - BoolProperty(SaveOrThrowInfo, false), + BoolProperty(SaveOrThrowInfo, false), BoolProperty(ShowChunkEdgeInfo, false), BoolProperty(ShowChunkBoundsInfo, false), BoolProperty(ShowChunkAABBInfo, false), - BoolProperty(HeightResolutionInfo, false), + BoolProperty(HeightResolutionInfo, false), BoolProperty(HeightIntensityInfo, false), BoolProperty(FrustumCullingInfo, true), BoolProperty(HorizonCullingInfo, true), @@ -353,17 +353,24 @@ RenderableGlobe::RenderableGlobe(const ghoul::Dictionary& dictionary) } } } +} + +void RenderableGlobe::initializeGL() { + _layerManager->initialize(); + + _layerManager->update(); + + _distanceSwitch.initializeGL(); + // Recompile the shaders directly so that it is not done the first time the render // function is called. _chunkedLodGlobe->recompileShaders(); } -void RenderableGlobe::initialize() { - _distanceSwitch.initialize(); -} +void RenderableGlobe::deinitializeGL() { + _distanceSwitch.deinitializeGL(); -void RenderableGlobe::deinitialize() { - _distanceSwitch.deinitialize(); + _layerManager->deinitialize(); } bool RenderableGlobe::isReady() const { @@ -462,7 +469,7 @@ const std::shared_ptr RenderableGlobe::savedCamera() const { } SurfacePositionHandle RenderableGlobe::calculateSurfacePositionHandle( - const glm::dvec3& targetModelSpace) + const glm::dvec3& targetModelSpace) { glm::dvec3 centerToEllipsoidSurface = _ellipsoid.geodeticSurfaceProjection(targetModelSpace); @@ -490,7 +497,7 @@ SurfacePositionHandle RenderableGlobe::calculateSurfacePositionHandle( }; } -void RenderableGlobe::setSaveCamera(std::shared_ptr camera) { +void RenderableGlobe::setSaveCamera(std::shared_ptr camera) { _savedCamera = camera; } diff --git a/modules/globebrowsing/globes/renderableglobe.h b/modules/globebrowsing/globes/renderableglobe.h index e923b3939c..fd4aceb2f1 100644 --- a/modules/globebrowsing/globes/renderableglobe.h +++ b/modules/globebrowsing/globes/renderableglobe.h @@ -51,7 +51,7 @@ class LayerManager; * algorithm for rendering. * The renderable uses a DistanceSwitch to determine if the renderable - * should be rendered. + * should be rendered. */ class RenderableGlobe : public Renderable { public: @@ -100,8 +100,8 @@ public: RenderableGlobe(const ghoul::Dictionary& dictionary); ~RenderableGlobe() = default; - void initialize() override; - void deinitialize() override; + void initializeGL() override; + void deinitializeGL() override; bool isReady() const override; void render(const RenderData& data, RendererTasks& rendererTask) override; @@ -126,7 +126,7 @@ public: void setSaveCamera(std::shared_ptr camera); virtual SurfacePositionHandle calculateSurfacePositionHandle( - const glm::dvec3& targetModelSpace) override; + const glm::dvec3& targetModelSpace) override; private: // Globes. These are renderables inserted in a distance switch so that the heavier diff --git a/modules/globebrowsing/meshes/basicgrid.h b/modules/globebrowsing/meshes/basicgrid.h index efcceff7c1..4edc91bcb5 100644 --- a/modules/globebrowsing/meshes/basicgrid.h +++ b/modules/globebrowsing/meshes/basicgrid.h @@ -45,7 +45,7 @@ public: * \param useNormals determines whether or not to upload any vertex normal data * to the GPU. */ - BasicGrid(unsigned int xSegments, unsigned int ySegments, + BasicGrid(unsigned int xSegments, unsigned int ySegments, TriangleSoup::Positions usePositions, TriangleSoup::TextureCoordinates useTextureCoordinates, TriangleSoup::Normals useNormals); diff --git a/modules/globebrowsing/meshes/grid.h b/modules/globebrowsing/meshes/grid.h index 8c4372e1c6..05444c26f7 100644 --- a/modules/globebrowsing/meshes/grid.h +++ b/modules/globebrowsing/meshes/grid.h @@ -62,9 +62,9 @@ public: protected: /** - * Should return the indices of vertices for a grid with size xSegments * - * ySegments. Where the number of vertices in each direction is the number - * of segments + 1. + * Should return the indices of vertices for a grid with size xSegments + * ySegments. Where the number of vertices in each direction is the + * number of segments + 1. */ virtual std::vector createElements(int xSegments, int ySegments) = 0; @@ -85,8 +85,8 @@ protected: /** * Should return the normals of vertices for a grid with size xSegments * - * ySegments. Where the number of vertices in each direction is the number - * of segments + 1. + * ySegments. Where the number of vertices in each direction is the + * number of segments + 1. */ virtual std::vector createNormals(int xSegments, int ySegments) = 0; diff --git a/modules/globebrowsing/meshes/skirtedgrid.cpp b/modules/globebrowsing/meshes/skirtedgrid.cpp index e3b194308d..bead0e6e66 100644 --- a/modules/globebrowsing/meshes/skirtedgrid.cpp +++ b/modules/globebrowsing/meshes/skirtedgrid.cpp @@ -45,7 +45,9 @@ SkirtedGrid::SkirtedGrid(unsigned int xSegments, unsigned int ySegments, _geometry->setVertexPositions(createPositions(_xSegments, _ySegments)); } if (useTextureCoordinates) { - _geometry->setVertexTextureCoordinates(createTextureCoordinates(_xSegments, _ySegments)); + _geometry->setVertexTextureCoordinates( + createTextureCoordinates(_xSegments, _ySegments) + ); } if (useNormals) { _geometry->setVertexNormals(createNormals(_xSegments, _ySegments)); diff --git a/modules/globebrowsing/meshes/trianglesoup.cpp b/modules/globebrowsing/meshes/trianglesoup.cpp index e83b9d4506..428aa3ed98 100644 --- a/modules/globebrowsing/meshes/trianglesoup.cpp +++ b/modules/globebrowsing/meshes/trianglesoup.cpp @@ -55,10 +55,10 @@ void TriangleSoup::setVertexPositions(std::vector positions) { _gpuDataNeedUpdate = true; _vertexData.resize(positions.size()); for (size_t i = 0; i < positions.size(); i++) { - _vertexData[i].position[0] = static_cast(positions[i].x); - _vertexData[i].position[1] = static_cast(positions[i].y); - _vertexData[i].position[2] = static_cast(positions[i].z); - _vertexData[i].position[3] = static_cast(positions[i].w); + _vertexData[i].position[0] = positions[i].x; + _vertexData[i].position[1] = positions[i].y; + _vertexData[i].position[2] = positions[i].z; + _vertexData[i].position[3] = positions[i].w; } } @@ -67,8 +67,8 @@ void TriangleSoup::setVertexTextureCoordinates(std::vector textures) _gpuDataNeedUpdate = true; _vertexData.resize(textures.size()); for (size_t i = 0; i < textures.size(); i++) { - _vertexData[i].texture[0] = static_cast(textures[i].s); - _vertexData[i].texture[1] = static_cast(textures[i].t); + _vertexData[i].texture[0] = textures[i].s; + _vertexData[i].texture[1] = textures[i].t; } } @@ -77,9 +77,9 @@ void TriangleSoup::setVertexNormals(std::vector normals) { _gpuDataNeedUpdate = true; _vertexData.resize(normals.size()); for (size_t i = 0; i < normals.size(); i++) { - _vertexData[i].normal[0] = static_cast(normals[i].x); - _vertexData[i].normal[1] = static_cast(normals[i].y); - _vertexData[i].normal[2] = static_cast(normals[i].z); + _vertexData[i].normal[0] = normals[i].x; + _vertexData[i].normal[1] = normals[i].y; + _vertexData[i].normal[2] = normals[i].z; } } diff --git a/modules/globebrowsing/other/distanceswitch.cpp b/modules/globebrowsing/other/distanceswitch.cpp index 043dc78967..4d5cbb08e9 100644 --- a/modules/globebrowsing/other/distanceswitch.cpp +++ b/modules/globebrowsing/other/distanceswitch.cpp @@ -37,6 +37,13 @@ bool DistanceSwitch::initialize() { return true; } +bool DistanceSwitch::initializeGL() { + for (unsigned int i = 0; i < _renderables.size(); ++i) { + _renderables[i]->initializeGL(); + } + return true; +} + bool DistanceSwitch::deinitialize() { for (unsigned int i = 0; i < _renderables.size(); ++i) { _renderables[i]->deinitialize(); @@ -44,6 +51,13 @@ bool DistanceSwitch::deinitialize() { return true; } +bool DistanceSwitch::deinitializeGL() { + for (unsigned int i = 0; i < _renderables.size(); ++i) { + _renderables[i]->deinitializeGL(); + } + return true; +} + void DistanceSwitch::render(const RenderData& data, RendererTasks& tasks) { const double distanceToCamera = distance(data.camera.positionVec3(), data.modelTransform.translation); diff --git a/modules/globebrowsing/other/distanceswitch.h b/modules/globebrowsing/other/distanceswitch.h index 45d9a6bd3c..810c1f71fd 100644 --- a/modules/globebrowsing/other/distanceswitch.h +++ b/modules/globebrowsing/other/distanceswitch.h @@ -38,7 +38,7 @@ namespace openspace { namespace openspace::globebrowsing { /** - * Selects a specific Renderable to be used for rendering, based on distance to the + * Selects a specific Renderable to be used for rendering, based on distance to the * camera */ class DistanceSwitch { @@ -46,10 +46,12 @@ public: ~DistanceSwitch(); bool initialize(); + bool initializeGL(); bool deinitialize(); + bool deinitializeGL(); /** - * Picks the first Renderable with the associated maxDistance greater than the + * Picks the first Renderable with the associated maxDistance greater than the * current distance to the camera */ void render(const RenderData& data, RendererTasks& rendererTask); diff --git a/modules/globebrowsing/other/lruthreadpool.h b/modules/globebrowsing/other/lruthreadpool.h index 99ea554d47..359c74349c 100644 --- a/modules/globebrowsing/other/lruthreadpool.h +++ b/modules/globebrowsing/other/lruthreadpool.h @@ -43,7 +43,7 @@ template class LRUThreadPool; template class LRUThreadPoolWorker { -public: +public: LRUThreadPoolWorker(LRUThreadPool& pool); void operator()(); private: diff --git a/modules/globebrowsing/other/pixelbuffer.cpp b/modules/globebrowsing/other/pixelbuffer.cpp index 5c313cd4a0..c34050495a 100644 --- a/modules/globebrowsing/other/pixelbuffer.cpp +++ b/modules/globebrowsing/other/pixelbuffer.cpp @@ -52,7 +52,9 @@ void* PixelBuffer::mapBuffer(Access access) { return dataPtr; } -void* PixelBuffer::mapBufferRange(GLintptr offset, GLsizeiptr length, BufferAccessMask access) { +void* PixelBuffer::mapBufferRange(GLintptr offset, GLsizeiptr length, + BufferAccessMask access) +{ void* dataPtr = glMapBufferRange(GL_PIXEL_UNPACK_BUFFER, offset, length, access); _isMapped = dataPtr ? true : false; return dataPtr; diff --git a/modules/globebrowsing/other/pixelbuffer.h b/modules/globebrowsing/other/pixelbuffer.h index 7cde0ab2ff..4765fbf2eb 100644 --- a/modules/globebrowsing/other/pixelbuffer.h +++ b/modules/globebrowsing/other/pixelbuffer.h @@ -116,7 +116,7 @@ public: void unbind(); /** - * \returns true of the buffer is mapped, otherwise false + * \returns true of the buffer is mapped, otherwise false */ bool isMapped() const; diff --git a/modules/globebrowsing/other/pixelbuffercontainer.h b/modules/globebrowsing/other/pixelbuffercontainer.h index 03259c6d88..f5e617aaec 100644 --- a/modules/globebrowsing/other/pixelbuffercontainer.h +++ b/modules/globebrowsing/other/pixelbuffercontainer.h @@ -92,8 +92,8 @@ public: bool unMapBuffer(KeyType key); /** - * \returns the GLuint id of a pixel buffer identified by key - * if it currently is mapped. + * \returns the GLuint id of a pixel buffer identified by + * key if it currently is mapped. */ GLuint idOfMappedBuffer(KeyType key); private: diff --git a/modules/globebrowsing/rendering/chunkrenderer.cpp b/modules/globebrowsing/rendering/chunkrenderer.cpp index a4b9afa6bf..7f5711961f 100644 --- a/modules/globebrowsing/rendering/chunkrenderer.cpp +++ b/modules/globebrowsing/rendering/chunkrenderer.cpp @@ -43,7 +43,7 @@ namespace openspace::globebrowsing { ChunkRenderer::ChunkRenderer(std::shared_ptr grid, std::shared_ptr layerManager) : _grid(grid) - ,_layerManager(layerManager) + , _layerManager(layerManager) { _globalLayerShaderManager = std::make_shared( "GlobalChunkedLodPatch", @@ -235,7 +235,7 @@ void ChunkRenderer::setCommonUniforms(ghoul::opengl::ProgramObject& programObjec } if (chunk.owner().generalProperties().useAccurateNormals && - !_layerManager->layerGroup(layergroupid::HeightLayers).activeLayers().empty()) + !_layerManager->layerGroup(layergroupid::HeightLayers).activeLayers().empty()) { glm::dvec3 corner00 = chunk.owner().ellipsoid().cartesianSurfacePosition( chunk.surfacePatch().getCorner(Quad::SOUTH_WEST)); @@ -423,9 +423,10 @@ void ChunkRenderer::renderChunkLocally(const Chunk& chunk, const RenderData& dat programObject->setUniform("patchNormalCameraSpace", patchNormalCameraSpace); - // TODO (JCC): Enable the right normal for displaced points in the patch - programObject->setUniform("patchNormalModelSpace", glm::normalize(patchNormalModelSpace)); - programObject->setUniform("projectionTransform", data.camera.sgctInternal.projectionMatrix()); + programObject->setUniform( + "projectionTransform", + data.camera.sgctInternal.projectionMatrix() + ); if (_layerManager->layerGroup(layergroupid::HeightLayers).activeLayers().size() > 0) { // Apply an extra scaling to the height if the object is scaled diff --git a/modules/globebrowsing/rendering/gpu/gpuchunktile.h b/modules/globebrowsing/rendering/gpu/gpuchunktile.h index e94536ecd7..7d5c1d3c3b 100644 --- a/modules/globebrowsing/rendering/gpu/gpuchunktile.h +++ b/modules/globebrowsing/rendering/gpu/gpuchunktile.h @@ -45,15 +45,15 @@ public: /** * Sets the value of ChunkTile to its corresponding - * GPU struct. OBS! Users must ensure bind has been + * GPU struct. OBS! Users must ensure bind has been * called before setting using this method. */ void setValue(ghoul::opengl::ProgramObject* programObject, const ChunkTile& chunkTile); - /** - * Binds GLSL variables with identifiers starting with - * nameBase within the provided shader program with this object. + /** + * Binds GLSL variables with identifiers starting with + * nameBase within the provided shader program with this object. * After this method has been called, users may invoke setValue. */ void bind(ghoul::opengl::ProgramObject* programObject, const std::string& nameBase); diff --git a/modules/globebrowsing/rendering/gpu/gpuchunktilepile.h b/modules/globebrowsing/rendering/gpu/gpuchunktilepile.h index be896aa15a..a7e1bf15a2 100644 --- a/modules/globebrowsing/rendering/gpu/gpuchunktilepile.h +++ b/modules/globebrowsing/rendering/gpu/gpuchunktilepile.h @@ -45,18 +45,18 @@ public: /** * Sets the value of ChunkTilePile to its corresponding - * GPU struct. OBS! Users must ensure bind has been + * GPU struct. OBS! Users must ensure bind has been * called before setting using this method. */ void setValue(ghoul::opengl::ProgramObject* programObject, const ChunkTilePile& chunkTilePile); - /** - * Binds this object with GLSL variables with identifiers starting + /** + * Binds this object with GLSL variables with identifiers starting * with nameBase within the provided shader program. * After this method has been called, users may invoke setValue. */ - void bind(ghoul::opengl::ProgramObject* programObject, const std::string& nameBase, + void bind(ghoul::opengl::ProgramObject* programObject, const std::string& nameBase, int pileSize); /** * Deactivates any TextureUnits assigned by this object. diff --git a/modules/globebrowsing/rendering/gpu/gpuheightlayer.h b/modules/globebrowsing/rendering/gpu/gpuheightlayer.h index c0b25b308f..48d61db381 100644 --- a/modules/globebrowsing/rendering/gpu/gpuheightlayer.h +++ b/modules/globebrowsing/rendering/gpu/gpuheightlayer.h @@ -49,14 +49,14 @@ public: /** * Sets the value of Layer to its corresponding - * GPU struct. OBS! Users must ensure bind has been + * GPU struct. OBS! Users must ensure bind has been * called before setting using this method. */ virtual void setValue(ghoul::opengl::ProgramObject* programObject, const Layer& layer, const TileIndex& tileIndex, int pileSize) override; - /** - * Binds this object with GLSL variables with identifiers starting + /** + * Binds this object with GLSL variables with identifiers starting * with nameBase within the provided shader program. * After this method has been called, users may invoke setValue. */ diff --git a/modules/globebrowsing/rendering/gpu/gpulayer.cpp b/modules/globebrowsing/rendering/gpu/gpulayer.cpp index 6168fa3ae5..7ce7541e3c 100644 --- a/modules/globebrowsing/rendering/gpu/gpulayer.cpp +++ b/modules/globebrowsing/rendering/gpu/gpulayer.cpp @@ -46,7 +46,10 @@ void GPULayer::setValue(ghoul::opengl::ProgramObject* programObject, const Layer ChunkTilePile chunkTilePile = layer.getChunkTilePile(tileIndex, pileSize); gpuChunkTilePile.setValue(programObject, chunkTilePile); paddingStartOffset.setValue(programObject, layer.tilePixelStartOffset()); - paddingSizeDifference.setValue(programObject, layer.tilePixelSizeDifference()); + paddingSizeDifference.setValue( + programObject, + layer.tilePixelSizeDifference() + ); break; } case layergroupid::TypeID::SolidColor: @@ -60,8 +63,16 @@ void GPULayer::setValue(ghoul::opengl::ProgramObject* programObject, const Layer void GPULayer::bind(ghoul::opengl::ProgramObject* programObject, const Layer& layer, const std::string& nameBase, int pileSize) { - gpuRenderSettings.bind(layer.renderSettings(), programObject, nameBase + "settings."); - gpuLayerAdjustment.bind(layer.layerAdjustment(), programObject, nameBase + "adjustment."); + gpuRenderSettings.bind( + layer.renderSettings(), + programObject, + nameBase + "settings." + ); + gpuLayerAdjustment.bind( + layer.layerAdjustment(), + programObject, + nameBase + "adjustment." + ); switch (layer.type()) { // Intentional fall through. Same for all tile layers @@ -74,7 +85,10 @@ void GPULayer::bind(ghoul::opengl::ProgramObject* programObject, const Layer& la case layergroupid::TypeID::ByLevelTileLayer: { gpuChunkTilePile.bind(programObject, nameBase + "pile.", pileSize); paddingStartOffset.bind(programObject, nameBase + "padding.startOffset"); - paddingSizeDifference.bind(programObject, nameBase + "padding.sizeDifference"); + paddingSizeDifference.bind( + programObject, + nameBase + "padding.sizeDifference" + ); break; } case layergroupid::TypeID::SolidColor: diff --git a/modules/globebrowsing/rendering/gpu/gpulayer.h b/modules/globebrowsing/rendering/gpu/gpulayer.h index 6e4f737a9e..7603544dde 100644 --- a/modules/globebrowsing/rendering/gpu/gpulayer.h +++ b/modules/globebrowsing/rendering/gpu/gpulayer.h @@ -48,14 +48,14 @@ public: /** * Sets the value of Layer to its corresponding - * GPU struct. OBS! Users must ensure bind has been + * GPU struct. OBS! Users must ensure bind has been * called before setting using this method. */ virtual void setValue(ghoul::opengl::ProgramObject* programObject, const Layer& layer, const TileIndex& tileIndex, int pileSize); - /** - * Binds this object with GLSL variables with identifiers starting + /** + * Binds this object with GLSL variables with identifiers starting * with nameBase within the provided shader program. * After this method has been called, users may invoke setValue. */ diff --git a/modules/globebrowsing/rendering/gpu/gpulayeradjustment.cpp b/modules/globebrowsing/rendering/gpu/gpulayeradjustment.cpp index 7634e693fe..a74b2f9217 100644 --- a/modules/globebrowsing/rendering/gpu/gpulayeradjustment.cpp +++ b/modules/globebrowsing/rendering/gpu/gpulayeradjustment.cpp @@ -34,8 +34,14 @@ void GPULayerAdjustment::setValue(ghoul::opengl::ProgramObject* programObject, case layergroupid::AdjustmentTypeID::None: break; case layergroupid::AdjustmentTypeID::ChromaKey: { - gpuChromaKeyColor.setValue(programObject, layerAdjustment.chromaKeyColor.value()); - gpuChromaKeyTolerance.setValue(programObject, layerAdjustment.chromaKeyTolerance.value()); + gpuChromaKeyColor.setValue( + programObject, + layerAdjustment.chromaKeyColor.value() + ); + gpuChromaKeyTolerance.setValue( + programObject, + layerAdjustment.chromaKeyTolerance.value() + ); break; } case layergroupid::AdjustmentTypeID::TransferFunction: diff --git a/modules/globebrowsing/rendering/gpu/gpulayergroup.cpp b/modules/globebrowsing/rendering/gpu/gpulayergroup.cpp index f73e2ab2ec..dc55b69019 100644 --- a/modules/globebrowsing/rendering/gpu/gpulayergroup.cpp +++ b/modules/globebrowsing/rendering/gpu/gpulayergroup.cpp @@ -58,7 +58,7 @@ void GPULayerGroup::bind(ghoul::opengl::ProgramObject* programObject, for (size_t i = 0; i < _gpuActiveLayers.size(); ++i) { // should maybe a proper GPULayer factory _gpuActiveLayers[i] = (category == layergroupid::GroupID::HeightLayers) ? - std::make_unique() : + std::make_unique() : std::make_unique(); std::string nameExtension = "[" + std::to_string(i) + "]."; _gpuActiveLayers[i]->bind( diff --git a/modules/globebrowsing/rendering/gpu/gpulayergroup.h b/modules/globebrowsing/rendering/gpu/gpulayergroup.h index d94c9daa32..ff186929be 100644 --- a/modules/globebrowsing/rendering/gpu/gpulayergroup.h +++ b/modules/globebrowsing/rendering/gpu/gpulayergroup.h @@ -55,14 +55,14 @@ public: /** * Sets the value of LayerGroup to its corresponding - * GPU struct. OBS! Users must ensure bind has been + * GPU struct. OBS! Users must ensure bind has been * called before setting using this method. */ virtual void setValue(ghoul::opengl::ProgramObject* programObject, const LayerGroup& layerGroup, const TileIndex& tileIndex); - /** - * Binds this object with GLSL variables with identifiers starting + /** + * Binds this object with GLSL variables with identifiers starting * with nameBase within the provided shader program. * After this method has been called, users may invoke setValue. */ diff --git a/modules/globebrowsing/rendering/gpu/gpulayermanager.cpp b/modules/globebrowsing/rendering/gpu/gpulayermanager.cpp index 475b744462..f3d0ea2e51 100644 --- a/modules/globebrowsing/rendering/gpu/gpulayermanager.cpp +++ b/modules/globebrowsing/rendering/gpu/gpulayermanager.cpp @@ -29,7 +29,7 @@ namespace openspace::globebrowsing { void GPULayerManager::setValue(ghoul::opengl::ProgramObject* programObject, - const LayerManager& layerManager, + const LayerManager& layerManager, const TileIndex& tileIndex) { auto layerGroups = layerManager.layerGroups(); diff --git a/modules/globebrowsing/rendering/gpu/gpulayermanager.h b/modules/globebrowsing/rendering/gpu/gpulayermanager.h index 8c6f237da7..bc196cc742 100644 --- a/modules/globebrowsing/rendering/gpu/gpulayermanager.h +++ b/modules/globebrowsing/rendering/gpu/gpulayermanager.h @@ -45,14 +45,14 @@ public: /** * Sets the value of LayerGroup to its corresponding - * GPU struct. OBS! Users must ensure bind has been + * GPU struct. OBS! Users must ensure bind has been * called before setting using this method. */ virtual void setValue(ghoul::opengl::ProgramObject* programObject, const LayerManager& layerManager, const TileIndex& tileIndex); - /** - * Binds this object with GLSL variables with identifiers starting + /** + * Binds this object with GLSL variables with identifiers starting * with nameBase within the provided shader program. * After this method has been called, users may invoke setValue. */ diff --git a/modules/globebrowsing/rendering/gpu/gpulayerrendersettings.h b/modules/globebrowsing/rendering/gpu/gpulayerrendersettings.h index 6b2c1c4f04..b0c206142c 100644 --- a/modules/globebrowsing/rendering/gpu/gpulayerrendersettings.h +++ b/modules/globebrowsing/rendering/gpu/gpulayerrendersettings.h @@ -42,18 +42,19 @@ class GPULayerRenderSettings{ public: /** * Sets the value of LayerRenderSettings to its corresponding - * GPU struct. OBS! Users must ensure bind has been + * GPU struct. OBS! Users must ensure bind has been * called before setting using this method. */ void setValue(ghoul::opengl::ProgramObject* programObject, const LayerRenderSettings& layerSettings); - /** - * Binds this object with GLSL variables with identifiers starting + /** + * Binds this object with GLSL variables with identifiers starting * with nameBase within the provided shader program. * After this method has been called, users may invoke setValue. */ - void bind(const LayerRenderSettings& layerSettings, ghoul::opengl::ProgramObject* programObject, const std::string& nameBase); + void bind(const LayerRenderSettings& layerSettings, + ghoul::opengl::ProgramObject* programObject, const std::string& nameBase); private: GPUData gpuOpacity; diff --git a/modules/globebrowsing/rendering/gpu/gputiledepthtransform.h b/modules/globebrowsing/rendering/gpu/gputiledepthtransform.h index 79065249c1..9de5a3d776 100644 --- a/modules/globebrowsing/rendering/gpu/gputiledepthtransform.h +++ b/modules/globebrowsing/rendering/gpu/gputiledepthtransform.h @@ -42,15 +42,15 @@ class GPUTileDepthTransform { public: /** * Sets the value of TileDepthTransform to its corresponding - * GPU struct. OBS! Users must ensure bind has been + * GPU struct. OBS! Users must ensure bind has been * called before setting using this method. */ void setValue(ghoul::opengl::ProgramObject* programObject, const TileDepthTransform& depthTransform); - /** - * Binds GLSL variables with identifiers starting with - * nameBase within the provided shader program with this object. + /** + * Binds GLSL variables with identifiers starting with + * nameBase within the provided shader program with this object. * After this method has been called, users may invoke setValue. */ void bind(ghoul::opengl::ProgramObject* programObject, diff --git a/modules/globebrowsing/rendering/gpu/gputileuvtransform.h b/modules/globebrowsing/rendering/gpu/gputileuvtransform.h index fb52dcaa33..9245742aff 100644 --- a/modules/globebrowsing/rendering/gpu/gputileuvtransform.h +++ b/modules/globebrowsing/rendering/gpu/gputileuvtransform.h @@ -42,15 +42,15 @@ class GPUTileUvTransform { public: /** * Sets the value of TileUvTransform to its corresponding - * GPU struct. OBS! Users must ensure bind has been + * GPU struct. OBS! Users must ensure bind has been * called before setting using this method. */ void setValue(ghoul::opengl::ProgramObject* programObject, const TileUvTransform& uvTransform); - /** - * Binds GLSL variables with identifiers starting with - * nameBase within the provided shader program with this object. + /** + * Binds GLSL variables with identifiers starting with + * nameBase within the provided shader program with this object. * After this method has been called, users may invoke setValue. */ void bind(ghoul::opengl::ProgramObject* programObject, diff --git a/modules/globebrowsing/rendering/layer/layer.cpp b/modules/globebrowsing/rendering/layer/layer.cpp index 1034cd385c..76fe4e1766 100644 --- a/modules/globebrowsing/rendering/layer/layer.cpp +++ b/modules/globebrowsing/rendering/layer/layer.cpp @@ -1,4 +1,4 @@ -/***************************************************************************************** +/***************************************************************************************** * * * OpenSpace * * * @@ -91,7 +91,9 @@ Layer::Layer(layergroupid::GroupID id, const ghoul::Dictionary& layerDict, LayerGroup& parent) : properties::PropertyOwner({ layerDict.value(keyName), - layerDict.hasKey(keyDescription) ? layerDict.value(keyDescription) : "" + layerDict.hasKey(keyDescription) ? + layerDict.value(keyDescription) : + "" }) , _parent(parent) , _typeOption(TypeInfo, properties::OptionProperty::DisplayType::Dropdown) @@ -171,12 +173,16 @@ Layer::Layer(layergroupid::GroupID id, const ghoul::Dictionary& layerDict, } }); - _remove.onChange([&](){ - if (_tileProvider) { - _tileProvider->reset(); + _remove.onChange([&]() { + try { + if (_tileProvider) { + _tileProvider->reset(); + } + } + catch (...) { + _parent.deleteLayer(name()); + throw; } - - _parent.deleteLayer(name()); }); _typeOption.onChange([&](){ @@ -219,11 +225,23 @@ Layer::Layer(layergroupid::GroupID id, const ghoul::Dictionary& layerDict, addPropertySubOwner(_layerAdjustment); } +void Layer::initialize() { + if (_tileProvider) { + _tileProvider->initialize(); + } +} + +void Layer::deinitialize() { + if (_tileProvider) { + _tileProvider->deinitialize(); + } +} + ChunkTilePile Layer::getChunkTilePile(const TileIndex& tileIndex, int pileSize) const { if (_tileProvider) { return _tileProvider->getChunkTilePile(tileIndex, pileSize); } - else { + else { ChunkTilePile chunkTilePile; chunkTilePile.resize(pileSize); for (int i = 0; i < pileSize; ++i) { @@ -299,7 +317,8 @@ glm::ivec2 Layer::tilePixelSizeDifference() const { return _padTilePixelSizeDifference; } -glm::vec2 Layer::compensateSourceTextureSampling(glm::vec2 startOffset, glm::vec2 sizeDiff, +glm::vec2 Layer::compensateSourceTextureSampling(glm::vec2 startOffset, + glm::vec2 sizeDiff, glm::uvec2 resolution, glm::vec2 tileUV) { glm::vec2 sourceSize = glm::vec2(resolution) + sizeDiff; @@ -333,7 +352,8 @@ layergroupid::TypeID Layer::parseTypeIdFromDictionary( } } -void Layer::initializeBasedOnType(layergroupid::TypeID typeId, ghoul::Dictionary initDict) { +void Layer::initializeBasedOnType(layergroupid::TypeID typeId, ghoul::Dictionary initDict) +{ switch (typeId) { // Intentional fall through. Same for all tile layers case layergroupid::TypeID::DefaultTileLayer: @@ -350,10 +370,13 @@ void Layer::initializeBasedOnType(layergroupid::TypeID typeId, ghoul::Dictionary if (tileProviderInitDict.hasKeyAndValue(keyName)) { std::string name; tileProviderInitDict.getValue(keyName, name); - LDEBUG("Initializing tile provider for layer: '" + name + "'"); + LDEBUG("Initializing tile provider for layer: '" + name + "'"); } _tileProvider = std::shared_ptr( - tileprovider::TileProvider::createFromDictionary(typeId, tileProviderInitDict) + tileprovider::TileProvider::createFromDictionary( + typeId, + tileProviderInitDict + ) ); break; } diff --git a/modules/globebrowsing/rendering/layer/layer.h b/modules/globebrowsing/rendering/layer/layer.h index 2b86269615..d7c4f1afca 100644 --- a/modules/globebrowsing/rendering/layer/layer.h +++ b/modules/globebrowsing/rendering/layer/layer.h @@ -53,7 +53,11 @@ public: properties::Vec3Property color; }; - Layer(layergroupid::GroupID id, const ghoul::Dictionary& layerDict, LayerGroup& parent); + Layer(layergroupid::GroupID id, const ghoul::Dictionary& layerDict, + LayerGroup& parent); + + void initialize(); + void deinitialize(); ChunkTilePile getChunkTilePile(const TileIndex& tileIndex, int pileSize) const; Tile::Status getTileStatus(const TileIndex& index) const; @@ -74,12 +78,14 @@ public: glm::ivec2 tilePixelStartOffset() const; glm::ivec2 tilePixelSizeDifference() const; glm::vec2 compensateSourceTextureSampling(glm::vec2 startOffset, glm::vec2 sizeDiff, - glm::uvec2 resolution, glm::vec2 tileUV); + glm::uvec2 resolution, glm::vec2 tileUV); glm::vec2 TileUvToTextureSamplePosition(const TileUvTransform& uvTransform, - glm::vec2 tileUV, glm::uvec2 resolution); + glm::vec2 tileUV, glm::uvec2 resolution); private: - layergroupid::TypeID parseTypeIdFromDictionary(const ghoul::Dictionary& initDict) const; + layergroupid::TypeID parseTypeIdFromDictionary( + const ghoul::Dictionary& initDict) const; + void initializeBasedOnType(layergroupid::TypeID typeId, ghoul::Dictionary initDict); void addVisibleProperties(); void removeVisibleProperties(); diff --git a/modules/globebrowsing/rendering/layer/layergroup.cpp b/modules/globebrowsing/rendering/layer/layergroup.cpp index 85ddabfecf..df0105a357 100644 --- a/modules/globebrowsing/rendering/layer/layergroup.cpp +++ b/modules/globebrowsing/rendering/layer/layergroup.cpp @@ -69,8 +69,8 @@ LayerGroup::LayerGroup(layergroupid::GroupID id, const ghoul::Dictionary& dict) try { addLayer(fallbackLayerDict); } - catch (const ghoul::RuntimeError& e) { - LERRORC(e.component, e.message); + catch (const ghoul::RuntimeError& except) { + LERRORC(except.component, except.message); continue; } } @@ -79,6 +79,18 @@ LayerGroup::LayerGroup(layergroupid::GroupID id, const ghoul::Dictionary& dict) } } +void LayerGroup::initialize() { + for (const std::shared_ptr& l : _layers) { + l->initialize(); + } +} + +void LayerGroup::deinitialize() { + for (const std::shared_ptr& l : _layers) { + l->deinitialize(); + } +} + void LayerGroup::update() { _activeLayers.clear(); @@ -90,32 +102,38 @@ void LayerGroup::update() { } } -void LayerGroup::addLayer(const ghoul::Dictionary& layerDict) { +std::shared_ptr LayerGroup::addLayer(const ghoul::Dictionary& layerDict) { if (!layerDict.hasKeyAndValue("Name")) { LERROR("'Name' must be specified for layer."); - return; + return nullptr; } auto layer = std::make_shared(_groupId, layerDict, *this); layer->onChange(_onChangeCallback); if (hasPropertySubOwner(layer->name())) { LINFO("Layer with name " + layer->name() + " already exists."); + _levelBlendingEnabled.setVisibility(properties::Property::Visibility::User); + return nullptr; } else { _layers.push_back(layer); - update(); + //update(); if (_onChangeCallback) { _onChangeCallback(); } addPropertySubOwner(layer.get()); + _levelBlendingEnabled.setVisibility(properties::Property::Visibility::User); + return layer; } - - _levelBlendingEnabled.setVisibility(properties::Property::Visibility::User); } void LayerGroup::deleteLayer(const std::string& layerName) { - for (std::vector>::iterator it = _layers.begin(); it != _layers.end(); ++it) { + for (std::vector>::iterator it = _layers.begin(); + it != _layers.end(); + ++it) + { if (it->get()->name() == layerName) { removePropertySubOwner(it->get()); + (*it)->deinitialize(); _layers.erase(it); update(); if (_onChangeCallback) { diff --git a/modules/globebrowsing/rendering/layer/layergroup.h b/modules/globebrowsing/rendering/layer/layergroup.h index 602cfaf342..e08641b333 100644 --- a/modules/globebrowsing/rendering/layer/layergroup.h +++ b/modules/globebrowsing/rendering/layer/layergroup.h @@ -46,10 +46,13 @@ struct LayerGroup : public properties::PropertyOwner { LayerGroup(layergroupid::GroupID id); LayerGroup(layergroupid::GroupID id, const ghoul::Dictionary& dict); + void initialize(); + void deinitialize(); + /// Updates all layers tile providers within this group void update(); - void addLayer(const ghoul::Dictionary& layerDict); + std::shared_ptr addLayer(const ghoul::Dictionary& layerDict); void deleteLayer(const std::string& layerName); /// @returns const vector of all layers diff --git a/modules/globebrowsing/rendering/layer/layermanager.cpp b/modules/globebrowsing/rendering/layer/layermanager.cpp index 2b7942d981..d3a870d063 100644 --- a/modules/globebrowsing/rendering/layer/layermanager.cpp +++ b/modules/globebrowsing/rendering/layer/layermanager.cpp @@ -68,9 +68,23 @@ LayerManager::LayerManager(const ghoul::Dictionary& layerGroupsDict) } } -void LayerManager::addLayer(layergroupid::GroupID groupId, ghoul::Dictionary layerDict) { +void LayerManager::initialize() { + for (const std::shared_ptr& lg : _layerGroups) { + lg->initialize(); + } +} + +void LayerManager::deinitialize() { + for (const std::shared_ptr& lg : _layerGroups) { + lg->deinitialize(); + } +} + +std::shared_ptr LayerManager::addLayer(layergroupid::GroupID groupId, + ghoul::Dictionary layerDict) +{ ghoul_assert(groupId != layergroupid::Unknown, "Layer group ID must be known"); - _layerGroups[groupId]->addLayer(layerDict); + return _layerGroups[groupId]->addLayer(layerDict); } void LayerManager::deleteLayer(layergroupid::GroupID groupId, std::string layerName) { diff --git a/modules/globebrowsing/rendering/layer/layermanager.h b/modules/globebrowsing/rendering/layer/layermanager.h index ec877a4539..1ffbbeb334 100644 --- a/modules/globebrowsing/rendering/layer/layermanager.h +++ b/modules/globebrowsing/rendering/layer/layermanager.h @@ -45,7 +45,10 @@ class LayerManager : public properties::PropertyOwner { public: LayerManager(const ghoul::Dictionary& textureCategoriesDictionary); - void addLayer(layergroupid::GroupID groupId, ghoul::Dictionary layerDict); + void initialize(); + void deinitialize(); + + std::shared_ptr addLayer(layergroupid::GroupID groupId, ghoul::Dictionary layerDict); void deleteLayer(layergroupid::GroupID groupId, std::string layerName); const LayerGroup& layerGroup(size_t groupId); diff --git a/modules/globebrowsing/rendering/layershadermanager.cpp b/modules/globebrowsing/rendering/layershadermanager.cpp index d64e91c358..991e7d0d47 100644 --- a/modules/globebrowsing/rendering/layershadermanager.cpp +++ b/modules/globebrowsing/rendering/layershadermanager.cpp @@ -37,13 +37,15 @@ namespace openspace::globebrowsing { -bool LayerShaderManager::LayerShaderPreprocessingData::LayerGroupPreprocessingData::operator==( - const LayerGroupPreprocessingData& other) const { +bool +LayerShaderManager::LayerShaderPreprocessingData::LayerGroupPreprocessingData::operator==( + const LayerGroupPreprocessingData& other) const +{ return layerType == other.layerType && - blendMode == other.blendMode && - layerAdjustmentType == other.layerAdjustmentType && - lastLayerIdx == other.lastLayerIdx && - layerBlendingEnabled == other.layerBlendingEnabled; + blendMode == other.blendMode && + layerAdjustmentType == other.layerAdjustmentType && + lastLayerIdx == other.lastLayerIdx && + layerBlendingEnabled == other.layerBlendingEnabled; } bool LayerShaderManager::LayerShaderPreprocessingData::operator==( @@ -92,7 +94,9 @@ LayerShaderManager::LayerShaderPreprocessingData for (const std::shared_ptr& layer : layers) { layeredTextureInfo.layerType.push_back(layer->type()); layeredTextureInfo.blendMode.push_back(layer->blendMode()); - layeredTextureInfo.layerAdjustmentType.push_back(layer->layerAdjustment().type()); + layeredTextureInfo.layerAdjustmentType.push_back( + layer->layerAdjustment().type() + ); } preprocessingData.layeredTextureInfo[i] = layeredTextureInfo; @@ -175,7 +179,10 @@ void LayerShaderManager::recompileShaderProgram( for (int j = 0; j < textureTypes[i].lastLayerIdx + 1; ++j) { std::string key = groupName + std::to_string(j) + "LayerType"; - shaderDictionary.setValue(key, static_cast(textureTypes[i].layerType[j])); + shaderDictionary.setValue( + key, + static_cast(textureTypes[i].layerType[j]) + ); } // This is to avoid errors from shader preprocessor @@ -184,7 +191,10 @@ void LayerShaderManager::recompileShaderProgram( for (int j = 0; j < textureTypes[i].lastLayerIdx + 1; ++j) { std::string key = groupName + std::to_string(j) + "BlendMode"; - shaderDictionary.setValue(key, static_cast(textureTypes[i].blendMode[j])); + shaderDictionary.setValue( + key, + static_cast(textureTypes[i].blendMode[j]) + ); } // This is to avoid errors from shader preprocessor @@ -193,7 +203,10 @@ void LayerShaderManager::recompileShaderProgram( for (int j = 0; j < textureTypes[i].lastLayerIdx + 1; ++j) { std::string key = groupName + std::to_string(j) + "LayerAdjustmentType"; - shaderDictionary.setValue(key, static_cast(textureTypes[i].layerAdjustmentType[j])); + shaderDictionary.setValue( + key, + static_cast(textureTypes[i].layerAdjustmentType[j]) + ); } } diff --git a/modules/globebrowsing/tile/pixelregion.cpp b/modules/globebrowsing/tile/pixelregion.cpp index df6d7a83a1..fabd02f3a7 100644 --- a/modules/globebrowsing/tile/pixelregion.cpp +++ b/modules/globebrowsing/tile/pixelregion.cpp @@ -31,7 +31,7 @@ namespace openspace::globebrowsing { PixelRegion::PixelRegion(const PixelCoordinate& pixelStart, const PixelRange& numberOfPixels) : start(pixelStart) - , numPixels(numberOfPixels) + , numPixels(numberOfPixels) {} PixelRegion::PixelRegion(const PixelRegion& o) @@ -91,20 +91,20 @@ void PixelRegion::align(Side side, int pos) { } } -void PixelRegion::alignLeft(int x) { - start.x = x; +void PixelRegion::alignLeft(int x) { + start.x = x; } -void PixelRegion::alignTop(int y) { - start.y = y; +void PixelRegion::alignTop(int y) { + start.y = y; } -void PixelRegion::alignRight(int x) { - start.x = x - numPixels.x; +void PixelRegion::alignRight(int x) { + start.x = x - numPixels.x; } -void PixelRegion::alignBottom(int y) { - start.y = y - numPixels.y; +void PixelRegion::alignBottom(int y) { + start.y = y - numPixels.y; } void PixelRegion::scale(const glm::dvec2& s) { diff --git a/modules/globebrowsing/tile/pixelregion.h b/modules/globebrowsing/tile/pixelregion.h index c597365443..018d67b294 100644 --- a/modules/globebrowsing/tile/pixelregion.h +++ b/modules/globebrowsing/tile/pixelregion.h @@ -58,7 +58,7 @@ struct PixelRegion { void setBottom(int y); /** - * Aligns one the sides of the pixel regino to the specified position. This does + * Aligns one the sides of the pixel regino to the specified position. This does * not change the number of pixels within the region. * * Example: Side = left and pos = 16: diff --git a/modules/globebrowsing/tile/rawtile.cpp b/modules/globebrowsing/tile/rawtile.cpp index 43a93496bc..e4a093f5c1 100644 --- a/modules/globebrowsing/tile/rawtile.cpp +++ b/modules/globebrowsing/tile/rawtile.cpp @@ -43,7 +43,7 @@ RawTile RawTile::createDefault(const TileTextureInitData& initData) { defaultRes.textureInitData = std::make_shared(initData); defaultRes.imageData = new char[initData.totalNumBytes()]; std::fill_n( - static_cast(defaultRes.imageData), + defaultRes.imageData, initData.totalNumBytes(), char(0) ); diff --git a/modules/globebrowsing/tile/rawtiledatareader/gdalrawtiledatareader.cpp b/modules/globebrowsing/tile/rawtiledatareader/gdalrawtiledatareader.cpp index a53f36092e..38b1198d33 100644 --- a/modules/globebrowsing/tile/rawtiledatareader/gdalrawtiledatareader.cpp +++ b/modules/globebrowsing/tile/rawtiledatareader/gdalrawtiledatareader.cpp @@ -130,8 +130,10 @@ void GdalRawTileDataReader::initialize() { _gdalDatasetMetaDataCached.offset = _dataset->GetRasterBand(1)->GetOffset(); _gdalDatasetMetaDataCached.rasterXSize = _dataset->GetRasterXSize(); _gdalDatasetMetaDataCached.rasterYSize = _dataset->GetRasterYSize(); - _gdalDatasetMetaDataCached.noDataValue = _dataset->GetRasterBand(1)->GetNoDataValue(); - _gdalDatasetMetaDataCached.dataType = tiledatatype::getGdalDataType(_initData.glType()); + _gdalDatasetMetaDataCached.noDataValue = + _dataset->GetRasterBand(1)->GetNoDataValue(); + _gdalDatasetMetaDataCached.dataType = + tiledatatype::getGdalDataType(_initData.glType()); CPLErr err = _dataset->GetGeoTransform(&_gdalDatasetMetaDataCached.padfTransform[0]); if (err == CE_Failure) { @@ -167,8 +169,8 @@ RawTile::ReadError GdalRawTileDataReader::rasterRead( char* dataDest = dataDestination; // GDAL reads pixels top to bottom, but we want our pixels bottom to top. - // Therefore, we increment the destination pointer to the last line on in the - // buffer, and the we specify in the rasterIO call that we want negative line + // Therefore, we increment the destination pointer to the last line on in the + // buffer, and the we specify in the rasterIO call that we want negative line // spacing. Doing this compensates the flipped Y axis dataDest += (io.write.totalNumBytes - io.write.bytesPerLine); diff --git a/modules/globebrowsing/tile/rawtiledatareader/gdalrawtiledatareader.h b/modules/globebrowsing/tile/rawtiledatareader/gdalrawtiledatareader.h index a4211de38d..78a2cfea5d 100644 --- a/modules/globebrowsing/tile/rawtiledatareader/gdalrawtiledatareader.h +++ b/modules/globebrowsing/tile/rawtiledatareader/gdalrawtiledatareader.h @@ -55,7 +55,7 @@ class GdalRawTileDataReader : public RawTileDataReader { public: /** - * Opens a GDALDataset in readonly mode and calculates meta data required for + * Opens a GDALDataset in readonly mode and calculates meta data required for * reading tile using a TileIndex. * * \param filePath, a path to a specific file GDAL can read @@ -103,7 +103,7 @@ private: /** * Use as a helper function when determining the maximum tile level. This function * returns the negated number of overviews requred to downscale the highest overview - * dataset so that it fits within minimumPixelSize pixels in the x-dimension. + * dataset so that it fits within minimumPixelSize pixels in the x-dimension. */ int calculateTileLevelDifference(int minimumPixelSize) const; diff --git a/modules/globebrowsing/tile/rawtiledatareader/rawtiledatareader.cpp b/modules/globebrowsing/tile/rawtiledatareader/rawtiledatareader.cpp index bf29c170c0..ed49aa1620 100644 --- a/modules/globebrowsing/tile/rawtiledatareader/rawtiledatareader.cpp +++ b/modules/globebrowsing/tile/rawtiledatareader/rawtiledatareader.cpp @@ -131,11 +131,13 @@ void RawTileDataReader::readImageData(IODescription& io, RawTile::ReadError& wor for (int i = 0; i < 3; i++) { // The final destination pointer is offsetted by one datum byte size // for every raster (or data channel, i.e. R in RGB) - char* dataDestination = imageDataDest + (i * _initData.bytesPerDatum()); + char* dataDestination = imageDataDest + + (i * _initData.bytesPerDatum()); RawTile::ReadError err = repeatedRasterRead(1, io, dataDestination); - // CE_None = 0, CE_Debug = 1, CE_Warning = 2, CE_Failure = 3, CE_Fatal = 4 + // CE_None = 0, CE_Debug = 1, CE_Warning = 2, + // CE_Failure = 3, CE_Fatal = 4 worstError = std::max(worstError, err); } } @@ -143,11 +145,13 @@ void RawTileDataReader::readImageData(IODescription& io, RawTile::ReadError& wor for (int i = 0; i < 3; i++) { // The final destination pointer is offsetted by one datum byte size // for every raster (or data channel, i.e. R in RGB) - char* dataDestination = imageDataDest + (i * _initData.bytesPerDatum()); + char* dataDestination = imageDataDest + + (i * _initData.bytesPerDatum()); RawTile::ReadError err = repeatedRasterRead(1, io, dataDestination); - // CE_None = 0, CE_Debug = 1, CE_Warning = 2, CE_Failure = 3, CE_Fatal = 4 + // CE_None = 0, CE_Debug = 1, CE_Warning = 2, + // CE_Failure = 3, CE_Fatal = 4 worstError = std::max(worstError, err); } // Last read is the alpha channel @@ -161,11 +165,17 @@ void RawTileDataReader::readImageData(IODescription& io, RawTile::ReadError& wor for (int i = 0; i < nRastersToRead; i++) { // The final destination pointer is offsetted by one datum byte size // for every raster (or data channel, i.e. R in RGB) - char* dataDestination = imageDataDest + (i * _initData.bytesPerDatum()); + char* dataDestination = imageDataDest + + (i * _initData.bytesPerDatum()); - RawTile::ReadError err = repeatedRasterRead(i + 1, io, dataDestination); + RawTile::ReadError err = repeatedRasterRead( + i + 1, + io, + dataDestination + ); - // CE_None = 0, CE_Debug = 1, CE_Warning = 2, CE_Failure = 3, CE_Fatal = 4 + // CE_None = 0, CE_Debug = 1, CE_Warning = 2, + // CE_Failure = 3, CE_Fatal = 4 worstError = std::max(worstError, err); } } @@ -177,11 +187,13 @@ void RawTileDataReader::readImageData(IODescription& io, RawTile::ReadError& wor for (int i = 0; i < 3; i++) { // The final destination pointer is offsetted by one datum byte size // for every raster (or data channel, i.e. R in RGB) - char* dataDestination = imageDataDest + (i * _initData.bytesPerDatum()); + char* dataDestination = imageDataDest + + (i * _initData.bytesPerDatum()); RawTile::ReadError err = repeatedRasterRead(1, io, dataDestination); - // CE_None = 0, CE_Debug = 1, CE_Warning = 2, CE_Failure = 3, CE_Fatal = 4 + // CE_None = 0, CE_Debug = 1, CE_Warning = 2, + // CE_Failure = 3, CE_Fatal = 4 worstError = std::max(worstError, err); } } @@ -189,29 +201,38 @@ void RawTileDataReader::readImageData(IODescription& io, RawTile::ReadError& wor for (int i = 0; i < 3; i++) { // The final destination pointer is offsetted by one datum byte size // for every raster (or data channel, i.e. R in RGB) - char* dataDestination = imageDataDest + (i * _initData.bytesPerDatum()); + char* dataDestination = imageDataDest + + (i * _initData.bytesPerDatum()); RawTile::ReadError err = repeatedRasterRead(1, io, dataDestination); - // CE_None = 0, CE_Debug = 1, CE_Warning = 2, CE_Failure = 3, CE_Fatal = 4 + // CE_None = 0, CE_Debug = 1, CE_Warning = 2, + // CE_Failure = 3, CE_Fatal = 4 worstError = std::max(worstError, err); } // Last read is the alpha channel char* dataDestination = imageDataDest + (3 * _initData.bytesPerDatum()); RawTile::ReadError err = repeatedRasterRead(2, io, dataDestination); - // CE_None = 0, CE_Debug = 1, CE_Warning = 2, CE_Failure = 3, CE_Fatal = 4 + // CE_None = 0, CE_Debug = 1, CE_Warning = 2, + // CE_Failure = 3, CE_Fatal = 4 worstError = std::max(worstError, err); } else { // Three or more rasters for (int i = 0; i < 3 && i < nRastersToRead; i++) { // The final destination pointer is offsetted by one datum byte size // for every raster (or data channel, i.e. R in RGB) - char* dataDestination = imageDataDest + (i * _initData.bytesPerDatum()); + char* dataDestination = imageDataDest + + (i * _initData.bytesPerDatum()); - RawTile::ReadError err = repeatedRasterRead(3 - i, io, dataDestination); + RawTile::ReadError err = repeatedRasterRead( + 3 - i, + io, + dataDestination + ); - // CE_None = 0, CE_Debug = 1, CE_Warning = 2, CE_Failure = 3, CE_Fatal = 4 + // CE_None = 0, CE_Debug = 1, CE_Warning = 2, + // CE_Failure = 3, CE_Fatal = 4 worstError = std::max(worstError, err); } } @@ -337,7 +358,8 @@ PixelRegion::PixelCoordinate RawTileDataReader::geodeticToPixel( //ghoul_assert(a[2] != 0.0, "a2 must not be zero!"); double P = (a[0] * b[2] - a[2] * b[0] + a[2] * Y - b[2] * X) / divisor; double L = (-a[0] * b[1] + a[1] * b[0] - a[1] * Y + b[1] * X) / divisor; - // ref: https://www.wolframalpha.com/input/?i=X+%3D+a0+%2B+a1P+%2B+a2L,+Y+%3D+b0+%2B+b1P+%2B+b2L,+solve+for+P+and+L + // ref: https://www.wolframalpha.com/input/?i=X+%3D+a0+%2B+a1P+%2B+a2L, + // +Y+%3D+b0+%2B+b1P+%2B+b2L,+solve+for+P+and+L double Xp = a[0] + P*a[1] + L*a[2]; double Yp = b[0] + P*b[1] + L*b[2]; @@ -358,7 +380,9 @@ Geodetic2 RawTileDataReader::pixelToGeodetic( return geodetic; } -PixelRegion RawTileDataReader::highestResPixelRegion(const GeodeticPatch& geodeticPatch) const { +PixelRegion RawTileDataReader::highestResPixelRegion( + const GeodeticPatch& geodeticPatch) const +{ Geodetic2 nwCorner = geodeticPatch.getCorner(Quad::NORTH_WEST); Geodetic2 swCorner = geodeticPatch.getCorner(Quad::SOUTH_EAST); PixelRegion::PixelCoordinate pixelStart = geodeticToPixel(nwCorner); @@ -373,15 +397,15 @@ RawTile::ReadError RawTileDataReader::repeatedRasterRead( { RawTile::ReadError worstError = RawTile::ReadError::None; - // NOTE: - // Ascii graphics illustrates the implementation details of this method, for one - // specific case. Even though the illustrated case is specific, readers can + // NOTE: + // Ascii graphics illustrates the implementation details of this method, for one + // specific case. Even though the illustrated case is specific, readers can // hopefully find it useful to get the general idea. // Make a copy of the full IO desription as we will have to modify it IODescription io = fullIO; - // Example: + // Example: // We have an io description that defines a WRITE and a READ region. // In this case the READ region extends outside of the defined io.read.fullRegion, // meaning we will have to perform wrapping @@ -389,12 +413,12 @@ RawTile::ReadError RawTileDataReader::repeatedRasterRead( // io.write.region io.read.region // | | // V V - // +-------+ +-------+ - // | | | |--------+ + // +-------+ +-------+ + // | | | |--------+ // | | | | | // | | | | | // +-------+ +-------+ | - // | | <-- io.read.fullRegion + // | | <-- io.read.fullRegion // | | // +--------------+ @@ -402,40 +426,42 @@ RawTile::ReadError RawTileDataReader::repeatedRasterRead( // Loop through each side: left, top, right, bottom for (int i = 0; i < 4; ++i) { - // Example: + // Example: // We are currently considering the left side of the pixel region PixelRegion::Side side = static_cast(i); IODescription cutoff = io.cut(side, io.read.fullRegion.edge(side)); - // Example: + // Example: // We cut off the left part that was outside the io.read.fullRegion, and we - // now have an additional io description for the cut off region. - // Note that the cut-method used above takes care of the corresponding + // now have an additional io description for the cut off region. + // Note that the cut-method used above takes care of the corresponding // WRITE region for us. // cutoff.write.region cutoff.read.region // | io.write.region | io.read.region // | | | | // V V V V - // +-+-----+ +-+-----+ + // +-+-----+ +-+-----+ // | | | | | |--------+ // | | | | | | | // | | | | | | | // +-+-----+ +-+-----+ | - // | | <-- io.read.fullRegion + // | | <-- io.read.fullRegion // | | // +--------------+ if (cutoff.read.region.area() > 0) { // Wrap by repeating - PixelRegion::Side oppositeSide = static_cast((i + 2) % 4); + PixelRegion::Side oppositeSide = static_cast( + (i + 2) % 4 + ); cutoff.read.region.align( oppositeSide, io.read.fullRegion.edge(oppositeSide)); // Example: // The cut off region is wrapped to the opposite side of the region, - // i.e. "repeated". Note that we don't want WRITE region to change, + // i.e. "repeated". Note that we don't want WRITE region to change, // we're only wrapping the READ region. // cutoff.write.region io.read.region cutoff.read.region @@ -443,15 +469,15 @@ RawTile::ReadError RawTileDataReader::repeatedRasterRead( // | | V V // V V +-----+ +-+ // +-+-----+ | |------| | - // | | | | | | | + // | | | | | | | // | | | | | | | // | | | +-----+ +-+ - // +-+-----+ | | <-- io.read.fullRegion + // +-+-----+ | | <-- io.read.fullRegion // | | // +--------------+ // Example: - // The cutoff region has been repeated along one of its sides, but + // The cutoff region has been repeated along one of its sides, but // as we can see in this example, it still has a top part outside the // defined gdal region. This is handled through recursion. RawTile::ReadError err = repeatedRasterRead( @@ -516,7 +542,9 @@ std::shared_ptr RawTileDataReader::getTileMetaData( } else { preprocessData->hasMissingData[raster] = true; - float& floatToRewrite = reinterpret_cast(rawTile->imageData[yi + i]); + float& floatToRewrite = reinterpret_cast( + rawTile->imageData[yi + i] + ); floatToRewrite = -FLT_MAX; } i += _initData.bytesPerDatum(); @@ -541,7 +569,9 @@ float RawTileDataReader::depthScale() const { TileDepthTransform RawTileDataReader::calculateTileDepthTransform() { bool isFloat = - (_initData.glType() == GL_HALF_FLOAT || _initData.glType() == GL_FLOAT || _initData.glType() == GL_DOUBLE); + (_initData.glType() == GL_HALF_FLOAT || + _initData.glType() == GL_FLOAT || + _initData.glType() == GL_DOUBLE); double maximumValue = isFloat ? 1.0 : tiledatatype::getMaximumValue(_initData.glType()); diff --git a/modules/globebrowsing/tile/rawtiledatareader/rawtiledatareader.h b/modules/globebrowsing/tile/rawtiledatareader/rawtiledatareader.h index 37562e4d8f..fe4cae764c 100644 --- a/modules/globebrowsing/tile/rawtiledatareader/rawtiledatareader.h +++ b/modules/globebrowsing/tile/rawtiledatareader/rawtiledatareader.h @@ -155,7 +155,8 @@ protected: std::shared_ptr getTileMetaData( std::shared_ptr result, const PixelRegion& region) const; TileDepthTransform calculateTileDepthTransform(); - RawTile::ReadError postProcessErrorCheck(std::shared_ptr ioResult) const; + RawTile::ReadError postProcessErrorCheck( + std::shared_ptr ioResult) const; struct Cached { int _maxLevel = -1; diff --git a/modules/globebrowsing/tile/rawtiledatareader/simplerawtiledatareader.cpp b/modules/globebrowsing/tile/rawtiledatareader/simplerawtiledatareader.cpp index 98f35f2302..46d8c6052d 100644 --- a/modules/globebrowsing/tile/rawtiledatareader/simplerawtiledatareader.cpp +++ b/modules/globebrowsing/tile/rawtiledatareader/simplerawtiledatareader.cpp @@ -187,7 +187,8 @@ RawTile::ReadError SimpleRawTileDataReader::rasterRead( return RawTile::ReadError::None; } -IODescription SimpleRawTileDataReader::adjustIODescription(const IODescription& io) const { +IODescription SimpleRawTileDataReader::adjustIODescription(const IODescription& io) const +{ // Modify to match OpenGL texture layout IODescription modifiedIO = io; modifiedIO.read.region.start.y = diff --git a/modules/globebrowsing/tile/rawtiledatareader/tiledatatype.cpp b/modules/globebrowsing/tile/rawtiledatareader/tiledatatype.cpp index 9c3da72259..ff2811e1ab 100644 --- a/modules/globebrowsing/tile/rawtiledatareader/tiledatatype.cpp +++ b/modules/globebrowsing/tile/rawtiledatareader/tiledatatype.cpp @@ -138,7 +138,7 @@ TextureFormat getTextureFormat(int rasterCount, GDALDataType gdalType) { // No representation of 64 bit float? //case GDT_Float64: // format.glFormat = GL_RED; - // break; + // break; default: LERROR("GDAL data type unknown to OpenGL: " << gdalType); } @@ -192,7 +192,7 @@ TextureFormat getTextureFormat(int rasterCount, GDALDataType gdalType) { case GDT_Float32: format.glFormat = GL_RGB32F; break; - // No representation of 64 bit float? + // No representation of 64 bit float? //case GDT_Float64: // format.glFormat = GL_RED; // break; @@ -224,7 +224,7 @@ TextureFormat getTextureFormat(int rasterCount, GDALDataType gdalType) { // No representation of 64 bit float? //case GDT_Float64: // format.glFormat = GL_RED; - // break; + // break; default: LERROR("GDAL data type unknown to OpenGL: " << gdalType); } @@ -264,7 +264,7 @@ TextureFormat getTextureFormatOptimized(int rasterCount, GDALDataType gdalType) // No representation of 64 bit float? //case GDT_Float64: // format.glFormat = GL_RED; - // break; + // break; default: LERROR("GDAL data type unknown to OpenGL: " << gdalType); } @@ -306,7 +306,7 @@ TextureFormat getTextureFormatOptimized(int rasterCount, GDALDataType gdalType) case GDT_UInt16: format.glFormat = GL_RGB16UI; break; - case GDT_Int16: + case GDT_Int16: format.glFormat = GL_RGB16_SNORM; break; case GDT_UInt32: @@ -318,7 +318,7 @@ TextureFormat getTextureFormatOptimized(int rasterCount, GDALDataType gdalType) case GDT_Float32: format.glFormat = GL_RGB32F; break; - // No representation of 64 bit float? + // No representation of 64 bit float? //case GDT_Float64: // format.glFormat = GL_RED; // break; @@ -350,7 +350,7 @@ TextureFormat getTextureFormatOptimized(int rasterCount, GDALDataType gdalType) // No representation of 64 bit float? //case GDT_Float64: // format.glFormat = GL_RED; - // break; + // break; default: LERROR("GDAL data type unknown to OpenGL: " << gdalType); } diff --git a/modules/globebrowsing/tile/tileindex.cpp b/modules/globebrowsing/tile/tileindex.cpp index b3e8e856ec..72f66bb578 100644 --- a/modules/globebrowsing/tile/tileindex.cpp +++ b/modules/globebrowsing/tile/tileindex.cpp @@ -38,8 +38,8 @@ namespace { namespace openspace::globebrowsing { -TileIndex::TileIndex(int x, int y, int level) - : x(x), y(y), level(level) +TileIndex::TileIndex(int x_, int y_, int level_) + : x(x_), y(y_), level(level_) {} TileIndex::TileIndex(const TileIndex& other) @@ -112,7 +112,7 @@ int TileIndex::manhattan(const TileIndex& other) const { } // Creates a hash which can be used as key in hash maps. -// +// // +-------+------------+-------+------------+ // | USAGE | BIT RANGE | #BITS | MAX VALUE | // +-------+------------+-------+------------+ diff --git a/modules/globebrowsing/tile/tileloadjob.h b/modules/globebrowsing/tile/tileloadjob.h index 515ca97472..21c60a56b2 100644 --- a/modules/globebrowsing/tile/tileloadjob.h +++ b/modules/globebrowsing/tile/tileloadjob.h @@ -46,7 +46,7 @@ struct TileLoadJob : public Job { /** * No data is allocated unless specified so by the TileTextureInitData of * rawTileDataReader but it is assumed that pboDataPtr is a mapped pointer to a pixel - * buffer object. + * buffer object. */ TileLoadJob(std::shared_ptr rawTileDataReader, const TileIndex& tileIndex, char* pboDataPtr); diff --git a/modules/globebrowsing/tile/tileprovider/defaulttileprovider.cpp b/modules/globebrowsing/tile/tileprovider/defaulttileprovider.cpp index fb1222f649..80a6d5051c 100644 --- a/modules/globebrowsing/tile/tileprovider/defaulttileprovider.cpp +++ b/modules/globebrowsing/tile/tileprovider/defaulttileprovider.cpp @@ -70,7 +70,7 @@ namespace { namespace openspace::globebrowsing::tileprovider { -DefaultTileProvider::DefaultTileProvider(const ghoul::Dictionary& dictionary) +DefaultTileProvider::DefaultTileProvider(const ghoul::Dictionary& dictionary) : TileProvider(dictionary) , _filePath(FilePathInfo, "") , _tilePixelSize(TilePixelSizeInfo, 32, 32, 2048) @@ -97,7 +97,7 @@ DefaultTileProvider::DefaultTileProvider(const ghoul::Dictionary& dictionary) int tilePixelSize = 0; if (dictionary.getValue(KeyTilePixelSize, pixelSize)) { LDEBUG("Default pixel size overridden: " << pixelSize); - tilePixelSize = static_cast(pixelSize); + tilePixelSize = static_cast(pixelSize); } _padTiles = true; @@ -126,8 +126,8 @@ DefaultTileProvider::DefaultTileProvider(const ghoul::Dictionary& dictionary) addProperty(_tilePixelSize); } -DefaultTileProvider::DefaultTileProvider(std::shared_ptr tileReader) - : _asyncTextureDataProvider(tileReader) +DefaultTileProvider::DefaultTileProvider(std::shared_ptr tr) + : _asyncTextureDataProvider(tr) , _filePath(FilePathInfo, "") , _tilePixelSize(TilePixelSizeInfo, 32, 32, 2048) {} @@ -140,10 +140,11 @@ void DefaultTileProvider::update() { initTexturesFromLoadedData(); if (_asyncTextureDataProvider->shouldBeDeleted()) { _asyncTextureDataProvider = nullptr; - TileTextureInitData initData( - LayerManager::getTileTextureInitData(_layerGroupID, _padTiles, - _tilePixelSize) - ); + TileTextureInitData initData(LayerManager::getTileTextureInitData( + _layerGroupID, + _padTiles, + _tilePixelSize + )); initAsyncTileDataReader(initData); } } @@ -155,10 +156,11 @@ void DefaultTileProvider::reset() { _asyncTextureDataProvider->prepairToBeDeleted(); } else { - TileTextureInitData initData( - LayerManager::getTileTextureInitData(_layerGroupID, _padTiles, - _tilePixelSize) - ); + TileTextureInitData initData(LayerManager::getTileTextureInitData( + _layerGroupID, + _padTiles, + _tilePixelSize + )); initAsyncTileDataReader(initData); } } @@ -206,7 +208,8 @@ float DefaultTileProvider::noDataValueAsFloat() { void DefaultTileProvider::initTexturesFromLoadedData() { if (_asyncTextureDataProvider) { - std::shared_ptr rawTile = _asyncTextureDataProvider->popFinishedRawTile(); + std::shared_ptr rawTile = + _asyncTextureDataProvider->popFinishedRawTile(); if (rawTile) { cache::ProviderTileKey key = { rawTile->tileIndex, uniqueIdentifier() }; ghoul_assert(!_tileCache->exist(key), "Tile must not be existing in cache"); @@ -224,14 +227,24 @@ void DefaultTileProvider::initAsyncTileDataReader(TileTextureInitData initData) // Initialize instance variables #ifdef GLOBEBROWSING_USE_GDAL - auto tileDataset = std::make_shared(_filePath, initData, - _basePath, preprocess); + auto tileDataset = std::make_shared( + _filePath, + initData, + _basePath, + preprocess + ); #else // GLOBEBROWSING_USE_GDAL - auto tileDataset = std::make_shared(_filePath, initData, - preprocess); + auto tileDataset = std::make_shared( + _filePath, + initData, + preprocess + ); #endif // GLOBEBROWSING_USE_GDAL - _asyncTextureDataProvider = std::make_shared(_name, tileDataset); + _asyncTextureDataProvider = std::make_shared( + _name, + tileDataset + ); // Tiles are only available for levels 2 and higher. if (_preCacheLevel >= 2) { diff --git a/modules/globebrowsing/tile/tileprovider/defaulttileprovider.h b/modules/globebrowsing/tile/tileprovider/defaulttileprovider.h index 83447d8e8e..9e7a8540a6 100644 --- a/modules/globebrowsing/tile/tileprovider/defaulttileprovider.h +++ b/modules/globebrowsing/tile/tileprovider/defaulttileprovider.h @@ -41,7 +41,7 @@ namespace openspace::globebrowsing { namespace openspace::globebrowsing::tileprovider { /** -* Provides tiles loaded by AsyncTileDataProvider and +* Provides tiles loaded by AsyncTileDataProvider and * caches them in memory using LRU caching */ class DefaultTileProvider : public TileProvider { @@ -52,8 +52,8 @@ public: virtual ~DefaultTileProvider() override; /** - * \returns a Tile with status OK iff it exists in in-memory - * cache. If not, it may enqueue some IO operations on a + * \returns a Tile with status OK iff it exists in in-memory + * cache. If not, it may enqueue some IO operations on a * separate thread. */ virtual Tile getTile(const TileIndex& tileIndex) override; @@ -68,7 +68,7 @@ public: private: /** * Collects all asynchronously downloaded RawTile - * and uses createTile to create Tiles, + * and uses createTile to create Tiles, * which are put in the LRU cache - potentially pushing out outdated * Tiles. */ diff --git a/modules/globebrowsing/tile/tileprovider/sizereferencetileprovider.cpp b/modules/globebrowsing/tile/tileprovider/sizereferencetileprovider.cpp index 4bb13d4a73..4cdb6bc8df 100644 --- a/modules/globebrowsing/tile/tileprovider/sizereferencetileprovider.cpp +++ b/modules/globebrowsing/tile/tileprovider/sizereferencetileprovider.cpp @@ -106,7 +106,8 @@ int SizeReferenceTileProvider::roundedLongitudalLength(const TileIndex& tileInde return l; } -TileIndex::TileHashKey SizeReferenceTileProvider::toHash(const TileIndex& tileIndex) const { +TileIndex::TileHashKey SizeReferenceTileProvider::toHash(const TileIndex& tileIndex) const +{ int l = roundedLongitudalLength(tileIndex); TileIndex::TileHashKey key = static_cast(l); return key; diff --git a/modules/globebrowsing/tile/tileprovider/temporaltileprovider.cpp b/modules/globebrowsing/tile/tileprovider/temporaltileprovider.cpp index a482fdaa17..af24cfbc68 100644 --- a/modules/globebrowsing/tile/tileprovider/temporaltileprovider.cpp +++ b/modules/globebrowsing/tile/tileprovider/temporaltileprovider.cpp @@ -61,7 +61,7 @@ const char* TemporalTileProvider::TemporalXMLTags::TIME_RESOLUTION = "OpenSpaceTimeResolution"; const char* TemporalTileProvider::TemporalXMLTags::TIME_FORMAT = "OpenSpaceTimeIdFormat"; -TemporalTileProvider::TemporalTileProvider(const ghoul::Dictionary& dictionary) +TemporalTileProvider::TemporalTileProvider(const ghoul::Dictionary& dictionary) : _initDict(dictionary) , _filePath(FilePathInfo) , _successfulInitialization(false) @@ -79,27 +79,39 @@ TemporalTileProvider::TemporalTileProvider(const ghoul::Dictionary& dictionary) addProperty(_filePath); if (readFilePath()) { - const bool hasStart = dictionary.hasKeyAndValue(KeyPreCacheStartTime); + const bool hasStart = dictionary.hasKeyAndValue( + KeyPreCacheStartTime + ); const bool hasEnd = dictionary.hasKeyAndValue(KeyPreCacheEndTime); if (hasStart && hasEnd) { const std::string start = dictionary.value(KeyPreCacheStartTime); const std::string end = dictionary.value(KeyPreCacheEndTime); - std::vector