diff --git a/apps/OpenSpace/ext/sgct b/apps/OpenSpace/ext/sgct index 8831533acd..575839eae2 160000 --- a/apps/OpenSpace/ext/sgct +++ b/apps/OpenSpace/ext/sgct @@ -1 +1 @@ -Subproject commit 8831533acdfee90db5cc18c0d8ef69a3c0dd7e53 +Subproject commit 575839eae2a101682f3620a9842cc6fb6d11a266 diff --git a/apps/OpenSpace/main.cpp b/apps/OpenSpace/main.cpp index 507c6e3e81..845b9d7848 100644 --- a/apps/OpenSpace/main.cpp +++ b/apps/OpenSpace/main.cpp @@ -143,10 +143,10 @@ LONG WINAPI generateMiniDump(EXCEPTION_POINTERS* exceptionPointers) { dumpFile.c_str(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_WRITE | FILE_SHARE_READ, - 0, + nullptr, CREATE_ALWAYS, 0, - 0 + nullptr ); MINIDUMP_EXCEPTION_INFORMATION exceptionParameter; @@ -358,13 +358,13 @@ void mainPreSyncFunc() { if (!state.isConnected) { // Joystick was added state.isConnected = true; - state.name = SgctEngine->getJoystickName(i); + state.name = sgct::Engine::getJoystickName(i); std::fill(state.axes.begin(), state.axes.end(), 0.f); std::fill(state.buttons.begin(), state.buttons.end(), JoystickAction::Idle); } - const float* axes = SgctEngine->getJoystickAxes(i, &state.nAxes); + const float* axes = sgct::Engine::getJoystickAxes(i, &state.nAxes); if (state.nAxes > JoystickInputState::MaxAxes) { LWARNING(fmt::format( "Joystick/Gamepad {} has {} axes, but only {} axes are supported. " @@ -375,7 +375,10 @@ void mainPreSyncFunc() { } std::memcpy(state.axes.data(), axes, state.nAxes * sizeof(float)); - const unsigned char* buttons = SgctEngine->getJoystickButtons(i, &state.nButtons); + const unsigned char* buttons = sgct::Engine::getJoystickButtons( + i, + &state.nButtons + ); if (state.nButtons > JoystickInputState::MaxButtons) { LWARNING(fmt::format( @@ -441,7 +444,7 @@ void mainRenderFunc() { LTRACE("main::mainRenderFunc(begin)"); glm::mat4 viewMatrix = SgctEngine->getCurrentViewMatrix() * - glm::translate(glm::mat4(1.f), SgctEngine->getDefaultUserPtr()->getPos()); + glm::translate(glm::mat4(1.f), sgct::Engine::getDefaultUserPtr()->getPos()); glm::mat4 projectionMatrix = SgctEngine->getCurrentProjectionMatrix(); #ifdef OPENVR_SUPPORT @@ -640,14 +643,14 @@ void setSgctDelegateFunctions() { sgctDelegate.mousePosition = []() { int id = sgct::Engine::instance()->getCurrentWindowPtr()->getId(); double posX, posY; - sgct::Engine::instance()->getMousePos(id, &posX, &posY); + sgct::Engine::getMousePos(id, &posX, &posY); return glm::vec2(posX, posY); }; sgctDelegate.mouseButtons = [](int maxNumber) { int id = sgct::Engine::instance()->getCurrentWindowPtr()->getId(); uint32_t result = 0; for (int i = 0; i < maxNumber; ++i) { - bool button = (sgct::Engine::instance()->getMouseButton(id, i) != 0); + bool button = (sgct::Engine::getMouseButton(id, i) != 0); if (button) { result |= (1 << i); } @@ -739,10 +742,10 @@ void setSgctDelegateFunctions() { }; sgctDelegate.isMaster = []() { return sgct::Engine::instance()->isMaster(); }; sgctDelegate.isUsingSwapGroups = []() { - return sgct::Engine::instance()->getCurrentWindowPtr()->isUsingSwapGroups(); + return sgct::SGCTWindow::isUsingSwapGroups(); }; sgctDelegate.isSwapGroupMaster = []() { - return sgct::Engine::instance()->getCurrentWindowPtr()->isSwapGroupMaster(); + return sgct::SGCTWindow::isSwapGroupMaster(); }; sgctDelegate.viewProjectionMatrix = []() { return sgct::Engine::instance()->getCurrentModelViewProjectionMatrix(); diff --git a/ext/ghoul b/ext/ghoul index e2e53560b6..94b6ad1756 160000 --- a/ext/ghoul +++ b/ext/ghoul @@ -1 +1 @@ -Subproject commit e2e53560b6aca0d25d06b3a2fc887d1f54c68ae1 +Subproject commit 94b6ad17564f2f470a72bc8223a3a9cade8437b8 diff --git a/include/openspace/documentation/documentation.h b/include/openspace/documentation/documentation.h index bce8395803..725a446fca 100644 --- a/include/openspace/documentation/documentation.h +++ b/include/openspace/documentation/documentation.h @@ -308,21 +308,19 @@ void testSpecificationAndThrow(const Documentation& documentation, namespace ghoul { template <> -std::string to_string(const openspace::documentation::TestResult& testResult); +std::string to_string(const openspace::documentation::TestResult& value); template <> -std::string to_string(const openspace::documentation::TestResult::Offense& offense); +std::string to_string(const openspace::documentation::TestResult::Offense& value); template <> -std::string to_string( - const openspace::documentation::TestResult::Offense::Reason& reason); +std::string to_string(const openspace::documentation::TestResult::Offense::Reason& value); template <> -std::string to_string(const openspace::documentation::TestResult::Warning& warning); +std::string to_string(const openspace::documentation::TestResult::Warning& value); template <> -std::string to_string( - const openspace::documentation::TestResult::Warning::Reason& reason); +std::string to_string(const openspace::documentation::TestResult::Warning::Reason& value); } // namespace ghoul diff --git a/include/openspace/interaction/joystickcamerastates.h b/include/openspace/interaction/joystickcamerastates.h index 17379cddcd..a9ebf23514 100644 --- a/include/openspace/interaction/joystickcamerastates.h +++ b/include/openspace/interaction/joystickcamerastates.h @@ -106,7 +106,8 @@ private: namespace ghoul { template <> -std::string to_string(const openspace::interaction::JoystickCameraStates::AxisType& type); +std::string to_string( + const openspace::interaction::JoystickCameraStates::AxisType& value); template <> openspace::interaction::JoystickCameraStates::AxisType diff --git a/include/openspace/interaction/joystickinputstate.h b/include/openspace/interaction/joystickinputstate.h index 59478d7a1f..099ac75400 100644 --- a/include/openspace/interaction/joystickinputstate.h +++ b/include/openspace/interaction/joystickinputstate.h @@ -113,7 +113,7 @@ struct JoystickInputStates : public std::array namespace ghoul { template <> -std::string to_string(const openspace::interaction::JoystickAction& action); +std::string to_string(const openspace::interaction::JoystickAction& value); template <> openspace::interaction::JoystickAction from_string(const std::string& str); diff --git a/include/openspace/interaction/orbitalnavigator.h b/include/openspace/interaction/orbitalnavigator.h index 36653722d0..3f0b14a5e6 100644 --- a/include/openspace/interaction/orbitalnavigator.h +++ b/include/openspace/interaction/orbitalnavigator.h @@ -104,7 +104,7 @@ private: SceneGraphNode* _focusNode = nullptr; glm::dvec3 _previousFocusNodePosition; glm::dquat _previousFocusNodeRotation; - double _currentCameraToSurfaceDistance; + double _currentCameraToSurfaceDistance = 0.0; bool _directlySetStereoDistance = false; Interpolator _rotateToFocusNodeInterpolator; diff --git a/include/openspace/interaction/sessionrecording.h b/include/openspace/interaction/sessionrecording.h index a3f768fdf8..a89bf2e618 100644 --- a/include/openspace/interaction/sessionrecording.h +++ b/include/openspace/interaction/sessionrecording.h @@ -69,7 +69,7 @@ public: * \param filename file saved with recorded keyframes. * \returns true if recording to file starts without errors. */ - bool startRecording(std::string filename); + bool startRecording(const std::string& filename); /** * Starts a recording session, which will save data to the provided filename @@ -160,10 +160,10 @@ private: }; ExternInteraction _externInteract; bool _isRecording = false; - double _timestampRecordStarted; - double _timestampPlaybackStarted_application; - double _timestampPlaybackStarted_simulation; - double _timestampApplicationStarted_simulation; + double _timestampRecordStarted = 0.0; + double _timestampPlaybackStarted_application = 0.0; + double _timestampPlaybackStarted_simulation = 0.0; + double _timestampApplicationStarted_simulation = 0.0; bool hasCameraChangedFromPrev(datamessagestructures::CameraKeyframe kfNew); double appropriateTimestamp(double timeOs, double timeRec, double timeSim); double equivalentSimulationTime(double timeOs, double timeRec, double timeSim); @@ -179,7 +179,7 @@ private: void writeToFileBuffer(std::vector& cvec); void writeToFileBuffer(const unsigned char c); void writeToFileBuffer(bool b); - void saveStringToFile(const std::string s); + void saveStringToFile(const std::string& s); void saveKeyframeToFileBinary(unsigned char* bufferSource, size_t size); void findFirstCameraKeyframeInTimeline(); std::string readHeaderElement(size_t readLen_chars); diff --git a/include/openspace/network/parallelpeer.h b/include/openspace/network/parallelpeer.h index c5994f2f22..5a028a2d1a 100644 --- a/include/openspace/network/parallelpeer.h +++ b/include/openspace/network/parallelpeer.h @@ -95,7 +95,7 @@ private: void setHostName(const std::string& hostName); void setNConnections(size_t nConnections); - double convertTimestamp(double originalTime); + double convertTimestamp(double messageTimestamp); void analyzeTimeDifference(double messageTimestamp); properties::StringProperty _password; diff --git a/include/openspace/network/parallelserver.h b/include/openspace/network/parallelserver.h index 73aa8447b0..7f5d83a3f6 100644 --- a/include/openspace/network/parallelserver.h +++ b/include/openspace/network/parallelserver.h @@ -65,10 +65,9 @@ private: ParallelConnection::Message message; }; - bool isConnected(std::shared_ptr peer) const; + bool isConnected(const Peer& peer) const; - void sendMessage(std::shared_ptr peer, - ParallelConnection::MessageType messageType, + void sendMessage(Peer& peer, ParallelConnection::MessageType messageType, const std::vector& message); void sendMessageToAll(ParallelConnection::MessageType messageType, @@ -77,17 +76,17 @@ private: void sendMessageToClients(ParallelConnection::MessageType messageType, const std::vector& message); - void disconnect(std::shared_ptr peer); - void setName(std::shared_ptr peer, std::string name); + void disconnect(Peer& peer); + void setName(Peer& peer, std::string name); void assignHost(std::shared_ptr newHost); - void setToClient(std::shared_ptr peer); + void setToClient(Peer& peer); void setNConnections(size_t nConnections); - void sendConnectionStatus(std::shared_ptr peer); + void sendConnectionStatus(Peer& peer); void handleAuthentication(std::shared_ptr peer, std::vector message); - void handleData(std::shared_ptr peer, std::vector data); + void handleData(const Peer& peer, std::vector data); void handleHostshipRequest(std::shared_ptr peer, std::vector message); - void handleHostshipResignation(std::shared_ptr peer, std::vector data); + void handleHostshipResignation(Peer& peer); void handleDisconnection(std::shared_ptr peer); void handleNewPeers(); diff --git a/include/openspace/performance/performancelayout.h b/include/openspace/performance/performancelayout.h index 104f3ddedf..b31540134f 100644 --- a/include/openspace/performance/performancelayout.h +++ b/include/openspace/performance/performancelayout.h @@ -45,14 +45,14 @@ struct PerformanceLayout { float updateRotation[NumberValues]; float updateScaling[NumberValues]; }; - SceneGraphPerformanceLayout sceneGraphEntries[MaxValues]; + SceneGraphPerformanceLayout sceneGraphEntries[MaxValues] = {}; int16_t nScaleGraphEntries = 0; struct FunctionPerformanceLayout { char name[LengthName]; float time[NumberValues]; }; - FunctionPerformanceLayout functionEntries[MaxValues]; + FunctionPerformanceLayout functionEntries[MaxValues] = {}; int16_t nFunctionEntries = 0; }; diff --git a/include/openspace/performance/performancemanager.h b/include/openspace/performance/performancemanager.h index 779149c4d5..c0eca8f6a7 100644 --- a/include/openspace/performance/performancemanager.h +++ b/include/openspace/performance/performancemanager.h @@ -42,8 +42,6 @@ public: static void CreateGlobalSharedMemory(); static void DestroyGlobalSharedMemory(); - ~PerformanceManager(); - void setEnabled(bool enabled); bool isEnabled() const; diff --git a/include/openspace/rendering/dashboard.h b/include/openspace/rendering/dashboard.h index 412417fbd3..a908ce5fe9 100644 --- a/include/openspace/rendering/dashboard.h +++ b/include/openspace/rendering/dashboard.h @@ -28,6 +28,7 @@ #include #include +#include #include #include #include @@ -36,12 +37,10 @@ namespace openspace { namespace scripting { struct LuaLibrary; } -class DashboardItem; - class Dashboard : public properties::PropertyOwner { public: Dashboard(); - ~Dashboard(); + ~Dashboard() = default; void render(glm::vec2& penPosition); diff --git a/include/openspace/rendering/loadingscreen.h b/include/openspace/rendering/loadingscreen.h index 1fe2e8563b..8e1c0dce97 100644 --- a/include/openspace/rendering/loadingscreen.h +++ b/include/openspace/rendering/loadingscreen.h @@ -68,6 +68,7 @@ public: void tickItem(); enum class Phase { + PreStart, Construction, Synchronization, Initialization @@ -97,7 +98,7 @@ private: bool _showNodeNames; bool _showProgressbar; - Phase _phase; + Phase _phase = Phase::PreStart; std::atomic_int _iProgress = 0; std::atomic_int _nItems = 0; diff --git a/include/openspace/scene/asset.h b/include/openspace/scene/asset.h index f94a918fce..46af70369b 100644 --- a/include/openspace/scene/asset.h +++ b/include/openspace/scene/asset.h @@ -141,7 +141,7 @@ public: private: void setState(State state); - void requiredAssetChangedState(std::shared_ptr asset, Asset::State childState); + void requiredAssetChangedState(Asset::State childState); void requestedAssetChangedState(Asset* child, Asset::State childState); bool isSyncResolveReady(); diff --git a/include/openspace/scene/scene.h b/include/openspace/scene/scene.h index 784567ef6c..7a99b5c7d0 100644 --- a/include/openspace/scene/scene.h +++ b/include/openspace/scene/scene.h @@ -58,8 +58,7 @@ public: * \param component The optional compoment that caused this exception to be thrown * \pre message may not be empty */ - explicit InvalidSceneError(const std::string& msg, - const std::string& comp = ""); + explicit InvalidSceneError(std::string msg, std::string comp = ""); }; /// This struct describes a time that has some intrinsic interesting-ness to this diff --git a/modules/atmosphere/rendering/atmospheredeferredcaster.cpp b/modules/atmosphere/rendering/atmospheredeferredcaster.cpp index 8bf989aed3..8ae5ff6d1e 100644 --- a/modules/atmosphere/rendering/atmospheredeferredcaster.cpp +++ b/modules/atmosphere/rendering/atmospheredeferredcaster.cpp @@ -84,7 +84,7 @@ #ifdef WIN32 #define _USE_MATH_DEFINES #endif // WIN32 -#include +#include namespace { @@ -1218,8 +1218,9 @@ void AtmosphereDeferredcaster::executeCalculations(GLuint quadCalcVAO, } // Restores OpenGL blending state - if (blendEnabled) + if (blendEnabled) { glEnable(GL_BLEND); + } glBlendEquationSeparate(blendEquationRGB, blendEquationAlpha); glBlendFuncSeparate(blendSrcRGB, blendDestRGB, blendSrcAlpha, blendDestAlpha); diff --git a/modules/atmosphere/rendering/atmospheredeferredcaster.h b/modules/atmosphere/rendering/atmospheredeferredcaster.h index 73e9d5d279..1a838651aa 100644 --- a/modules/atmosphere/rendering/atmospheredeferredcaster.h +++ b/modules/atmosphere/rendering/atmospheredeferredcaster.h @@ -186,7 +186,7 @@ private: int _nu_samples; glm::dmat4 _modelTransform; - double _time; + double _time = 0.0; // Eclipse Shadows std::vector _shadowConfArray; diff --git a/modules/base/lightsource/cameralightsource.cpp b/modules/base/lightsource/cameralightsource.cpp index 2a1b0e84af..9b6647bade 100644 --- a/modules/base/lightsource/cameralightsource.cpp +++ b/modules/base/lightsource/cameralightsource.cpp @@ -61,8 +61,7 @@ documentation::Documentation CameraLightSource::Documentation() { } CameraLightSource::CameraLightSource() - : LightSource() - , _intensity(IntensityInfo, 1.f, 0.f, 1.f) + : _intensity(IntensityInfo, 1.f, 0.f, 1.f) { addProperty(_intensity); } diff --git a/modules/base/lightsource/scenegraphlightsource.cpp b/modules/base/lightsource/scenegraphlightsource.cpp index 4da2606253..c4b9ad55f3 100644 --- a/modules/base/lightsource/scenegraphlightsource.cpp +++ b/modules/base/lightsource/scenegraphlightsource.cpp @@ -76,8 +76,7 @@ documentation::Documentation SceneGraphLightSource::Documentation() { } SceneGraphLightSource::SceneGraphLightSource() - : LightSource() - , _intensity(IntensityInfo, 1.f, 0.f, 1.f) + : _intensity(IntensityInfo, 1.f, 0.f, 1.f) , _sceneGraphNodeReference(NodeInfo, "") { addProperty(_intensity); diff --git a/modules/base/rendering/renderablemodel.cpp b/modules/base/rendering/renderablemodel.cpp index e58068f457..b0a936449f 100644 --- a/modules/base/rendering/renderablemodel.cpp +++ b/modules/base/rendering/renderablemodel.cpp @@ -240,8 +240,6 @@ RenderableModel::RenderableModel(const ghoul::Dictionary& dictionary) addProperty(_performShading); } -RenderableModel::~RenderableModel() {} - bool RenderableModel::isReady() const { return _program && _texture; } diff --git a/modules/base/rendering/renderablemodel.h b/modules/base/rendering/renderablemodel.h index 859c7e562d..9a015d02a5 100644 --- a/modules/base/rendering/renderablemodel.h +++ b/modules/base/rendering/renderablemodel.h @@ -51,7 +51,7 @@ namespace modelgeometry { class ModelGeometry; } class RenderableModel : public Renderable { public: RenderableModel(const ghoul::Dictionary& dictionary); - ~RenderableModel(); + ~RenderableModel() = default; void initialize() override; void initializeGL() override; diff --git a/modules/base/rendering/renderableplaneimagelocal.h b/modules/base/rendering/renderableplaneimagelocal.h index f48314438d..817876ec62 100644 --- a/modules/base/rendering/renderableplaneimagelocal.h +++ b/modules/base/rendering/renderableplaneimagelocal.h @@ -57,7 +57,7 @@ private: void loadTexture(); properties::StringProperty _texturePath; - ghoul::opengl::Texture* _texture; + ghoul::opengl::Texture* _texture = nullptr; std::unique_ptr _textureFile; bool _textureIsDirty = false; diff --git a/modules/base/timeframe/timeframeinterval.cpp b/modules/base/timeframe/timeframeinterval.cpp index 32eafcfa3c..b778502a2e 100644 --- a/modules/base/timeframe/timeframeinterval.cpp +++ b/modules/base/timeframe/timeframeinterval.cpp @@ -114,8 +114,7 @@ TimeFrameInterval::TimeFrameInterval() } TimeFrameInterval::TimeFrameInterval(const ghoul::Dictionary& dictionary) - : TimeFrame() - , _hasStart(HasStartInfo, false) + : _hasStart(HasStartInfo, false) , _start(StartInfo, 0, 0, 1E9) , _hasEnd(HasEndInfo, false) , _end(EndInfo, 0, 0, 1E9) diff --git a/modules/base/timeframe/timeframeunion.cpp b/modules/base/timeframe/timeframeunion.cpp index 40efc5c796..2fcad46663 100644 --- a/modules/base/timeframe/timeframeunion.cpp +++ b/modules/base/timeframe/timeframeunion.cpp @@ -73,8 +73,6 @@ bool TimeFrameUnion::isActive(const Time& time) const { return false; } -TimeFrameUnion::TimeFrameUnion() {} - TimeFrameUnion::TimeFrameUnion(const ghoul::Dictionary& dictionary) : TimeFrame() { diff --git a/modules/base/timeframe/timeframeunion.h b/modules/base/timeframe/timeframeunion.h index 59fd402c67..1f45f8dc92 100644 --- a/modules/base/timeframe/timeframeunion.h +++ b/modules/base/timeframe/timeframeunion.h @@ -35,7 +35,7 @@ namespace documentation { struct Documentation; } class TimeFrameUnion : public TimeFrame { public: - TimeFrameUnion(); + TimeFrameUnion() = default; TimeFrameUnion(const ghoul::Dictionary& dictionary); bool isActive(const Time&) const override; diff --git a/modules/cefwebgui/cefwebguimodule.cpp b/modules/cefwebgui/cefwebguimodule.cpp index 71a9e4531c..f600b1bf0e 100644 --- a/modules/cefwebgui/cefwebguimodule.cpp +++ b/modules/cefwebgui/cefwebguimodule.cpp @@ -139,11 +139,11 @@ void CefWebGuiModule::internalInitialize(const ghoul::Dictionary& configuration) _visible = configuration.hasValue(VisibleInfo.identifier) && configuration.value(VisibleInfo.identifier); - global::callback::initializeGL.push_back([this]() { + global::callback::initializeGL.emplace_back([this]() { startOrStopGui(); }); - global::callback::draw2D.push_back([this](){ + global::callback::draw2D.emplace_back([this](){ const bool isGuiWindow = global::windowDelegate.hasGuiWindow() ? global::windowDelegate.isGuiWindow() : @@ -160,7 +160,7 @@ void CefWebGuiModule::internalInitialize(const ghoul::Dictionary& configuration) } }); - global::callback::deinitializeGL.push_back([this]() { + global::callback::deinitializeGL.emplace_back([this]() { _enabled = false; startOrStopGui(); }); diff --git a/modules/cefwebgui/src/guikeyboardhandler.cpp b/modules/cefwebgui/src/guikeyboardhandler.cpp index 7e4ae58364..7d853addf2 100644 --- a/modules/cefwebgui/src/guikeyboardhandler.cpp +++ b/modules/cefwebgui/src/guikeyboardhandler.cpp @@ -31,7 +31,7 @@ namespace openspace { GUIKeyboardHandler::GUIKeyboardHandler() { _keyConsumed = false; - global::callback::keyboard.push_back( + global::callback::keyboard.emplace_back( [&](Key, KeyModifier, KeyAction) -> bool { const bool previous = _keyConsumed; _keyConsumed = false; diff --git a/modules/cefwebgui/src/guirenderhandler.cpp b/modules/cefwebgui/src/guirenderhandler.cpp index 86c7f8b1d8..0f7f8d47b6 100644 --- a/modules/cefwebgui/src/guirenderhandler.cpp +++ b/modules/cefwebgui/src/guirenderhandler.cpp @@ -57,7 +57,7 @@ GUIRenderHandler::GUIRenderHandler() { glBindBuffer(GL_ARRAY_BUFFER, _vbo); glBufferData(GL_ARRAY_BUFFER, sizeof(data), data, GL_STATIC_DRAW); glEnableVertexAttribArray(0); - glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(GLfloat), 0); + glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(GLfloat), nullptr); glBindVertexArray(0); LDEBUG("Initializing CEF GL environment... done!"); } diff --git a/modules/debugging/rendering/debugrenderer.cpp b/modules/debugging/rendering/debugrenderer.cpp index a5847d6e68..e3f31b6cfe 100644 --- a/modules/debugging/rendering/debugrenderer.cpp +++ b/modules/debugging/rendering/debugrenderer.cpp @@ -55,8 +55,6 @@ DebugRenderer::DebugRenderer(std::unique_ptr progr // nothing to do } -DebugRenderer::~DebugRenderer() { } - const DebugRenderer& DebugRenderer::ref() { if (!_reference) { try { @@ -70,7 +68,7 @@ const DebugRenderer& DebugRenderer::ref() { } void DebugRenderer::renderVertices(const Vertices& clippingSpacePoints, GLenum mode, - const glm::vec4& rgba) const + const glm::vec4& color) const { if (clippingSpacePoints.empty()) { return; @@ -88,7 +86,7 @@ void DebugRenderer::renderVertices(const Vertices& clippingSpacePoints, GLenum m // Activate the shader program and set the uniform color within the shader _programObject->activate(); - _programObject->setUniform("color", rgba); + _programObject->setUniform("color", color); glBindVertexArray(_vaoID); glBindBuffer(GL_ARRAY_BUFFER, _vertexBufferID); diff --git a/modules/debugging/rendering/debugrenderer.h b/modules/debugging/rendering/debugrenderer.h index 4b6274c746..2a84f88a36 100644 --- a/modules/debugging/rendering/debugrenderer.h +++ b/modules/debugging/rendering/debugrenderer.h @@ -61,7 +61,7 @@ public: * Instantiate a new DebugRenderer with a custom shader program */ DebugRenderer(std::unique_ptr programObject); - ~DebugRenderer(); + ~DebugRenderer() = default; /** * Access the static reference diff --git a/modules/debugging/rendering/renderabledebugplane.cpp b/modules/debugging/rendering/renderabledebugplane.cpp index 3297fc1fb8..f1701e27d1 100644 --- a/modules/debugging/rendering/renderabledebugplane.cpp +++ b/modules/debugging/rendering/renderabledebugplane.cpp @@ -173,8 +173,6 @@ RenderableDebugPlane::RenderableDebugPlane(const ghoul::Dictionary& dictionary) setBoundingSphere(_size); } -RenderableDebugPlane::~RenderableDebugPlane() {} - bool RenderableDebugPlane::isReady() const { bool ready = true; if (!_shader) { @@ -220,7 +218,7 @@ void RenderableDebugPlane::render(const RenderData& data, RendererTasks&) { _shader->setUniform("ViewProjection", data.camera.viewProjectionMatrix()); _shader->setUniform("ModelTransform", transform); - setPscUniforms(*_shader.get(), data.camera, data.position); + setPscUniforms(*_shader, data.camera, data.position); ghoul::opengl::TextureUnit unit; unit.activate(); diff --git a/modules/debugging/rendering/renderabledebugplane.h b/modules/debugging/rendering/renderabledebugplane.h index 6f55d84a72..4976be3c07 100644 --- a/modules/debugging/rendering/renderabledebugplane.h +++ b/modules/debugging/rendering/renderabledebugplane.h @@ -48,7 +48,7 @@ struct UpdateStructure; class RenderableDebugPlane : public Renderable { public: RenderableDebugPlane(const ghoul::Dictionary& dictionary); - ~RenderableDebugPlane(); + ~RenderableDebugPlane() = default; void initializeGL() override; void deinitializeGL() override; diff --git a/modules/digitaluniverse/rendering/renderablebillboardscloud.cpp b/modules/digitaluniverse/rendering/renderablebillboardscloud.cpp index ca900ec1ca..7514f85ac7 100644 --- a/modules/digitaluniverse/rendering/renderablebillboardscloud.cpp +++ b/modules/digitaluniverse/rendering/renderablebillboardscloud.cpp @@ -47,7 +47,7 @@ #include #include #include -#include +#include #include #include @@ -423,8 +423,7 @@ RenderableBillboardsCloud::RenderableBillboardsCloud(const ghoul::Dictionary& di if (dictionary.hasKey(KeyFile)) { _speckFile = absPath(dictionary.value(KeyFile)); _hasSpeckFile = true; - _drawElements.onChange([&]() { - _hasSpeckFile = _hasSpeckFile == true? false : true; }); + _drawElements.onChange([&]() { _hasSpeckFile = !_hasSpeckFile; }); addProperty(_drawElements); } @@ -1163,7 +1162,7 @@ bool RenderableBillboardsCloud::readSpeckFile() { // 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 = ""; + std::string line; while (true) { std::streampos position = file.tellg(); std::getline(file, line); @@ -1253,7 +1252,7 @@ bool RenderableBillboardsCloud::readColorMapFile() { // 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 = ""; + std::string line; while (true) { // std::streampos position = file.tellg(); std::getline(file, line); @@ -1300,7 +1299,7 @@ bool RenderableBillboardsCloud::readLabelFile() { // 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 = ""; + std::string line; while (true) { std::streampos position = file.tellg(); std::getline(file, line); @@ -1375,7 +1374,7 @@ bool RenderableBillboardsCloud::readLabelFile() { glm::vec3 transformedPos = glm::vec3( _transformationMatrix * glm::dvec4(position, 1.0) ); - _labelData.push_back(std::make_pair(transformedPos, label)); + _labelData.emplace_back(std::make_pair(transformedPos, label)); } while (!file.eof()); return true; @@ -1411,12 +1410,10 @@ 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; - for (int c = 0; c < keySize; ++c) { - char t; - fileStream.read(&t, sizeof(char)); - key.append(1, t); - } + std::vector buffer(keySize); + fileStream.read(buffer.data(), keySize); + + std::string key(buffer.begin(), buffer.end()); int32_t value = 0; fileStream.read(reinterpret_cast(&value), sizeof(int32_t)); @@ -1461,23 +1458,21 @@ bool RenderableBillboardsCloud::saveCachedFile(const std::string& file) const { int32_t nItems = static_cast(_variableDataPositionMap.size()); fileStream.write(reinterpret_cast(&nItems), sizeof(int32_t)); - for (auto pair : _variableDataPositionMap) { + for (const std::pair& pair : + _variableDataPositionMap) + { int32_t keySize = static_cast(pair.first.size()); fileStream.write( reinterpret_cast(&keySize), sizeof(int32_t) ); - for (size_t c = 0; c < pair.first.size(); ++c) { - char keyChar = static_cast(pair.first[c]); - fileStream.write(&keyChar, sizeof(char)); - } + fileStream.write(pair.first.data(), keySize); int32_t value = static_cast(pair.second); fileStream.write(reinterpret_cast(&value), sizeof(int32_t)); } } - bool success = fileStream.good(); - return success; + return fileStream.good(); } else { LERROR(fmt::format("Error opening file '{}' for save cache file", file)); @@ -1532,8 +1527,9 @@ void RenderableBillboardsCloud::createDataSlice() { int c = static_cast(colorBins.size() - 1); while (variableColor < colorBins[c]) { --c; - if (c == 0) + if (c == 0) { break; + } } int colorIndex = diff --git a/modules/digitaluniverse/rendering/renderablebillboardscloud.h b/modules/digitaluniverse/rendering/renderablebillboardscloud.h index 0a8ba138f3..e822305fb7 100644 --- a/modules/digitaluniverse/rendering/renderablebillboardscloud.h +++ b/modules/digitaluniverse/rendering/renderablebillboardscloud.h @@ -131,8 +131,8 @@ private: // DEBUG: properties::OptionProperty _renderOption; - ghoul::opengl::Texture* _polygonTexture; - ghoul::opengl::Texture* _spriteTexture; + ghoul::opengl::Texture* _polygonTexture = nullptr; + ghoul::opengl::Texture* _spriteTexture = nullptr; ghoul::opengl::ProgramObject* _program = nullptr; ghoul::opengl::ProgramObject* _renderToPolygonProgram = nullptr; diff --git a/modules/digitaluniverse/rendering/renderabledumeshes.cpp b/modules/digitaluniverse/rendering/renderabledumeshes.cpp index 18cefd9ed2..f5b7fe3a83 100644 --- a/modules/digitaluniverse/rendering/renderabledumeshes.cpp +++ b/modules/digitaluniverse/rendering/renderabledumeshes.cpp @@ -43,7 +43,7 @@ #include #include #include -#include +#include namespace { constexpr const char* _loggerCat = "RenderableDUMeshes"; @@ -268,8 +268,7 @@ RenderableDUMeshes::RenderableDUMeshes(const ghoul::Dictionary& dictionary) if (dictionary.hasKey(KeyFile)) { _speckFile = absPath(dictionary.value(KeyFile)); _hasSpeckFile = true; - _drawElements.onChange([&]() { - _hasSpeckFile = _hasSpeckFile == true ? false : true; }); + _drawElements.onChange([&]() { _hasSpeckFile = !_hasSpeckFile; }); addProperty(_drawElements); } @@ -706,7 +705,7 @@ bool RenderableDUMeshes::readSpeckFile() { // 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 = ""; + std::string line; while (true) { std::streampos position = file.tellg(); std::getline(file, line); @@ -827,7 +826,7 @@ bool RenderableDUMeshes::readLabelFile() { // 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 = ""; + std::string line; while (true) { std::streampos position = file.tellg(); std::getline(file, line); @@ -899,7 +898,7 @@ bool RenderableDUMeshes::readLabelFile() { glm::vec3 transformedPos = glm::vec3( _transformationMatrix * glm::dvec4(position, 1.0) ); - _labelData.push_back(std::make_pair(transformedPos, label)); + _labelData.emplace_back(std::make_pair(transformedPos, label)); } while (!file.eof()); diff --git a/modules/digitaluniverse/rendering/renderableplanescloud.cpp b/modules/digitaluniverse/rendering/renderableplanescloud.cpp index a7b7fde7d2..d5ea484389 100644 --- a/modules/digitaluniverse/rendering/renderableplanescloud.cpp +++ b/modules/digitaluniverse/rendering/renderableplanescloud.cpp @@ -873,7 +873,7 @@ bool RenderablePlanesCloud::readSpeckFile() { // 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 = ""; + std::string line; while (true) { std::streampos position = file.tellg(); std::getline(file, line); @@ -950,7 +950,7 @@ bool RenderablePlanesCloud::readSpeckFile() { if (line.substr(0, 8) == "texture ") { std::stringstream str(line); - std::size_t found = line.find("-"); + std::size_t found = line.find('-'); int textureIndex = 0; @@ -1055,7 +1055,7 @@ bool RenderablePlanesCloud::readLabelFile() { // 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 = ""; + std::string line; while (true) { std::streampos position = file.tellg(); std::getline(file, line); @@ -1125,7 +1125,7 @@ bool RenderablePlanesCloud::readLabelFile() { glm::vec3 transformedPos = glm::vec3( _transformationMatrix * glm::dvec4(position, 1.0) ); - _labelData.push_back(std::make_pair(transformedPos, label)); + _labelData.emplace_back(std::make_pair(transformedPos, label)); } while (!file.eof()); diff --git a/modules/digitaluniverse/rendering/renderableplanescloud.h b/modules/digitaluniverse/rendering/renderableplanescloud.h index 34df2dcd9a..18c081e45e 100644 --- a/modules/digitaluniverse/rendering/renderableplanescloud.h +++ b/modules/digitaluniverse/rendering/renderableplanescloud.h @@ -96,7 +96,7 @@ private: const glm::dmat4& projectionMatrix, float fadeInVariable); void renderLabels(const RenderData& data, const glm::dmat4& modelViewProjectionMatrix, const glm::dvec3& orthoRight, - const glm::dvec3& orthoUp, float fadeInVarible); + const glm::dvec3& orthoUp, float fadeInVariable); bool loadData(); bool loadTextures(); diff --git a/modules/digitaluniverse/rendering/renderablepoints.cpp b/modules/digitaluniverse/rendering/renderablepoints.cpp index 750021eee5..22a21e3212 100644 --- a/modules/digitaluniverse/rendering/renderablepoints.cpp +++ b/modules/digitaluniverse/rendering/renderablepoints.cpp @@ -41,7 +41,7 @@ #include #include #include -#include +#include #include namespace { @@ -406,7 +406,7 @@ void RenderablePoints::update(const UpdateData&) { if (_hasSpriteTexture && _spriteTextureIsDirty) { LDEBUG("Reloading Sprite Texture"); _spriteTexture = nullptr; - if (_spriteTexturePath.value() != "") { + if (!_spriteTexturePath.value().empty()) { _spriteTexture = ghoul::io::TextureReader::ref().loadTexture( absPath(_spriteTexturePath) ); @@ -489,7 +489,7 @@ bool RenderablePoints::readSpeckFile() { // 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 = ""; + std::string line; while (true) { std::streampos position = file.tellg(); std::getline(file, line); @@ -556,7 +556,7 @@ bool RenderablePoints::readColorMapFile() { // 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 = ""; + std::string line; while (true) { // std::streampos position = file.tellg(); std::getline(file, line); diff --git a/modules/fitsfilereader/include/fitsfilereader.h b/modules/fitsfilereader/include/fitsfilereader.h index bba4e9f7a1..18b98cfbdd 100644 --- a/modules/fitsfilereader/include/fitsfilereader.h +++ b/modules/fitsfilereader/include/fitsfilereader.h @@ -96,7 +96,7 @@ public: * Reads a single SPECK file and returns a vector with nRenderValues * per star. Reads data in pre-defined order based on AMNH's star data files. */ - std::vector readSpeckFile(std::string filePath, int& nRenderValues); + std::vector readSpeckFile(const std::string& filePath, int& nRenderValues); private: std::unique_ptr _infile; diff --git a/modules/fitsfilereader/src/fitsfilereader.cpp b/modules/fitsfilereader/src/fitsfilereader.cpp index e0cff969dd..9a105f1519 100644 --- a/modules/fitsfilereader/src/fitsfilereader.cpp +++ b/modules/fitsfilereader/src/fitsfilereader.cpp @@ -52,7 +52,7 @@ FitsFileReader::~FitsFileReader() { } bool FitsFileReader::isPrimaryHDU() { - return _infile->extension().size() == 0; + return _infile->extension().empty(); } template @@ -507,9 +507,10 @@ std::vector FitsFileReader::readFitsFile(std::string filePath, int& nValu return fullData; } -std::vector FitsFileReader::readSpeckFile(std::string filePath, int& nRenderValues) +std::vector FitsFileReader::readSpeckFile(const std::string& filePath, + int& nRenderValues) { - auto fullData = std::vector(); + std::vector fullData; std::ifstream fileStream(filePath); @@ -525,7 +526,7 @@ std::vector FitsFileReader::readSpeckFile(std::string filePath, int& nRen // 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', 'texture' and 'maxcomment') - std::string line = ""; + std::string line; while (true) { std::streampos position = fileStream.tellg(); std::getline(fileStream, line); @@ -591,8 +592,8 @@ std::vector FitsFileReader::readSpeckFile(std::string filePath, int& nRen // Check if star is a nullArray. bool nullArray = true; - for (size_t i = 0; i < readValues.size(); ++i) { - if (readValues[i] != 0.0) { + for (float f : readValues) { + if (f != 0.0) { nullArray = false; break; } diff --git a/modules/gaia/rendering/octreemanager.cpp b/modules/gaia/rendering/octreemanager.cpp index 31331cb90f..d6462292e8 100644 --- a/modules/gaia/rendering/octreemanager.cpp +++ b/modules/gaia/rendering/octreemanager.cpp @@ -38,8 +38,6 @@ namespace { namespace openspace { -OctreeManager::~OctreeManager() {} - void OctreeManager::initOctree(long long cpuRamBudget, int maxDist, int maxStarsPerNode) { if (_root) { LDEBUG("Clear existing Octree"); @@ -121,16 +119,16 @@ void OctreeManager::initBufferIndexStack(long long maxNodes, bool useVBO, void OctreeManager::insert(const std::vector& starValues) { size_t index = getChildIndex(starValues[0], starValues[1], starValues[2]); - insertInNode(_root->Children[index], starValues); + insertInNode(*_root->Children[index], starValues); } void OctreeManager::sliceLodData(size_t branchIndex) { if (branchIndex != 8) { - sliceNodeLodCache(_root->Children[branchIndex]); + sliceNodeLodCache(*_root->Children[branchIndex]); } else { for (int i = 0; i < 7; ++i) { - sliceNodeLodCache(_root->Children[i]); + sliceNodeLodCache(*_root->Children[i]); } } } @@ -140,7 +138,7 @@ void OctreeManager::printStarsPerNode() const { for (int i = 0; i < 8; ++i) { std::string prefix = "{" + std::to_string(i); - accumulatedString += printStarsPerNode(_root->Children[i], prefix); + accumulatedString += printStarsPerNode(*_root->Children[i], prefix); } LINFO(fmt::format("Number of stars per node: \n{}", accumulatedString)); LINFO(fmt::format("Number of leaf nodes: {}", std::to_string(_numLeafNodes))); @@ -159,7 +157,7 @@ void OctreeManager::fetchSurroundingNodes(const glm::dvec3& cameraPos, // Only traverse Octree once! if (_parentNodeOfCamera == 8) { // Fetch first layer of children - fetchChildrenNodes(_root, 0); + fetchChildrenNodes(*_root, 0); for (int i = 0; i < 8; ++i) { // Check so branch doesn't have a single layer. @@ -170,12 +168,9 @@ void OctreeManager::fetchSurroundingNodes(const glm::dvec3& cameraPos, // Use multithreading to load files and detach thread from main execution // so it can execute independently. Thread will be destroyed when // finished! - std::thread( - &OctreeManager::fetchChildrenNodes, - this, - _root->Children[i], - -1 - ).detach(); + std::thread([this, n = _root->Children[i]]() { + fetchChildrenNodes(*n, -1); + }).detach(); } _parentNodeOfCamera = 0; } @@ -187,7 +182,7 @@ void OctreeManager::fetchSurroundingNodes(const glm::dvec3& cameraPos, cameraPos / (1000.0 * distanceconstants::Parsec) ); size_t idx = getChildIndex(fCameraPos.x, fCameraPos.y, fCameraPos.z); - std::shared_ptr node = _root->Children[idx]; + std::shared_ptr node = _root->Children[idx]; while (!node->isLeaf) { idx = getChildIndex( @@ -306,7 +301,7 @@ void OctreeManager::findAndFetchNeighborNode(unsigned long long firstParentId, i // Fetch first layer children if we're already at root. if (parentId == 8) { - fetchChildrenNodes(_root, 0); + fetchChildrenNodes(*_root, 0); return; } @@ -382,7 +377,7 @@ void OctreeManager::findAndFetchNeighborNode(unsigned long long firstParentId, i } // Traverse to that parent node (as long as such a child exists!). - std::shared_ptr node = _root; + std::shared_ptr node = _root; while (!indexStack.empty() && !node->Children[indexStack.top()]->isLeaf) { node = node->Children[indexStack.top()]; node->hasLoadedDescendant = true; @@ -392,12 +387,9 @@ void OctreeManager::findAndFetchNeighborNode(unsigned long long firstParentId, i // Fetch all children nodes from found parent. Use multithreading to load files // asynchronously! Detach thread from main execution so it can execute independently. // Thread will then be destroyed when it has finished! - std::thread( - &OctreeManager::fetchChildrenNodes, - this, - node, - additionalLevelsToFetch - ).detach(); + std::thread([this, node, additionalLevelsToFetch]() { + fetchChildrenNodes(*node, additionalLevelsToFetch); + }).detach(); } std::map> OctreeManager::traverseData(const glm::dmat4& mvp, @@ -452,14 +444,16 @@ std::map> OctreeManager::traverseData(const glm::dmat4& glm::dvec3 pos = glm::dvec3(x, y, z) * 1000.0 * distanceconstants::Parsec; corners[i] = glm::dvec4(pos, 1.0); } - if (!_culler->isVisible(corners, mvp)) return renderData; + if (!_culler->isVisible(corners, mvp)) { + return renderData; + } glm::vec2 nodeSize = _culler->getNodeSizeInPixels(corners, mvp, screenSize); float totalPixels = nodeSize.x * nodeSize.y; if (totalPixels < _minTotalPixelsLod * 2) { // Remove LOD from first layer of children. for (int i = 0; i < 8; ++i) { std::map> tmpData = removeNodeFromCache( - _root->Children[i], + *_root->Children[i], deltaStars ); renderData.insert(tmpData.begin(), tmpData.end()); @@ -473,7 +467,7 @@ std::map> OctreeManager::traverseData(const glm::dmat4& } std::map> tmpData = checkNodeIntersection( - _root->Children[i], + *_root->Children[i], mvp, screenSize, deltaStars, @@ -531,7 +525,7 @@ std::vector OctreeManager::getAllData(gaia::RenderOption option) { std::vector fullData; for (size_t i = 0; i < 8; ++i) { - auto tmpData = getNodeData(_root->Children[i], option); + std::vector tmpData = getNodeData(*_root->Children[i], option); fullData.insert(fullData.end(), tmpData.begin(), tmpData.end()); } return fullData; @@ -540,11 +534,11 @@ std::vector OctreeManager::getAllData(gaia::RenderOption option) { void OctreeManager::clearAllData(int branchIndex) { // Don't clear everything if not needed. if (branchIndex != -1) { - clearNodeData(_root->Children[branchIndex]); + clearNodeData(*_root->Children[branchIndex]); } else { for (size_t i = 0; i < 8; ++i) { - clearNodeData(_root->Children[i]); + clearNodeData(*_root->Children[i]); } } } @@ -559,24 +553,24 @@ void OctreeManager::writeToFile(std::ofstream& outFileStream, bool writeData) { // Use pre-traversal (Morton code / Z-order). for (size_t i = 0; i < 8; ++i) { - writeNodeToFile(outFileStream, _root->Children[i], writeData); + writeNodeToFile(outFileStream, *_root->Children[i], writeData); } } -void OctreeManager::writeNodeToFile(std::ofstream& outFileStream, - std::shared_ptr node, bool writeData) +void OctreeManager::writeNodeToFile(std::ofstream& outFileStream, const OctreeNode& node, + bool writeData) { // Write node structure. - bool isLeaf = node->isLeaf; - int32_t numStars = static_cast(node->numStars); + bool isLeaf = node.isLeaf; + int32_t numStars = static_cast(node.numStars); outFileStream.write(reinterpret_cast(&isLeaf), sizeof(bool)); outFileStream.write(reinterpret_cast(&numStars), sizeof(int32_t)); // Write node data if specified if (writeData) { - std::vector nodeData = node->posData; - nodeData.insert(nodeData.end(), node->colData.begin(), node->colData.end()); - nodeData.insert(nodeData.end(), node->velData.begin(), node->velData.end()); + std::vector nodeData = node.posData; + nodeData.insert(nodeData.end(), node.colData.begin(), node.colData.end()); + nodeData.insert(nodeData.end(), node.velData.begin(), node.velData.end()); int32_t nDataSize = static_cast(nodeData.size()); size_t nBytes = nDataSize * sizeof(nodeData[0]); @@ -587,9 +581,9 @@ void OctreeManager::writeNodeToFile(std::ofstream& outFileStream, } // Write children to file (in Morton order) if we're in an inner node. - if (!node->isLeaf) { + if (!node.isLeaf) { for (size_t i = 0; i < 8; ++i) { - writeNodeToFile(outFileStream, node->Children[i], writeData); + writeNodeToFile(outFileStream, *node.Children[i], writeData); } } } @@ -638,13 +632,13 @@ int OctreeManager::readFromFile(std::ifstream& inFileStream, bool readData, // Use the same technique to construct octree from file. for (size_t i = 0; i < 8; ++i) { - nStarsRead += readNodeFromFile(inFileStream, _root->Children[i], readData); + nStarsRead += readNodeFromFile(inFileStream, *_root->Children[i], readData); } return nStarsRead; } -int OctreeManager::readNodeFromFile(std::ifstream& inFileStream, - std::shared_ptr node, bool readData) +int OctreeManager::readNodeFromFile(std::ifstream& inFileStream, OctreeNode& node, + bool readData) { // Read node structure. bool isLeaf; @@ -653,8 +647,8 @@ int OctreeManager::readNodeFromFile(std::ifstream& inFileStream, inFileStream.read(reinterpret_cast(&isLeaf), sizeof(bool)); inFileStream.read(reinterpret_cast(&numStars), sizeof(int32_t)); - node->isLeaf = isLeaf; - node->numStars = numStars; + node.isLeaf = isLeaf; + node.numStars = numStars; // Read node data if specified. if (readData) { @@ -671,18 +665,18 @@ int OctreeManager::readNodeFromFile(std::ifstream& inFileStream, auto posEnd = fetchedData.begin() + (starsInNode * POS_SIZE); auto colEnd = posEnd + (starsInNode * COL_SIZE); auto velEnd = colEnd + (starsInNode * VEL_SIZE); - node->posData = std::vector(fetchedData.begin(), posEnd); - node->colData = std::vector(posEnd, colEnd); - node->velData = std::vector(colEnd, velEnd); + node.posData = std::vector(fetchedData.begin(), posEnd); + node.colData = std::vector(posEnd, colEnd); + node.velData = std::vector(colEnd, velEnd); } } // Create children if we're in an inner node and read from the corresponding nodes. - if (!node->isLeaf) { + if (!node.isLeaf) { numStars = 0; createNodeChildren(node); for (size_t i = 0; i < 8; ++i) { - numStars += readNodeFromFile(inFileStream, node->Children[i], readData); + numStars += readNodeFromFile(inFileStream, *node.Children[i], readData); } } @@ -696,21 +690,20 @@ void OctreeManager::writeToMultipleFiles(const std::string& outFolderPath, // Write entire branch to disc, with one file per node. std::string outFilePrefix = outFolderPath + std::to_string(branchIndex); // More threads doesn't make it much faster, disk speed still the limiter. - writeNodeToMultipleFiles(outFilePrefix, _root->Children[branchIndex], false); + writeNodeToMultipleFiles(outFilePrefix, *_root->Children[branchIndex], false); // Clear all data in branch. LINFO(fmt::format("Clear all data from branch {} in octree", branchIndex)); - clearNodeData(_root->Children[branchIndex]); + clearNodeData(*_root->Children[branchIndex]); } void OctreeManager::writeNodeToMultipleFiles(const std::string& outFilePrefix, - std::shared_ptr node, - bool threadWrites) + OctreeNode& node, bool threadWrites) { // Prepare node data, save nothing else. - std::vector nodeData = node->posData; - nodeData.insert(nodeData.end(), node->colData.begin(), node->colData.end()); - nodeData.insert(nodeData.end(), node->velData.begin(), node->velData.end()); + std::vector nodeData = node.posData; + nodeData.insert(nodeData.end(), node.colData.begin(), node.colData.end()); + nodeData.insert(nodeData.end(), node.velData.begin(), node.velData.end()); int32_t nDataSize = static_cast(nodeData.size()); size_t nBytes = nDataSize * sizeof(nodeData[0]); @@ -735,23 +728,21 @@ void OctreeManager::writeNodeToMultipleFiles(const std::string& outFilePrefix, } // Recursively write children to file (in Morton order) if we're in an inner node. - if (!node->isLeaf) { + if (!node.isLeaf) { std::vector writeThreads(8); for (size_t i = 0; i < 8; ++i) { std::string newOutFilePrefix = outFilePrefix + std::to_string(i); if (threadWrites) { // Divide writing to new threads to speed up the process. std::thread t( - &OctreeManager::writeNodeToMultipleFiles, - this, - newOutFilePrefix, - node->Children[i], - false + [this, newOutFilePrefix, n = node.Children[i]]() { + writeNodeToMultipleFiles(newOutFilePrefix, *n, false); + } ); writeThreads[i] = std::move(t); } else { - writeNodeToMultipleFiles(newOutFilePrefix, node->Children[i], false); + writeNodeToMultipleFiles(newOutFilePrefix, *node.Children[i], false); } } if (threadWrites) { @@ -763,34 +754,33 @@ void OctreeManager::writeNodeToMultipleFiles(const std::string& outFilePrefix, } } -void OctreeManager::fetchChildrenNodes( - std::shared_ptr parentNode, - int additionalLevelsToFetch) +void OctreeManager::fetchChildrenNodes(OctreeNode& parentNode, + int additionalLevelsToFetch) { // Lock node to make sure nobody else are trying to load the same children. - std::lock_guard lock(parentNode->loadingLock); + std::lock_guard lock(parentNode.loadingLock); for (int i = 0; i < 8; ++i) { // Fetch node data if we're streaming and it doesn't exist in RAM yet. // (As long as there is any RAM budget left and node actually has any data!) - if (!parentNode->Children[i]->isLoaded && - (parentNode->Children[i]->numStars > 0) && - _cpuRamBudget > static_cast(parentNode->Children[i]->numStars + if (!parentNode.Children[i]->isLoaded && + (parentNode.Children[i]->numStars > 0) && + _cpuRamBudget > static_cast(parentNode.Children[i]->numStars * (POS_SIZE + COL_SIZE + VEL_SIZE) * 4)) { - fetchNodeDataFromFile(parentNode->Children[i]); + fetchNodeDataFromFile(*parentNode.Children[i]); } // Fetch all Children's Children if recursive is set to true! - if (additionalLevelsToFetch != 0 && !parentNode->Children[i]->isLeaf) { - fetchChildrenNodes(parentNode->Children[i], --additionalLevelsToFetch); + if (additionalLevelsToFetch != 0 && !parentNode.Children[i]->isLeaf) { + fetchChildrenNodes(*parentNode.Children[i], --additionalLevelsToFetch); } } } -void OctreeManager::fetchNodeDataFromFile(std::shared_ptr node) { +void OctreeManager::fetchNodeDataFromFile(OctreeNode& node) { // Remove root ID ("8") from index before loading file. - std::string posId = std::to_string(node->octreePositionIndex); + std::string posId = std::to_string(node.octreePositionIndex); posId.erase(posId.begin()); std::string inFilePath = _streamFolderPath + posId + BINARY_SUFFIX; @@ -815,15 +805,15 @@ void OctreeManager::fetchNodeDataFromFile(std::shared_ptr node) { auto posEnd = readData.begin() + (starsInNode * POS_SIZE); auto colEnd = posEnd + (starsInNode * COL_SIZE); auto velEnd = colEnd + (starsInNode * VEL_SIZE); - node->posData = std::vector(readData.begin(), posEnd); - node->colData = std::vector(posEnd, colEnd); - node->velData = std::vector(colEnd, velEnd); + node.posData = std::vector(readData.begin(), posEnd); + node.colData = std::vector(posEnd, colEnd); + node.velData = std::vector(colEnd, velEnd); // Keep track of nodes that are loaded and update CPU RAM budget. - node->isLoaded = true; + node.isLoaded = true; if (!_datasetFitInMemory) { std::lock_guard g(_leastRecentlyFetchedNodesMutex); - _leastRecentlyFetchedNodes.push(node->octreePositionIndex); + _leastRecentlyFetchedNodes.push(node.octreePositionIndex); } _cpuRamBudget -= nBytes; } @@ -846,37 +836,37 @@ void OctreeManager::removeNodesFromRam( } // Traverse to node and remove it. - std::shared_ptr node = _root; + std::shared_ptr node = _root; std::vector> ancestors; while (!indexStack.empty()) { ancestors.push_back(node); node = node->Children[indexStack.top()]; indexStack.pop(); } - removeNode(node); + removeNode(*node); propagateUnloadedNodes(ancestors); } } -void OctreeManager::removeNode(std::shared_ptr node) { +void OctreeManager::removeNode(OctreeNode& node) { // Lock node to make sure nobody else is trying to access it while removing. - std::lock_guard lock(node->loadingLock); + std::lock_guard lock(node.loadingLock); int nBytes = static_cast( - node->numStars * _valuesPerStar * sizeof(node->posData[0]) + node.numStars * _valuesPerStar * sizeof(node.posData[0]) ); // Keep track of which nodes that are loaded and update CPU RAM budget. - node->isLoaded = false; + node.isLoaded = false; _cpuRamBudget += nBytes; // Clear data - node->posData.clear(); - node->posData.shrink_to_fit(); - node->colData.clear(); - node->colData.shrink_to_fit(); - node->velData.clear(); - node->velData.shrink_to_fit(); + node.posData.clear(); + node.posData.shrink_to_fit(); + node.colData.clear(); + node.colData.shrink_to_fit(); + node.velData.clear(); + node.velData.shrink_to_fit(); } void OctreeManager::propagateUnloadedNodes( @@ -966,10 +956,10 @@ size_t OctreeManager::getChildIndex(float posX, float posY, float posZ, float or return index; } -bool OctreeManager::insertInNode(std::shared_ptr node, - const std::vector& starValues, int depth) +bool OctreeManager::insertInNode(OctreeNode& node, const std::vector& starValues, + int depth) { - if (node->isLeaf && node->numStars < MAX_STARS_PER_NODE) { + if (node.isLeaf && node.numStars < MAX_STARS_PER_NODE) { // Node is a leaf and it's not yet full -> insert star. storeStarData(node, starValues); @@ -978,7 +968,7 @@ bool OctreeManager::insertInNode(std::shared_ptr node, } return true; } - else if (node->isLeaf) { + else if (node.isLeaf) { // Too many stars in leaf node, subdivide into 8 new nodes. // Create children and clean up parent. createNodeChildren(node); @@ -986,15 +976,15 @@ bool OctreeManager::insertInNode(std::shared_ptr node, // Distribute stars from parent node into children. for (size_t n = 0; n < MAX_STARS_PER_NODE; ++n) { // Position data. - auto posBegin = node->posData.begin() + n * POS_SIZE; + auto posBegin = node.posData.begin() + n * POS_SIZE; auto posEnd = posBegin + POS_SIZE; std::vector tmpValues(posBegin, posEnd); // Color data. - auto colBegin = node->colData.begin() + n * COL_SIZE; + auto colBegin = node.colData.begin() + n * COL_SIZE; auto colEnd = colBegin + COL_SIZE; tmpValues.insert(tmpValues.end(), colBegin, colEnd); // Velocity data. - auto velBegin = node->velData.begin() + n * VEL_SIZE; + auto velBegin = node.velData.begin() + n * VEL_SIZE; auto velEnd = velBegin + VEL_SIZE; tmpValues.insert(tmpValues.end(), velBegin, velEnd); @@ -1003,16 +993,16 @@ bool OctreeManager::insertInNode(std::shared_ptr node, tmpValues[0], tmpValues[1], tmpValues[2], - node->originX, - node->originY, - node->originZ + node.originX, + node.originY, + node.originZ ); - insertInNode(node->Children[index], tmpValues, depth); + insertInNode(*node.Children[index], tmpValues, depth); } // Sort magnitudes in inner node. // (The last value will be used as comparison for what to store in LOD cache.) - std::sort(node->magOrder.begin(), node->magOrder.end()); + std::sort(node.magOrder.begin(), node.magOrder.end()); } // Node is an inner node, keep recursion going. @@ -1021,96 +1011,94 @@ bool OctreeManager::insertInNode(std::shared_ptr node, starValues[0], starValues[1], starValues[2], - node->originX, - node->originY, - node->originZ + node.originX, + node.originY, + node.originZ ); // Determine if new star should be kept in our LOD cache. // Keeps track of the brightest nodes in children. - if (starValues[POS_SIZE] < node->magOrder[MAX_STARS_PER_NODE - 1].first) { + if (starValues[POS_SIZE] < node.magOrder[MAX_STARS_PER_NODE - 1].first) { storeStarData(node, starValues); } - return insertInNode(node->Children[index], starValues, ++depth); + return insertInNode(*node.Children[index], starValues, ++depth); } -void OctreeManager::sliceNodeLodCache(std::shared_ptr node) { +void OctreeManager::sliceNodeLodCache(OctreeNode& node) { // Slice stored LOD data in inner nodes. - if (!node->isLeaf) { + if (!node.isLeaf) { // Sort by magnitude. Inverse relation (i.e. a lower magnitude means a brighter // star!) - std::sort(node->magOrder.begin(), node->magOrder.end()); - node->magOrder.resize(MAX_STARS_PER_NODE); + std::sort(node.magOrder.begin(), node.magOrder.end()); + node.magOrder.resize(MAX_STARS_PER_NODE); std::vector tmpPos; std::vector tmpCol; std::vector tmpVel; // Ordered map contain the MAX_STARS_PER_NODE brightest stars in all children! - for (auto const &[absMag, placement] : node->magOrder) { - auto posBegin = node->posData.begin() + placement * POS_SIZE; - auto colBegin = node->colData.begin() + placement * COL_SIZE; - auto velBegin = node->velData.begin() + placement * VEL_SIZE; + for (auto const &[absMag, placement] : node.magOrder) { + auto posBegin = node.posData.begin() + placement * POS_SIZE; + auto colBegin = node.colData.begin() + placement * COL_SIZE; + auto velBegin = node.velData.begin() + placement * VEL_SIZE; tmpPos.insert(tmpPos.end(), posBegin, posBegin + POS_SIZE); tmpCol.insert(tmpCol.end(), colBegin, colBegin + COL_SIZE); tmpVel.insert(tmpVel.end(), velBegin, velBegin + VEL_SIZE); } - node->posData = std::move(tmpPos); - node->colData = std::move(tmpCol); - node->velData = std::move(tmpVel); - node->numStars = node->magOrder.size(); // = MAX_STARS_PER_NODE + node.posData = std::move(tmpPos); + node.colData = std::move(tmpCol); + node.velData = std::move(tmpVel); + node.numStars = node.magOrder.size(); // = MAX_STARS_PER_NODE for (int i = 0; i < 8; ++i) { - sliceNodeLodCache(node->Children[i]); + sliceNodeLodCache(*node.Children[i]); } } } -void OctreeManager::storeStarData(std::shared_ptr node, - const std::vector& starValues) +void OctreeManager::storeStarData(OctreeNode& node, const std::vector& starValues) { // Insert star data at the back of vectors and store a vector with pairs consisting of // star magnitude and insert index for later sorting and slicing of LOD cache. float mag = starValues[POS_SIZE]; - node->magOrder.insert(node->magOrder.end(), std::make_pair(mag, node->numStars)); - node->numStars++; + node.magOrder.insert(node.magOrder.end(), std::make_pair(mag, node.numStars)); + node.numStars++; // If LOD is growing too large then sort it and resize to [chunk size] to avoid too // much RAM usage and increase threshold for adding new stars. - if (node->magOrder.size() > MAX_STARS_PER_NODE * 2) { - std::sort(node->magOrder.begin(), node->magOrder.end()); - node->magOrder.resize(MAX_STARS_PER_NODE); + if (node.magOrder.size() > MAX_STARS_PER_NODE * 2) { + std::sort(node.magOrder.begin(), node.magOrder.end()); + node.magOrder.resize(MAX_STARS_PER_NODE); } auto posEnd = starValues.begin() + POS_SIZE; auto colEnd = posEnd + COL_SIZE; - node->posData.insert(node->posData.end(), starValues.begin(), posEnd); - node->colData.insert(node->colData.end(), posEnd, colEnd); - node->velData.insert(node->velData.end(), colEnd, starValues.end()); + node.posData.insert(node.posData.end(), starValues.begin(), posEnd); + node.colData.insert(node.colData.end(), posEnd, colEnd); + node.velData.insert(node.velData.end(), colEnd, starValues.end()); } -std::string OctreeManager::printStarsPerNode(std::shared_ptr node, +std::string OctreeManager::printStarsPerNode(const OctreeNode& node, const std::string& prefix) const { // Print both inner and leaf nodes. - auto str = prefix + "} : " + std::to_string(node->numStars); + auto str = prefix + "} : " + std::to_string(node.numStars); - if (node->isLeaf) { + if (node.isLeaf) { return str + " - [Leaf] \n"; } else { - str += fmt::format("LOD: {} - [Parent]\n", node->posData.size() / POS_SIZE); + str += fmt::format("LOD: {} - [Parent]\n", node.posData.size() / POS_SIZE); for (int i = 0; i < 8; ++i) { auto pref = prefix + "->" + std::to_string(i); - str += printStarsPerNode(node->Children[i], pref); + str += printStarsPerNode(*node.Children[i], pref); } return str; } } -std::map> OctreeManager::checkNodeIntersection( - std::shared_ptr node, +std::map> OctreeManager::checkNodeIntersection(OctreeNode& node, const glm::dmat4& mvp, const glm::vec2& screenSize, int& deltaStars, @@ -1123,14 +1111,14 @@ std::map> OctreeManager::checkNodeIntersection( std::vector corners(8); for (int i = 0; i < 8; ++i) { const float x = (i % 2 == 0) ? - node->originX + node->halfDimension : - node->originX - node->halfDimension; + node.originX + node.halfDimension : + node.originX - node.halfDimension; const float y = (i % 4 < 2) ? - node->originY + node->halfDimension : - node->originY - node->halfDimension; + node.originY + node.halfDimension : + node.originY - node.halfDimension; const float z = (i < 4) ? - node->originZ + node->halfDimension : - node->originZ - node->halfDimension; + node.originZ + node.halfDimension : + node.originZ - node.halfDimension; glm::dvec3 pos = glm::dvec3(x, y, z) * 1000.0 * distanceconstants::Parsec; corners[i] = glm::dvec4(pos, 1.0); } @@ -1145,7 +1133,7 @@ std::map> OctreeManager::checkNodeIntersection( // Remove node if it has been unloaded while still in view. // (While streaming big datasets.) - if (node->bufferIndex != DEFAULT_INDEX && !node->isLoaded && _streamOctree && + if (node.bufferIndex != DEFAULT_INDEX && !node.isLoaded && _streamOctree && !_datasetFitInMemory) { fetchedData = removeNodeFromCache(node, deltaStars); @@ -1153,7 +1141,7 @@ std::map> OctreeManager::checkNodeIntersection( } // Take care of inner nodes. - if (!(node->isLeaf)) { + if (!(node.isLeaf)) { glm::vec2 nodeSize = _culler->getNodeSizeInPixels(corners, mvp, screenSize); float totalPixels = nodeSize.x * nodeSize.y; @@ -1162,11 +1150,11 @@ std::map> OctreeManager::checkNodeIntersection( // (as long as it doesn't have loaded children because then we should traverse to // lowest loaded level and render it instead)! if ((totalPixels < _minTotalPixelsLod) || (_streamOctree && - !_datasetFitInMemory && node->isLoaded && !node->hasLoadedDescendant)) + !_datasetFitInMemory && node.isLoaded && !node.hasLoadedDescendant)) { // Get correct insert index from stack if node didn't exist already. Otherwise // we will overwrite the old data. Key merging is not a problem here. - if ((node->bufferIndex == DEFAULT_INDEX) || _rebuildBuffer) { + if ((node.bufferIndex == DEFAULT_INDEX) || _rebuildBuffer) { // Return empty if we couldn't claim a buffer stream index. if (!updateBufferIndex(node)) { return fetchedData; @@ -1175,14 +1163,14 @@ std::map> OctreeManager::checkNodeIntersection( // We're in an inner node, remove indices from potential children in cache for (int i = 0; i < 8; ++i) { std::map> tmpData = removeNodeFromCache( - node->Children[i], + *node.Children[i], deltaStars ); fetchedData.insert(tmpData.begin(), tmpData.end()); } // Insert data and adjust stars added in this frame. - fetchedData[node->bufferIndex] = constructInsertData( + fetchedData[node.bufferIndex] = constructInsertData( node, option, deltaStars @@ -1194,14 +1182,14 @@ std::map> OctreeManager::checkNodeIntersection( // Return node data if node is a leaf. else { // If node already is in cache then skip it, otherwise store it. - if ((node->bufferIndex == DEFAULT_INDEX) || _rebuildBuffer) { + if ((node.bufferIndex == DEFAULT_INDEX) || _rebuildBuffer) { // Return empty if we couldn't claim a buffer stream index. if (!updateBufferIndex(node)) { return fetchedData; } // Insert data and adjust stars added in this frame. - fetchedData[node->bufferIndex] = constructInsertData( + fetchedData[node.bufferIndex] = constructInsertData( node, option, deltaStars @@ -1219,7 +1207,7 @@ std::map> OctreeManager::checkNodeIntersection( // Observe that if there exists identical keys in fetchedData then those values in // tmpData will be ignored! Thus we store the removed keys until next render call! std::map> tmpData = checkNodeIntersection( - node->Children[i], + *node.Children[i], mvp, screenSize, deltaStars, @@ -1230,10 +1218,9 @@ std::map> OctreeManager::checkNodeIntersection( return fetchedData; } -std::map> OctreeManager::removeNodeFromCache( - std::shared_ptr node, - int& deltaStars, - bool recursive) +std::map> OctreeManager::removeNodeFromCache(OctreeNode& node, + int& deltaStars, + bool recursive) { std::map> keysToRemove; @@ -1241,24 +1228,24 @@ std::map> OctreeManager::removeNodeFromCache( //if (_rebuildBuffer) return keysToRemove; // Check if this node was rendered == had a specified index. - if (node->bufferIndex != DEFAULT_INDEX) { + if (node.bufferIndex != DEFAULT_INDEX) { // Reclaim that index. We need to wait until next render call to use it again! - _removedKeysInPrevCall.insert(node->bufferIndex); + _removedKeysInPrevCall.insert(node.bufferIndex); // Insert dummy node at offset index that should be removed from render. - keysToRemove[node->bufferIndex] = std::vector(); + keysToRemove[node.bufferIndex] = std::vector(); // Reset index and adjust stars removed this frame. - node->bufferIndex = DEFAULT_INDEX; - deltaStars -= static_cast(node->numStars); + node.bufferIndex = DEFAULT_INDEX; + deltaStars -= static_cast(node.numStars); } // Check children recursively if we're in an inner node. - if (!(node->isLeaf) && recursive) { + if (!(node.isLeaf) && recursive) { for (int i = 0; i < 8; ++i) { std::map> tmpData = removeNodeFromCache( - node->Children[i], + *node.Children[i], deltaStars ); keysToRemove.insert(tmpData.begin(), tmpData.end()); @@ -1267,11 +1254,11 @@ std::map> OctreeManager::removeNodeFromCache( return keysToRemove; } -std::vector OctreeManager::getNodeData(std::shared_ptr node, +std::vector OctreeManager::getNodeData(const OctreeNode& node, gaia::RenderOption option) { // Return node data if node is a leaf. - if (node->isLeaf) { + if (node.isLeaf) { int dStars = 0; return constructInsertData(node, option, dStars); } @@ -1279,88 +1266,89 @@ std::vector OctreeManager::getNodeData(std::shared_ptr node, // If we're not in a leaf, get data from all children recursively. auto nodeData = std::vector(); for (size_t i = 0; i < 8; ++i) { - std::vector tmpData = getNodeData(node->Children[i], option); + std::vector tmpData = getNodeData(*node.Children[i], option); nodeData.insert(nodeData.end(), tmpData.begin(), tmpData.end()); } return nodeData; } -void OctreeManager::clearNodeData(std::shared_ptr node) { +void OctreeManager::clearNodeData(OctreeNode& node) { // Clear data and its allocated memory. - node->posData.clear(); - node->posData.shrink_to_fit(); - node->colData.clear(); - node->colData.shrink_to_fit(); - node->velData.clear(); - node->velData.shrink_to_fit(); + node.posData.clear(); + node.posData.shrink_to_fit(); + node.colData.clear(); + node.colData.shrink_to_fit(); + node.velData.clear(); + node.velData.shrink_to_fit(); // Clear magnitudes as well! //std::vector>().swap(node->magOrder); - node->magOrder.clear(); + node.magOrder.clear(); - if (!node->isLeaf) { + if (!node.isLeaf) { // Remove data from all children recursively. for (size_t i = 0; i < 8; ++i) { - clearNodeData(node->Children[i]); + clearNodeData(*node.Children[i]); } } } -void OctreeManager::createNodeChildren(std::shared_ptr node) { +void OctreeManager::createNodeChildren(OctreeNode& node) { for (size_t i = 0; i < 8; ++i) { _numLeafNodes++; - node->Children[i] = std::make_shared(); - node->Children[i]->isLeaf = true; - node->Children[i]->isLoaded = false; - node->Children[i]->hasLoadedDescendant = false; - node->Children[i]->bufferIndex = DEFAULT_INDEX; - node->Children[i]->octreePositionIndex = (node->octreePositionIndex * 10) + i; - node->Children[i]->numStars = 0; - node->Children[i]->posData = std::vector(); - node->Children[i]->colData = std::vector(); - node->Children[i]->velData = std::vector(); - node->Children[i]->magOrder = std::vector>(); - node->Children[i]->halfDimension = node->halfDimension / 2.f; + node.Children[i] = std::make_shared(); + node.Children[i]->isLeaf = true; + node.Children[i]->isLoaded = false; + node.Children[i]->hasLoadedDescendant = false; + node.Children[i]->bufferIndex = DEFAULT_INDEX; + node.Children[i]->octreePositionIndex = (node.octreePositionIndex * 10) + i; + node.Children[i]->numStars = 0; + node.Children[i]->posData = std::vector(); + node.Children[i]->colData = std::vector(); + node.Children[i]->velData = std::vector(); + node.Children[i]->magOrder = std::vector>(); + node.Children[i]->halfDimension = node.halfDimension / 2.f; // Calculate new origin. - node->Children[i]->originX = node->originX; - node->Children[i]->originX += (i % 2 == 0) ? - node->Children[i]->halfDimension : - -node->Children[i]->halfDimension; - node->Children[i]->originY = node->originY; - node->Children[i]->originY += (i % 4 < 2) ? - node->Children[i]->halfDimension : - -node->Children[i]->halfDimension; - node->Children[i]->originZ = node->originZ; - node->Children[i]->originZ += (i < 4) ? - node->Children[i]->halfDimension : - -node->Children[i]->halfDimension; + node.Children[i]->originX = node.originX; + node.Children[i]->originX += (i % 2 == 0) ? + node.Children[i]->halfDimension : + -node.Children[i]->halfDimension; + node.Children[i]->originY = node.originY; + node.Children[i]->originY += (i % 4 < 2) ? + node.Children[i]->halfDimension : + -node.Children[i]->halfDimension; + node.Children[i]->originZ = node.originZ; + node.Children[i]->originZ += (i < 4) ? + node.Children[i]->halfDimension : + -node.Children[i]->halfDimension; } // Clean up parent. - node->isLeaf = false; + node.isLeaf = false; _numLeafNodes--; _numInnerNodes++; } -bool OctreeManager::updateBufferIndex(std::shared_ptr node) { - if (node->bufferIndex != DEFAULT_INDEX) { +bool OctreeManager::updateBufferIndex(OctreeNode& node) { + if (node.bufferIndex != DEFAULT_INDEX) { // If we're rebuilding Buffer Index Cache then store indices to overwrite later. - _removedKeysInPrevCall.insert(node->bufferIndex); + _removedKeysInPrevCall.insert(node.bufferIndex); } // Make sure node isn't loading/unloading as we're checking isLoaded flag. - std::lock_guard lock(node->loadingLock); + std::lock_guard lock(node.loadingLock); // Return false if there are no more spots in our buffer, or if we're streaming and // node isn't loaded yet, or if node doesn't have any stars. - if (_freeSpotsInBuffer.empty() || (_streamOctree && !node->isLoaded) || - node->numStars == 0) { + if (_freeSpotsInBuffer.empty() || (_streamOctree && !node.isLoaded) || + node.numStars == 0) + { return false; } // Get correct insert index from stack. - node->bufferIndex = _freeSpotsInBuffer.top(); + node.bufferIndex = _freeSpotsInBuffer.top(); _freeSpotsInBuffer.pop(); // Keep track of how many chunks are in use (ceiling). @@ -1373,32 +1361,28 @@ bool OctreeManager::updateBufferIndex(std::shared_ptr node) { return true; } -std::vector OctreeManager::constructInsertData(std::shared_ptr node, +std::vector OctreeManager::constructInsertData(const OctreeNode& node, gaia::RenderOption option, int& deltaStars) { // Return early if node doesn't contain any stars! - if (node->numStars == 0) { + if (node.numStars == 0) { return std::vector(); } // Fill chunk by appending zeroes to data so we overwrite possible earlier values. // And more importantly so our attribute pointers knows where to read! - auto insertData = std::vector(node->posData.begin(), node->posData.end()); + auto insertData = std::vector(node.posData.begin(), node.posData.end()); if (_useVBO) { insertData.resize(POS_SIZE * MAX_STARS_PER_NODE, 0.f); } if (option != gaia::RenderOption::Static) { - insertData.insert(insertData.end(), node->colData.begin(), node->colData.end()); + insertData.insert(insertData.end(), node.colData.begin(), node.colData.end()); if (_useVBO) { insertData.resize((POS_SIZE + COL_SIZE) * MAX_STARS_PER_NODE, 0.f); } if (option == gaia::RenderOption::Motion) { - insertData.insert( - insertData.end(), - node->velData.begin(), - node->velData.end() - ); + insertData.insert(insertData.end(), node.velData.begin(), node.velData.end()); if (_useVBO) { insertData.resize( (POS_SIZE + COL_SIZE + VEL_SIZE) * MAX_STARS_PER_NODE, 0.f @@ -1408,7 +1392,7 @@ std::vector OctreeManager::constructInsertData(std::shared_ptr(node->numStars); + deltaStars += static_cast(node.numStars); return insertData; } diff --git a/modules/gaia/rendering/octreemanager.h b/modules/gaia/rendering/octreemanager.h index bf60722acc..d8d4b3fe85 100644 --- a/modules/gaia/rendering/octreemanager.h +++ b/modules/gaia/rendering/octreemanager.h @@ -60,7 +60,7 @@ public: }; OctreeManager() = default; - ~OctreeManager(); + ~OctreeManager() = default; /** * Initializes a one layer Octree with root and 8 children that covers all stars. @@ -212,28 +212,27 @@ private: * If node is an inner node, then star is stores in LOD cache if it is among the * brightest stars in all children. */ - bool insertInNode(std::shared_ptr node, - const std::vector& starValues, int depth = 1); + bool insertInNode(OctreeNode& node, const std::vector& starValues, + int depth = 1); /** * Slices LOD cache data in node to the MAX_STARS_PER_NODE brightest stars. This needs * to be called after the last star has been inserted into Octree but before it is * saved to file(s). Slices all descendants recursively. */ - void sliceNodeLodCache(std::shared_ptr node); + void sliceNodeLodCache(OctreeNode& node); /** * Private help function for insertInNode(). Stores star data in node and * keeps track of the brightest stars all children. */ - void storeStarData(std::shared_ptr node, - const std::vector& starValues); + void storeStarData(OctreeNode& node, const std::vector& starValues); /** * Private help function for printStarsPerNode(). \returns an accumulated * string containing all descendant nodes. */ - std::string printStarsPerNode(std::shared_ptr node, + std::string printStarsPerNode(const OctreeNode& node, const std::string& prefix) const; /** @@ -243,9 +242,9 @@ private: * loaded (if streaming). \param deltaStars keeps track of how many stars that were * added/removed this render call. */ - std::map> checkNodeIntersection( - std::shared_ptr node, const glm::dmat4& mvp, - const glm::vec2& screenSize, int& deltaStars, gaia::RenderOption option); + std::map> checkNodeIntersection(OctreeNode& node, + const glm::dmat4& mvp, const glm::vec2& screenSize, int& deltaStars, + gaia::RenderOption option); /** * Checks if specified node existed in cache, and removes it if that's the case. @@ -253,31 +252,30 @@ private: * long as \param recursive is not set to false. \param deltaStars keeps track of how * many stars that were removed. */ - std::map> removeNodeFromCache( - std::shared_ptr node, int& deltaStars, bool recursive = true); + std::map> removeNodeFromCache(OctreeNode& node, + int& deltaStars, bool recursive = true); /** * Get data in node and its descendants regardless if they are visible or not. */ - std::vector getNodeData(std::shared_ptr node, - gaia::RenderOption option); + std::vector getNodeData(const OctreeNode& node, gaia::RenderOption option); /** * Clear data from node and its descendants and shrink vectors to deallocate memory. */ - void clearNodeData(std::shared_ptr node); + void clearNodeData(OctreeNode& node); /** * Contruct default children nodes for specified node. */ - void createNodeChildren(std::shared_ptr node); + void createNodeChildren(OctreeNode& node); /** * Checks if node should be inserted into stream or not. \returns true if it should, * (i.e. it doesn't already exists, there is room for it in the buffer and node data * is loaded if streaming). \returns false otherwise. */ - bool updateBufferIndex(std::shared_ptr node); + bool updateBufferIndex(OctreeNode& node); /** * Node should be inserted into stream. This function \returns the data to be @@ -286,14 +284,14 @@ private: * * \param deltaStars keeps track of how many stars that were added. */ - std::vector constructInsertData(std::shared_ptr node, + std::vector constructInsertData(const OctreeNode& node, gaia::RenderOption option, int& deltaStars); /** * Write a node to outFileStream. \param writeData defines if data should be included * or if only structure should be written. */ - void writeNodeToFile(std::ofstream& outFileStream, std::shared_ptr node, + void writeNodeToFile(std::ofstream& outFileStream, const OctreeNode& node, bool writeData); /** @@ -301,16 +299,15 @@ private: * data or only structure should be read. * \returns accumulated sum of all read stars in node and its descendants. */ - int readNodeFromFile(std::ifstream& inFileStream, std::shared_ptr node, - bool readData); + int readNodeFromFile(std::ifstream& inFileStream, OctreeNode& node, bool readData); /** * Write node data to a file. \param outFilePrefix specifies the accumulated path * and name of the file. If \param threadWrites is set to true then one new thread * will be created for each child to write its descendents. */ - void writeNodeToMultipleFiles(const std::string& outFilePrefix, - std::shared_ptr node, bool threadWrites); + void writeNodeToMultipleFiles(const std::string& outFilePrefix, OctreeNode& node, + bool threadWrites); /** * Finds the neighboring node on the same level (or a higher level if there is no @@ -329,15 +326,14 @@ private: * If it is set to a negative value then all descendants will be fetched recursively. * Calls fetchNodeDataFromFile() for every child that passes the tests. */ - void fetchChildrenNodes(std::shared_ptr parentNode, - int additionalLevelsToFetch); + void fetchChildrenNodes(OctreeNode& parentNode, int additionalLevelsToFetch); /** * Fetches data for specified node from file. * OBS! Only call if node file exists (i.e. node has any data, node->numStars > 0) * and is not already loaded. */ - void fetchNodeDataFromFile(std::shared_ptr node); + void fetchNodeDataFromFile(OctreeNode& node); /** * Loops though all nodes in \param nodesToRemove and clears them from RAM. @@ -350,7 +346,7 @@ private: * Removes data in specified node from main memory and updates RAM budget and flags * accordingly. */ - void removeNode(std::shared_ptr node); + void removeNode(OctreeNode& node); /** * Loops through \param ancestorNodes backwards and checks if parent node has any diff --git a/modules/gaia/rendering/renderablegaiastars.cpp b/modules/gaia/rendering/renderablegaiastars.cpp index 24fe3331c6..ea568a0ba5 100644 --- a/modules/gaia/rendering/renderablegaiastars.cpp +++ b/modules/gaia/rendering/renderablegaiastars.cpp @@ -45,7 +45,7 @@ #include #include #include -#include +#include namespace { constexpr const char* _loggerCat = "RenderableGaiaStars"; @@ -856,8 +856,6 @@ RenderableGaiaStars::RenderableGaiaStars(const ghoul::Dictionary& dictionary) addProperty(_gpuStreamBudgetProperty); } -RenderableGaiaStars::~RenderableGaiaStars() {} - bool RenderableGaiaStars::isReady() const { return _program && _programTM; } @@ -1157,7 +1155,9 @@ void RenderableGaiaStars::render(const RenderData& data, RendererTasks&) { _previousCameraRotation = data.camera.rotationQuaternion(); return; } - else _firstDrawCalls = false; + else { + _firstDrawCalls = false; + } // Update which nodes that are stored in memory as the camera moves around // (if streaming) diff --git a/modules/gaia/rendering/renderablegaiastars.h b/modules/gaia/rendering/renderablegaiastars.h index 6b9179bc07..816f5a1435 100644 --- a/modules/gaia/rendering/renderablegaiastars.h +++ b/modules/gaia/rendering/renderablegaiastars.h @@ -53,7 +53,7 @@ namespace documentation { struct Documentation; } class RenderableGaiaStars : public Renderable { public: explicit RenderableGaiaStars(const ghoul::Dictionary& dictionary); - virtual ~RenderableGaiaStars(); + virtual ~RenderableGaiaStars() = default; void initializeGL() override; void deinitializeGL() override; diff --git a/modules/gaia/tasks/constructoctreetask.cpp b/modules/gaia/tasks/constructoctreetask.cpp index 095d6bd750..4263675243 100644 --- a/modules/gaia/tasks/constructoctreetask.cpp +++ b/modules/gaia/tasks/constructoctreetask.cpp @@ -195,28 +195,27 @@ ConstructOctreeTask::ConstructOctreeTask(const ghoul::Dictionary& dictionary) { } } -ConstructOctreeTask::~ConstructOctreeTask() {} - std::string ConstructOctreeTask::description() { return "Read bin file (or files in folder): " + _inFileOrFolderPath + "\n " "and write octree data file (or files) into: " + _outFileOrFolderPath + "\n"; } -void ConstructOctreeTask::perform(const Task::ProgressCallback& progressCallback) { - progressCallback(0.0f); +void ConstructOctreeTask::perform(const Task::ProgressCallback& onProgress) { + onProgress(0.0f); if (_singleFileInput) { - constructOctreeFromSingleFile(progressCallback); + constructOctreeFromSingleFile(onProgress); } else { - constructOctreeFromFolder(progressCallback); + constructOctreeFromFolder(onProgress); } - progressCallback(1.0f); + onProgress(1.0f); } void ConstructOctreeTask::constructOctreeFromSingleFile( - const Task::ProgressCallback& progressCallback) { + const Task::ProgressCallback& progressCallback) +{ std::vector fullData; int32_t nValues = 0; int32_t nValuesPerStar = 0; diff --git a/modules/gaia/tasks/constructoctreetask.h b/modules/gaia/tasks/constructoctreetask.h index 12d50d5c34..ce31454c01 100644 --- a/modules/gaia/tasks/constructoctreetask.h +++ b/modules/gaia/tasks/constructoctreetask.h @@ -37,7 +37,7 @@ namespace documentation { struct Documentation; } class ConstructOctreeTask : public Task { public: ConstructOctreeTask(const ghoul::Dictionary& dictionary); - virtual ~ConstructOctreeTask(); + virtual ~ConstructOctreeTask() = default; std::string description() override; void perform(const Task::ProgressCallback& onProgress) override; diff --git a/modules/gaia/tasks/readfilejob.cpp b/modules/gaia/tasks/readfilejob.cpp index 2295c28840..9d7292c030 100644 --- a/modules/gaia/tasks/readfilejob.cpp +++ b/modules/gaia/tasks/readfilejob.cpp @@ -35,17 +35,16 @@ namespace { namespace openspace::gaia { -ReadFileJob::ReadFileJob(const std::string& filePath, - const std::vector& allColumns, int firstRow, - int lastRow, size_t nDefaultCols, int nValuesPerStar, - std::shared_ptr fitsReader) - : _inFilePath(filePath) - , _allColumns(allColumns) +ReadFileJob::ReadFileJob(std::string filePath, std::vector allColumns, + int firstRow, int lastRow, size_t nDefaultCols, + int nValuesPerStar, std::shared_ptr fitsReader) + : _inFilePath(std::move(filePath)) + , _allColumns(std::move(allColumns)) , _firstRow(firstRow) , _lastRow(lastRow) , _nDefaultCols(nDefaultCols) , _nValuesPerStar(nValuesPerStar) - , _fitsFileReader(fitsReader) + , _fitsFileReader(std::move(fitsReader)) , _octants(8) {} diff --git a/modules/gaia/tasks/readfilejob.h b/modules/gaia/tasks/readfilejob.h index 6433f7c930..b6742881a3 100644 --- a/modules/gaia/tasks/readfilejob.h +++ b/modules/gaia/tasks/readfilejob.h @@ -44,8 +44,8 @@ struct ReadFileJob : public Job>> { * If \param lastRow < firstRow then entire table will be read. * \param nValuesPerStar defines how many values that will be stored per star. */ - ReadFileJob(const std::string& filePath, const std::vector& allColumns, - int firstRow, int lastRow, size_t nDefaultCols, int nValuesPerStar, + ReadFileJob(std::string filePath, std::vector allColumns, int firstRow, + int lastRow, size_t nDefaultCols, int nValuesPerStar, std::shared_ptr fitsReader); ~ReadFileJob() = default; diff --git a/modules/gaia/tasks/readfitstask.cpp b/modules/gaia/tasks/readfitstask.cpp index 2c5985699c..07d1eb2d0c 100644 --- a/modules/gaia/tasks/readfitstask.cpp +++ b/modules/gaia/tasks/readfitstask.cpp @@ -108,17 +108,17 @@ std::string ReadFitsTask::description() { ); } -void ReadFitsTask::perform(const Task::ProgressCallback& progressCallback) { - progressCallback(0.f); +void ReadFitsTask::perform(const Task::ProgressCallback& onProgress) { + onProgress(0.f); if (_singleFileProcess) { - readSingleFitsFile(progressCallback); + readSingleFitsFile(onProgress); } else { - readAllFitsFilesFromFolder(progressCallback); + readAllFitsFilesFromFolder(onProgress); } - progressCallback(1.f); + onProgress(1.f); } void ReadFitsTask::readSingleFitsFile(const Task::ProgressCallback& progressCallback) { diff --git a/modules/gaia/tasks/readspecktask.cpp b/modules/gaia/tasks/readspecktask.cpp index 409028c78d..aa9600fb36 100644 --- a/modules/gaia/tasks/readspecktask.cpp +++ b/modules/gaia/tasks/readspecktask.cpp @@ -59,15 +59,15 @@ std::string ReadSpeckTask::description() { ); } -void ReadSpeckTask::perform(const Task::ProgressCallback& progressCallback) { - progressCallback(0.f); +void ReadSpeckTask::perform(const Task::ProgressCallback& onProgress) { + onProgress(0.f); int32_t nRenderValues = 0; FitsFileReader fileReader(false); std::vector fullData = fileReader.readSpeckFile(_inFilePath, nRenderValues); - progressCallback(0.9f); + onProgress(0.9f); std::ofstream fileStream(_outFilePath, std::ofstream::binary); if (fileStream.good()) { @@ -89,7 +89,7 @@ void ReadSpeckTask::perform(const Task::ProgressCallback& progressCallback) { LERROR(fmt::format("Error opening file: {} as output data file.", _outFilePath)); } - progressCallback(1.f); + onProgress(1.f); } documentation::Documentation ReadSpeckTask::Documentation() { diff --git a/modules/galaxy/rendering/galaxyraycaster.cpp b/modules/galaxy/rendering/galaxyraycaster.cpp index 0030ab2be6..79f6d90d32 100644 --- a/modules/galaxy/rendering/galaxyraycaster.cpp +++ b/modules/galaxy/rendering/galaxyraycaster.cpp @@ -48,8 +48,6 @@ GalaxyRaycaster::GalaxyRaycaster(ghoul::opengl::Texture& texture) , _textureUnit(nullptr) {} -GalaxyRaycaster::~GalaxyRaycaster() {} - void GalaxyRaycaster::initialize() { _boundingBox.initialize(); } diff --git a/modules/galaxy/rendering/galaxyraycaster.h b/modules/galaxy/rendering/galaxyraycaster.h index b8979c08b5..c758858811 100644 --- a/modules/galaxy/rendering/galaxyraycaster.h +++ b/modules/galaxy/rendering/galaxyraycaster.h @@ -47,7 +47,7 @@ class GalaxyRaycaster : public VolumeRaycaster { public: GalaxyRaycaster(ghoul::opengl::Texture& texture); - virtual ~GalaxyRaycaster(); + virtual ~GalaxyRaycaster() = default; void initialize(); void renderEntryPoints(const RenderData& data, diff --git a/modules/galaxy/rendering/renderablegalaxy.cpp b/modules/galaxy/rendering/renderablegalaxy.cpp index 5ffcc79942..ad1f16d8a2 100644 --- a/modules/galaxy/rendering/renderablegalaxy.cpp +++ b/modules/galaxy/rendering/renderablegalaxy.cpp @@ -135,8 +135,6 @@ namespace openspace { pointsDictionary.getValue("Scaling", _pointScaling); } -RenderableGalaxy::~RenderableGalaxy() {} - void RenderableGalaxy::initializeGL() { // Aspect is currently hardcoded to cubic voxels. _aspect = static_cast(_volumeDimensions); @@ -167,14 +165,14 @@ void RenderableGalaxy::initializeGL() { _raycaster = std::make_unique(*_texture); _raycaster->initialize(); - global::raycasterManager.attachRaycaster(*_raycaster.get()); + global::raycasterManager.attachRaycaster(*_raycaster); auto onChange = [&](bool enabled) { if (enabled) { - global::raycasterManager.attachRaycaster(*_raycaster.get()); + global::raycasterManager.attachRaycaster(*_raycaster); } else { - global::raycasterManager.detachRaycaster(*_raycaster.get()); + global::raycasterManager.detachRaycaster(*_raycaster); } }; @@ -217,8 +215,8 @@ void RenderableGalaxy::initializeGL() { 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)); + pointPositions.emplace_back(x, y, z); + pointColors.emplace_back(r, g, b); } std::cout << maxdist << std::endl; @@ -269,7 +267,7 @@ void RenderableGalaxy::initializeGL() { void RenderableGalaxy::deinitializeGL() { if (_raycaster) { - global::raycasterManager.detachRaycaster(*_raycaster.get()); + global::raycasterManager.detachRaycaster(*_raycaster); _raycaster = nullptr; } } diff --git a/modules/galaxy/rendering/renderablegalaxy.h b/modules/galaxy/rendering/renderablegalaxy.h index 7bfefd0f87..b221f5f989 100644 --- a/modules/galaxy/rendering/renderablegalaxy.h +++ b/modules/galaxy/rendering/renderablegalaxy.h @@ -41,7 +41,7 @@ struct RenderData; class RenderableGalaxy : public Renderable { public: RenderableGalaxy(const ghoul::Dictionary& dictionary); - ~RenderableGalaxy(); + virtual ~RenderableGalaxy() = default; void initializeGL() override; void deinitializeGL() override; diff --git a/modules/galaxy/tasks/milkywayconversiontask.cpp b/modules/galaxy/tasks/milkywayconversiontask.cpp index 5472864b24..0f8e825527 100644 --- a/modules/galaxy/tasks/milkywayconversiontask.cpp +++ b/modules/galaxy/tasks/milkywayconversiontask.cpp @@ -45,7 +45,10 @@ namespace { namespace openspace { -MilkywayConversionTask::MilkywayConversionTask(const ghoul::Dictionary& dictionary) { +MilkywayConversionTask::MilkywayConversionTask(const ghoul::Dictionary& dictionary) + : _inFirstIndex(0) + , _inNSlices(0) +{ dictionary.getValue(KeyInFilenamePrefix, _inFilenamePrefix); dictionary.getValue(KeyInFilenameSuffix, _inFilenameSuffix); dictionary.getValue(KeyInFirstIndex, _inFirstIndex); @@ -54,13 +57,11 @@ MilkywayConversionTask::MilkywayConversionTask(const ghoul::Dictionary& dictiona dictionary.getValue(KeyOutDimensions, _outDimensions); } -MilkywayConversionTask::~MilkywayConversionTask() {} - std::string MilkywayConversionTask::description() { return std::string(); } -void MilkywayConversionTask::perform(const Task::ProgressCallback& progressCallback) { +void MilkywayConversionTask::perform(const Task::ProgressCallback& onProgress) { using namespace openspace::volume; std::vector filenames; @@ -91,7 +92,7 @@ void MilkywayConversionTask::perform(const Task::ProgressCallback& progressCallb return value; }; - rawWriter.write(sampleFunction, progressCallback); + rawWriter.write(sampleFunction, onProgress); } documentation::Documentation MilkywayConversionTask::documentation() { diff --git a/modules/galaxy/tasks/milkywayconversiontask.h b/modules/galaxy/tasks/milkywayconversiontask.h index 5b66a3568d..216357c12d 100644 --- a/modules/galaxy/tasks/milkywayconversiontask.h +++ b/modules/galaxy/tasks/milkywayconversiontask.h @@ -41,7 +41,7 @@ namespace documentation { struct Documentation; } class MilkywayConversionTask : public Task { public: MilkywayConversionTask(const ghoul::Dictionary& dictionary); - virtual ~MilkywayConversionTask(); + virtual ~MilkywayConversionTask() = default; std::string description() override; void perform(const Task::ProgressCallback& onProgress) override; diff --git a/modules/galaxy/tasks/milkywaypointsconversiontask.cpp b/modules/galaxy/tasks/milkywaypointsconversiontask.cpp index b108ebb069..f445813dbb 100644 --- a/modules/galaxy/tasks/milkywaypointsconversiontask.cpp +++ b/modules/galaxy/tasks/milkywaypointsconversiontask.cpp @@ -40,8 +40,6 @@ namespace openspace { MilkywayPointsConversionTask::MilkywayPointsConversionTask(const ghoul::Dictionary&) {} -MilkywayPointsConversionTask::~MilkywayPointsConversionTask() {} - std::string MilkywayPointsConversionTask::description() { return std::string(); } diff --git a/modules/galaxy/tasks/milkywaypointsconversiontask.h b/modules/galaxy/tasks/milkywaypointsconversiontask.h index a66ecb91a3..81c5036160 100644 --- a/modules/galaxy/tasks/milkywaypointsconversiontask.h +++ b/modules/galaxy/tasks/milkywaypointsconversiontask.h @@ -42,7 +42,7 @@ namespace documentation { struct Documentation; } class MilkywayPointsConversionTask : public Task { public: MilkywayPointsConversionTask(const ghoul::Dictionary& dictionary); - virtual ~MilkywayPointsConversionTask(); + virtual ~MilkywayPointsConversionTask() = default; std::string description() override; void perform(const Task::ProgressCallback& progressCallback) override; diff --git a/modules/globebrowsing/globebrowsingmodule.cpp b/modules/globebrowsing/globebrowsingmodule.cpp index 234a44a65b..704ee43acc 100644 --- a/modules/globebrowsing/globebrowsingmodule.cpp +++ b/modules/globebrowsing/globebrowsingmodule.cpp @@ -191,7 +191,7 @@ void GlobeBrowsingModule::internalInitialize(const ghoul::Dictionary& dict) { // Initialize - global::callback::initializeGL.push_back([&]() { + global::callback::initializeGL.emplace_back([&]() { _tileCache = std::make_unique(); addPropertySubOwner(*_tileCache); @@ -205,16 +205,16 @@ void GlobeBrowsingModule::internalInitialize(const ghoul::Dictionary& dict) { addPropertySubOwner(GdalWrapper::ref()); }); - global::callback::deinitializeGL.push_back([]() { + global::callback::deinitializeGL.emplace_back([]() { tileprovider::deinitializeDefaultTile(); }); // Render - global::callback::render.push_back([&]() { _tileCache->update(); }); + global::callback::render.emplace_back([&]() { _tileCache->update(); }); // Deinitialize - global::callback::deinitialize.push_back([&]() { GdalWrapper::ref().destroy(); }); + global::callback::deinitialize.emplace_back([&]() { GdalWrapper::destroy(); }); // Get factories auto fRenderable = FactoryManager::ref().factory(); diff --git a/modules/globebrowsing/src/basictypes.h b/modules/globebrowsing/src/basictypes.h index f9af24593b..b54e4188da 100644 --- a/modules/globebrowsing/src/basictypes.h +++ b/modules/globebrowsing/src/basictypes.h @@ -42,15 +42,15 @@ struct AABB3 { struct Geodetic2 { - double lat; - double lon; + double lat = 0.0; + double lon = 0.0; }; struct Geodetic3 { Geodetic2 geodetic2; - double height; + double height = 0.0; }; diff --git a/modules/globebrowsing/src/ellipsoid.cpp b/modules/globebrowsing/src/ellipsoid.cpp index a9bd4fce1d..4954cf162b 100644 --- a/modules/globebrowsing/src/ellipsoid.cpp +++ b/modules/globebrowsing/src/ellipsoid.cpp @@ -143,10 +143,10 @@ double Ellipsoid::greatCircleDistance(const Geodetic2& p1, const Geodetic2& p2) Geodetic2 Ellipsoid::cartesianToGeodetic2(const glm::dvec3& p) const { const glm::dvec3 normal = geodeticSurfaceNormalForGeocentricallyProjectedPoint(p); - Geodetic2 res; - res.lat = asin(normal.z / length(normal)); - res.lon = atan2(normal.y, normal.x); - return res; + return { + asin(normal.z / length(normal)), + atan2(normal.y, normal.x) + }; } glm::dvec3 Ellipsoid::cartesianSurfacePosition(const Geodetic2& geodetic2) const { diff --git a/modules/globebrowsing/src/geodeticpatch.cpp b/modules/globebrowsing/src/geodeticpatch.cpp index 4444421c3d..89225577ba 100644 --- a/modules/globebrowsing/src/geodeticpatch.cpp +++ b/modules/globebrowsing/src/geodeticpatch.cpp @@ -157,10 +157,10 @@ Geodetic2 GeodeticPatch::clamp(const Geodetic2& p) const { double pointLat = normalizedAngleAround(p.lat, _center.lat); double pointLon = normalizedAngleAround(p.lon, _center.lon); - Geodetic2 res; - res.lat = glm::clamp(pointLat, minLat(), maxLat()); - res.lon = glm::clamp(pointLon, minLon(), maxLon()); - return res; + return { + glm::clamp(pointLat, minLat(), maxLat()), + glm::clamp(pointLon, minLon(), maxLon()) + }; } Geodetic2 GeodeticPatch::closestCorner(const Geodetic2& p) const { diff --git a/modules/globebrowsing/src/layergroup.cpp b/modules/globebrowsing/src/layergroup.cpp index bda8d69d8e..d849fb162d 100644 --- a/modules/globebrowsing/src/layergroup.cpp +++ b/modules/globebrowsing/src/layergroup.cpp @@ -75,7 +75,6 @@ void LayerGroup::setLayersFromDict(const ghoul::Dictionary& dict) { LERRORC(except.component, except.message); } } - continue; } } } diff --git a/modules/globebrowsing/src/layermanager.cpp b/modules/globebrowsing/src/layermanager.cpp index b1d292f194..2bd565ea9f 100644 --- a/modules/globebrowsing/src/layermanager.cpp +++ b/modules/globebrowsing/src/layermanager.cpp @@ -104,7 +104,7 @@ bool LayerManager::hasAnyBlendingLayersEnabled() const { std::array LayerManager::layerGroups() const { - std::array res; + std::array res = {}; for (int i = 0; i < NumLayerGroups; ++i) { res[i] = _layerGroups[i].get(); } diff --git a/modules/globebrowsing/src/rawtile.cpp b/modules/globebrowsing/src/rawtile.cpp index 5a4638bc3d..2906db5367 100644 --- a/modules/globebrowsing/src/rawtile.cpp +++ b/modules/globebrowsing/src/rawtile.cpp @@ -28,10 +28,10 @@ namespace openspace::globebrowsing { RawTile createDefaultTile(TileTextureInitData initData) { RawTile defaultRes; - defaultRes.textureInitData = std::move(initData); std::byte* data = new std::byte[initData.totalNumBytes]; defaultRes.imageData = std::unique_ptr(data); std::fill_n(defaultRes.imageData.get(), initData.totalNumBytes, std::byte(0)); + defaultRes.textureInitData = std::move(initData); return defaultRes; } diff --git a/modules/globebrowsing/src/rawtiledatareader.cpp b/modules/globebrowsing/src/rawtiledatareader.cpp index 324251b093..fdc3d4d8f4 100644 --- a/modules/globebrowsing/src/rawtiledatareader.cpp +++ b/modules/globebrowsing/src/rawtiledatareader.cpp @@ -331,14 +331,14 @@ std::array geoTransform(int rasterX, int rasterY) { Geodetic2{ 0.0, 0.0 }, Geodetic2{ glm::half_pi(), glm::pi() } ); - std::array res; - res[0] = glm::degrees(cov.corner(Quad::NORTH_WEST).lon); - res[1] = glm::degrees(cov.size().lon) / rasterX; - res[2] = 0.0; - res[3] = glm::degrees(cov.corner(Quad::NORTH_WEST).lat); - res[4] = 0.0; - res[5] = glm::degrees(-cov.size().lat) / rasterY; - return res; + return { + glm::degrees(cov.corner(Quad::NORTH_WEST).lon), + glm::degrees(cov.size().lon) / rasterX, + 0.0, + glm::degrees(cov.corner(Quad::NORTH_WEST).lat), + 0.0, + glm::degrees(-cov.size().lat) / rasterY + }; } /** diff --git a/modules/globebrowsing/src/rawtiledatareader.h b/modules/globebrowsing/src/rawtiledatareader.h index 2ba04fd852..2f374b06d0 100644 --- a/modules/globebrowsing/src/rawtiledatareader.h +++ b/modules/globebrowsing/src/rawtiledatareader.h @@ -68,7 +68,7 @@ private: void initialize(); RawTile::ReadError rasterRead(int rasterBand, const IODescription& io, - char* dst) const; + char* dataDestination) const; void readImageData(IODescription& io, RawTile::ReadError& worstError, char* imageDataDest) const; diff --git a/modules/globebrowsing/src/renderableglobe.cpp b/modules/globebrowsing/src/renderableglobe.cpp index b61a9c81c8..4e76d27bc0 100644 --- a/modules/globebrowsing/src/renderableglobe.cpp +++ b/modules/globebrowsing/src/renderableglobe.cpp @@ -83,7 +83,7 @@ namespace { // them at a cutoff level, and I think this might still be the best solution for the // time being. --abock 2018-10-30 constexpr const int DefaultSkirtedGridSegments = 64; - constexpr static const int UnknownDesiredLevel = -1; + constexpr const int UnknownDesiredLevel = -1; const openspace::globebrowsing::GeodeticPatch Coverage = openspace::globebrowsing::GeodeticPatch(0, 0, 90, 180); @@ -385,6 +385,7 @@ bool intersects(const AABB3& bb, const AABB3& o) { Chunk::Chunk(const TileIndex& ti) : tileIndex(ti) , surfacePatch(ti) + , status(Status::DoNothing) {} RenderableGlobe::RenderableGlobe(const ghoul::Dictionary& dictionary) diff --git a/modules/globebrowsing/src/tileprovider.cpp b/modules/globebrowsing/src/tileprovider.cpp index ffcce43c7d..720a832452 100644 --- a/modules/globebrowsing/src/tileprovider.cpp +++ b/modules/globebrowsing/src/tileprovider.cpp @@ -292,7 +292,7 @@ std::string timeStringify(TemporalTileProvider::TimeFormatType type, const Time& } std::unique_ptr initTileProvider(TemporalTileProvider& t, - TemporalTileProvider::TimeKey timekey) + const TemporalTileProvider::TimeKey& timekey) { static const std::vector IgnoredTokens = { // From: http://www.gdal.org/frmt_wms.html @@ -569,8 +569,8 @@ SingleImageProvider::SingleImageProvider(const ghoul::Dictionary& dictionary) -TextTileProvider::TextTileProvider(const TileTextureInitData& initData, size_t fontSize) - : initData(initData) +TextTileProvider::TextTileProvider(TileTextureInitData initData, size_t fontSize) + : initData(std::move(initData)) , fontSize(fontSize) { tileCache = global::moduleEngine.module()->tileCache(); @@ -771,9 +771,9 @@ TemporalTileProvider::TemporalTileProvider(const ghoul::Dictionary& dictionary) bool initialize(TileProvider& tp) { ghoul_assert(!tp.isInitialized, "TileProvider can only be initialized once."); - tp.uniqueIdentifier = tp.NumTileProviders++; - if (tp.NumTileProviders == std::numeric_limits::max()) { - --tp.NumTileProviders; + tp.uniqueIdentifier = TileProvider::NumTileProviders++; + if (TileProvider::NumTileProviders == std::numeric_limits::max()) { + --TileProvider::NumTileProviders; return false; } diff --git a/modules/globebrowsing/src/tileprovider.h b/modules/globebrowsing/src/tileprovider.h index 68f044378f..f3d9c1e904 100644 --- a/modules/globebrowsing/src/tileprovider.h +++ b/modules/globebrowsing/src/tileprovider.h @@ -104,7 +104,7 @@ struct SingleImageProvider : public TileProvider { }; struct TextTileProvider : public TileProvider { - TextTileProvider(const TileTextureInitData& initData, size_t fontSize = 48); + TextTileProvider(TileTextureInitData initData, size_t fontSize = 48); const TileTextureInitData initData; diff --git a/modules/globebrowsing/src/tiletextureinitdata.h b/modules/globebrowsing/src/tiletextureinitdata.h index 4dfb4efc20..9beaeebd1f 100644 --- a/modules/globebrowsing/src/tiletextureinitdata.h +++ b/modules/globebrowsing/src/tiletextureinitdata.h @@ -42,9 +42,9 @@ public: BooleanType(ShouldAllocateDataOnCPU); BooleanType(PadTiles); - TileTextureInitData(size_t width, size_t height, GLenum glType, - ghoul::opengl::Texture::Format textureFormat, PadTiles padTiles, - ShouldAllocateDataOnCPU cpuAlloc = ShouldAllocateDataOnCPU::No); + TileTextureInitData(size_t width, size_t height, GLenum type, + ghoul::opengl::Texture::Format textureFormat, PadTiles pad, + ShouldAllocateDataOnCPU allocCpu = ShouldAllocateDataOnCPU::No); TileTextureInitData(const TileTextureInitData& original) = default; TileTextureInitData(TileTextureInitData&& original) = default; diff --git a/modules/imgui/imguimodule.cpp b/modules/imgui/imguimodule.cpp index b00adb0f32..539199cc06 100644 --- a/modules/imgui/imguimodule.cpp +++ b/modules/imgui/imguimodule.cpp @@ -43,7 +43,7 @@ namespace openspace { ImGUIModule::ImGUIModule() : OpenSpaceModule(Name) { addPropertySubOwner(gui); - global::callback::initialize.push_back([&]() { + global::callback::initialize.emplace_back([&]() { LDEBUGC("ImGUIModule", "Initializing GUI"); gui.initialize(); @@ -129,22 +129,22 @@ ImGUIModule::ImGUIModule() : OpenSpaceModule(Name) { ); }); - global::callback::deinitialize.push_back([&]() { + global::callback::deinitialize.emplace_back([&]() { LDEBUGC("ImGui", "Deinitialize GUI"); gui.deinitialize(); }); - global::callback::initializeGL.push_back([&]() { + global::callback::initializeGL.emplace_back([&]() { LDEBUGC("ImGui", "Initializing GUI OpenGL"); gui.initializeGL(); }); - global::callback::deinitializeGL.push_back([&]() { + global::callback::deinitializeGL.emplace_back([&]() { LDEBUGC("ImGui", "Deinitialize GUI OpenGL"); gui.deinitializeGL(); }); - global::callback::draw2D.push_back([&]() { + global::callback::draw2D.emplace_back([&]() { // TODO emiax: Make sure this is only called for one of the eyes, in the case // of side-by-side / top-bottom stereo. @@ -176,7 +176,7 @@ ImGUIModule::ImGUIModule() : OpenSpaceModule(Name) { } }); - global::callback::keyboard.push_back( + global::callback::keyboard.emplace_back( [&](Key key, KeyModifier mod, KeyAction action) -> bool { // A list of all the windows that can show up by themselves if (gui.isEnabled() || gui._performance.isEnabled() || @@ -190,7 +190,7 @@ ImGUIModule::ImGUIModule() : OpenSpaceModule(Name) { } ); - global::callback::character.push_back( + global::callback::character.emplace_back( [&](unsigned int codepoint, KeyModifier modifier) -> bool { // A list of all the windows that can show up by themselves if (gui.isEnabled() || gui._performance.isEnabled() || @@ -204,7 +204,7 @@ ImGUIModule::ImGUIModule() : OpenSpaceModule(Name) { } ); - global::callback::mouseButton.push_back( + global::callback::mouseButton.emplace_back( [&](MouseButton button, MouseAction action) -> bool { // A list of all the windows that can show up by themselves if (gui.isEnabled() || gui._performance.isEnabled() || @@ -218,7 +218,7 @@ ImGUIModule::ImGUIModule() : OpenSpaceModule(Name) { } ); - global::callback::mouseScrollWheel.push_back( + global::callback::mouseScrollWheel.emplace_back( [&](double, double posY) -> bool { // A list of all the windows that can show up by themselves if (gui.isEnabled() || gui._performance.isEnabled() || diff --git a/modules/server/include/topics/shortcuttopic.h b/modules/server/include/topics/shortcuttopic.h index 4958f171eb..721d7a0d44 100644 --- a/modules/server/include/topics/shortcuttopic.h +++ b/modules/server/include/topics/shortcuttopic.h @@ -33,7 +33,7 @@ class ShortcutTopic : public Topic { public: virtual ~ShortcutTopic() = default; - void handleJson(const nlohmann::json& json) override; + void handleJson(const nlohmann::json& input) override; bool isDone() const override; private: diff --git a/modules/server/servermodule.cpp b/modules/server/servermodule.cpp index 49fbec2a53..b488c09071 100644 --- a/modules/server/servermodule.cpp +++ b/modules/server/servermodule.cpp @@ -68,7 +68,7 @@ void ServerModule::internalInitialize(const ghoul::Dictionary&) { _servers.push_back(std::move(tcpServer)); _servers.push_back(std::move(wsServer)); - global::callback::preSync.push_back([this]() { preSync(); }); + global::callback::preSync.emplace_back([this]() { preSync(); }); } void ServerModule::preSync() { diff --git a/modules/space/rendering/renderablestars.cpp b/modules/space/rendering/renderablestars.cpp index 6572aed9ab..2d0c9787d4 100644 --- a/modules/space/rendering/renderablestars.cpp +++ b/modules/space/rendering/renderablestars.cpp @@ -453,7 +453,7 @@ void RenderableStars::render(const RenderData& data, RendererTasks&) { glm::vec2(global::renderEngine.renderingResolution()) ); - setPscUniforms(*_program.get(), data.camera, data.position); + setPscUniforms(*_program, data.camera, data.position); _program->setUniform(_uniformCache.scaling, scaling); ghoul::opengl::TextureUnit psfUnit; @@ -650,7 +650,7 @@ void RenderableStars::update(const UpdateData&) { if (_pointSpreadFunctionTextureIsDirty) { LDEBUG("Reloading Point Spread Function texture"); _pointSpreadFunctionTexture = nullptr; - if (_pointSpreadFunctionTexturePath.value() != "") { + if (!_pointSpreadFunctionTexturePath.value().empty()) { _pointSpreadFunctionTexture = ghoul::io::TextureReader::ref().loadTexture( absPath(_pointSpreadFunctionTexturePath) ); @@ -706,7 +706,7 @@ void RenderableStars::update(const UpdateData&) { if (_otherDataColorMapIsDirty) { LDEBUG("Reloading Color Texture"); _otherDataColorMapTexture = nullptr; - if (_otherDataColorMapPath.value() != "") { + if (!_otherDataColorMapPath.value().empty()) { _otherDataColorMapTexture = ghoul::io::TextureReader::ref().loadTexture( absPath(_otherDataColorMapPath) ); @@ -837,8 +837,8 @@ void RenderableStars::readSpeckFile() { str >> values[i]; } bool nullArray = true; - for (size_t i = 0; i < values.size(); ++i) { - if (values[i] != 0.0) { + for (float v : values) { + if (v != 0.0) { nullArray = false; break; } @@ -949,7 +949,7 @@ void RenderableStars::createDataSlice(ColorOption option) { union { ColorVBOLayout value; std::array data; - } layout; + } layout = {}; layout.value.position = { { position[0], position[1], position[2], position[3] @@ -976,7 +976,7 @@ void RenderableStars::createDataSlice(ColorOption option) { union { VelocityVBOLayout value; std::array data; - } layout; + } layout = {}; layout.value.position = { { position[0], position[1], position[2], position[3] @@ -1000,7 +1000,7 @@ void RenderableStars::createDataSlice(ColorOption option) { union { SpeedVBOLayout value; std::array data; - } layout; + } layout = {}; layout.value.position = { { position[0], position[1], position[2], position[3] @@ -1022,7 +1022,7 @@ void RenderableStars::createDataSlice(ColorOption option) { union { OtherDataLayout value; std::array data; - } layout; + } layout = {}; layout.value.position = { { position[0], position[1], position[2], position[3] } diff --git a/modules/space/translation/horizonstranslation.cpp b/modules/space/translation/horizonstranslation.cpp index 2d54dce171..7605d4c431 100644 --- a/modules/space/translation/horizonstranslation.cpp +++ b/modules/space/translation/horizonstranslation.cpp @@ -143,7 +143,7 @@ void HorizonsTranslation::readHorizonsTextFile(const std::string& horizonsTextFi // The beginning of a Horizons file has a header with a lot of information about the // query that we do not care about. Ignore everything until data starts, including // the row marked by $$SOE (i.e. Start Of Ephemerides). - std::string line = ""; + std::string line; while (line[0] != '$') { std::getline(fileStream, line); } diff --git a/modules/space/translation/horizonstranslation.h b/modules/space/translation/horizonstranslation.h index 6523deeeec..9a7d699a24 100644 --- a/modules/space/translation/horizonstranslation.h +++ b/modules/space/translation/horizonstranslation.h @@ -54,7 +54,7 @@ public: HorizonsTranslation(); HorizonsTranslation(const ghoul::Dictionary& dictionary); - glm::dvec3 position(const UpdateData& time) const override; + glm::dvec3 position(const UpdateData& data) const override; static documentation::Documentation Documentation(); diff --git a/modules/spacecraftinstruments/rendering/renderablemodelprojection.cpp b/modules/spacecraftinstruments/rendering/renderablemodelprojection.cpp index 2df466d341..9348632bf8 100644 --- a/modules/spacecraftinstruments/rendering/renderablemodelprojection.cpp +++ b/modules/spacecraftinstruments/rendering/renderablemodelprojection.cpp @@ -382,7 +382,7 @@ void RenderableModelProjection::update(const UpdateData& data) { } void RenderableModelProjection::imageProjectGPU( - std::shared_ptr projectionTexture) + const ghoul::opengl::Texture& projectionTexture) { if (_projectionComponent.needsShadowMap()) { _projectionComponent.depthMapRenderBegin(); @@ -408,7 +408,7 @@ void RenderableModelProjection::imageProjectGPU( ghoul::opengl::TextureUnit unitFbo; unitFbo.activate(); - projectionTexture->bind(); + projectionTexture.bind(); _fboProgramObject->setUniform(_fboUniformCache.projectionTexture, unitFbo); _fboProgramObject->setUniform( @@ -489,7 +489,7 @@ void RenderableModelProjection::project() { attitudeParameters(img.timeRange.start); std::shared_ptr projTexture = _projectionComponent.loadProjectionTexture(img.path, img.isPlaceholder); - imageProjectGPU(projTexture); + imageProjectGPU(*projTexture); } _shouldCapture = false; } diff --git a/modules/spacecraftinstruments/rendering/renderablemodelprojection.h b/modules/spacecraftinstruments/rendering/renderablemodelprojection.h index 77c899125a..1129e06899 100644 --- a/modules/spacecraftinstruments/rendering/renderablemodelprojection.h +++ b/modules/spacecraftinstruments/rendering/renderablemodelprojection.h @@ -67,7 +67,7 @@ public: private: bool loadTextures(); void attitudeParameters(double time); - void imageProjectGPU(std::shared_ptr projectionTexture); + void imageProjectGPU(const ghoul::opengl::Texture& projectionTexture); void project(); diff --git a/modules/spacecraftinstruments/rendering/renderableplanetprojection.cpp b/modules/spacecraftinstruments/rendering/renderableplanetprojection.cpp index ac38e99d75..67df17050f 100644 --- a/modules/spacecraftinstruments/rendering/renderableplanetprojection.cpp +++ b/modules/spacecraftinstruments/rendering/renderableplanetprojection.cpp @@ -466,7 +466,7 @@ bool RenderablePlanetProjection::isReady() const { } void RenderablePlanetProjection::imageProjectGPU( - std::shared_ptr projectionTexture) + const ghoul::opengl::Texture& projectionTexture) { _projectionComponent.imageProjectBegin(); @@ -474,7 +474,7 @@ void RenderablePlanetProjection::imageProjectGPU( ghoul::opengl::TextureUnit unitFbo; unitFbo.activate(); - projectionTexture->bind(); + projectionTexture.bind(); _fboProgramObject->setUniform(_fboUniformCache.projectionTexture, unitFbo); _fboProgramObject->setUniform(_fboUniformCache.projectorMatrix, _projectorMatrix); @@ -596,7 +596,9 @@ void RenderablePlanetProjection::render(const RenderData& data, RendererTasks&) break; } RenderablePlanetProjection::attitudeParameters(img.timeRange.start); - imageProjectGPU(_projectionComponent.loadProjectionTexture(img.path)); + std::shared_ptr t = + _projectionComponent.loadProjectionTexture(img.path); + imageProjectGPU(*t); ++nPerformedProjections; } _imageTimes.erase( diff --git a/modules/spacecraftinstruments/rendering/renderableplanetprojection.h b/modules/spacecraftinstruments/rendering/renderableplanetprojection.h index da4c7c7f24..90842409d3 100644 --- a/modules/spacecraftinstruments/rendering/renderableplanetprojection.h +++ b/modules/spacecraftinstruments/rendering/renderableplanetprojection.h @@ -63,7 +63,7 @@ protected: void attitudeParameters(double time); private: - void imageProjectGPU(std::shared_ptr projectionTexture); + void imageProjectGPU(const ghoul::opengl::Texture& projectionTexture); void clearProjectionBufferAfterTime(double time); void insertImageProjections(const std::vector& images); diff --git a/modules/spacecraftinstruments/util/sequenceparser.cpp b/modules/spacecraftinstruments/util/sequenceparser.cpp index 73268a88b8..4f04f6716b 100644 --- a/modules/spacecraftinstruments/util/sequenceparser.cpp +++ b/modules/spacecraftinstruments/util/sequenceparser.cpp @@ -111,7 +111,7 @@ void SequenceParser::sendPlaybookInformation(const std::string& name) { std::map targetMap; uint8_t currentTargetId = 0; - for (auto target : _subsetMap) { + for (const std::pair& target : _subsetMap) { if (targetMap.find(target.first) == targetMap.end()) { targetMap[target.first] = currentTargetId++; } @@ -181,7 +181,7 @@ void SequenceParser::sendPlaybookInformation(const std::string& name) { union { uint32_t value; std::array data; - } sizeBuffer; + } sizeBuffer = {}; sizeBuffer.value = static_cast(currentWriteLocation); buffer.insert(buffer.begin(), sizeBuffer.data.begin(), sizeBuffer.data.end()); currentWriteLocation += sizeof(uint32_t); diff --git a/modules/sync/syncmodule.cpp b/modules/sync/syncmodule.cpp index eceb8a08da..00306c73f1 100644 --- a/modules/sync/syncmodule.cpp +++ b/modules/sync/syncmodule.cpp @@ -114,7 +114,7 @@ void SyncModule::internalInitialize(const ghoul::Dictionary& configuration) { _torrentClient.initialize(); - global::callback::deinitialize.push_back([&]() { _torrentClient.deinitialize(); }); + global::callback::deinitialize.emplace_back([&]() { _torrentClient.deinitialize(); }); } void SyncModule::internalDeinitialize() { diff --git a/modules/sync/syncs/httpsynchronization.cpp b/modules/sync/syncs/httpsynchronization.cpp index 38deb58135..23944e4ce9 100644 --- a/modules/sync/syncs/httpsynchronization.cpp +++ b/modules/sync/syncs/httpsynchronization.cpp @@ -74,12 +74,12 @@ documentation::Documentation HttpSynchronization::Documentation() { } HttpSynchronization::HttpSynchronization(const ghoul::Dictionary& dict, - const std::string& synchronizationRoot, - const std::vector& synchronizationRepositories + std::string synchronizationRoot, + std::vector synchronizationRepositories ) : openspace::ResourceSynchronization(dict) - , _synchronizationRoot(synchronizationRoot) - , _synchronizationRepositories(synchronizationRepositories) + , _synchronizationRoot(std::move(synchronizationRoot)) + , _synchronizationRepositories(std::move(synchronizationRepositories)) { documentation::testSpecificationAndThrow( Documentation(), @@ -184,7 +184,7 @@ bool HttpSynchronization::hasSyncFile() { } bool HttpSynchronization::trySyncFromUrl(std::string listUrl) { - HttpRequest::RequestOptions opt; + HttpRequest::RequestOptions opt = {}; opt.requestTimeoutSeconds = 0; SyncHttpMemoryDownload fileListDownload(std::move(listUrl)); diff --git a/modules/sync/syncs/httpsynchronization.h b/modules/sync/syncs/httpsynchronization.h index d682190b3f..818c8b8b05 100644 --- a/modules/sync/syncs/httpsynchronization.h +++ b/modules/sync/syncs/httpsynchronization.h @@ -34,9 +34,8 @@ namespace openspace { class HttpSynchronization : public ResourceSynchronization { public: - HttpSynchronization(const ghoul::Dictionary& dict, - const std::string& synchronizationRoot, - const std::vector& synchronizationRepositories); + HttpSynchronization(const ghoul::Dictionary& dict, std::string synchronizationRoot, + std::vector synchronizationRepositories); virtual ~HttpSynchronization(); diff --git a/modules/sync/syncs/torrentsynchronization.cpp b/modules/sync/syncs/torrentsynchronization.cpp index 64a0da560d..cf33af2087 100644 --- a/modules/sync/syncs/torrentsynchronization.cpp +++ b/modules/sync/syncs/torrentsynchronization.cpp @@ -61,10 +61,10 @@ documentation::Documentation TorrentSynchronization::Documentation() { } TorrentSynchronization::TorrentSynchronization(const ghoul::Dictionary& dict, - const std::string& synchronizationRoot, + std::string synchronizationRoot, TorrentClient& torrentClient) : ResourceSynchronization(dict) - , _synchronizationRoot(synchronizationRoot) + , _synchronizationRoot(std::move(synchronizationRoot)) , _torrentClient(torrentClient) { documentation::testSpecificationAndThrow( diff --git a/modules/sync/syncs/torrentsynchronization.h b/modules/sync/syncs/torrentsynchronization.h index 3d3f3ebe81..2b749626ba 100644 --- a/modules/sync/syncs/torrentsynchronization.h +++ b/modules/sync/syncs/torrentsynchronization.h @@ -35,8 +35,8 @@ class TorrentSynchronizationJob; class TorrentSynchronization : public ResourceSynchronization { public: - TorrentSynchronization(const ghoul::Dictionary& dict, - const std::string& synchronizationRoot, TorrentClient& client); + TorrentSynchronization(const ghoul::Dictionary& dict, std::string synchronizationRoot, + TorrentClient& client); virtual ~TorrentSynchronization(); @@ -59,7 +59,7 @@ private: std::atomic_bool _enabled = false; - TorrentClient::TorrentId _torrentId; + TorrentClient::TorrentId _torrentId = 0; TorrentClient::TorrentProgress _progress; std::mutex _progressMutex; std::string _identifier; diff --git a/modules/sync/syncs/urlsynchronization.cpp b/modules/sync/syncs/urlsynchronization.cpp index 78ccd4e7af..0d7cd0bbdd 100644 --- a/modules/sync/syncs/urlsynchronization.cpp +++ b/modules/sync/syncs/urlsynchronization.cpp @@ -96,9 +96,9 @@ documentation::Documentation UrlSynchronization::Documentation() { } UrlSynchronization::UrlSynchronization(const ghoul::Dictionary& dict, - const std::string& synchronizationRoot) + std::string synchronizationRoot) : ResourceSynchronization(dict) - , _synchronizationRoot(synchronizationRoot) + , _synchronizationRoot(std::move(synchronizationRoot)) { documentation::testSpecificationAndThrow( Documentation(), @@ -225,7 +225,7 @@ void UrlSynchronization::start() { return !_shouldCancel; }); - HttpRequest::RequestOptions opt; + HttpRequest::RequestOptions opt = {}; opt.requestTimeoutSeconds = 0; fileDownload->start(opt); } diff --git a/modules/sync/syncs/urlsynchronization.h b/modules/sync/syncs/urlsynchronization.h index 50596f2efa..ef49426065 100644 --- a/modules/sync/syncs/urlsynchronization.h +++ b/modules/sync/syncs/urlsynchronization.h @@ -35,8 +35,7 @@ namespace openspace { class UrlSynchronization : public ResourceSynchronization { public: - UrlSynchronization(const ghoul::Dictionary& dict, - const std::string& synchronizationRoot); + UrlSynchronization(const ghoul::Dictionary& dict, std::string synchronizationRoot); virtual ~UrlSynchronization(); diff --git a/modules/webbrowser/include/cefhost.h b/modules/webbrowser/include/cefhost.h index 869057a731..47f805f0fa 100644 --- a/modules/webbrowser/include/cefhost.h +++ b/modules/webbrowser/include/cefhost.h @@ -35,7 +35,7 @@ namespace openspace { class CefHost { public: - CefHost(std::string helperLocation); + CefHost(const std::string& helperLocation); ~CefHost(); void doMessageLoopWork(); diff --git a/modules/webbrowser/src/cefhost.cpp b/modules/webbrowser/src/cefhost.cpp index 388b32f727..5279d8132b 100644 --- a/modules/webbrowser/src/cefhost.cpp +++ b/modules/webbrowser/src/cefhost.cpp @@ -36,7 +36,7 @@ namespace { namespace openspace { -CefHost::CefHost(std::string helperLocation) { +CefHost::CefHost(const std::string& helperLocation) { LDEBUG("Initializing CEF..."); CefSettings settings; @@ -50,7 +50,7 @@ CefHost::CefHost(std::string helperLocation) { CefRefPtr app(new WebBrowserApp); CefMainArgs args; - CefInitialize(args, settings, app.get(), NULL); + CefInitialize(args, settings, app.get(), nullptr); LDEBUG("Initializing CEF... done!"); } diff --git a/modules/webbrowser/src/defaultbrowserlauncher.cpp b/modules/webbrowser/src/defaultbrowserlauncher.cpp index 9c04603b56..dddfaf69fc 100644 --- a/modules/webbrowser/src/defaultbrowserlauncher.cpp +++ b/modules/webbrowser/src/defaultbrowserlauncher.cpp @@ -35,7 +35,7 @@ namespace { void launchBrowser(const std::string& url) { LDEBUGC("DefaultBrowserLauncher", "Launching default browser: " + url); #ifdef WIN32 - ShellExecute(0, 0, url.c_str(), 0, 0, SW_SHOW); + ShellExecute(nullptr, nullptr, url.c_str(), nullptr, nullptr, SW_SHOW); #endif } diff --git a/modules/webbrowser/src/eventhandler.cpp b/modules/webbrowser/src/eventhandler.cpp index e572c81fa5..c263e1f92d 100644 --- a/modules/webbrowser/src/eventhandler.cpp +++ b/modules/webbrowser/src/eventhandler.cpp @@ -100,7 +100,7 @@ namespace { namespace openspace { void EventHandler::initialize() { - global::callback::character.push_back( + global::callback::character.emplace_back( [this](unsigned int charCode, KeyModifier mod) -> bool { if (_browserInstance) { return charCallback(charCode, mod); @@ -108,7 +108,7 @@ void EventHandler::initialize() { return false; } ); - global::callback::keyboard.push_back( + global::callback::keyboard.emplace_back( [this](Key key, KeyModifier mod, KeyAction action) -> bool { if (_browserInstance) { return keyboardCallback(key, mod, action); @@ -116,7 +116,7 @@ void EventHandler::initialize() { return false; } ); - global::callback::mousePosition.push_back( + global::callback::mousePosition.emplace_back( [this](double x, double y) -> bool { if (_browserInstance) { return mousePositionCallback(x, y); @@ -124,7 +124,7 @@ void EventHandler::initialize() { return false; } ); - global::callback::mouseButton.push_back( + global::callback::mouseButton.emplace_back( [this](MouseButton button, MouseAction action) -> bool { if (_browserInstance) { return mouseButtonCallback(button, action); @@ -132,7 +132,7 @@ void EventHandler::initialize() { return false; } ); - global::callback::mouseScrollWheel.push_back( + global::callback::mouseScrollWheel.emplace_back( [this](double x, double y) -> bool { if (_browserInstance) { const glm::ivec2 delta(x, y); diff --git a/modules/webbrowser/src/webrenderhandler.cpp b/modules/webbrowser/src/webrenderhandler.cpp index 8b70a4ccc4..2a5739a003 100644 --- a/modules/webbrowser/src/webrenderhandler.cpp +++ b/modules/webbrowser/src/webrenderhandler.cpp @@ -38,13 +38,12 @@ void WebRenderHandler::reshape(int w, int h) { _needsRepaint = true; } -bool WebRenderHandler::GetViewRect(CefRefPtr browser, CefRect& rect) { +bool WebRenderHandler::GetViewRect(CefRefPtr, CefRect& rect) { rect = CefRect(0, 0, _windowSize.x, _windowSize.y); return true; } -void WebRenderHandler::OnPaint(CefRefPtr browser, - CefRenderHandler::PaintElementType, +void WebRenderHandler::OnPaint(CefRefPtr, CefRenderHandler::PaintElementType, const CefRenderHandler::RectList& dirtyRects, const void* buffer, int w, int h) { @@ -61,16 +60,15 @@ void WebRenderHandler::OnPaint(CefRefPtr browser, _lowerDirtyRectBound = lowerUpdatingRectBound = glm::ivec2(0, 0); } - for (auto it = dirtyRects.begin(); it != dirtyRects.end(); ++it) { - lowerUpdatingRectBound = glm::min( - lowerUpdatingRectBound, - glm::ivec2(it->x, it->y) - ); + for (const CefRect& r : dirtyRects) { + lowerUpdatingRectBound = glm::min(lowerUpdatingRectBound, glm::ivec2(r.x, r.y)); upperUpdatingRectBound = glm::max( upperUpdatingRectBound, - glm::ivec2(it->x + it->width, it->y + it->height) + glm::ivec2(r.x + r.width, r.y + r.height) ); + } + const glm::ivec2 rectSize = upperUpdatingRectBound - lowerUpdatingRectBound; if (rectSize.x > 0 && rectSize.y > 0) { _textureIsDirty = true; diff --git a/modules/webbrowser/webbrowsermodule.cpp b/modules/webbrowser/webbrowsermodule.cpp index dad38e731d..e5d1e5f8c0 100644 --- a/modules/webbrowser/webbrowsermodule.cpp +++ b/modules/webbrowser/webbrowsermodule.cpp @@ -51,7 +51,7 @@ namespace { namespace openspace { WebBrowserModule::WebBrowserModule() : OpenSpaceModule(WebBrowserModule::Name) { - global::callback::deinitialize.push_back([this]() { deinitialize(); }); + global::callback::deinitialize.emplace_back([this]() { deinitialize(); }); } void WebBrowserModule::internalDeinitialize() { @@ -100,7 +100,7 @@ void WebBrowserModule::internalInitialize(const ghoul::Dictionary& dictionary) { _cefHost = std::make_unique(std::move(helperLocation)); LDEBUG("Starting CEF... done!"); - global::callback::preSync.push_back([this]() { + global::callback::preSync.emplace_back([this]() { if (_cefHost && !_browsers.empty()) { _cefHost->doMessageLoopWork(); } diff --git a/modules/webbrowser/webbrowsermodule.h b/modules/webbrowser/webbrowsermodule.h index f420320808..349b6a12f2 100644 --- a/modules/webbrowser/webbrowsermodule.h +++ b/modules/webbrowser/webbrowsermodule.h @@ -47,7 +47,7 @@ public: bool isEnabled() const; protected: - void internalInitialize(const ghoul::Dictionary& configuration) override; + void internalInitialize(const ghoul::Dictionary& dictionary) override; void internalDeinitialize() override; private: diff --git a/src/documentation/documentation.cpp b/src/documentation/documentation.cpp index f24709f09e..6b0c81f71f 100644 --- a/src/documentation/documentation.cpp +++ b/src/documentation/documentation.cpp @@ -63,21 +63,21 @@ struct WarningCompare { namespace ghoul { template <> -std::string to_string(const openspace::documentation::TestResult& testResult) { +std::string to_string(const openspace::documentation::TestResult& value) { using namespace openspace::documentation; - if (testResult.success) { + if (value.success) { return "Success"; } else { std::stringstream stream; stream << "Failure." << '\n'; - for (const TestResult::Offense& offense : testResult.offenses) { + for (const TestResult::Offense& offense : value.offenses) { stream << " " << ghoul::to_string(offense) << '\n'; } - for (const TestResult::Warning& warning : testResult.warnings) { + for (const TestResult::Warning& warning : value.warnings) { stream << " " << ghoul::to_string(warning) << '\n'; } @@ -86,14 +86,14 @@ std::string to_string(const openspace::documentation::TestResult& testResult) { } template <> -std::string to_string(const openspace::documentation::TestResult::Offense& offense) { - return offense.offender + ": " + ghoul::to_string(offense.reason); +std::string to_string(const openspace::documentation::TestResult::Offense& value) { + return value.offender + ": " + ghoul::to_string(value.reason); } template <> -std::string to_string(const openspace::documentation::TestResult::Offense::Reason& reason) +std::string to_string(const openspace::documentation::TestResult::Offense::Reason& value) { - switch (reason) { + switch (value) { case openspace::documentation::TestResult::Offense::Reason::ExtraKey: return "Extra key"; case openspace::documentation::TestResult::Offense::Reason::MissingKey: @@ -110,15 +110,14 @@ std::string to_string(const openspace::documentation::TestResult::Offense::Reaso } template <> -std::string to_string(const openspace::documentation::TestResult::Warning& warning) { - return warning.offender + ": " + ghoul::to_string(warning.reason); +std::string to_string(const openspace::documentation::TestResult::Warning& value) { + return value.offender + ": " + ghoul::to_string(value.reason); } template <> -std::string to_string( - const openspace::documentation::TestResult::Warning::Reason& reason) +std::string to_string(const openspace::documentation::TestResult::Warning::Reason& value) { - switch (reason) { + switch (value) { case openspace::documentation::TestResult::Warning::Reason::Deprecated: return "Deprecated"; default: diff --git a/src/documentation/verifier.cpp b/src/documentation/verifier.cpp index 170be90e5f..8c0251ca79 100644 --- a/src/documentation/verifier.cpp +++ b/src/documentation/verifier.cpp @@ -292,10 +292,10 @@ std::string ReferencingVerifier::documentation() const { return "Referencing Documentation: '" + identifier + "'"; } -AndVerifier::AndVerifier(const std::vector vs) { - ghoul_assert(!vs.empty(), "values must not be empty"); - for (Verifier* v : vs) { - values.push_back(std::shared_ptr(v)); +AndVerifier::AndVerifier(const std::vector values) { + ghoul_assert(!values.empty(), "values must not be empty"); + for (Verifier* v : values) { + this->values.push_back(std::shared_ptr(v)); } } @@ -354,10 +354,10 @@ std::string AndVerifier::documentation() const { return ghoul::join(documentations, ", "); } -OrVerifier::OrVerifier(const std::vector vs) { - ghoul_assert(!vs.empty(), "values must not be empty"); - for (Verifier* v : vs) { - values.push_back(std::shared_ptr(v)); +OrVerifier::OrVerifier(const std::vector values) { + ghoul_assert(!values.empty(), "values must not be empty"); + for (Verifier* v : values) { + this->values.push_back(std::shared_ptr(v)); } } diff --git a/src/interaction/externinteraction.cpp b/src/interaction/externinteraction.cpp index 612d3a79a1..5144789fbd 100644 --- a/src/interaction/externinteraction.cpp +++ b/src/interaction/externinteraction.cpp @@ -44,25 +44,25 @@ const uint32_t ProtocolVersion = 3; const size_t MaxLatencyDiffs = 64; const char* _loggerCat = "ExternInteraction"; -static const openspace::properties::Property::PropertyInfo BufferTimeInfo = { +constexpr openspace::properties::Property::PropertyInfo BufferTimeInfo = { "BufferTime", "Buffer Time", "" // @TODO Missing documentation }; -static const openspace::properties::Property::PropertyInfo TimeKeyFrameInfo = { +constexpr openspace::properties::Property::PropertyInfo TimeKeyFrameInfo = { "TimeKeyframeInterval", "Time keyframe interval", "" // @TODO Missing documentation }; -static const openspace::properties::Property::PropertyInfo CameraKeyFrameInfo = { +constexpr openspace::properties::Property::PropertyInfo CameraKeyFrameInfo = { "CameraKeyframeInterval", "Camera Keyframe interval", "" // @TODO Missing documentation }; -static const openspace::properties::Property::PropertyInfo TimeToleranceInfo = { +constexpr openspace::properties::Property::PropertyInfo TimeToleranceInfo = { "TimeTolerance", "Time tolerance", "" // @TODO Missing documentation diff --git a/src/interaction/joystickcamerastates.cpp b/src/interaction/joystickcamerastates.cpp index e4bb651ca7..65c8f539fc 100644 --- a/src/interaction/joystickcamerastates.cpp +++ b/src/interaction/joystickcamerastates.cpp @@ -226,10 +226,10 @@ std::vector JoystickCameraStates::buttonCommand(int button) const { namespace ghoul { template <> -std::string to_string(const openspace::interaction::JoystickCameraStates::AxisType& type) +std::string to_string(const openspace::interaction::JoystickCameraStates::AxisType& value) { using T = openspace::interaction::JoystickCameraStates::AxisType; - switch (type) { + switch (value) { case T::None: return "None"; case T::OrbitX: return "Orbit X"; case T::OrbitY: return "Orbit Y"; diff --git a/src/interaction/joystickinputstate.cpp b/src/interaction/joystickinputstate.cpp index ace519ab12..463c4f6a2c 100644 --- a/src/interaction/joystickinputstate.cpp +++ b/src/interaction/joystickinputstate.cpp @@ -72,8 +72,8 @@ bool JoystickInputStates::button(int button, JoystickAction action) const { namespace ghoul { template <> -std::string to_string(const openspace::interaction::JoystickAction& action) { - switch (action) { +std::string to_string(const openspace::interaction::JoystickAction& value) { + switch (value) { case openspace::interaction::JoystickAction::Idle: return "Idle"; case openspace::interaction::JoystickAction::Press: return "Press"; case openspace::interaction::JoystickAction::Repeat: return "Repeat"; diff --git a/src/interaction/keybindingmanager.cpp b/src/interaction/keybindingmanager.cpp index e406b0a58e..3ce077797f 100644 --- a/src/interaction/keybindingmanager.cpp +++ b/src/interaction/keybindingmanager.cpp @@ -151,12 +151,12 @@ std::string KeybindingManager::generateJson() const { } first = false; json << "{"; - json << "\"key\": \"" << ghoul::to_string(p.first) << "\","; - json << "\"script\": \"" << escapedJson(p.second.command) << "\","; - json << "\"remoteScripting\": " + json << R"("key": ")" << ghoul::to_string(p.first) << "\","; + json << R"("script": ")" << escapedJson(p.second.command) << "\","; + json << R"("remoteScripting: ")" << (p.second.synchronization ? "true," : "false,"); - json << "\"documentation\": \"" << escapedJson(p.second.documentation) << "\","; - json << "\"name\": \"" << escapedJson(p.second.name) << "\""; + json << R"("documentation": ")" << escapedJson(p.second.documentation) << "\","; + json << R"("name: ")" << escapedJson(p.second.name) << "\""; json << "}"; } json << "]"; diff --git a/src/interaction/navigationhandler.cpp b/src/interaction/navigationhandler.cpp index be2465ae7c..06ba77616c 100644 --- a/src/interaction/navigationhandler.cpp +++ b/src/interaction/navigationhandler.cpp @@ -272,8 +272,8 @@ void NavigationHandler::saveCameraStateToFile(const std::string& filepath) { ghoul::Dictionary cameraDict = cameraStateDictionary(); - // TODO : Should get the camera state as a dictionary and save the dictionary to - // a file in form of a lua state and not use ofstreams here. + // TODO(abock): Should get the camera state as a dictionary and save the + // dictionary to a file in form of a lua state and not use ofstreams here. std::ofstream ofs(fullpath.c_str()); diff --git a/src/interaction/orbitalnavigator.cpp b/src/interaction/orbitalnavigator.cpp index 6df681d3a3..e2a5fe349f 100644 --- a/src/interaction/orbitalnavigator.cpp +++ b/src/interaction/orbitalnavigator.cpp @@ -356,11 +356,12 @@ void OrbitalNavigator::updateCameraStateFromStates(Camera& camera, double deltaT } } -glm::dvec3 OrbitalNavigator::cameraToSurfaceVector(const glm::dvec3& camPos, - const glm::dvec3& centerPos, const SurfacePositionHandle& posHandle) +glm::dvec3 OrbitalNavigator::cameraToSurfaceVector(const glm::dvec3& cameraPos, + const glm::dvec3& centerPos, + const SurfacePositionHandle& posHandle) { glm::dmat4 modelTransform = _focusNode->modelTransform(); - glm::dvec3 posDiff = camPos - centerPos; + glm::dvec3 posDiff = cameraPos - centerPos; glm::dvec3 centerToActualSurfaceModelSpace = posHandle.centerToReferenceSurface + posHandle.referenceSurfaceOutDirection * posHandle.heightToSurface; diff --git a/src/interaction/sessionrecording.cpp b/src/interaction/sessionrecording.cpp index 41b1c46188..82b7ce1d03 100644 --- a/src/interaction/sessionrecording.cpp +++ b/src/interaction/sessionrecording.cpp @@ -73,7 +73,7 @@ void SessionRecording::setRecordDataFormat(RecordedDataMode dataMode) { _recordingDataMode = dataMode; } -bool SessionRecording::startRecording(std::string filename) { +bool SessionRecording::startRecording(const std::string& filename) { if (_state == SessionState::Playback) { _playbackFile.close(); } @@ -315,12 +315,7 @@ void SessionRecording::cleanUpPlayback() { } bool SessionRecording::isDataModeBinary() { - if (_recordingDataMode == RecordedDataMode::Binary) { - return true; - } - else { - return false; - } + return _recordingDataMode == RecordedDataMode::Binary; } void SessionRecording::writeToFileBuffer(const double src) { @@ -353,7 +348,7 @@ void SessionRecording::writeToFileBuffer(const bool b) { _bufferIndex += writeSize_bytes; } -void SessionRecording::saveStringToFile(const std::string s) { +void SessionRecording::saveStringToFile(const std::string& s) { size_t strLen = s.size(); size_t writeSize_bytes = sizeof(size_t); @@ -1022,12 +1017,7 @@ void SessionRecording::updateCameraWithOrWithoutNewKeyframes(double currTime) { bool SessionRecording::isTimeToHandleNextNonCameraKeyframe(double currTime) { bool isNonCameraPlaybackActive = (_playbackActive_time || _playbackActive_script); - if ((currTime > getNextTimestamp()) && isNonCameraPlaybackActive) { - return true; - } - else { - return false; - } + return (currTime > getNextTimestamp()) && isNonCameraPlaybackActive; } bool SessionRecording::findNextFutureCameraIndex(double currTime) { @@ -1251,7 +1241,7 @@ void SessionRecording::saveKeyframeToFileBinary(unsigned char* buffer, size_t si } void SessionRecording::saveKeyframeToFile(std::string entry) { - _recordFile << entry << std::endl; + _recordFile << std::move(entry) << std::endl; } scripting::LuaLibrary SessionRecording::luaLibrary() { diff --git a/src/network/networkengine.cpp b/src/network/networkengine.cpp index 3f2f73cb8e..ecf300c2aa 100644 --- a/src/network/networkengine.cpp +++ b/src/network/networkengine.cpp @@ -181,7 +181,7 @@ void NetworkEngine::sendMessages() { union { MessageIdentifier value; std::array data; - } identifier; + } identifier = {}; identifier.value = m.identifer; // Prepending the message identifier to the front @@ -199,7 +199,7 @@ void NetworkEngine::sendInitialInformation() { union { MessageIdentifier value; std::array data; - } identifier; + } identifier = {}; identifier.value = m.identifer; std::vector payload = m.body; @@ -218,7 +218,7 @@ void NetworkEngine::sendInitialInformation() { union { MessageIdentifier value; std::array data; - } identifier; + } identifier = {}; identifier.value = _initialMessageFinishedIdentifier; std::vector d; diff --git a/src/network/parallelpeer.cpp b/src/network/parallelpeer.cpp index 6955cf8ad1..ad76aa09d8 100644 --- a/src/network/parallelpeer.cpp +++ b/src/network/parallelpeer.cpp @@ -313,7 +313,7 @@ void ParallelPeer::dataMessageReceived(const std::vector& message) // If there are new keyframes incoming, make sure to erase all keyframes // that already exist after the first new keyframe. - if (keyframesMessage.size() > 0) { + if (!keyframesMessage.empty()) { const double convertedTimestamp = convertTimestamp(keyframesMessage[0]._timestamp); @@ -627,7 +627,7 @@ void ParallelPeer::sendCameraKeyframe() { void ParallelPeer::sendTimeTimeline() { // Create a keyframe with current position and orientation of camera - const Timeline timeline = global::timeManager.timeline(); + const Timeline& timeline = global::timeManager.timeline(); std::deque> keyframes = timeline.keyframes(); datamessagestructures::TimeTimeline timelineMessage; diff --git a/src/network/parallelserver.cpp b/src/network/parallelserver.cpp index 3fb11f1303..f6d3d3497e 100644 --- a/src/network/parallelserver.cpp +++ b/src/network/parallelserver.cpp @@ -144,16 +144,16 @@ void ParallelServer::handlePeerMessage(PeerMessage peerMessage) { handleAuthentication(peer, std::move(data)); break; case ParallelConnection::MessageType::Data: - handleData(peer, std::move(data)); + handleData(*peer, std::move(data)); break; case ParallelConnection::MessageType::HostshipRequest: handleHostshipRequest(peer, std::move(data)); break; case ParallelConnection::MessageType::HostshipResignation: - handleHostshipResignation(peer, std::move(data)); + handleHostshipResignation(*peer); break; case ParallelConnection::MessageType::Disconnection: - disconnect(peer); + disconnect(*peer); break; default: LERROR(fmt::format( @@ -174,7 +174,7 @@ void ParallelServer::handleAuthentication(std::shared_ptr peer, if (passwordHash != _passwordHash) { LERROR(fmt::format("Connection {} provided incorrect passcode.", peer->id)); - disconnect(peer); + disconnect(*peer); return; } @@ -190,7 +190,7 @@ void ParallelServer::handleAuthentication(std::shared_ptr peer, name = "Anonymous"; } - setName(peer, name); + setName(*peer, name); LINFO(fmt::format("Connection established with {} \"{}\"", peer->id, name)); @@ -208,20 +208,20 @@ void ParallelServer::handleAuthentication(std::shared_ptr peer, assignHost(peer); for (std::pair>& it : _peers) { // sendConnectionStatus(it->second) ? - sendConnectionStatus(peer); + sendConnectionStatus(*peer); } } else { - setToClient(peer); + setToClient(*peer); } setNConnections(nConnections() + 1); } -void ParallelServer::handleData(std::shared_ptr peer, std::vector data) { - if (peer->id != _hostPeerId) { +void ParallelServer::handleData(const Peer& peer, std::vector data) { + if (peer.id != _hostPeerId) { LINFO(fmt::format( - "Connection {} tried to send data without being the host. Ignoring", peer->id + "Connection {} tried to send data without being the host. Ignoring", peer.id )); } sendMessageToClients(ParallelConnection::MessageType::Data, data); @@ -258,10 +258,8 @@ void ParallelServer::handleHostshipRequest(std::shared_ptr peer, LINFO(fmt::format("Switched host from {} to {}.", oldHostPeerId, peer->id)); } -void ParallelServer::handleHostshipResignation(std::shared_ptr peer, - std::vector) -{ - LINFO(fmt::format("Connection {} wants to resign its hostship.", peer->id)); +void ParallelServer::handleHostshipResignation(Peer& peer) { + LINFO(fmt::format("Connection {} wants to resign its hostship.", peer.id)); size_t oldHostPeerId = 0; { @@ -271,26 +269,26 @@ void ParallelServer::handleHostshipResignation(std::shared_ptr peer, setToClient(peer); - LINFO(fmt::format("Connection {} resigned as host.", peer->id)); + LINFO(fmt::format("Connection {} resigned as host.", peer.id)); } -bool ParallelServer::isConnected(std::shared_ptr peer) const { - return peer->status != ParallelConnection::Status::Connecting && - peer->status != ParallelConnection::Status::Disconnected; +bool ParallelServer::isConnected(const Peer& peer) const { + return peer.status != ParallelConnection::Status::Connecting && + peer.status != ParallelConnection::Status::Disconnected; } -void ParallelServer::sendMessage(std::shared_ptr peer, +void ParallelServer::sendMessage(Peer& peer, ParallelConnection::MessageType messageType, const std::vector& message) { - peer->parallelConnection.sendMessage({ messageType, message }); + peer.parallelConnection.sendMessage({ messageType, message }); } void ParallelServer::sendMessageToAll(ParallelConnection::MessageType messageType, const std::vector& message) { for (std::pair>& it : _peers) { - if (isConnected(it.second)) { + if (isConnected(*it.second)) { it.second->parallelConnection.sendMessage({ messageType, message }); } } @@ -306,7 +304,7 @@ void ParallelServer::sendMessageToClients(ParallelConnection::MessageType messag } } -void ParallelServer::disconnect(std::shared_ptr peer) { +void ParallelServer::disconnect(Peer& peer) { if (isConnected(peer)) { setNConnections(nConnections() - 1); } @@ -319,27 +317,27 @@ void ParallelServer::disconnect(std::shared_ptr peer) { // Make sure any disconnecting host is first degraded to client, // in order to notify other clients about host disconnection. - if (peer->id == hostPeerId) { + if (peer.id == hostPeerId) { setToClient(peer); } - peer->parallelConnection.disconnect(); - peer->thread.join(); - _peers.erase(peer->id); + peer.parallelConnection.disconnect(); + peer.thread.join(); + _peers.erase(peer.id); } -void ParallelServer::setName(std::shared_ptr peer, std::string name) { - peer->name = name; +void ParallelServer::setName(Peer& peer, std::string name) { + peer.name = name; size_t hostPeerId = 0; { - std::lock_guard lock(_hostInfoMutex); + std::lock_guard lock(_hostInfoMutex); hostPeerId = _hostPeerId; } // Make sure everyone gets the new host name. - if (peer->id == hostPeerId) { + if (peer.id == hostPeerId) { { - std::lock_guard lock(_hostInfoMutex); + std::lock_guard lock(_hostInfoMutex); _hostName = name; } @@ -352,7 +350,7 @@ void ParallelServer::setName(std::shared_ptr peer, std::string name) { void ParallelServer::assignHost(std::shared_ptr newHost) { { - std::lock_guard lock(_hostInfoMutex); + std::lock_guard lock(_hostInfoMutex); std::shared_ptr oldHost = peer(_hostPeerId); if (oldHost) { @@ -367,14 +365,14 @@ void ParallelServer::assignHost(std::shared_ptr newHost) { if (it.second != newHost) { it.second->status = ParallelConnection::Status::ClientWithHost; } - sendConnectionStatus(it.second); + sendConnectionStatus(*it.second); } } -void ParallelServer::setToClient(std::shared_ptr peer) { - if (peer->status == ParallelConnection::Status::Host) { +void ParallelServer::setToClient(Peer& peer) { + if (peer.status == ParallelConnection::Status::Host) { { - std::lock_guard lock(_hostInfoMutex); + std::lock_guard lock(_hostInfoMutex); _hostPeerId = 0; _hostName = ""; } @@ -382,10 +380,10 @@ void ParallelServer::setToClient(std::shared_ptr peer) { // If host becomes client, make all clients hostless. for (std::pair>& it : _peers) { it.second->status = ParallelConnection::Status::ClientWithoutHost; - sendConnectionStatus(it.second); + sendConnectionStatus(*it.second); } } else { - peer->status = (_hostPeerId > 0) ? + peer.status = (_hostPeerId > 0) ? ParallelConnection::Status::ClientWithHost : ParallelConnection::Status::ClientWithoutHost; sendConnectionStatus(peer); @@ -404,9 +402,9 @@ void ParallelServer::setNConnections(size_t nConnections) { sendMessageToAll(ParallelConnection::MessageType::NConnections, data); } -void ParallelServer::sendConnectionStatus(std::shared_ptr peer) { +void ParallelServer::sendConnectionStatus(Peer& peer) { std::vector data; - const uint32_t outStatus = static_cast(peer->status); + const uint32_t outStatus = static_cast(peer.status); data.insert( data.end(), reinterpret_cast(&outStatus), diff --git a/src/performance/performancemanager.cpp b/src/performance/performancemanager.cpp index 33e870e82c..7832b689bb 100644 --- a/src/performance/performancemanager.cpp +++ b/src/performance/performancemanager.cpp @@ -130,8 +130,6 @@ void PerformanceManager::DestroyGlobalSharedMemory() { sharedMemory.releaseLock(); } -PerformanceManager::~PerformanceManager() {} - void PerformanceManager::setEnabled(bool enabled) { _logDir = absPath("${BASE}"); _prefix = "PM-"; diff --git a/src/properties/optionproperty.cpp b/src/properties/optionproperty.cpp index 7690f36c6f..9cdd5dfda2 100644 --- a/src/properties/optionproperty.cpp +++ b/src/properties/optionproperty.cpp @@ -146,7 +146,8 @@ std::string OptionProperty::generateAdditionalJsonDescription() const { std::string d = o.description; std::string dSan = sanitizeString(d); - result += "{\"" + vSan + "\": \"" + dSan+ "\"}"; + result += fmt::format(R"("{}": "{}"})", vSan, dSan); + if (i != _options.size() - 1) { result += ","; } diff --git a/src/properties/propertyowner.cpp b/src/properties/propertyowner.cpp index 5a2579ee1a..bd6d681fc9 100644 --- a/src/properties/propertyowner.cpp +++ b/src/properties/propertyowner.cpp @@ -364,19 +364,23 @@ std::string PropertyOwner::generateJson() const { std::function createJson = [&createJson](properties::PropertyOwner* owner) -> std::string { + constexpr const char* replStr = R"("{}": "{}",)"; + std::stringstream json; json << "{"; - json << "\"name\": \"" << owner->identifier() << "\","; + json << fmt::format(replStr, "name", owner->identifier()); json << "\"properties\": ["; - auto properties = owner->properties(); + const std::vector& properties = owner->properties(); for (properties::Property* p : properties) { json << "{"; - json << "\"id\": \"" << p->identifier() << "\","; - json << "\"type\": \"" << p->className() << "\","; - json << "\"fullyQualifiedId\": \"" << p->fullyQualifiedIdentifier() << "\","; - json << "\"guiName\": \"" << p->guiName() << "\","; - json << "\"description\": \"" << escapedJson(p->description()) << "\""; + json << fmt::format(replStr, "id", p->identifier()); + json << fmt::format(replStr, "type", p->className()); + json << fmt::format( + replStr, "fullyQualifiedId", p->fullyQualifiedIdentifier() + ); + json << fmt::format(replStr, "guiName", p->guiName()); + json << fmt::format(replStr, "description", escapedJson(p->description())); json << "}"; if (p != properties.back()) { json << ","; diff --git a/src/properties/selectionproperty.cpp b/src/properties/selectionproperty.cpp index f4e22449e7..68a6571471 100644 --- a/src/properties/selectionproperty.cpp +++ b/src/properties/selectionproperty.cpp @@ -165,7 +165,7 @@ std::string SelectionProperty::generateAdditionalJsonDescription() const { std::string dSan = sanitizeString(d); result += "{"; - result += "\"" + vSan + "\": \"" + dSan + "\""; + result += fmt::format(R"("{}": "{}")", vSan, dSan); result += "}"; if (i != _options.size() - 1) { result += ","; diff --git a/src/rendering/dashboard.cpp b/src/rendering/dashboard.cpp index 3e0fe9daf2..ba2c9bb4aa 100644 --- a/src/rendering/dashboard.cpp +++ b/src/rendering/dashboard.cpp @@ -48,8 +48,6 @@ Dashboard::Dashboard() addProperty(_isEnabled); } -Dashboard::~Dashboard() {} - void Dashboard::addDashboardItem(std::unique_ptr item) { const std::string& originalIdentifier = item->identifier(); int suffix = 1; diff --git a/src/rendering/loadingscreen.cpp b/src/rendering/loadingscreen.cpp index 19600d5c80..929cf963f8 100644 --- a/src/rendering/loadingscreen.cpp +++ b/src/rendering/loadingscreen.cpp @@ -150,6 +150,10 @@ LoadingScreen::~LoadingScreen() { } void LoadingScreen::render() { + if (_phase != Phase::PreStart) { + return; + } + // We have to recalculate the positions here because we will not be informed about a // window size change @@ -222,6 +226,8 @@ void LoadingScreen::render() { glm::vec4 color; switch (_phase) { + case Phase::PreStart: + break; case Phase::Construction: color = PhaseColorConstruction; break; diff --git a/src/rendering/renderengine.cpp b/src/rendering/renderengine.cpp index 474f6577d6..0ee89eff7d 100644 --- a/src/rendering/renderengine.cpp +++ b/src/rendering/renderengine.cpp @@ -526,11 +526,11 @@ void RenderEngine::render(const glm::mat4& sceneMatrix, const glm::mat4& viewMat std::vector ssrs; ssrs.reserve(global::screenSpaceRenderables.size()); - for (size_t i = 0; i < global::screenSpaceRenderables.size(); ++i) { - const bool isEnabled = global::screenSpaceRenderables[i]->isEnabled(); - const bool isReady = global::screenSpaceRenderables[i]->isReady(); - if (isEnabled && isReady) { - ssrs.push_back(global::screenSpaceRenderables[i].get()); + for (const std::unique_ptr& ssr : + global::screenSpaceRenderables) + { + if (ssr->isEnabled() && ssr->isReady()) { + ssrs.push_back(ssr.get()); } } @@ -1045,7 +1045,8 @@ void RenderEngine::renderCameraInformation() { constexpr const float YSeparation = 5.f; constexpr const float XSeparation = 5.f; - interaction::OrbitalNavigator nav = global::navigationHandler.orbitalNavigator(); + const interaction::OrbitalNavigator& nav = + global::navigationHandler.orbitalNavigator(); _cameraButtonLocations.rotation = { fontResolution().x - rotationBox.boundingBox.x - XSeparation, diff --git a/src/scene/asset.cpp b/src/scene/asset.cpp index 6a17df79e0..aacc974cd2 100644 --- a/src/scene/asset.cpp +++ b/src/scene/asset.cpp @@ -112,7 +112,7 @@ void Asset::setState(Asset::State state) { for (const std::weak_ptr& requiringAsset : _requiringAssets) { if (std::shared_ptr a = requiringAsset.lock()) { - a->requiredAssetChangedState(thisAsset, state); + a->requiredAssetChangedState(state); } } @@ -123,7 +123,7 @@ void Asset::setState(Asset::State state) { } } -void Asset::requiredAssetChangedState(std::shared_ptr, Asset::State childState) { +void Asset::requiredAssetChangedState(Asset::State childState) { if (!isLoaded()) { // Prohibit state change to SyncResolved if additional requirements // may still be added. diff --git a/src/scene/scene.cpp b/src/scene/scene.cpp index dfa37c0a63..f1b9915a9c 100644 --- a/src/scene/scene.cpp +++ b/src/scene/scene.cpp @@ -50,9 +50,8 @@ namespace { namespace openspace { -Scene::InvalidSceneError::InvalidSceneError(const std::string& msg, - const std::string& comp) - : ghoul::RuntimeError(msg, comp) +Scene::InvalidSceneError::InvalidSceneError(std::string msg, std::string comp) + : ghoul::RuntimeError(std::move(msg), std::move(comp)) {} Scene::Scene(std::unique_ptr initializer) diff --git a/src/scene/scenegraphnode.cpp b/src/scene/scenegraphnode.cpp index 21e41b7a59..bd76b529a2 100644 --- a/src/scene/scenegraphnode.cpp +++ b/src/scene/scenegraphnode.cpp @@ -180,7 +180,7 @@ std::unique_ptr SceneGraphNode::createFromDictionary( ghoul::Dictionary renderableDictionary; dictionary.getValue(KeyRenderable, renderableDictionary); - renderableDictionary.setValue(KeyIdentifier, identifier); + renderableDictionary.setValue(KeyIdentifier, result->_identifier); result->_renderable = Renderable::createFromDictionary(renderableDictionary); if (result->_renderable == nullptr) { diff --git a/src/scene/scenelicensewriter.cpp b/src/scene/scenelicensewriter.cpp index ecb6b44a00..3e169b3080 100644 --- a/src/scene/scenelicensewriter.cpp +++ b/src/scene/scenelicensewriter.cpp @@ -25,6 +25,7 @@ #include #include +#include #include namespace { @@ -53,12 +54,14 @@ std::string SceneLicenseWriter::generateJson() const { std::stringstream json; json << "["; for (const SceneLicense& license : _licenses) { + constexpr const char* replStr = R"("{}": "{}", )"; + constexpr const char* replStr2 = R"("{}": "{}")"; json << "{"; - json << "\"module\": \"" << escapedJson(license.module) << "\", "; - json << "\"name\": \"" << escapedJson(license.name) << "\", "; - json << "\"attribution\": \"" << escapedJson(license.attribution) << "\", "; - json << "\"url\": \"" << escapedJson(license.url) << "\", "; - json << "\"licenseText\": \"" << escapedJson(license.licenseText) << "\""; + json << fmt::format(replStr, "module", escapedJson(license.module)); + json << fmt::format(replStr, "name", escapedJson(license.name)); + json << fmt::format(replStr, "attribution", escapedJson(license.attribution)); + json << fmt::format(replStr, "url", escapedJson(license.url)); + json << fmt::format(replStr2, "licenseText", escapedJson(license.licenseText)); json << "}"; if (&license != &(_licenses.back())) { diff --git a/src/scripting/scriptengine.cpp b/src/scripting/scriptengine.cpp index 29b9739089..03e93c5b32 100644 --- a/src/scripting/scriptengine.cpp +++ b/src/scripting/scriptengine.cpp @@ -551,20 +551,23 @@ std::string ScriptEngine::generateJson() const { bool first = true; for (const LuaLibrary& l : _registeredLibraries) { + constexpr const char* replStr = R"("{}": "{}", )"; + constexpr const char* replStr2 = R"("{}": "{}")"; + if (!first) { json << ","; } first = false; json << "{"; - json << "\"library\": \"" << l.name << "\","; + json << fmt::format(replStr, "library", l.name); json << "\"functions\": ["; for (const LuaLibrary::Function& f : l.functions) { json << "{"; - json << "\"name\": \"" << f.name << "\", "; - json << "\"arguments\": \"" << escapedJson(f.argumentText) << "\", "; - json << "\"help\": \"" << escapedJson(f.helpText) << "\""; + json << fmt::format(replStr, "library", f.name); + json << fmt::format(replStr, "arguments", escapedJson(f.argumentText)); + json << fmt::format(replStr2, "help", escapedJson(f.helpText)); json << "}"; if (&f != &l.functions.back() || !l.documentations.empty()) { json << ","; @@ -573,9 +576,9 @@ std::string ScriptEngine::generateJson() const { for (const LuaLibrary::Documentation& doc : l.documentations) { json << "{"; - json << "\"name\": \"" << doc.name << "\", "; - json << "\"arguments\": \"" << escapedJson(doc.parameter) << "\", "; - json << "\"help\": \"" << escapedJson(doc.description) << "\""; + json << fmt::format(replStr, "name", doc.name); + json << fmt::format(replStr, "arguments", escapedJson(doc.parameter)); + json << fmt::format(replStr2, "help", escapedJson(doc.description)); json << "}"; if (&doc != &l.documentations.back()) { json << ",";