diff --git a/apps/OpenSpace/main.cpp b/apps/OpenSpace/main.cpp index b98fe3a5a2..a4e914a7ed 100644 --- a/apps/OpenSpace/main.cpp +++ b/apps/OpenSpace/main.cpp @@ -813,7 +813,7 @@ void setSgctDelegateFunctions() { }; sgctDelegate.osDpiScaling = []() { ZoneScoped - + // Detect which DPI scaling to use // 1. If there is a GUI window, use the GUI window's content scale value const Window* dpiWindow = nullptr; @@ -1017,10 +1017,10 @@ std::string selectedSgctProfileFromLauncher(LauncherWindow& lw, bool hasCliSGCTC } else { std::filesystem::path c = absPath(config); - + std::filesystem::path cj = c; cj.replace_extension(".json"); - + std::filesystem::path cx = c; cx.replace_extension(".xml"); diff --git a/include/openspace/interaction/joystickcamerastates.h b/include/openspace/interaction/joystickcamerastates.h index c93eb8486c..6aa19a5b94 100644 --- a/include/openspace/interaction/joystickcamerastates.h +++ b/include/openspace/interaction/joystickcamerastates.h @@ -115,14 +115,14 @@ private: struct JoystickCameraState { std::string joystickName; - // We use an array for the axes and a map for the buttons since the axis are going to - // be accessed much more often and thus have to be more efficient. And storing a few - // extra AxisInformation that are not used will not matter that much; finding an axis - // location in a potential map each frame, however, would + // We use an array for the axes and a map for the buttons since the axis are going + // to be accessed much more often and thus have to be more efficient. And storing + // a few extra AxisInformation that are not used will not matter that much; + // finding an axis location in a potential map each frame, however, would std::array axisMapping; - // This array is used to store the old axis values from the previous frame, - // it is used to calculate the difference in the values in the case of a sticky axis + // This array is used to store the old axis values from the previous frame, it is + // used to calculate the difference in the values in the case of a sticky axis std::array prevAxisValues; struct ButtonInformation { diff --git a/include/openspace/interaction/sessionrecording.h b/include/openspace/interaction/sessionrecording.h index a24b13f1e0..735400dfb5 100644 --- a/include/openspace/interaction/sessionrecording.h +++ b/include/openspace/interaction/sessionrecording.h @@ -492,7 +492,8 @@ public: /** * Reads header information from a session recording file * - * \param stringstream reference to ifstream that contains the session recording file data + * \param stringstream reference to ifstream that contains the session recording file + * data * \param readLen_chars number of characters to be read, which may be the expected * length of the header line, or an arbitrary number of characters within it */ diff --git a/include/openspace/rendering/texturecomponent.h b/include/openspace/rendering/texturecomponent.h index d50d8f688c..2d41fd2073 100644 --- a/include/openspace/rendering/texturecomponent.h +++ b/include/openspace/rendering/texturecomponent.h @@ -64,7 +64,7 @@ private: ghoul::opengl::Texture::FilterMode::LinearMipMap; ghoul::opengl::Texture::WrappingMode _wrappingMode = ghoul::opengl::Texture::WrappingMode::Repeat; - + bool _shouldWatchFile = true; bool _shouldPurgeFromRAM = true; diff --git a/include/openspace/scene/profile.h b/include/openspace/scene/profile.h index 450ba77119..f8722b0219 100644 --- a/include/openspace/scene/profile.h +++ b/include/openspace/scene/profile.h @@ -89,12 +89,12 @@ public: bool isLocal; std::string script; }; - + struct Keybinding { KeyWithModifier key; std::string action; }; - + struct Time { enum class Type { Absolute, @@ -104,7 +104,7 @@ public: Type type; std::string value; }; - + struct CameraNavState { static constexpr const char* Type = "setNavigationState"; @@ -116,7 +116,7 @@ public: std::optional yaw; std::optional pitch; }; - + struct CameraGoToGeo { static constexpr const char* Type = "goToGeo"; @@ -125,7 +125,7 @@ public: double longitude; std::optional altitude; }; - + using CameraType = std::variant; Profile() = default; diff --git a/modules/base/rendering/renderablenodeline.cpp b/modules/base/rendering/renderablenodeline.cpp index 102c9681ea..139d63b0d4 100644 --- a/modules/base/rendering/renderablenodeline.cpp +++ b/modules/base/rendering/renderablenodeline.cpp @@ -212,7 +212,7 @@ void RenderableNodeLine::updateVertexData() { _start.value(), _end.value() ) ); - + return; } diff --git a/modules/base/rendering/renderableplane.h b/modules/base/rendering/renderableplane.h index 843cdd9a36..9c927a6d61 100644 --- a/modules/base/rendering/renderableplane.h +++ b/modules/base/rendering/renderableplane.h @@ -68,15 +68,15 @@ protected: virtual void bindTexture(); virtual void unbindTexture(); void createPlane(); - + properties::OptionProperty _blendMode; properties::BoolProperty _mirrorBackside; properties::BoolProperty _billboard; properties::FloatProperty _size; properties::Vec3Property _multiplyColor; - + ghoul::opengl::ProgramObject* _shader = nullptr; - + GLuint _quad = 0; GLuint _vertexPositionBuffer = 0; diff --git a/modules/base/rendering/renderableplanetimevaryingimage.cpp b/modules/base/rendering/renderableplanetimevaryingimage.cpp index d957708bce..76d8e3982d 100644 --- a/modules/base/rendering/renderableplanetimevaryingimage.cpp +++ b/modules/base/rendering/renderableplanetimevaryingimage.cpp @@ -88,9 +88,9 @@ RenderablePlaneTimeVaryingImage::RenderablePlaneTimeVaryingImage( , _sourceFolder(SourceFolderInfo) { const Parameters p = codegen::bake(dictionary); - + addProperty(_blendMode); - + _sourceFolder = p.sourceFolder; if (!std::filesystem::is_directory(absPath(_sourceFolder))) { LERROR(fmt::format( @@ -133,7 +133,7 @@ void RenderablePlaneTimeVaryingImage::initialize() { return; } extractTriggerTimesFromFileNames(); - computeSequenceEndTime(); + computeSequenceEndTime(); } void RenderablePlaneTimeVaryingImage::initializeGL() { @@ -197,7 +197,7 @@ void RenderablePlaneTimeVaryingImage::bindTexture() { void RenderablePlaneTimeVaryingImage::update(const UpdateData& data) { ZoneScoped RenderablePlane::update(data); - + if (!_enabled || _startTimes.empty()) { return; } @@ -231,8 +231,8 @@ void RenderablePlaneTimeVaryingImage::update(const UpdateData& data) { void RenderablePlaneTimeVaryingImage::render(const RenderData& data, RendererTasks& t) { if (!_startTimes.empty() && - data.time.j2000Seconds() < _sequenceEndTime && - data.time.j2000Seconds() > _startTimes[0]) + data.time.j2000Seconds() < _sequenceEndTime && + data.time.j2000Seconds() > _startTimes[0]) { glDisable(GL_CULL_FACE); RenderablePlane::render(data, t); diff --git a/modules/base/rendering/renderabletimevaryingsphere.cpp b/modules/base/rendering/renderabletimevaryingsphere.cpp index 3bfe8e508b..d947c1ae8b 100644 --- a/modules/base/rendering/renderabletimevaryingsphere.cpp +++ b/modules/base/rendering/renderabletimevaryingsphere.cpp @@ -44,7 +44,7 @@ namespace { constexpr const char* ProgramName = "Timevarying Sphere"; - + constexpr const std::array UniformNames = { "opacity", "modelViewProjection", "modelViewRotation", "colorTexture", "mirrorTexture" @@ -308,7 +308,7 @@ void RenderableTimeVaryingSphere::render(const RenderData& data, RendererTasks&) const float startLogFadeDistance = glm::log(_size * _fadeOutThreshold); const float stopLogFadeDistance = startLogFadeDistance + 1.f; - if (logDistCamera > startLogFadeDistance && + if (logDistCamera > startLogFadeDistance && logDistCamera < stopLogFadeDistance) { const float fadeFactor = glm::clamp( @@ -404,7 +404,7 @@ void RenderableTimeVaryingSphere::extractMandatoryInfoFromSourceFolder() { } std::sort( - _files.begin(), _files.end(), + _files.begin(), _files.end(), [](const FileData& a, const FileData& b) { return a.time < b.time; } @@ -436,7 +436,7 @@ void RenderableTimeVaryingSphere::update(const UpdateData& data) { // true => We stepped forward to a time represented by another state (nextIdx < _files.size() && currentTime >= _files[nextIdx].time)) { - updateActiveTriggerTimeIndex(currentTime); + updateActiveTriggerTimeIndex(currentTime); _sphereIsDirty = true; } // else {we're still in same state as previous frame (no changes needed)} } @@ -500,7 +500,7 @@ void RenderableTimeVaryingSphere::computeSequenceEndTime() { } void RenderableTimeVaryingSphere::loadTexture() { - if (_activeTriggerTimeIndex != -1) { + if (_activeTriggerTimeIndex != -1) { _texture = _files[_activeTriggerTimeIndex].texture.get(); } } diff --git a/modules/debugging/debuggingmodule_lua.inl b/modules/debugging/debuggingmodule_lua.inl index eae448dd5c..82df2e0dc1 100644 --- a/modules/debugging/debuggingmodule_lua.inl +++ b/modules/debugging/debuggingmodule_lua.inl @@ -63,7 +63,7 @@ std::string makeIdentifier(std::string s) { const interaction::Path* currentPath = global::navigationHandler->pathNavigator().currentPath(); - // Parent node. Note that we only render one path at a time, so remove the previously + // Parent node. Note that we only render one path at a time, so remove the previously // rendered one, if any std::string addParentScript = fmt::format( "if openspace.hasSceneGraphNode('{0}') then " diff --git a/modules/exoplanets/exoplanetsmodule.cpp b/modules/exoplanets/exoplanetsmodule.cpp index c602a9cedc..a3bc02c4a2 100644 --- a/modules/exoplanets/exoplanetsmodule.cpp +++ b/modules/exoplanets/exoplanetsmodule.cpp @@ -224,7 +224,7 @@ std::string ExoplanetsModule::exoplanetsDataPath() const { std::string ExoplanetsModule::lookUpTablePath() const { ghoul_assert(hasDataFiles(), "Data files not loaded"); - + return absPath( fmt::format("{}/{}", _exoplanetsDataFolder.value(), LookupTableFileName) ).string(); diff --git a/modules/fieldlinessequence/fieldlinessequencemodule.cpp b/modules/fieldlinessequence/fieldlinessequencemodule.cpp index c8e3fda02d..ddf0d19d20 100644 --- a/modules/fieldlinessequence/fieldlinessequencemodule.cpp +++ b/modules/fieldlinessequence/fieldlinessequencemodule.cpp @@ -67,7 +67,8 @@ void FieldlinesSequenceModule::internalInitialize(const ghoul::Dictionary&) { factory->registerClass("RenderableFieldlinesSequence"); } -std::vector FieldlinesSequenceModule::documentations() const { +std::vector FieldlinesSequenceModule::documentations() const +{ return { RenderableFieldlinesSequence::Documentation() }; diff --git a/modules/fieldlinessequence/rendering/renderablefieldlinessequence.cpp b/modules/fieldlinessequence/rendering/renderablefieldlinessequence.cpp index 8aa6da1996..1e04c66efd 100644 --- a/modules/fieldlinessequence/rendering/renderablefieldlinessequence.cpp +++ b/modules/fieldlinessequence/rendering/renderablefieldlinessequence.cpp @@ -185,7 +185,7 @@ namespace { // Extra variables such as rho, p or t std::optional> extraVariables; - + // Which variable in CDF file to trace. b is default for fieldline std::optional tracingVariable; @@ -207,11 +207,11 @@ namespace { // [[codegen::verbatim(ColorQuantityInfo.description)]] std::optional colorQuantity; - // List of ranges for which their corresponding parameters values will be + // List of ranges for which their corresponding parameters values will be // colorized by. Should be entered as {min value, max value} per range std::optional> colorTableRanges; - // Enables flow, showing the direction, but not accurate speed, that particles + // Enables flow, showing the direction, but not accurate speed, that particles // would be traveling std::optional flowEnabled; @@ -221,7 +221,7 @@ namespace { // [[codegen::verbatim(MaskingQuantityInfo.description)]] std::optional maskingQuantity; - // List of ranges for which their corresponding parameters values will be + // List of ranges for which their corresponding parameters values will be // masked by. Should be entered as {min value, max value} per range std::optional> maskingRanges; diff --git a/modules/fieldlinessequence/util/kameleonfieldlinehelper.cpp b/modules/fieldlinessequence/util/kameleonfieldlinehelper.cpp index 498fcc2a18..de50940813 100644 --- a/modules/fieldlinessequence/util/kameleonfieldlinehelper.cpp +++ b/modules/fieldlinessequence/util/kameleonfieldlinehelper.cpp @@ -89,7 +89,7 @@ namespace openspace::fls { * vector at each line vertex */ bool convertCdfToFieldlinesState(FieldlinesState& state, const std::string& cdfPath, - const std::unordered_map>& seedMap, double manualTimeOffset, const std::string& tracingVar, @@ -310,7 +310,7 @@ void prepareStateAndKameleonForExtras(ccmc::Kameleon* kameleon, std::string& str = extraScalarVars[i]; bool success = kameleon->doesVariableExist(str) && kameleon->loadVariable(str); if (!success && - (model == fls::Model::Batsrus && + (model == fls::Model::Batsrus && (str == TAsPOverRho || str == "T" || str == "t")) ) { diff --git a/modules/fieldlinessequence/util/kameleonfieldlinehelper.h b/modules/fieldlinessequence/util/kameleonfieldlinehelper.h index c86c146bb0..c849e46e85 100644 --- a/modules/fieldlinessequence/util/kameleonfieldlinehelper.h +++ b/modules/fieldlinessequence/util/kameleonfieldlinehelper.h @@ -37,8 +37,8 @@ class FieldlinesState; namespace fls { bool convertCdfToFieldlinesState(FieldlinesState& state, const std::string& cdfPath, - const std::unordered_map>& seedMap, - double manualTimeOffset, const std::string& tracingVar, + const std::unordered_map>& seedMap, + double manualTimeOffset, const std::string& tracingVar, std::vector& extraVars, std::vector& extraMagVars); } // namespace fls diff --git a/modules/globebrowsing/globebrowsingmodule_lua.inl b/modules/globebrowsing/globebrowsingmodule_lua.inl index 3b85f60227..01f6232007 100644 --- a/modules/globebrowsing/globebrowsingmodule_lua.inl +++ b/modules/globebrowsing/globebrowsingmodule_lua.inl @@ -355,7 +355,7 @@ getLocalPositionFromGeo(std::string globeIdentifier, double latitude, double lon { using namespace openspace; using namespace globebrowsing; - + SceneGraphNode* n = sceneGraphNode(globeIdentifier); if (!n) { throw ghoul::lua::LuaError("Unknown globe identifier: " + globeIdentifier); @@ -372,17 +372,18 @@ getLocalPositionFromGeo(std::string globeIdentifier, double latitude, double lon /** * Get geographic coordinates of the camera position in latitude, longitude, and altitude - * (degrees and meters). If the optional bool paramater is specified, the camera + * (degrees and meters). If the optional bool paramater is specified, the camera * eye postion will be used instead */ -[[codegen::luawrap]] std::tuple -getGeoPositionForCamera(bool useEyePosition = false) +[[codegen::luawrap]] std::tuple +getGeoPositionForCamera(bool useEyePosition = false) { using namespace openspace; using namespace globebrowsing; GlobeBrowsingModule* module = global::moduleEngine->module(); - const RenderableGlobe* globe = module->castFocusNodeRenderableToGlobe();//focus vs anchor + // focus vs anchor + const RenderableGlobe* globe = module->castFocusNodeRenderableToGlobe(); if (!globe) { throw ghoul::lua::LuaError("Focus node must be a RenderableGlobe"); } @@ -394,17 +395,21 @@ getGeoPositionForCamera(bool useEyePosition = false) const SceneGraphNode* anchor = global::navigationHandler->orbitalNavigator().anchorNode(); const glm::dmat4 inverseModelTransform = glm::inverse(anchor->modelTransform()); - + glm::dvec3 target; - ///@TODO (04-08-2022, micahnyc) - //adjust this to use the camera lookat - //once we fix this calculation, then we just add true to the function call in the asset + // @TODO (04-08-2022, micahnyc) + // adjust this to use the camera lookat + // once we fix this calculation, then we just add true to the function call in the + // asset if (useEyePosition) { const glm::dvec3 anchorPos = anchor->worldPosition(); const glm::dvec3 cameraDir = ghoul::viewDirection(camera->rotationQuaternion()); const double anchorToCameraDistance = glm::distance(anchorPos, cameraPosition); - const double anchorToPosDistance = glm::distance(anchorPos + globe->boundingSphere(), cameraPosition); + const double anchorToPosDistance = glm::distance( + anchorPos + globe->boundingSphere(), + cameraPosition + ); target = cameraPosition + anchorToPosDistance * cameraDir; } else { diff --git a/modules/globebrowsing/src/tileprovider/defaulttileprovider.cpp b/modules/globebrowsing/src/tileprovider/defaulttileprovider.cpp index c3ec9b5916..caf43fc98c 100644 --- a/modules/globebrowsing/src/tileprovider/defaulttileprovider.cpp +++ b/modules/globebrowsing/src/tileprovider/defaulttileprovider.cpp @@ -134,7 +134,7 @@ void DefaultTileProvider::initAsyncTileDataReader(TileTextureInitData initData) Tile DefaultTileProvider::tile(const TileIndex& tileIndex) { ZoneScoped - + ghoul_assert(_asyncTextureDataProvider, "No data provider"); if (tileIndex.level > maxLevel()) { return Tile{ nullptr, std::nullopt, Tile::Status::OutOfRange }; diff --git a/modules/globebrowsing/src/tileprovider/singleimagetileprovider.cpp b/modules/globebrowsing/src/tileprovider/singleimagetileprovider.cpp index 69698568d7..abb1a39454 100644 --- a/modules/globebrowsing/src/tileprovider/singleimagetileprovider.cpp +++ b/modules/globebrowsing/src/tileprovider/singleimagetileprovider.cpp @@ -80,7 +80,7 @@ void SingleImageProvider::reset() { if (_filePath.value().empty()) { return; } - + _tileTexture = ghoul::io::TextureReader::ref().loadTexture(_filePath, 2); if (!_tileTexture) { throw ghoul::RuntimeError( diff --git a/modules/globebrowsing/src/tileprovider/singleimagetileprovider.h b/modules/globebrowsing/src/tileprovider/singleimagetileprovider.h index c1132b5e33..62d852f7b4 100644 --- a/modules/globebrowsing/src/tileprovider/singleimagetileprovider.h +++ b/modules/globebrowsing/src/tileprovider/singleimagetileprovider.h @@ -48,7 +48,7 @@ public: private: properties::StringProperty _filePath; - + std::unique_ptr _tileTexture; Tile _tile; }; diff --git a/modules/globebrowsing/src/tileprovider/spoutimageprovider.cpp b/modules/globebrowsing/src/tileprovider/spoutimageprovider.cpp index a85c065445..50acecfbb7 100644 --- a/modules/globebrowsing/src/tileprovider/spoutimageprovider.cpp +++ b/modules/globebrowsing/src/tileprovider/spoutimageprovider.cpp @@ -197,7 +197,7 @@ void SpoutImageProvider::update() { return; } } - + spoutReceiver->updateReceiver(); #endif // OPENSPACE_HAS_SPOUT } diff --git a/modules/globebrowsing/src/tileprovider/temporaltileprovider.cpp b/modules/globebrowsing/src/tileprovider/temporaltileprovider.cpp index 77201c5c75..563f989e47 100644 --- a/modules/globebrowsing/src/tileprovider/temporaltileprovider.cpp +++ b/modules/globebrowsing/src/tileprovider/temporaltileprovider.cpp @@ -45,7 +45,7 @@ namespace { constexpr const char* TimePlaceholder = "${OpenSpaceTimeId}"; - + constexpr openspace::properties::Property::PropertyInfo UseFixedTimeInfo = { "UseFixedTime", "Use Fixed Time", @@ -113,7 +113,7 @@ namespace { // is checked against the provided format and added if it adheres to said // format std::filesystem::path folder [[codegen::directory()]]; - + // The format of files that is pared in the provided folder. The format string // has to be compatible to the C++ function get_time. // https://en.cppreference.com/w/cpp/io/manip/get_time @@ -124,7 +124,7 @@ namespace { // Determines whether this tile provider should interpolate between two adjacent // layers std::optional interpolation; - + // If provided, the tile provider will use this color map to convert a greyscale // image to color std::optional colormap; @@ -299,7 +299,7 @@ TemporalTileProvider::TemporalTileProvider(const ghoul::Dictionary& dictionary) )); } } - + _isInterpolating = p.interpolation.value_or(_isInterpolating); if (_isInterpolating) { _interpolateTileProvider = std::make_unique(dictionary); @@ -479,7 +479,7 @@ TemporalTileProvider::tileProvider( return p.first < t; } ); - + if (it != _folder.files.begin()) { it -= 1; } @@ -555,7 +555,7 @@ TemporalTileProvider::tileProvider( Time secondToFirst = Time(_prototyped.startTimeJ2000); _interpolateTileProvider->t1 = retrieveTileProvider(tCopy); - + // if the images are for each hour if (_prototyped.temporalResolution == "1h") { constexpr const int Hour = 60 * 60; @@ -765,7 +765,7 @@ Tile TemporalTileProvider::InterpolateTileProvider::tile(const TileIndex& tileIn glDisable(GL_BLEND); GLenum textureBuffers[1] = { GL_COLOR_ATTACHMENT0 }; glDrawBuffers(1, textureBuffers); - + // Setup our own viewport settings GLsizei w = static_cast(writeTexture->width()); GLsizei h = static_cast(writeTexture->height()); diff --git a/modules/globebrowsing/src/tileprovider/texttileprovider.h b/modules/globebrowsing/src/tileprovider/texttileprovider.h index 5f3b0816a1..937bf05f71 100644 --- a/modules/globebrowsing/src/tileprovider/texttileprovider.h +++ b/modules/globebrowsing/src/tileprovider/texttileprovider.h @@ -39,7 +39,7 @@ public: protected: Tile renderTile(const TileIndex& tileIndex, const std::string& text, const glm::vec2& position, const glm::vec4& color); - + const TileTextureInitData initData; std::unique_ptr fontRenderer; diff --git a/modules/globebrowsing/src/tileprovider/tileprovider.h b/modules/globebrowsing/src/tileprovider/tileprovider.h index 25698c9caf..ca62fb099f 100644 --- a/modules/globebrowsing/src/tileprovider/tileprovider.h +++ b/modules/globebrowsing/src/tileprovider/tileprovider.h @@ -86,7 +86,7 @@ struct TileProvider : public properties::PropertyOwner { void deinitialize(); virtual Tile tile(const TileIndex& tileIndex) = 0; - + /** * Returns the status of a Tile. The Tile::Status * corresponds the Tile that would be returned if the function @@ -94,7 +94,7 @@ struct TileProvider : public properties::PropertyOwner { * this point in time. */ virtual Tile::Status tileStatus(const TileIndex& index) = 0; - + /** * Get the associated depth transform for this TileProvider. This is necessary for * TileProviders serving height map data, in order to correcly map pixel values to diff --git a/modules/globebrowsing/src/tileprovider/tileproviderbyindex.cpp b/modules/globebrowsing/src/tileprovider/tileproviderbyindex.cpp index 4e651fd9f7..84d9e89dd6 100644 --- a/modules/globebrowsing/src/tileprovider/tileproviderbyindex.cpp +++ b/modules/globebrowsing/src/tileprovider/tileproviderbyindex.cpp @@ -73,7 +73,7 @@ TileProviderByIndex::TileProviderByIndex(const ghoul::Dictionary& dictionary) { if (p.defaultProvider.hasValue("Type")) { std::string type = p.defaultProvider.value("Type"); typeID = ghoul::from_string(type); - + if (typeID == layergroupid::TypeID::Unknown) { throw ghoul::RuntimeError("Unknown layer type: " + type); } diff --git a/modules/iswa/util/iswamanager_lua.inl b/modules/iswa/util/iswamanager_lua.inl index 8e3f2c2ac7..8c39e11b6e 100644 --- a/modules/iswa/util/iswamanager_lua.inl +++ b/modules/iswa/util/iswamanager_lua.inl @@ -78,7 +78,7 @@ namespace { // Remove a Screen Space Cygnets. [[codegen::luawrap]] void removeScreenSpaceCygnet(int id) { using namespace openspace; - + std::map> cygnetInformation = IswaManager::ref().cygnetInformation(); if (cygnetInformation.find(id) == cygnetInformation.end()) { @@ -103,7 +103,7 @@ namespace { // Remove a group of Cygnets. [[codegen::luawrap]] void removeGroup(std::string name) { using namespace openspace; - + std::map> groups = IswaManager::ref().groups(); if (groups.find(name) != groups.end()) { diff --git a/modules/skybrowser/include/browser.h b/modules/skybrowser/include/browser.h index cb79d09428..97fb2853a5 100644 --- a/modules/skybrowser/include/browser.h +++ b/modules/skybrowser/include/browser.h @@ -73,7 +73,7 @@ public: void updateBrowserSize(); - glm::vec2 browserPixelDimensions() const; + glm::vec2 browserPixelDimensions() const; float browserRatio() const; void setCallbackDimensions(const std::function& function); @@ -83,7 +83,7 @@ protected: properties::TriggerProperty _reload; std::unique_ptr _texture; - + void executeJavascript(const std::string& script) const; private: diff --git a/modules/skybrowser/include/targetbrowserpair.h b/modules/skybrowser/include/targetbrowserpair.h index b0f467f7f5..5908df2438 100644 --- a/modules/skybrowser/include/targetbrowserpair.h +++ b/modules/skybrowser/include/targetbrowserpair.h @@ -46,7 +46,7 @@ public: // Target & Browser void initialize(); // Highlighting - void removeHighlight(const glm::ivec3& color); + void removeHighlight(const glm::ivec3& color); void highlight(const glm::ivec3& color); // Animation void startAnimation(glm::dvec3 coordsEnd, double fovEnd); @@ -91,11 +91,11 @@ public: std::string targetNodeId() const; std::string selectedId(); glm::vec2 size() const; - + SceneGraphNode* targetNode() const; ScreenSpaceSkyBrowser* browser() const; const std::deque& selectedImages() const; - + // WorldWide Telescope image handling void setImageOrder(int i, int order); void selectImage(const ImageData& image, int i); @@ -104,10 +104,8 @@ public: void setImageOpacity(int i, float opacity); void hideChromeInterface(bool shouldHide); - friend bool operator==(const TargetBrowserPair& lhs, - const TargetBrowserPair& rhs); - friend bool operator!=(const TargetBrowserPair& lhs, - const TargetBrowserPair& rhs); + friend bool operator==(const TargetBrowserPair& lhs, const TargetBrowserPair& rhs); + friend bool operator!=(const TargetBrowserPair& lhs, const TargetBrowserPair& rhs); private: void aimTargetGalactic(glm::dvec3 direction); @@ -127,7 +125,7 @@ private: // Dragging glm::dvec3 _startTargetPosition = glm::dvec3(0.0); - + glm::dvec2 _equatorialAim = glm::dvec2(0.0); glm::ivec3 _borderColor = glm::ivec3(255); glm::vec2 _dimensions = glm::vec2(0.5f); diff --git a/modules/skybrowser/include/utility.h b/modules/skybrowser/include/utility.h index 432793be4c..60d5bdcc24 100644 --- a/modules/skybrowser/include/utility.h +++ b/modules/skybrowser/include/utility.h @@ -30,6 +30,7 @@ #include namespace openspace::skybrowser { + // Constants constexpr const double ScreenSpaceZ = -2.1; constexpr const glm::dvec3 NorthPole = { 0.0, 0.0, 1.0 }; @@ -46,12 +47,14 @@ const glm::dmat3 conversionMatrix = glm::dmat3({ // Galactic coordinates are projected onto the celestial sphere // Equatorial coordinates are unit length // Conversion spherical <-> Cartesian + /** * Converts from Cartesian coordinates to spherical coordinates with unit length. * \param coords Cartesian coordinates * \return Spherical coordinates with unit length in degrees */ glm::dvec2 cartesianToSpherical(const glm::dvec3& coords); + /** * Converts from spherical coordinates to Cartesian coordinates with unit length. * \param coords Spherical coordinates in degrees @@ -61,16 +64,16 @@ glm::dvec3 sphericalToCartesian(const glm::dvec2& coords); // Conversion J2000 equatorial <-> galactic /** - * Converts from Cartesian galactic coordinates to Cartesian equatorial coordinates in epoch - * J2000 with unit length. + * Converts from Cartesian galactic coordinates to Cartesian equatorial coordinates in + * epoch J2000 with unit length. * \param coords Cartesian galactic coordinates * \return Cartesian equatorial coordinates in the epoch of J2000 with unit length */ glm::dvec3 galacticToEquatorial(const glm::dvec3& coords); + /** - * Converts from Cartesian equatorial coordinates to Cartesian galactic - * coordinates. The galactic coordinates vector has the length of the radius of the - * Celestial sphere. + * Converts from Cartesian equatorial coordinates to Cartesian galactic coordinates. The + * galactic coordinates vector has the length of the radius of the Celestial sphere. * \param coords Cartesian equatorial coordinates * \return Cartesian galactic coordinates placed on the Celestial sphere */ @@ -84,6 +87,7 @@ glm::dvec3 equatorialToGalactic(const glm::dvec3& coords); * \return Cartesian galactic coordinates placed on the Celestial sphere */ glm::dvec3 localCameraToScreenSpace3d(const glm::dvec3& coords); + /** * Converts from pixel coordinates to screenspace coordinates in 2D. * \param mouseCoordinate Pixel coordinate @@ -98,18 +102,21 @@ glm::vec2 pixelToScreenSpace2d(const glm::vec2& mouseCoordinate); * \return Local camera coordinates with unit length */ glm::dvec3 equatorialToLocalCamera(const glm::dvec3& coords); + /** * Converts from Cartesian galactic coordinates to local camera space with unit length. * \param coords Cartesian galactic coordinates * \return Cartesian local camera coordinates with unit length */ glm::dvec3 galacticToLocalCamera(const glm::dvec3& coords); + /** * Converts from Cartesian local camera coordinates to galactic coordinates. * \param coords Cartesian local camera coordinates * \return Cartesian galactic coordinates placed on the Celestial sphere */ glm::dvec3 localCameraToGalactic(const glm::dvec3& coords); + /** * Converts from local camera coordinates to Cartesian equatorial coordinates in the epoch * J2000. @@ -120,22 +127,24 @@ glm::dvec3 localCameraToEquatorial(const glm::dvec3& coords); // Camera roll and direction /** - * Returns the angle between the up direction of the OpenSpace camera and the equatorial + * Returns the angle between the up direction of the OpenSpace camera and the equatorial * North Pole direction. * \return Angle in degrees between the OpenSpace camera's up direction vector and the * equatorial North Pole direction. */ double targetRoll(const glm::dvec3& up, const glm::dvec3& forward); + /** * Returns the view direction of the OpenSpace camera in galactic coordinates. * \return View direction of the OpenSpace camera in Cartesian galactic coordinates. */ glm::dvec3 cameraDirectionGalactic(); + /** * Returns the view direction of the OpenSpace camera in equatorial coordinates in epoch * J2000. - * \return View direction of the OpenSpace camera in Cartesian equatorial coordinates in - * epoch J2000. + * \return View direction of the OpenSpace camera in Cartesian equatorial coordinates in + * epoch J2000. */ glm::dvec3 cameraDirectionEquatorial(); @@ -145,20 +154,22 @@ glm::dvec3 cameraDirectionEquatorial(); * \return The window ratio x / y */ float windowRatio(); + /** * Returns the vertical and horizontal field of view of the OpenSpace window. * \return The horizontal and vertical field of view in degrees. */ glm::dvec2 fovWindow(); + /** - * Returns true if the Cartesian equatorial coordinate is in the current view of the + * Returns true if the Cartesian equatorial coordinate is in the current view of the * camera. * \param equatorial Cartesian equatorial coordinates in epoch J2000 * \return True if the coordinates are in the camera's current field of view */ bool isCoordinateInView(const glm::dvec3& equatorial); -// Animation for target and camera +// Animation for target and camera /** * Returns the angle between two vectors. * \param start Cartesian vector @@ -166,6 +177,7 @@ bool isCoordinateInView(const glm::dvec3& equatorial); * \return Angle between two vectors in radians */ double angleBetweenVectors(const glm::dvec3& start, const glm::dvec3& end); + /** * Returns a 4x4 matrix for an incremental rotation of a vector. The matrix should be used * multiple times in order to animate. @@ -175,18 +187,19 @@ double angleBetweenVectors(const glm::dvec3& start, const glm::dvec3& end); * rotate * \return 4x4 matrix for incremental rotation animation of a vector */ -glm::dmat4 incrementalAnimationMatrix(const glm::dvec3& start, const glm::dvec3& end, +glm::dmat4 incrementalAnimationMatrix(const glm::dvec3& start, const glm::dvec3& end, double percentage); + /** - * Returns the size in meters that for example a plane would need to have in order to - * display a specified field of view. + * Returns the size in meters that for example a plane would need to have in order to + * display a specified field of view. * \param fov The set field of view - * \param worldPosition The galactic position of the plane + * \param worldPosition The galactic position of the plane * \return Field of view */ double sizeFromFov(double fov, glm::dvec3 worldPosition); -template +template class Animation { public: Animation(T start, T goal, double time) @@ -210,8 +223,7 @@ public: private: std::chrono::duration timeSpent() const { - using namespace std::chrono; - system_clock::time_point now = system_clock::now(); + std::chrono::system_clock::time_point now = std::chrono::system_clock::now(); std::chrono::duration timeSpent = now - _startTime; return timeSpent; } @@ -236,7 +248,7 @@ private: std::chrono::milliseconds _animationTime = std::chrono::milliseconds(2000); std::chrono::system_clock::time_point _startTime; }; - + } // namespace openspace::skybrowser #endif // __OPENSPACE_MODULE_SKYBROWSER___UTILITY___H__ diff --git a/modules/skybrowser/include/wwtcommunicator.h b/modules/skybrowser/include/wwtcommunicator.h index c0e76c3185..626e97b06b 100644 --- a/modules/skybrowser/include/wwtcommunicator.h +++ b/modules/skybrowser/include/wwtcommunicator.h @@ -73,7 +73,7 @@ public: void removeHighlight(const glm::ivec3& removal); void updateBorderColor(); void updateAim(); - + protected: void setIdInBrowser(const std::string& id); @@ -97,7 +97,7 @@ private: ghoul::Dictionary removeImageMessage(const std::string& id); ghoul::Dictionary setImageOpacityMessage(const std::string& id, double opacity); ghoul::Dictionary setLayerOrderMessage(const std::string& id, int version); - + bool _isSyncedWithWwt = false; bool _borderColorIsDirty = false; bool _equatorialAimIsDirty = false; diff --git a/modules/skybrowser/skybrowsermodule.cpp b/modules/skybrowser/skybrowsermodule.cpp index 225856ea9a..79059716c8 100644 --- a/modules/skybrowser/skybrowsermodule.cpp +++ b/modules/skybrowser/skybrowsermodule.cpp @@ -79,7 +79,7 @@ namespace { // [[codegen::verbatim(BrowserSpeedInfo.description)]] std::optional browserSpeed; }; - + #include "skybrowsermodule_codegen.cpp" } // namespace @@ -99,9 +99,9 @@ SkyBrowserModule::SkyBrowserModule() // Set callback functions global::callback::mouseButton->emplace(global::callback::mouseButton->begin(), [&](MouseButton button, MouseAction action, KeyModifier modifier) -> bool { - if (action == MouseAction::Press) { + if (action == MouseAction::Press) { _cameraRotation.stop(); - return false; + return false; } else { return false; @@ -121,7 +121,7 @@ SkyBrowserModule::SkyBrowserModule() // Camera moved into the solar system _isFading = true; _goal = Transparency::Transparent; - + float transparency = [](Transparency goal) { switch (goal) { case Transparency::Transparent: @@ -146,7 +146,7 @@ SkyBrowserModule::SkyBrowserModule() } if (_isCameraInSolarSystem) { std::for_each( - _targetsBrowsers.begin(), + _targetsBrowsers.begin(), _targetsBrowsers.end(), [&](const std::unique_ptr& pair) { pair->synchronizeAim(); @@ -157,14 +157,14 @@ SkyBrowserModule::SkyBrowserModule() if (_cameraRotation.isAnimating() && _allowCameraRotation) { incrementallyRotateCamera(); } - }); -} + }); +} void SkyBrowserModule::internalInitialize(const ghoul::Dictionary& dict) { const Parameters p = codegen::bake(dict); // Register ScreenSpaceRenderable - ghoul::TemplateFactory* fScreenSpaceRenderable = + ghoul::TemplateFactory* fScreenSpaceRenderable = FactoryManager::ref().factory(); ghoul_assert(fScreenSpaceRenderable, "ScreenSpaceRenderable factory was not created"); @@ -179,22 +179,24 @@ void SkyBrowserModule::internalInitialize(const ghoul::Dictionary& dict) { // Register ScreenSpaceSkyTarget fRenderable->registerClass("RenderableSkyTarget"); - + // Create data handler dynamically to avoid the linking error that // came up when including the include file in the module header file _dataHandler = std::make_unique(); } -void SkyBrowserModule::addTargetBrowserPair(const std::string& targetId, const std::string& browserId) { - if (!global::renderEngine->scene()) { - return; +void SkyBrowserModule::addTargetBrowserPair(const std::string& targetId, + const std::string& browserId) +{ + if (!global::renderEngine->scene()) { + return; } SceneGraphNode* target = global::renderEngine->scene()->sceneGraphNode(targetId); ScreenSpaceSkyBrowser* browser = dynamic_cast( global::renderEngine->screenSpaceRenderable(browserId) ); - + // Ensure pair has both target and browser if (browser && target) { _targetsBrowsers.push_back(std::make_unique(target, browser)); @@ -208,7 +210,7 @@ void SkyBrowserModule::removeTargetBrowserPair(const std::string& id) { } auto it = std::remove_if( - _targetsBrowsers.begin(), + _targetsBrowsers.begin(), _targetsBrowsers.end(), [&](const std::unique_ptr& pair) { return *found == *(pair.get()); @@ -225,7 +227,7 @@ void SkyBrowserModule::lookAtTarget(const std::string& id) { startRotatingCamera(pair->targetDirectionGalactic()); } } - + void SkyBrowserModule::setHoverCircle(SceneGraphNode* circle) { _hoverCircle = circle; } @@ -238,11 +240,11 @@ void SkyBrowserModule::moveHoverCircle(int i) { // Make circle visible _hoverCircle->renderable()->property("Enabled")->set(true); - // Set the exact target position - // Move it slightly outside of the celestial sphere so it doesn't overlap with + // Set the exact target position + // Move it slightly outside of the celestial sphere so it doesn't overlap with // the target glm::dvec3 pos = skybrowser::equatorialToGalactic(image.equatorialCartesian); - pos *= skybrowser::CelestialSphereRadius * 1.1; + pos *= skybrowser::CelestialSphereRadius * 1.1; // Uris for properties std::string id = _hoverCircle->identifier(); std::string positionUri = "Scene." + id + ".Translation.Position"; @@ -261,8 +263,9 @@ void SkyBrowserModule::disableHoverCircle() { } } -void SkyBrowserModule::loadImages(const std::string& root, - const std::filesystem::path& directory) { +void SkyBrowserModule::loadImages(const std::string& root, + const std::filesystem::path& directory) +{ _dataHandler->loadImages(root, directory); } @@ -284,7 +287,7 @@ int SkyBrowserModule::nPairs() { TargetBrowserPair* SkyBrowserModule::getPair(const std::string& id) { auto it = std::find_if( - _targetsBrowsers.begin(), + _targetsBrowsers.begin(), _targetsBrowsers.end(), [&](const std::unique_ptr& pair) { bool foundBrowser = pair->browserId() == id; @@ -308,18 +311,17 @@ void SkyBrowserModule::startRotatingCamera(glm::dvec3 endAnimation) { double time = angle / _cameraRotationSpeed; _cameraRotation = skybrowser::Animation(start, endAnimation, time); _cameraRotation.start(); -} +} void SkyBrowserModule::incrementallyRotateCamera() { - if(_cameraRotation.isAnimating()) { + if (_cameraRotation.isAnimating()) { glm::dmat4 rotMat = _cameraRotation.getRotationMatrix(); // Rotate global::navigationHandler->camera()->rotate(glm::quat_cast(rotMat)); } } -void SkyBrowserModule::incrementallyFadeBrowserTargets(Transparency goal) -{ +void SkyBrowserModule::incrementallyFadeBrowserTargets(Transparency goal) { bool isAllFinished = true; for (std::unique_ptr& pair : _targetsBrowsers) { if (pair->isEnabled()) { diff --git a/modules/skybrowser/skybrowsermodule.h b/modules/skybrowser/skybrowsermodule.h index 486b73c9be..b1f1d98a3b 100644 --- a/modules/skybrowser/skybrowsermodule.h +++ b/modules/skybrowser/skybrowsermodule.h @@ -72,7 +72,7 @@ public: void setSelectedBrowser(const std::string& id); void setSelectedObject(); // Manage mouse interactions void setHoverCircle(SceneGraphNode* circle); - + // Rotation, animation, placement void lookAtTarget(const std::string& id); void startRotatingCamera(glm::dvec3 endAnimation); // Pass in galactic coordinate @@ -81,19 +81,19 @@ public: void incrementallyAnimateTargets(); double targetAnimationSpeed() const; double browserAnimationSpeed() const; - + bool isCameraInSolarSystem() const; bool isSelectedPairFacingCamera(); bool isSelectedPairUsingRae(); - // Managing the target browser pairs + // Managing the target browser pairs void removeTargetBrowserPair(const std::string& browserId); void addTargetBrowserPair(const std::string& targetId, const std::string& browserId); // Hover circle void moveHoverCircle(int i); void disableHoverCircle(); - + // Image collection handling void loadImages(const std::string& root, const std::filesystem::path& directory); int nLoadedImages(); @@ -104,7 +104,7 @@ public: scripting::LuaLibrary luaLibrary() const override; //std::vector documentations() const override; -protected: +protected: void internalInitialize(const ghoul::Dictionary& dict) override; private: @@ -122,7 +122,7 @@ private: // Fading Transparency _goal = Transparency::Opaque; - + // Flags bool _isCameraInSolarSystem = true; // Visualization modes bool _isFading = false; @@ -135,12 +135,13 @@ private: glm::dvec3 _startTargetPosition; // Animation of rotation of camera to look at coordinate galactic coordinates - skybrowser::Animation _cameraRotation = + skybrowser::Animation _cameraRotation = skybrowser::Animation(glm::dvec3(0.0), glm::dvec3(0.0), 0.0); - + // Data handler for the image collections - std::unique_ptr _dataHandler; + std::unique_ptr _dataHandler; }; + } // namespace openspace #endif // __OPENSPACE_MODULE_SKYBROWSER___SKYBROWSERMODULE___H__ diff --git a/modules/skybrowser/skybrowsermodule_lua.inl b/modules/skybrowser/skybrowsermodule_lua.inl index 03d08c7e2e..01bb77c989 100644 --- a/modules/skybrowser/skybrowsermodule_lua.inl +++ b/modules/skybrowser/skybrowsermodule_lua.inl @@ -41,10 +41,10 @@ namespace { using namespace openspace; /** -* Takes an index to an image and selects that image in the currently -* selected sky browser. -* \param i Index of image -*/ + * Takes an index to an image and selects that image in the currently + * selected sky browser. + * \param i Index of image + */ [[codegen::luawrap]] void selectImage(int i) { // Load image SkyBrowserModule* module = global::moduleEngine->module(); @@ -75,41 +75,44 @@ namespace { } } } + /** -* Takes an identifier to a screen space renderable and adds it to the module. -* \param id Identifier -*/ + * Takes an identifier to a screen space renderable and adds it to the module. + * \param id Identifier + */ [[codegen::luawrap]] void setHoverCircle(std::string id) { SkyBrowserModule* module = global::moduleEngine->module(); SceneGraphNode* circle = global::renderEngine->scene()->sceneGraphNode(id); - module->setHoverCircle(circle); + module->setHoverCircle(circle); } + /** -* Moves the hover circle to the coordinate specified by the image index. -* \param i Index of image -*/ + * Moves the hover circle to the coordinate specified by the image index. + * \param i Index of image + */ [[codegen::luawrap]] void moveCircleToHoverImage(int i) { // Load image SkyBrowserModule* module = global::moduleEngine->module(); module->moveHoverCircle(i); } + /** -* Disables the hover circle, if there is one added to the sky browser -* module. -*/ + * Disables the hover circle, if there is one added to the sky browser module. + */ [[codegen::luawrap]] void disableHoverCircle() { SkyBrowserModule* module = global::moduleEngine->module(); module->disableHoverCircle(); } + /** -* Takes an identifier to a sky browser or a sky target, an image index -* and the order which it should have in the selected image list. The -* image is then changed to have this order. -* \param id Identifier -* \param i Image index -* \param order Order of image -*/ + * Takes an identifier to a sky browser or a sky target, an image index and the order + * which it should have in the selected image list. The image is then changed to have this + * order. + * \param id Identifier + * \param i Image index + * \param order Order of image + */ [[codegen::luawrap]] void setImageLayerOrder(std::string id, int i, int order) { SkyBrowserModule* module = global::moduleEngine->module(); @@ -118,17 +121,18 @@ namespace { module->getPair(id)->setImageOrder(i, order); } } + /** -* Takes an identifier to a sky browser or target and loads the WWT image -* collection to that browser. -* \param id Identifier -*/ + * Takes an identifier to a sky browser or target and loads the WWT image collection to + * that browser. + * \param id Identifier + */ [[codegen::luawrap]] void loadImagesToWWT(std::string id) { // Load images from url LINFO("Connection established to WorldWide Telescope application in " + id); LINFO("Loading image collections to " + id); - // Load the collections here because here we know that the browser can execute + // Load the collections here because here we know that the browser can execute // javascript std::string root = "https://raw.githubusercontent.com/WorldWideTelescope/" "wwt-web-client/master/assets/webclient-explore-root.wtml"; @@ -140,10 +144,11 @@ namespace { module->getPair(id)->loadImageCollection(root); } } + /** -* Starts the setup process of the sky browers. This function calls -* the lua function 'sendOutIdsToBrowsers' in all nodes in the cluster. -*/ + * Starts the setup process of the sky browers. This function calls the lua function + * 'sendOutIdsToBrowsers' in all nodes in the cluster. + */ [[codegen::luawrap]] void startSetup() { // This is called when the sky_browser website is connected to OpenSpace // Set all border colors to the border color in the master node @@ -154,10 +159,10 @@ namespace { std::string id = pair->browserId(); glm::ivec3 color = pair->borderColor(); std::string script = fmt::format( - "openspace.skybrowser.setBorderColor('{}', {}, {}, {})", - id, - color.r, - color.g, + "openspace.skybrowser.setBorderColor('{}', {}, {}, {})", + id, + color.r, + color.g, color.b ); global::scriptEngine->queueScript( @@ -166,7 +171,7 @@ namespace { ); } } - + // To ensure each node in a cluster calls its own instance of the wwt application // Do not send this script to the other nodes global::scriptEngine->queueScript( @@ -174,9 +179,10 @@ namespace { scripting::ScriptEngine::RemoteScripting::No ); } + /** -* Sends all sky browsers' identifiers to their respective CEF browser. -*/ + * Sends all sky browsers' identifiers to their respective CEF browser. + */ [[codegen::luawrap]] void sendOutIdsToBrowsers() { // This is called when the sky_browser website is connected to OpenSpace // Send out identifiers to the browsers @@ -186,13 +192,14 @@ namespace { pair->sendIdToBrowser(); } } + /** -* Takes an identifier to a sky browser and starts the initialization -* for that browser. That means that the browser starts to try to connect -* to the AAS WorldWide Telescope application by sending it messages. And -* that the target matches its appearance to its corresponding browser. -* \param id Identifier -*/ + * Takes an identifier to a sky browser and starts the initialization for that browser. + * That means that the browser starts to try to connect to the AAS WorldWide Telescope + * application by sending it messages. And that the target matches its appearance to its + * corresponding browser. + * \param id Identifier + */ [[codegen::luawrap]] void initializeBrowser(std::string id) { // Initialize browser with ID and its corresponding target LINFO("Initializing sky browser " + id); @@ -203,28 +210,30 @@ namespace { found->initialize(); } } + /** -* Takes the identifier of the sky target and a sky browser and adds them -* to the sky browser module. -* \param targetId Identifier of target (either SceneGraphNode or Renderable) -* \param browserId Identifier of browser -*/ -[[codegen::luawrap]] void addPairToSkyBrowserModule(std::string targetId, std::string browserId) { + * Takes the identifier of the sky target and a sky browser and adds them to the sky + * browser module. + * \param targetId Identifier of target (either SceneGraphNode or Renderable) + * \param browserId Identifier of browser + */ +[[codegen::luawrap]] void addPairToSkyBrowserModule(std::string targetId, + std::string browserId) +{ SkyBrowserModule* module = global::moduleEngine->module(); LINFO("Add browser " + browserId + " to sky browser module"); LINFO("Add target " + targetId + " to sky browser module"); - + module->addTargetBrowserPair(targetId, browserId); } -/** -* Returns a list of all the loaded AAS WorldWide Telescope images that -* have been loaded. Each image has a name, thumbnail url, equatorial -* spherical coordinates RA and Dec, equatorial Cartesian coordinates, -* if the image has celestial coordinates, credits text, credits url -* and the identifier of the image which is a unique number. -*/ +/** + * Returns a list of all the loaded AAS WorldWide Telescope images that have been loaded. + * Each image has a name, thumbnail url, equatorial spherical coordinates RA and Dec, + * equatorial Cartesian coordinates, if the image has celestial coordinates, credits text, + * credits url and the identifier of the image which is a unique number. + */ [[codegen::luawrap]] ghoul::Dictionary getListOfImages() { // Send image list to GUI SkyBrowserModule* module = global::moduleEngine->module(); @@ -238,14 +247,14 @@ namespace { module->loadImages(root, directory); } - + // Create Lua table to send to the GUI ghoul::Dictionary list; for (int i = 0; i < module->nLoadedImages(); i++) { const ImageData& img = module->getWwtDataHandler()->getImage(i); using namespace std::string_literals; - + // Push ("Key", value) ghoul::Dictionary image; image.setValue("name", img.name); @@ -260,23 +269,23 @@ namespace { image.setValue("creditsUrl", img.creditsUrl); image.setValue("identifier", std::to_string(i)); - // Index for current ImageData + // Index for current ImageData // Set table for the current ImageData list.setValue(std::to_string(i + 1), image); } return list; } + /** -* Returns a table of data regarding the current view and the sky browsers -* and targets. -* \return Dictionary of data regarding the current targets -*/ + * Returns a table of data regarding the current view and the sky browsers and targets. + * \return Dictionary of data regarding the current targets + */ [[codegen::luawrap]] ghoul::Dictionary getTargetData() { using namespace std::string_literals; SkyBrowserModule* module = global::moduleEngine->module(); ghoul::Dictionary data; - + // The current viewport data for OpenSpace ghoul::Dictionary openSpace; @@ -311,13 +320,13 @@ namespace { std::vector selectedImagesVector; const std::deque selectedImages = pair->selectedImages(); std::for_each( - selectedImages.begin(), - selectedImages.end(), + selectedImages.begin(), + selectedImages.end(), [&](int i) { selectedImagesVector.push_back(i); } ); - + glm::dvec2 spherical = pair->targetDirectionEquatorial(); glm::dvec3 cartesian = skybrowser::sphericalToCartesian(spherical); @@ -346,11 +355,12 @@ namespace { return data; } + /** -* Takes an identifier to a sky browser or sky target. Rotates the camera -* so that the target is placed in the center of the view. -* \param id -*/ + * Takes an identifier to a sky browser or sky target. Rotates the camera so that the + * target is placed in the center of the view. + * \param id + */ [[codegen::luawrap]] void adjustCamera(std::string id) { SkyBrowserModule* module = global::moduleEngine->module(); @@ -358,13 +368,14 @@ namespace { module->lookAtTarget(id); } } + /** -* Takes an identifier to a sky browser or sky target, an index to an image -* and a value for the opacity. -* \param id Identifier -* \param i Image index -* \param opacity -*/ + * Takes an identifier to a sky browser or sky target, an index to an image and a value + * for the opacity. + * \param id Identifier + * \param i Image index + * \param opacity + */ [[codegen::luawrap]] void setOpacityOfImageLayer(std::string id, int i, double opacity) { SkyBrowserModule* module = global::moduleEngine->module(); TargetBrowserPair* found = module->getPair(id); @@ -372,11 +383,12 @@ namespace { found->setImageOpacity(i, opacity); } } + /** -* Takes an identifier to a sky browser and animates its corresponding -* target to the center of the current view. -* \param id Identifier -*/ + * Takes an identifier to a sky browser and animates its corresponding target to the + * center of the current view. + * \param id Identifier + */ [[codegen::luawrap]] void centerTargetOnScreen(std::string id) { SkyBrowserModule* module = global::moduleEngine->module(); TargetBrowserPair* pair = module->getPair(id); @@ -384,18 +396,20 @@ namespace { pair->centerTargetOnScreen(); } } + /** -* Takes an identifier to a sky browser or target. Sets that sky browser -* currently selected. -* \param id -*/ + * Takes an identifier to a sky browser or target. Sets that sky browser currently + * selected. + * \param id + */ [[codegen::luawrap]] void setSelectedBrowser(std::string id) { SkyBrowserModule* module = global::moduleEngine->module(); module->setSelectedBrowser(id); } + /** -* Creates a sky browser and a target. -*/ + * Creates a sky browser and a target. + */ [[codegen::luawrap]] void createTargetBrowserPair() { SkyBrowserModule* module = global::moduleEngine->module(); @@ -476,10 +490,11 @@ namespace { scripting::ScriptEngine::RemoteScripting::No ); } + /** -* Takes in identifier to a sky browser or target and removes them. -* \param id Identifier -*/ + * Takes in identifier to a sky browser or target and removes them. + * \param id Identifier + */ [[codegen::luawrap]] void removeTargetBrowserPair(std::string id) { SkyBrowserModule* module = global::moduleEngine->module(); TargetBrowserPair* found = module->getPair(id); @@ -501,17 +516,18 @@ namespace { ); } } + /** -* Takes an identifier to a sky browser or sky target and the [x, y] -* starting position and the [x, y] translation vector. -* \param id Identifier -* \param startX Starting x-position -* \param startY Starting y-position -* \param transX Translation x-value -* \param transY Translation y-value -*/ -[[codegen::luawrap]] void translateScreenSpaceRenderable(std::string id, float startX, - float startY, float transX, + * Takes an identifier to a sky browser or sky target and the [x, y] starting position and + * the [x, y] translation vector. + * \param id Identifier + * \param startX Starting x-position + * \param startY Starting y-position + * \param transX Translation x-value + * \param transY Translation y-value + */ +[[codegen::luawrap]] void translateScreenSpaceRenderable(std::string id, float startX, + float startY, float transX, float transY) { ScreenSpaceRenderable* renderable = global::renderEngine->screenSpaceRenderable(id); @@ -519,30 +535,32 @@ namespace { renderable->translate(glm::vec2(transX, transY), glm::vec2(startX, startY)); } } + /** -* Takes an identifier to a sky browser or target and an index to an -* image. Removes that image from that sky browser. -* \param id Identifier -* \i Index of image -*/ + * Takes an identifier to a sky browser or target and an index to an image. Removes that + * image from that sky browser. + * \param id Identifier + * \i Index of image + */ [[codegen::luawrap]] void removeSelectedImageInBrowser(std::string id, int i) { // Get browser SkyBrowserModule* module = global::moduleEngine->module(); const ImageData& image = module->getWwtDataHandler()->getImage(i); - + TargetBrowserPair* pair = module->getPair(id); if (pair) { pair->removeSelectedImage(i); } } + /** -* Takes the identifier of a sky browser or a sky target and equatorial -* coordinates Right Ascension and Declination. The target will animate to -* this coordinate and the browser will display the coordinate. -* \param id Identifier -* \param ra Right Ascension -* \param dec Declination -*/ + * Takes the identifier of a sky browser or a sky target and equatorial coordinates Right + * Ascension and Declination. The target will animate to this coordinate and the browser + * will display the coordinate. + * \param id Identifier + * \param ra Right Ascension + * \param dec Declination + */ [[codegen::luawrap]] void setEquatorialAim(std::string id, double ra, double dec) { // Get module SkyBrowserModule* module = global::moduleEngine->module(); @@ -552,12 +570,13 @@ namespace { pair->setEquatorialAim(glm::dvec2(ra, dec)); } } + /** -* Takes an identifier to a sky browser or a sky target and a vertical -* field of view. Changes the field of view as specified by the input. -* \param id Identifier -* \param vfov Vertical Field of View -*/ + * Takes an identifier to a sky browser or a sky target and a vertical field of view. + * Changes the field of view as specified by the input. + * \param id Identifier + * \param vfov Vertical Field of View + */ [[codegen::luawrap]] void setVerticalFov(std::string id, float vfov) { // Get module SkyBrowserModule* module = global::moduleEngine->module(); @@ -569,11 +588,11 @@ namespace { } /** -* Takes an identifier to a sky browser or a sky target and a vertical -* field of view. Changes the field of view as specified by the input. -* \param id Identifier -* \param vfov Vertical Field of View -*/ + * Takes an identifier to a sky browser or a sky target and a vertical field of view. + * Changes the field of view as specified by the input. + * \param id Identifier + * \param vfov Vertical Field of View + */ [[codegen::luawrap]] void scrollOverBrowser(std::string id, float scroll) { // Get module SkyBrowserModule* module = global::moduleEngine->module(); @@ -583,14 +602,15 @@ namespace { pair->setVerticalFovWithScroll(scroll); } } + /** -* Takes an identifier to a sky browser or a sky target and a rgb color -* in the ranges [0, 255]. -* \param id Identifier -* \param r Red -* \param g Green -* \param b Blue -*/ + * Takes an identifier to a sky browser or a sky target and a rgb color in the ranges + * [0, 255]. + * \param id Identifier + * \param r Red + * \param g Green + * \param b Blue + */ [[codegen::luawrap]] void setBorderColor(std::string id, int r, int g, int b) { glm::ivec3 color{ r, g, b }; // Get module @@ -601,13 +621,14 @@ namespace { pair->setBorderColor(color); } } + /** -* Sets the screen space size of the sky browser to the numbers specified -* by the input [x, y]. -* \param id -* \param sizeX Size on the x-axis -* \param sizeY Size on the y-axis -*/ + * Sets the screen space size of the sky browser to the numbers specified by the input + * [x, y]. + * \param id + * \param sizeX Size on the x-axis + * \param sizeY Size on the y-axis + */ [[codegen::luawrap]] void setScreenSpaceSize(std::string id, float sizeX, float sizeY) { // Get module SkyBrowserModule* module = global::moduleEngine->module(); @@ -617,14 +638,17 @@ namespace { pair->setScreenSpaceSize(glm::vec2(sizeX, sizeY)); } } + /** -* Takes an identifier to a sky browser and adds a rendered copy to it. -* \param id Identifier -* \param raePosition Position in radius, azimuth, elevation coordinates -* \param nCopies Number of copies -*/ -[[codegen::luawrap]] void addRenderCopy(std::string id, - int nCopies = 1, glm::vec3 raePosition = glm::vec3(2.1f, 0.f, 0.f)) { + * Takes an identifier to a sky browser and adds a rendered copy to it. + * \param id Identifier + * \param raePosition Position in radius, azimuth, elevation coordinates + * \param nCopies Number of copies + */ +[[codegen::luawrap]] void addRenderCopy(std::string id, + int nCopies = 1, + glm::vec3 raePosition = glm::vec3(2.1f, 0.f, 0.f)) +{ // Get module SkyBrowserModule* module = global::moduleEngine->module(); @@ -633,11 +657,11 @@ namespace { pair->browser()->addRenderCopy(raePosition, nCopies); } } + /** -* Takes an identifier to a sky browser and removes the latest added -* rendered copy to it. -* \param id Identifier -*/ + * Takes an identifier to a sky browser and removes the latest added rendered copy to it. + * \param id Identifier + */ [[codegen::luawrap]] void removeRenderCopy(std::string id) { // Get module SkyBrowserModule* module = global::moduleEngine->module(); @@ -649,10 +673,9 @@ namespace { } /** -* Starts the finetuning of the target -* rendered copy to it. -* \param id Identifier to browser -*/ + * Starts the finetuning of the target rendered copy to it. + * \param id Identifier to browser + */ [[codegen::luawrap]] void startFinetuningTarget(std::string id) { // Get module @@ -664,12 +687,11 @@ namespace { } /** -* Finetunes the target depending on a mouse drag. -* rendered copy to it. -* \param id Identifier to browser -* \param start Start pixel position of drag -* \param end Current pixel position of mouse during drag -*/ + * Finetunes the target depending on a mouse drag. rendered copy to it. + * \param id Identifier to browser + * \param start Start pixel position of drag + * \param end Current pixel position of mouse during drag + */ [[codegen::luawrap]] void finetuneTargetPosition(std::string id, glm::vec2 start, glm::vec2 end) { // Get module @@ -687,4 +709,3 @@ namespace { #include "skybrowsermodule_lua_codegen.cpp" } // namespace - diff --git a/modules/skybrowser/src/browser.cpp b/modules/skybrowser/src/browser.cpp index 615f558ff4..020d46bb32 100644 --- a/modules/skybrowser/src/browser.cpp +++ b/modules/skybrowser/src/browser.cpp @@ -81,9 +81,14 @@ void Browser::RenderHandler::setTexture(GLuint t) { Browser::Browser(const ghoul::Dictionary& dictionary) : _url(UrlInfo) - , _browserPixeldimensions(DimensionsInfo, glm::vec2(500.f), glm::vec2(10.f), glm::vec2(3000.f)) + , _browserPixeldimensions( + DimensionsInfo, + glm::vec2(500.f), + glm::vec2(10.f), + glm::vec2(3000.f) + ) , _reload(ReloadInfo) -{ +{ if (dictionary.hasValue(UrlInfo.identifier)) { _url = dictionary.value(UrlInfo.identifier); } @@ -110,7 +115,7 @@ Browser::Browser(const ghoul::Dictionary& dictionary) WebBrowserModule* webBrowser = global::moduleEngine->module(); if (webBrowser) { webBrowser->addBrowser(_browserInstance.get()); - } + } } Browser::~Browser() {} @@ -120,7 +125,7 @@ bool Browser::initializeGL() { glm::uvec3(glm::ivec2(_browserPixeldimensions.value()), 1), GL_TEXTURE_2D ); - + _renderHandler->setTexture(*_texture); _browserInstance->initialize(); @@ -163,7 +168,7 @@ void Browser::update() { } if (_isDimensionsDirty) { if (_browserPixeldimensions.value().x > 0 && - _browserPixeldimensions.value().y > 0) + _browserPixeldimensions.value().y > 0) { _browserInstance->reshape(_browserPixeldimensions.value()); _isDimensionsDirty = false; @@ -173,7 +178,7 @@ void Browser::update() { if (_shouldReload) { _browserInstance->reloadBrowser(); _shouldReload = false; - } + } } bool Browser::isReady() const { diff --git a/modules/skybrowser/src/renderableskytarget.cpp b/modules/skybrowser/src/renderableskytarget.cpp index 86570065c4..f70cdb7c1d 100644 --- a/modules/skybrowser/src/renderableskytarget.cpp +++ b/modules/skybrowser/src/renderableskytarget.cpp @@ -54,8 +54,8 @@ namespace { "CrosshairSize", "Crosshair Size", "Determines the size of the crosshair. The size is determined in fov (degrees). " - }; - + }; + constexpr const openspace::properties::Property::PropertyInfo RectangleThresholdInfo = { "RectangleThreshold", diff --git a/modules/skybrowser/src/screenspaceskybrowser.cpp b/modules/skybrowser/src/screenspaceskybrowser.cpp index 488d2cf8a3..d2d346b4db 100644 --- a/modules/skybrowser/src/screenspaceskybrowser.cpp +++ b/modules/skybrowser/src/screenspaceskybrowser.cpp @@ -21,6 +21,7 @@ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ + #include #include @@ -30,10 +31,10 @@ #include #include #include -#include +#include #include #include -#include +#include #include namespace { @@ -58,7 +59,8 @@ namespace { "RenderOnlyOnMaster", "Render Only On Master", "Render the interactive sky browser only on the master node (this setting won't " - "affect the copies). This setting allows mouse interactions in a dome environment." + "affect the copies). This setting allows mouse interactions in a dome " + "environment." }; struct [[codegen::Dictionary(ScreenSpaceSkyBrowser)]] Parameters { @@ -77,7 +79,7 @@ glm::ivec3 randomBorderColor(glm::ivec3 highlight) { std::random_device rd; // Hue is in the unit degrees [0, 360] std::uniform_real_distribution hue(0.f, 360.f); - + // Value in saturation are in the unit percent [0,1] float value = 0.9f; // Brightness float saturation = 0.5f; @@ -88,7 +90,7 @@ glm::ivec3 randomBorderColor(glm::ivec3 highlight) { rgbColor = glm::ivec3(glm::rgbColor(hsvColor) * 255.f); highlighted = rgbColor + highlight; } while (highlighted.x < 255 && highlighted.y < 255 && highlighted.z < 255); - + return rgbColor; } @@ -115,7 +117,7 @@ namespace openspace { _textureQuality.onChange([this]() { _textureDimensionsIsDirty = true; - }); + }); // Ensure that the browser is placed at the z-coordinate of the screen space plane glm::vec2 screenPosition = _cartesianPosition.value(); @@ -124,7 +126,7 @@ namespace openspace { if (global::windowDelegate->isMaster()) { SkyBrowserModule* module = global::moduleEngine->module(); _borderColor = randomBorderColor(module->highlight()); - } + } _scale = _size.y * 0.5; } @@ -157,7 +159,7 @@ glm::dvec2 ScreenSpaceSkyBrowser::fineTuneVector(glm::dvec2 drag) { glm::dvec2 result = - convertToScreenSpace * resultRelativeOs; return result; } - + void ScreenSpaceSkyBrowser::setIdInBrowser() { WwtCommunicator::setIdInBrowser(identifier()); } @@ -166,9 +168,9 @@ void ScreenSpaceSkyBrowser::updateTextureResolution() { // Scale texture depending on the height of the window // Set texture size to the actual pixel size it covers glm::vec2 pixels = glm::vec2(global::windowDelegate->currentSubwindowSize()); - + // If the scale is 1, it covers half the window. Hence multiplication with 2 - float newResY = pixels.y * 2.f * _scale; + float newResY = pixels.y * 2.f * _scale; float ratio = _size.x / _size.y; float newResX = newResY * ratio; glm::vec2 newSize = glm::vec2(newResX , newResY) * _textureQuality.value(); @@ -188,7 +190,7 @@ void ScreenSpaceSkyBrowser::addRenderCopy(const glm::vec3& raePosition, int nCop info.identifier = id.c_str(); _renderCopies.push_back( std::make_unique( - info, + info, position, glm::vec3(0.f, -glm::pi(), -glm::half_pi()), glm::vec3(10.f, glm::pi(), glm::half_pi()) @@ -212,9 +214,9 @@ std::vector> ScreenSpaceSkyBrowser::renderCo _renderCopies.begin(), _renderCopies.end(), [&](const std::unique_ptr& copy) { - std::pair pair = { - copy.get()->identifier(), - glm::dvec3(copy.get()->value()) + std::pair pair = { + copy.get()->identifier(), + glm::dvec3(copy.get()->value()) }; vec.push_back(pair); }); @@ -230,7 +232,7 @@ void ScreenSpaceSkyBrowser::moveRenderCopy(int i, glm::vec3 raePosition) { bool ScreenSpaceSkyBrowser::deinitializeGL() { ScreenSpaceRenderable::deinitializeGL(); WwtCommunicator::deinitializeGL(); - + return true; } @@ -318,7 +320,7 @@ void ScreenSpaceSkyBrowser::setOpacity(float opacity) { _opacity = opacity; } -void ScreenSpaceSkyBrowser::setScreenSpaceSize(const glm::vec2& newSize) { +void ScreenSpaceSkyBrowser::setScreenSpaceSize(const glm::vec2& newSize) { _size = newSize; _sizeIsDirty = true; } diff --git a/modules/skybrowser/src/targetbrowserpair.cpp b/modules/skybrowser/src/targetbrowserpair.cpp index f0589918a1..d3b80db441 100644 --- a/modules/skybrowser/src/targetbrowserpair.cpp +++ b/modules/skybrowser/src/targetbrowserpair.cpp @@ -41,8 +41,8 @@ namespace openspace { -TargetBrowserPair::TargetBrowserPair(SceneGraphNode* targetNode, - ScreenSpaceSkyBrowser* browser) +TargetBrowserPair::TargetBrowserPair(SceneGraphNode* targetNode, + ScreenSpaceSkyBrowser* browser) : _targetNode(targetNode), _browser(browser) { ghoul_assert(browser != nullptr, "Sky browser is null pointer!"); @@ -75,7 +75,7 @@ void TargetBrowserPair::aimTargetGalactic(glm::dvec3 direction) { std::string id = _targetNode->identifier(); // Uris for properties std::string positionUri = "Scene." + id + ".Translation.Position"; - glm::dvec3 positionCelestial = glm::normalize(direction) * + glm::dvec3 positionCelestial = glm::normalize(direction) * skybrowser::CelestialSphereRadius; std::string setValue = "openspace.setPropertyValueSingle('"; @@ -89,15 +89,15 @@ void TargetBrowserPair::startFinetuningTarget() { _startTargetPosition = _targetNode->worldPosition(); } -// The fine tune of the target is a way to "drag and drop" the target with right click -// drag on the sky browser window. This is to be able to drag the target around when it +// The fine tune of the target is a way to "drag and drop" the target with right click +// drag on the sky browser window. This is to be able to drag the target around when it // has a very small field of view void TargetBrowserPair::fineTuneTarget(const glm::vec2& startMouse, const glm::vec2& translation) { glm::vec2 fineTune = _browser->fineTuneVector(translation); glm::vec2 endMouse = startMouse + fineTune; - + // Translation world glm::dvec3 startWorld = skybrowser::localCameraToGalactic( glm::vec3(startMouse, skybrowser::ScreenSpaceZ) @@ -290,7 +290,7 @@ void TargetBrowserPair::startAnimation(glm::dvec3 galacticCoords, double fovEnd) _fovAnimation = skybrowser::Animation(_browser->verticalFov(), fovEnd, fovTime); // Target animation - glm::dvec3 start = glm::normalize(_targetNode->worldPosition()) * + glm::dvec3 start = glm::normalize(_targetNode->worldPosition()) * skybrowser::CelestialSphereRadius; double targetSpeed = module->targetAnimationSpeed(); double angle = skybrowser::angleBetweenVectors(start, galacticCoords); @@ -354,7 +354,7 @@ void TargetBrowserPair::incrementallyFade() _targetRenderable->setOpacity(_fadeTarget.getNewValue()); } } - + bool operator==(const TargetBrowserPair& lhs, const TargetBrowserPair& rhs) { return lhs._targetNode == rhs._targetNode && lhs._browser == rhs._browser; } @@ -362,4 +362,5 @@ bool operator==(const TargetBrowserPair& lhs, const TargetBrowserPair& rhs) { bool operator!=(const TargetBrowserPair& lhs, const TargetBrowserPair& rhs) { return !(lhs == rhs); } + } // namespace openspace diff --git a/modules/skybrowser/src/utility.cpp b/modules/skybrowser/src/utility.cpp index b0f381e758..7223df89ba 100644 --- a/modules/skybrowser/src/utility.cpp +++ b/modules/skybrowser/src/utility.cpp @@ -61,15 +61,15 @@ glm::dvec2 cartesianToSpherical(const glm::dvec3& coord) { glm::dvec3 galacticToEquatorial(const glm::dvec3& coords) { return glm::transpose(conversionMatrix) * glm::normalize(coords); } - + glm::dvec3 equatorialToGalactic(const glm::dvec3& coords) { // On the unit sphere - glm::dvec3 rGalactic = conversionMatrix * glm::normalize(coords); + glm::dvec3 rGalactic = conversionMatrix * glm::normalize(coords); return rGalactic; } - + glm::dvec3 localCameraToScreenSpace3d(const glm::dvec3& coords) { - // Ensure that if the coord is behind the camera, + // Ensure that if the coord is behind the camera, // the converted coordinate will be there too double zCoord = coords.z > 0 ? -ScreenSpaceZ : ScreenSpaceZ; @@ -78,7 +78,7 @@ glm::dvec3 localCameraToScreenSpace3d(const glm::dvec3& coords) { double tanY = coords.y / coords.z; glm::dvec3 screenSpace = glm::dvec3(zCoord * tanX, zCoord * tanY, zCoord); - + return screenSpace; } @@ -95,16 +95,16 @@ glm::dvec3 localCameraToGalactic(const glm::dvec3& coords) { } glm::dvec3 localCameraToEquatorial(const glm::dvec3& coords) { - // Calculate the galactic coordinate of the target direction + // Calculate the galactic coordinate of the target direction // projected onto the celestial sphere glm::dvec3 camPos = global::navigationHandler->camera()->positionVec3(); glm::dvec3 galactic = camPos + skybrowser::localCameraToGalactic(coords); return skybrowser::galacticToEquatorial(galactic); } - + glm::dvec3 equatorialToLocalCamera(const glm::dvec3& coords) { - // Transform equatorial J2000 to galactic coord with infinite radius + // Transform equatorial J2000 to galactic coord with infinite radius glm::dvec3 galactic = equatorialToGalactic(coords) * CelestialSphereRadius; glm::dvec3 localCamera = galacticToLocalCamera(galactic); return localCamera; @@ -125,15 +125,15 @@ double targetRoll(const glm::dvec3& up, const glm::dvec3& forward) { glm::dvec3 crossUpNorth = glm::cross(upJ2000, NorthPole); double dotNorthUp = glm::dot(NorthPole, upJ2000); double dotCrossUpNorthForward = glm::dot(crossUpNorth, forwardJ2000); - + return glm::degrees(atan2(dotCrossUpNorthForward, dotNorthUp)); } glm::dvec3 cameraDirectionEquatorial() { // Get the view direction of the screen in cartesian J2000 coordinates return galacticToEquatorial(cameraDirectionGalactic()); -} - +} + glm::dvec3 cameraDirectionGalactic() { // Get the view direction of the screen in galactic coordinates glm::dvec3 camPos = global::navigationHandler->camera()->positionVec3(); @@ -154,7 +154,7 @@ bool isCoordinateInView(const glm::dvec3& equatorial) { glm::dvec3 coordsScreen = localCameraToScreenSpace3d(localCamera); double r = static_cast(windowRatio()); - bool isCoordInView = abs(coordsScreen.x) < r && abs(coordsScreen.y) < 1.f && + bool isCoordInView = abs(coordsScreen.x) < r && abs(coordsScreen.y) < 1.f && coordsScreen.z < 0; return isCoordInView; @@ -189,9 +189,9 @@ double angleBetweenVectors(const glm::dvec3& start, const glm::dvec3& end) { return std::acos(std::clamp(cos, -1.0, 1.0)); } -glm::dmat4 incrementalAnimationMatrix(const glm::dvec3& start, const glm::dvec3& end, - double percentage) -{ +glm::dmat4 incrementalAnimationMatrix(const glm::dvec3& start, const glm::dvec3& end, + double percentage) +{ double smallestAngle = angleBetweenVectors(start, end); // Calculate rotation this frame double rotationAngle = smallestAngle * percentage; @@ -204,7 +204,7 @@ double sizeFromFov(double fov, glm::dvec3 worldPosition) { // Calculate the size with trigonometry // /| - // /_| Adjacent is the horizontal line, opposite the vertical + // /_| Adjacent is the horizontal line, opposite the vertical // \ | Calculate for half the triangle first, then multiply with 2 // \| double adjacent = glm::length(worldPosition); @@ -262,8 +262,5 @@ glm::dvec3 Animation::getNewValue() { // Rotate direction return glm::dvec3(rotMat * glm::dvec4(_start, 1.0));; } + } // namespace openspace - - - - diff --git a/modules/skybrowser/src/wwtcommunicator.cpp b/modules/skybrowser/src/wwtcommunicator.cpp index 2aaef0e890..7f0edbd4b6 100644 --- a/modules/skybrowser/src/wwtcommunicator.cpp +++ b/modules/skybrowser/src/wwtcommunicator.cpp @@ -41,7 +41,7 @@ WwtCommunicator::WwtCommunicator(const ghoul::Dictionary& dictionary) WwtCommunicator::~WwtCommunicator() {} -void WwtCommunicator::displayImage(const std::string& url, int i) { +void WwtCommunicator::displayImage(const std::string& url, int i) { // Ensure there are no duplicates auto it = std::find(_selectedImages.begin(), _selectedImages.end(), i); if (it == _selectedImages.end()) { @@ -177,7 +177,7 @@ void WwtCommunicator::hideChromeInterface(bool shouldHide) { } void WwtCommunicator::update() { - Browser::update(); + Browser::update(); // Cap how messages are passed std::chrono::system_clock::time_point now = std::chrono::system_clock::now(); std::chrono::system_clock::duration timeSinceLastUpdate = now - _lastUpdateTime; @@ -225,9 +225,9 @@ double WwtCommunicator::verticalFov() const { } // WWT messages -ghoul::Dictionary WwtCommunicator::moveCameraMessage(const glm::dvec2& celestCoords, - double fov, double roll, - bool shouldMoveInstantly) +ghoul::Dictionary WwtCommunicator::moveCameraMessage(const glm::dvec2& celestCoords, + double fov, double roll, + bool shouldMoveInstantly) { using namespace std::string_literals; ghoul::Dictionary msg; @@ -261,8 +261,8 @@ ghoul::Dictionary WwtCommunicator::setForegroundMessage(const std::string& name) return msg; } -ghoul::Dictionary WwtCommunicator::addImageMessage(const std::string& id, - const std::string& url) +ghoul::Dictionary WwtCommunicator::addImageMessage(const std::string& id, + const std::string& url) { using namespace std::string_literals; ghoul::Dictionary msg; @@ -284,8 +284,8 @@ ghoul::Dictionary WwtCommunicator::removeImageMessage(const std::string& imageId return msg; } -ghoul::Dictionary WwtCommunicator::setImageOpacityMessage(const std::string& imageId, - double opacity) +ghoul::Dictionary WwtCommunicator::setImageOpacityMessage(const std::string& imageId, + double opacity) { using namespace std::string_literals; ghoul::Dictionary msg; @@ -297,7 +297,8 @@ ghoul::Dictionary WwtCommunicator::setImageOpacityMessage(const std::string& ima return msg; } -ghoul::Dictionary WwtCommunicator::setLayerOrderMessage(const std::string& id, int order) { +ghoul::Dictionary WwtCommunicator::setLayerOrderMessage(const std::string& id, int order) +{ // The lower the layer order, the more towards the back the image is placed // 0 is the background using namespace std::string_literals; @@ -311,4 +312,5 @@ ghoul::Dictionary WwtCommunicator::setLayerOrderMessage(const std::string& id, i return msg; } + } // namespace openspace diff --git a/modules/skybrowser/src/wwtdatahandler.cpp b/modules/skybrowser/src/wwtdatahandler.cpp index dc0281f462..01be6b9304 100644 --- a/modules/skybrowser/src/wwtdatahandler.cpp +++ b/modules/skybrowser/src/wwtdatahandler.cpp @@ -25,7 +25,7 @@ #include #include -#include +#include #include #include #include @@ -54,8 +54,8 @@ std::string attribute(const tinyxml2::XMLElement* element, const std::string& na bool downloadFile(const std::string& url, const std::filesystem::path& fileDestination) { // Get the web page and save to file HttpFileDownload wtmlRoot( - url, - fileDestination, + url, + fileDestination, HttpFileDownload::Overwrite::Yes ); wtmlRoot.start(std::chrono::milliseconds(10000)); @@ -70,8 +70,8 @@ std::string createSearchableString(std::string str) { // Remove white spaces and all special characters str.erase( std::remove_if( - str.begin(), - str.end(), + str.begin(), + str.end(), [](char c) { const bool isNumberOrLetter = std::isdigit(c) || std::isalpha(c); return !isNumberOrLetter; @@ -81,9 +81,9 @@ std::string createSearchableString(std::string str) { ); // Make the word lower case std::transform( - str.begin(), - str.end(), - str.begin(), + str.begin(), + str.end(), + str.begin(), [](char c) { return std::tolower(c); } @@ -91,8 +91,8 @@ std::string createSearchableString(std::string str) { return str; } -tinyxml2::XMLElement* getDirectChildNode(tinyxml2::XMLElement* node, - const std::string& name) +tinyxml2::XMLElement* getDirectChildNode(tinyxml2::XMLElement* node, + const std::string& name) { while (node && node->Name() != name) { node = node->FirstChildElement(); @@ -100,8 +100,8 @@ tinyxml2::XMLElement* getDirectChildNode(tinyxml2::XMLElement* node, return node; } -tinyxml2::XMLElement* getChildNode(tinyxml2::XMLElement* node, - const std::string& name) +tinyxml2::XMLElement* getChildNode(tinyxml2::XMLElement* node, + const std::string& name) { tinyxml2::XMLElement* child = node->FirstChildElement(); tinyxml2::XMLElement* imageSet = nullptr; @@ -119,7 +119,7 @@ tinyxml2::XMLElement* getChildNode(tinyxml2::XMLElement* node, } std::string getChildNodeContentFromImageSet(tinyxml2::XMLElement* imageSet, - const std::string& elementName) + const std::string& elementName) { // Find the thumbnail image url // The thumbnail is the last node so traverse backwards for speed @@ -137,7 +137,7 @@ std::string getUrlFromPlace(tinyxml2::XMLElement* place) { // If the place has a thumbnail url, return it if (hasAttribute(place, wwt::Thumbnail)) { return attribute(place, wwt::Thumbnail); - } + } // If the place doesn't have a thumbnail url data attribute, // Load the image set it stores instead @@ -149,10 +149,9 @@ std::string getUrlFromPlace(tinyxml2::XMLElement* place) { } // If it doesn't contain an ImageSet, it doesn't have an url return wwt::Undefined; -} - +} -void parseWtmlsFromDisc(std::vector& _xmls, +void parseWtmlsFromDisc(std::vector& _xmls, const std::filesystem::path& directory) { for (const auto& entry : std::filesystem::directory_iterator(directory)) { @@ -198,8 +197,8 @@ bool downloadAndParseWtmlFilesFromUrl(std::vector& _xmls XMLElement* element = root->FirstChildElement(wwt::Folder.c_str()); const bool folderExists = element; const bool folderContainNoUrls = folderExists && !hasAttribute(element, wwt::Url); - - // If the file contains no folders, or there are folders but without urls, + + // If the file contains no folders, or there are folders but without urls, // stop recursion if (!folderExists || folderContainNoUrls) { _xmls.push_back(doc); @@ -207,7 +206,7 @@ bool downloadAndParseWtmlFilesFromUrl(std::vector& _xmls return true; } - // Iterate through all the folders in the XML file + // Iterate through all the folders in the XML file while (element && std::string(element->Value()) == wwt::Folder) { // If folder contains urls, download and parse those urls if (hasAttribute(element, wwt::Url) && hasAttribute(element, wwt::Name)) { @@ -225,15 +224,15 @@ WwtDataHandler::~WwtDataHandler() { _xmls.clear(); } -void WwtDataHandler::loadImages(const std::string& root, - const std::filesystem::path& directory) +void WwtDataHandler::loadImages(const std::string& root, + const std::filesystem::path& directory) { // Collect the wtml files, either by reading from disc or from a url if (directoryExists(directory) && !std::filesystem::is_empty(directory)) { parseWtmlsFromDisc(_xmls, directory); LINFO("Loading images from directory"); - } - else { + } + else { downloadAndParseWtmlFilesFromUrl(_xmls, directory, root, "root"); LINFO("Loading images from url"); } @@ -247,8 +246,8 @@ void WwtDataHandler::loadImages(const std::string& root, // Sort images in alphabetical order std::sort( - _images.begin(), - _images.end(), + _images.begin(), + _images.end(), [](ImageData& a, ImageData& b) { // If the first character in the names are lowercase, make it upper case if (std::islower(a.name[0])) { @@ -274,7 +273,7 @@ const ImageData& WwtDataHandler::getImage(const int i) const { return _images[i]; } -void WwtDataHandler::saveImageFromNode(tinyxml2::XMLElement* node, +void WwtDataHandler::saveImageFromNode(tinyxml2::XMLElement* node, std::string collection) { // Collect the image set of the node. The structure is different depending on if @@ -286,18 +285,18 @@ void WwtDataHandler::saveImageFromNode(tinyxml2::XMLElement* node, if (type == wwt::ImageSet) { thumbnailUrl = getChildNodeContentFromImageSet(node, wwt::ThumbnailUrl); imageSet = node; - } + } else if (type == wwt::Place) { thumbnailUrl = getUrlFromPlace(node); imageSet = getChildNode(node, wwt::ImageSet); } - // Only collect the images that have a thumbnail image, that are sky images and + // Only collect the images that have a thumbnail image, that are sky images and // that have an image const bool hasThumbnailUrl = thumbnailUrl != wwt::Undefined; const bool isSkyImage = attribute(node, wwt::DataSetType) == wwt::Sky; const bool hasImageUrl = imageSet ? hasAttribute(imageSet, wwt::Url) : false; - + if (!(hasThumbnailUrl && isSkyImage && hasImageUrl)) { return; } @@ -310,7 +309,7 @@ void WwtDataHandler::saveImageFromNode(tinyxml2::XMLElement* node, imageSet, wwt::CreditsUrl ); - // Collect equatorial coordinates. All-sky surveys do not have this kind of + // Collect equatorial coordinates. All-sky surveys do not have this kind of // coordinate bool hasCelestialCoords = hasAttribute(node, wwt::RA) && hasAttribute(node, wwt::Dec); @@ -318,7 +317,7 @@ void WwtDataHandler::saveImageFromNode(tinyxml2::XMLElement* node, glm::dvec3 equatorialCartesian{ 0.0 }; if (hasCelestialCoords) { - // The RA from WWT is in the unit hours: + // The RA from WWT is in the unit hours: // to convert to degrees, multiply with 360 (deg) /24 (h) = 15 double ra = 15.0 * std::stod(attribute(node, wwt::RA)); double dec = std::stod(attribute(node, wwt::Dec)); @@ -350,7 +349,7 @@ void WwtDataHandler::saveImageFromNode(tinyxml2::XMLElement* node, _images.push_back(image); } -void WwtDataHandler::saveImagesFromXml(tinyxml2::XMLElement* root, +void WwtDataHandler::saveImagesFromXml(tinyxml2::XMLElement* root, std::string collection) { // Get direct child of node called Place @@ -361,7 +360,7 @@ void WwtDataHandler::saveImagesFromXml(tinyxml2::XMLElement* root, // If sibling is image, save it. while (node) { const std::string name = node->Name(); - // If node is an image or place, load it + // If node is an image or place, load it if (name == wwt::ImageSet || name == wwt::Place) { saveImageFromNode(node, collection); } diff --git a/modules/space/horizonsfile.cpp b/modules/space/horizonsfile.cpp index 912296f21b..03e5841274 100644 --- a/modules/space/horizonsfile.cpp +++ b/modules/space/horizonsfile.cpp @@ -696,7 +696,9 @@ std::vector HorizonsFile::parseMatches(const std::string& startPhra matches.push_back(line); break; } - else if (!altStartPhrase.empty() && line.find(altStartPhrase) != std::string::npos) { + else if (!altStartPhrase.empty() && + line.find(altStartPhrase) != std::string::npos) + { matches.push_back(line); break; } @@ -778,7 +780,9 @@ std::pair HorizonsFile::parseValidTimeRange( if (line.find(startPhrase) != std::string::npos) { break; } - else if (!altStartPhrase.empty() && line.find(altStartPhrase) != std::string::npos) { + else if (!altStartPhrase.empty() && + line.find(altStartPhrase) != std::string::npos) + { break; } diff --git a/modules/space/rendering/renderablefluxnodes.cpp b/modules/space/rendering/renderablefluxnodes.cpp index 74055f818f..05b904465e 100644 --- a/modules/space/rendering/renderablefluxnodes.cpp +++ b/modules/space/rendering/renderablefluxnodes.cpp @@ -41,20 +41,20 @@ #include #include #include -#include +#include #include #include #include namespace { constexpr const char* _loggerCat = "RenderableFluxNodes"; - + constexpr const std::array UniformNames = { - "streamColor", "nodeSize", "proximityNodesSize", + "streamColor", "nodeSize", "proximityNodesSize", "thresholdFlux", "colorMode", "filterLower", "filterUpper", "scalingMode", "colorTableRange", "domainLimZ", "nodeSkip", "nodeSkipDefault", "nodeSkipEarth", "nodeSkipMethod", "nodeSkipFluxThreshold", "nodeSkipRadiusThreshold", - "fluxColorAlpha", "earthPos", "distanceThreshold", "time", "maxNodeDistanceSize", + "fluxColorAlpha", "earthPos", "distanceThreshold", "time", "maxNodeDistanceSize", "usingCameraPerspective", "drawCircles", "drawHollow", "useGaussian", "perspectiveDistanceFactor", "minMaxNodeSize", "usingPulse", "usingGaussianPulse" @@ -149,7 +149,7 @@ namespace { "Skipping Nodes By Flux", "Select nodes to skip depending on flux value." }; - constexpr openspace::properties::Property::PropertyInfo + constexpr openspace::properties::Property::PropertyInfo RadiusNodeSkipThresholdInfo = { "SkippingNodesByRadius", "Skipping Nodes By Radius", @@ -170,7 +170,7 @@ namespace { "Max Node Distance Size", "The maximum size of the nodes at a certin distance." }; - constexpr openspace::properties::Property::PropertyInfo + constexpr openspace::properties::Property::PropertyInfo CameraPerspectiveEnabledInfo = { "CameraPerspectiveEnabled", "Use Camera perspective", @@ -193,7 +193,7 @@ namespace { "Using fragment shader to draw nodes with Gaussian filter for alpha value." }; - constexpr openspace::properties::Property::PropertyInfo + constexpr openspace::properties::Property::PropertyInfo PerspectiveDistanceFactorInfo = { "PerspectiveDistanceFactor", "Perspective Distance factor", @@ -283,12 +283,12 @@ RenderableFluxNodes::RenderableFluxNodes(const ghoul::Dictionary& dictionary) _colorTablePath = p.colorTablePath; _transferFunction = std::make_unique(_colorTablePath); _colorTableRange = p.colorTableRange.value_or(_colorTableRange); - + _binarySourceFolderPath = p.sourceFolder; if (std::filesystem::is_directory(_binarySourceFolderPath)) { // Extract all file paths from the provided folder namespace fs = std::filesystem; - for (const fs::directory_entry& e : + for (const fs::directory_entry& e : fs::directory_iterator(_binarySourceFolderPath)) { if (e.is_regular_file()) { @@ -303,8 +303,8 @@ RenderableFluxNodes::RenderableFluxNodes(const ghoul::Dictionary& dictionary) } } else { - LERROR(fmt::format("Source folder {} is not a valid directory", - _binarySourceFolderPath + LERROR(fmt::format( + "Source folder {} is not a valid directory", _binarySourceFolderPath )); } @@ -339,7 +339,7 @@ void RenderableFluxNodes::initialize() { loadNodeData(_goesEnergyBins.option().value); computeSequenceEndTime(); } - + void RenderableFluxNodes::initializeGL() { // Setup shader program _shaderProgram = global::renderEngine->buildRenderProgram( @@ -353,7 +353,7 @@ void RenderableFluxNodes::initializeGL() { _uniformCache.thresholdFlux = _shaderProgram->uniformLocation("thresholdFlux"); ghoul::opengl::updateUniformLocations(*_shaderProgram, _uniformCache, UniformNames); - + glGenVertexArrays(1, &_vertexArrayObject); glGenBuffers(1, &_vertexPositionBuffer); glGenBuffers(1, &_vertexColorBuffer); @@ -450,7 +450,7 @@ void RenderableFluxNodes::loadNodeData(int energybinOption) { void RenderableFluxNodes::setupProperties() { addProperty(_goesEnergyBins); - + addPropertySubOwner(_styleGroup); addPropertySubOwner(_streamGroup); addPropertySubOwner(_nodesAmountGroup); @@ -537,8 +537,8 @@ void RenderableFluxNodes::populateStartTimes() { break; } //if no file extention but word "time" in file name - else if (filePath.find("time") != std::string::npos && - filePath.find(".") == std::string::npos) + else if (filePath.find("time") != std::string::npos && + filePath.find(".") == std::string::npos) { break; } @@ -553,8 +553,8 @@ void RenderableFluxNodes::populateStartTimes() { if (timeFile.empty()) { LERROR( - "Could not find a metadata file with time steps, " - "such as a csv, dat, txt or no file extention with 'time' in filename" + "Could not find a metadata file with time steps, such as a csv, dat, txt or " + "no file extention with 'time' in filename" ); } @@ -566,7 +566,7 @@ void RenderableFluxNodes::populateStartTimes() { std::string line; // gets only first line to "remove" header - std::getline(tfs, line); + std::getline(tfs, line); std::stringstream s; s << line; @@ -640,7 +640,7 @@ void RenderableFluxNodes::render(const RenderData& data, RendererTasks&) { LWARNING("Could not find scene graph node 'Earth'"); } glm::vec3 earthPos = earthNode->worldPosition() * data.modelTransform.rotation; - + _shaderProgram->setUniform(_uniformCache.streamColor, _streamColor); _shaderProgram->setUniform(_uniformCache.nodeSize, _nodeSize); _shaderProgram->setUniform(_uniformCache.thresholdFlux, _thresholdFlux); @@ -659,7 +659,7 @@ void RenderableFluxNodes::render(const RenderData& data, RendererTasks&) { _fluxNodeskipThreshold ); _shaderProgram->setUniform( - _uniformCache.nodeSkipRadiusThreshold, + _uniformCache.nodeSkipRadiusThreshold, _radiusNodeSkipThreshold ); _shaderProgram->setUniform(_uniformCache.fluxColorAlpha, _fluxColorAlpha); @@ -672,11 +672,11 @@ void RenderableFluxNodes::render(const RenderData& data, RendererTasks&) { global::windowDelegate->applicationTime() ); _shaderProgram->setUniform( - _uniformCache.maxNodeDistanceSize, + _uniformCache.maxNodeDistanceSize, _maxNodeDistanceSize ); _shaderProgram->setUniform( - _uniformCache.usingCameraPerspective, + _uniformCache.usingCameraPerspective, _cameraPerspectiveEnabled ); _shaderProgram->setUniform(_uniformCache.drawCircles, _drawingCircles); @@ -684,20 +684,20 @@ void RenderableFluxNodes::render(const RenderData& data, RendererTasks&) { _shaderProgram->setUniform(_uniformCache.useGaussian, _gaussianAlphaFilter); _shaderProgram->setUniform( - _uniformCache.perspectiveDistanceFactor, + _uniformCache.perspectiveDistanceFactor, _perspectiveDistanceFactor ); _shaderProgram->setUniform(_uniformCache.minMaxNodeSize, _minMaxNodeSize); _shaderProgram->setUniform(_uniformCache.usingPulse, _pulseEnabled); _shaderProgram->setUniform( - _uniformCache.usingGaussianPulse, + _uniformCache.usingGaussianPulse, _gaussianPulseEnabled ); - + glm::vec3 cameraPos = data.camera.positionVec3() * data.modelTransform.rotation; - + _shaderProgram->setUniform("cameraPos", cameraPos); - + if (_colorMode == static_cast(ColorMethod::ByFluxValue)) { ghoul::opengl::TextureUnit textureUnit; textureUnit.activate(); @@ -776,8 +776,8 @@ void RenderableFluxNodes::update(const UpdateData& data) { if (_shaderProgram->isDirty()) { _shaderProgram->rebuildFromFile(); ghoul::opengl::updateUniformLocations( - *_shaderProgram, - _uniformCache, + *_shaderProgram, + _uniformCache, UniformNames ); } diff --git a/modules/space/rendering/renderablefluxnodes.h b/modules/space/rendering/renderablefluxnodes.h index 5e85dd24f2..56826dd5f5 100644 --- a/modules/space/rendering/renderablefluxnodes.h +++ b/modules/space/rendering/renderablefluxnodes.h @@ -22,6 +22,9 @@ * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ +#ifndef __OPENSPACE_MODULE_SPACE___RENDERABLEFLUXNODES___H__ +#define __OPENSPACE_MODULE_SPACE___RENDERABLEFLUXNODES___H__ + #include #include @@ -94,12 +97,12 @@ private: Illuminance = 3, }; - UniformCache(streamColor, nodeSize, proximityNodesSize, + UniformCache(streamColor, nodeSize, proximityNodesSize, thresholdFlux, colorMode, filterLower, filterUpper, scalingMode, colorTableRange, domainLimZ, nodeSkip, nodeSkipDefault, nodeSkipEarth, nodeSkipMethod, nodeSkipFluxThreshold, nodeSkipRadiusThreshold, fluxColorAlpha, earthPos, distanceThreshold, time, maxNodeDistanceSize, usingCameraPerspective, - drawCircles, drawHollow, useGaussian, perspectiveDistanceFactor, minMaxNodeSize, + drawCircles, drawHollow, useGaussian, perspectiveDistanceFactor, minMaxNodeSize, usingPulse, usingGaussianPulse) _uniformCache; std::filesystem::path _binarySourceFolderPath; @@ -195,7 +198,7 @@ private: properties::FloatProperty _fluxNodeskipThreshold; //The nodeskip for values within the range of the radius threshold to Earth properties::IntProperty _earthNodeSkip; - // The Radius threshold to decide the line between + // The Radius threshold to decide the line between //_pDefaultNodeSkip and _pAmountofNodes properties::FloatProperty _radiusNodeSkipThreshold; @@ -208,4 +211,7 @@ private: properties::BoolProperty _pulseEnabled; properties::BoolProperty _gaussianPulseEnabled; }; + } // namespace openspace + +#endif // __OPENSPACE_MODULE_SPACE___RENDERABLEFLUXNODES___H__ diff --git a/modules/space/translation/horizonstranslation.cpp b/modules/space/translation/horizonstranslation.cpp index 33eb02e47b..3422ca0cc1 100644 --- a/modules/space/translation/horizonstranslation.cpp +++ b/modules/space/translation/horizonstranslation.cpp @@ -233,12 +233,22 @@ bool HorizonsTranslation::loadCachedFile(const std::filesystem::path& file) { // Read all data in one go std::vector cacheKeyframes; cacheKeyframes.reserve(nKeyframes); - fileStream.read(reinterpret_cast(cacheKeyframes.data()), sizeof(CacheKeyframe) * nKeyframes); + fileStream.read( + reinterpret_cast(cacheKeyframes.data()), + sizeof(CacheKeyframe) * nKeyframes + ); // Extract the data from the cache Keyframe vector for (int i = 0; i < nKeyframes; ++i) { // Add keyframe in timeline - _timeline.addKeyframe(std::move(cacheKeyframes[i].timestamp), std::move(cacheKeyframes[i].position)); + _timeline.addKeyframe( + std::move(cacheKeyframes[i].timestamp), + { + cacheKeyframes[i].position[0], + cacheKeyframes[i].position[1], + cacheKeyframes[i].position[2] + } + ); } return fileStream.good(); @@ -271,7 +281,9 @@ void HorizonsTranslation::saveCachedFile(const std::filesystem::path& file) cons for (int i = 0; i < nKeyframes; i++) { CacheKeyframe cacheKeyframe; cacheKeyframe.timestamp = keyframes[i].timestamp; - cacheKeyframe.position = keyframes[i].data; + cacheKeyframe.position[0] = keyframes[i].data.x; + cacheKeyframe.position[1] = keyframes[i].data.y; + cacheKeyframe.position[2] = keyframes[i].data.z; cachKeyframes.push_back(cacheKeyframe); } @@ -279,8 +291,8 @@ void HorizonsTranslation::saveCachedFile(const std::filesystem::path& file) cons // Write of entire vector will only work if the data is plain old data type, // is_pod is depricated in C++20 and replaced with both is_trivial and // is_standard_layout - assert(std::is_trivial::value); - assert(std::is_standard_layout::value); + static_assert(std::is_trivial_v); + static_assert(std::is_standard_layout_v); // Write data fileStream.write( diff --git a/modules/space/translation/horizonstranslation.h b/modules/space/translation/horizonstranslation.h index ea769e987a..fca4ccdfd6 100644 --- a/modules/space/translation/horizonstranslation.h +++ b/modules/space/translation/horizonstranslation.h @@ -78,7 +78,7 @@ public: private: struct CacheKeyframe { double timestamp; - glm::dvec3 position; + std::array position; }; void loadData(); diff --git a/modules/spacecraftinstruments/rendering/renderableplaneprojection.cpp b/modules/spacecraftinstruments/rendering/renderableplaneprojection.cpp index 45b93d5141..3871f31c11 100644 --- a/modules/spacecraftinstruments/rendering/renderableplaneprojection.cpp +++ b/modules/spacecraftinstruments/rendering/renderableplaneprojection.cpp @@ -48,7 +48,7 @@ namespace { struct [[codegen::Dictionary(RenderablePlaneProjection)]] Parameters { // The SPICE name of the spacecraft from which the projection is performed std::string spacecraft; - + // The SPICE name of the instrument that is used to project the image onto this // RenderablePlaneProjection std::string instrument; diff --git a/modules/spout/screenspacespout.h b/modules/spout/screenspacespout.h index fd4a764894..967f667fc9 100644 --- a/modules/spout/screenspacespout.h +++ b/modules/spout/screenspacespout.h @@ -50,7 +50,7 @@ public: private: void bindTexture() override; void unbindTexture() override; - + spout::SpoutReceiverPropertyProxy _spoutReceiver; }; diff --git a/modules/sync/syncmodule_lua.inl b/modules/sync/syncmodule_lua.inl index 0feb0c8ed8..1fe260aad4 100644 --- a/modules/sync/syncmodule_lua.inl +++ b/modules/sync/syncmodule_lua.inl @@ -57,9 +57,11 @@ namespace { * unsynchronized, if the parameter is not provided, all versions for the specified http * resource are removed. */ -[[codegen::luawrap]] void unsyncResource(std::string identifier, std::optional version) { +[[codegen::luawrap]] void unsyncResource(std::string identifier, + std::optional version) +{ using namespace openspace; - + const SyncModule* module = global::moduleEngine->module(); std::filesystem::path sync = absPath(module->synchronizationRoot()); std::filesystem::path base = sync / "http" / identifier; diff --git a/modules/webbrowser/include/screenspacebrowser.h b/modules/webbrowser/include/screenspacebrowser.h index 417706e9a8..35a6462d5b 100644 --- a/modules/webbrowser/include/screenspacebrowser.h +++ b/modules/webbrowser/include/screenspacebrowser.h @@ -95,7 +95,7 @@ private: properties::TriggerProperty _reload; CefRefPtr _keyboardHandler; - + bool _isUrlDirty = false; bool _isDimensionsDirty = false; }; diff --git a/src/interaction/joystickcamerastates.cpp b/src/interaction/joystickcamerastates.cpp index 6b5c4a1ff3..0e8ab1b985 100644 --- a/src/interaction/joystickcamerastates.cpp +++ b/src/interaction/joystickcamerastates.cpp @@ -78,7 +78,10 @@ void JoystickCameraStates::updateStateFromInput( if ((t.joystickType == JoystickType::JoystickLike && std::abs(value) <= t.deadzone) || - (t.joystickType == JoystickType::TriggerLike && value <= -1.f + t.deadzone)) + ( + t.joystickType == JoystickType::TriggerLike && + value <= -1.f + t.deadzone + )) { continue; } @@ -150,8 +153,10 @@ void JoystickCameraStates::updateStateFromInput( localRotation.second.y += value; break; case AxisType::Property: - std::string script = fmt::format("openspace.setPropertyValue('{}', {});", - t.propertyUri, value); + std::string script = fmt::format( + "openspace.setPropertyValue('{}', {});", + t.propertyUri, value + ); global::scriptEngine->queueScript( script, @@ -173,7 +178,9 @@ void JoystickCameraStates::updateStateFromInput( if (active) { global::scriptEngine->queueScript( it->second.command, - scripting::ScriptEngine::RemoteScripting(it->second.synchronization) + scripting::ScriptEngine::RemoteScripting( + it->second.synchronization + ) ); } } diff --git a/src/interaction/joystickinputstate.cpp b/src/interaction/joystickinputstate.cpp index 6142b3d7c2..c372a8f4d1 100644 --- a/src/interaction/joystickinputstate.cpp +++ b/src/interaction/joystickinputstate.cpp @@ -49,8 +49,8 @@ float JoystickInputStates::axis(const std::string& joystickName, int axis) const } ); - // If multiple joysticks are connected, we might get values outside the -1,1 range by - // summing them up + // If multiple joysticks are connected, we might get values outside the -1,1 range + // by summing them up glm::clamp(res, -1.f, 1.f); return res; } @@ -69,7 +69,9 @@ float JoystickInputStates::axis(const std::string& joystickName, int axis) const return state->axes[axis]; } -bool JoystickInputStates::button(const std::string& joystickName, int button, JoystickAction action) const { +bool JoystickInputStates::button(const std::string& joystickName, int button, + JoystickAction action) const +{ ghoul_precondition(button >= 0, "button must be 0 or positive"); if (joystickName.empty()) { diff --git a/src/interaction/sessionrecording.cpp b/src/interaction/sessionrecording.cpp index d69f578a5f..5bd811854e 100644 --- a/src/interaction/sessionrecording.cpp +++ b/src/interaction/sessionrecording.cpp @@ -238,7 +238,7 @@ bool SessionRecording::startRecording(const std::string& filename) { _timestampRecordStarted = global::windowDelegate->applicationTime(); // Record the current delta time as the first property to save in the file. - // This needs to be saved as a baseline whether or not it changes during recording. + // This needs to be saved as a baseline whether or not it changes during recording _timestamps3RecordStarted = { _timestampRecordStarted, 0.0, diff --git a/src/interaction/sessionrecording_lua.inl b/src/interaction/sessionrecording_lua.inl index 66766e7e22..28f33a62ed 100644 --- a/src/interaction/sessionrecording_lua.inl +++ b/src/interaction/sessionrecording_lua.inl @@ -46,7 +46,7 @@ namespace { */ [[codegen::luawrap]] void startRecordingAscii(std::string recordFilePath) { using namespace openspace; - + if (recordFilePath.empty()) { throw ghoul::lua::LuaError("Filepath string is empty"); } @@ -74,7 +74,7 @@ namespace { bool loop = false) { using namespace openspace; - + if (file.empty()) { throw ghoul::lua::LuaError("Filepath string is empty"); } @@ -94,7 +94,7 @@ namespace { */ [[codegen::luawrap]] void startPlaybackApplicationTime(std::string file) { using namespace openspace; - + if (file.empty()) { throw ghoul::lua::LuaError("Filepath string is empty"); } @@ -115,7 +115,7 @@ namespace { */ [[codegen::luawrap]] void startPlaybackRecordedTime(std::string file, bool loop = false) { using namespace openspace; - + if (file.empty()) { throw ghoul::lua::LuaError("Filepath string is empty"); } @@ -134,7 +134,7 @@ namespace { */ [[codegen::luawrap]] void startPlaybackSimulationTime(std::string file) { using namespace openspace; - + if (file.empty()) { throw ghoul::lua::LuaError("Filepath string is empty"); } diff --git a/src/navigation/navigationhandler_lua.inl b/src/navigation/navigationhandler_lua.inl index 05b8dfcd6d..6b284837cf 100644 --- a/src/navigation/navigationhandler_lua.inl +++ b/src/navigation/navigationhandler_lua.inl @@ -274,7 +274,10 @@ joystickAxis(std::string joystickName, int axis) * currently bound to the button identified by the second argument. */ [[codegen::luawrap]] void clearJoystickButton(std::string joystickName, int button) { - openspace::global::navigationHandler->clearJoystickButtonCommand(joystickName, button); + openspace::global::navigationHandler->clearJoystickButtonCommand( + joystickName, + button + ); } /** diff --git a/src/navigation/path.cpp b/src/navigation/path.cpp index 9bbe6e3450..828b0bce14 100644 --- a/src/navigation/path.cpp +++ b/src/navigation/path.cpp @@ -440,7 +440,8 @@ SceneGraphNode* findNodeNearTarget(const SceneGraphNode* node) { bool isSame = (n->identifier() == node->identifier()); // If the nodes are in the very same position, they are probably representing // the same object - isSame |= glm::distance(n->worldPosition(), node->worldPosition()) < LengthEpsilon; + isSame |= + glm::distance(n->worldPosition(), node->worldPosition()) < LengthEpsilon; if (isSame) { continue; diff --git a/src/navigation/pathcurve.cpp b/src/navigation/pathcurve.cpp index 72aab1dc54..7c3ee120a3 100644 --- a/src/navigation/pathcurve.cpp +++ b/src/navigation/pathcurve.cpp @@ -113,7 +113,9 @@ void PathCurve::initializeParameterData() { double s = sStart + arcLength(uStart, u); // Identify samples that are indistinguishable due to precision limitations if (std::abs(s - _parameterSamples.back().s) < LengthEpsilon) { - throw InsufficientPrecisionError("Insufficient precision due to path length"); + throw InsufficientPrecisionError( + "Insufficient precision due to path length" + ); } _parameterSamples.push_back({ u, s }); } @@ -241,7 +243,7 @@ double PathCurve::arcLength(double lowerLimit, double upperLimit) const { glm::dvec3 PathCurve::interpolate(double u) const { const double max = _curveParameterSteps.back(); - ghoul_assert(u >= 0 && u <= max, "Interpolation variable must be in range [0,_nSegments]"); + ghoul_assert(u >= 0 && u <= max, "Interpolation variable must be in [0, _nSegments]"); if (u <= 0.0) { return _points[1]; diff --git a/src/navigation/pathcurves/avoidcollisioncurve.cpp b/src/navigation/pathcurves/avoidcollisioncurve.cpp index d5365e299f..9b6d1b1cb9 100644 --- a/src/navigation/pathcurves/avoidcollisioncurve.cpp +++ b/src/navigation/pathcurves/avoidcollisioncurve.cpp @@ -93,7 +93,9 @@ AvoidCollisionCurve::AvoidCollisionCurve(const Waypoint& start, const Waypoint& const double maxRadius = std::max(startNodeRadius, endNodeRadius); bool nodesAreDifferent = start.nodeIdentifier() != end.nodeIdentifier(); if (glm::length(startToEnd) > 0.5 * maxRadius && nodesAreDifferent) { - double cosAngleToTarget = glm::dot(normalize(-startViewDir), normalize(startToEnd)); + double cosAngleToTarget = glm::dot( + normalize(-startViewDir), normalize(startToEnd) + ); bool targetInOppositeDirection = cosAngleToTarget > 0.7; if (targetInOppositeDirection) { diff --git a/src/navigation/pathnavigator.cpp b/src/navigation/pathnavigator.cpp index 42005bf26a..a40a69021d 100644 --- a/src/navigation/pathnavigator.cpp +++ b/src/navigation/pathnavigator.cpp @@ -135,7 +135,10 @@ PathNavigator::PathNavigator() { static_cast(Path::Type::AvoidCollision), "AvoidCollision" }, { static_cast(Path::Type::ZoomOutOverview), "ZoomOutOverview" }, { static_cast(Path::Type::Linear), "Linear" }, - { static_cast(Path::Type::AvoidCollisionWithLookAt), "AvoidCollisionWithLookAt"} + { + static_cast(Path::Type::AvoidCollisionWithLookAt), + "AvoidCollisionWithLookAt" + } }); addProperty(_defaultPathType); diff --git a/src/navigation/pathnavigator_lua.inl b/src/navigation/pathnavigator_lua.inl index 9de9e62daa..ca1a44da8b 100644 --- a/src/navigation/pathnavigator_lua.inl +++ b/src/navigation/pathnavigator_lua.inl @@ -23,7 +23,7 @@ ****************************************************************************************/ namespace { - + // Returns true if a camera path is currently running, and false otherwise. [[codegen::luawrap]] bool isFlying() { using namespace openspace; diff --git a/src/rendering/renderable.cpp b/src/rendering/renderable.cpp index 262e923727..3f0d3a8646 100644 --- a/src/rendering/renderable.cpp +++ b/src/rendering/renderable.cpp @@ -125,7 +125,8 @@ ghoul::mm_unique_ptr Renderable::createFromDictionary( documentation::testSpecificationAndThrow(Documentation(), dictionary, "Renderable"); std::string renderableType = dictionary.value(KeyType); - ghoul::TemplateFactory* factory = FactoryManager::ref().factory(); + ghoul::TemplateFactory* factory = + FactoryManager::ref().factory(); ghoul_assert(factory, "Renderable factory did not exist"); Renderable* result = factory->create( renderableType, diff --git a/src/scene/asset.cpp b/src/scene/asset.cpp index fbfcff7fb8..30b9849623 100644 --- a/src/scene/asset.cpp +++ b/src/scene/asset.cpp @@ -209,7 +209,7 @@ void Asset::addIdentifier(std::string identifier) { if (!_metaInformation.has_value()) { _metaInformation = MetaInformation(); } - + _metaInformation->identifiers.push_back(std::move(identifier)); } diff --git a/src/util/spicemanager_lua.inl b/src/util/spicemanager_lua.inl index 4e7e01dd73..0405e3168c 100644 --- a/src/util/spicemanager_lua.inl +++ b/src/util/spicemanager_lua.inl @@ -54,7 +54,7 @@ namespace { * builtInFrames. Returns User loaded frames if !builtInFrames. */ [[codegen::luawrap]] std::map spiceBodies(bool includeBuiltIn) { - std::vector> bodies = + std::vector> bodies = openspace::SpiceManager::ref().spiceBodies(includeBuiltIn); std::map res; @@ -93,7 +93,7 @@ namespace { std::string frame, std::string date) { using namespace openspace; - + const double ephemerisTime = SpiceManager::ref().ephemerisTimeFromDate(date); glm::dvec3 position = SpiceManager::ref().targetPosition( target, diff --git a/src/util/time_lua.inl b/src/util/time_lua.inl index ae68fc9c6f..857dead156 100644 --- a/src/util/time_lua.inl +++ b/src/util/time_lua.inl @@ -81,7 +81,7 @@ namespace { std::optional interpolationDuration) { using namespace openspace; - + double interp = interpolationDuration.value_or( global::timeManager->defaultDeltaTimeInterpolationDuration() ); diff --git a/src/util/versionchecker.cpp b/src/util/versionchecker.cpp index 6d1af19e41..b50ed5a83e 100644 --- a/src/util/versionchecker.cpp +++ b/src/util/versionchecker.cpp @@ -44,7 +44,7 @@ VersionChecker::~VersionChecker() { void VersionChecker::requestLatestVersion(const std::string& url) { using GCC = ghoul::systemcapabilities::GeneralCapabilitiesComponent; std::string operatingSystem = SysCap.component().operatingSystemString(); - + // Need to escape non-http characters when passing the operating system in the url for (size_t i = 0; i < operatingSystem.size(); i++) { if (operatingSystem[i] == ' ') { diff --git a/support/coding/check_style_guide.py b/support/coding/check_style_guide.py index 13b56a079c..02beca004a 100644 --- a/support/coding/check_style_guide.py +++ b/support/coding/check_style_guide.py @@ -59,512 +59,511 @@ import os import re import sys -current_year = '2021' +current_year = '2022' is_strict_mode = False is_silent_mode = False def get_ifndef_symbol(lines): - index = [i for i,s in enumerate(lines) if '#ifndef ' in s] + index = [i for i,s in enumerate(lines) if '#ifndef ' in s] - if len(index) == 0: - return '', -1 + if len(index) == 0: + return '', -1 - result = re.search('#ifndef (.*)\n', lines[index[0]]) - return result.group(1), index[0] + result = re.search('#ifndef (.*)\n', lines[index[0]]) + return result.group(1), index[0] def get_define_symbol(lines): - index = [i for i,s in enumerate(lines) if '#define ' in s] + index = [i for i,s in enumerate(lines) if '#define ' in s] - if len(index) == 0: - return '', -1 + if len(index) == 0: + return '', -1 - result = re.search('#define (.*)\n', lines[index[0]]) - return result.group(1), index[0] + result = re.search('#define (.*)\n', lines[index[0]]) + return result.group(1), index[0] def check_correctness(lines): - ifndef_symbol, line_number = get_ifndef_symbol(lines) - if line_number == -1: - return 'No #ifndef in file' + ifndef_symbol, line_number = get_ifndef_symbol(lines) + if line_number == -1: + return 'No #ifndef in file' - define_symbol, line_number = get_define_symbol(lines) - if (line_number == -1): - return 'No #define in file' + define_symbol, line_number = get_define_symbol(lines) + if (line_number == -1): + return 'No #define in file' - index = [i for i,s in enumerate(lines) if '#endif' in s] - if len(index) == 0: - return 'No #endif in file' + index = [i for i,s in enumerate(lines) if '#endif' in s] + if len(index) == 0: + return 'No #endif in file' - return '' + return '' def check_equality(lines): - ifndef, _ = get_ifndef_symbol(lines) - define, _ = get_define_symbol(lines) + ifndef, _ = get_ifndef_symbol(lines) + define, _ = get_define_symbol(lines) - if ifndef == define: - return '' - else: - return ifndef + ' ' + define + if ifndef == define: + return '' + else: + return ifndef + ' ' + define def check_styling(lines): - ifndef_symbol, ifndef_line = get_ifndef_symbol(lines) - _, define_line = get_define_symbol(lines) + ifndef_symbol, ifndef_line = get_ifndef_symbol(lines) + _, define_line = get_define_symbol(lines) - if abs(ifndef_line - define_line) != 1: - return '#ifndef and #define lines are not subsequent' + if abs(ifndef_line - define_line) != 1: + return '#ifndef and #define lines are not subsequent' - if lines[ifndef_line - 1].strip() != '': - return 'Preceding line is not empty' + if lines[ifndef_line - 1].strip() != '': + return 'Preceding line is not empty' - if lines[define_line + 1].strip() != '': - return 'Following line is not empty' + if lines[define_line + 1].strip() != '': + return 'Following line is not empty' - if not lines[-1][-1] in ['\n', '\r']: - return 'Last line must end with a newline' + if not lines[-1][-1] in ['\n', '\r']: + return 'Last line must end with a newline' - for l in lines[2:23]: - if l[0] != ' ': - return 'Copyright header must be indented' + for l in lines[2:23]: + if l[0] != ' ': + return 'Copyright header must be indented' - if ifndef_symbol != ifndef_symbol.upper(): - return 'Include guard is not all upper case' + if ifndef_symbol != ifndef_symbol.upper(): + return 'Include guard is not all upper case' - return '' + return '' def check_styling_filename(lines, filename): - ifndef_symbol, _ = get_ifndef_symbol(lines) - file = os.path.splitext(os.path.basename(filename))[0].upper() + ifndef_symbol, _ = get_ifndef_symbol(lines) + file = os.path.splitext(os.path.basename(filename))[0].upper() - if not (file in ifndef_symbol or file in ifndef_symbol.replace('_', '')): - return 'Malformed include guard: ' + ifndef_symbol + ' || ' + file + if not (file in ifndef_symbol or file in ifndef_symbol.replace('_', '')): + return 'Malformed include guard: ' + ifndef_symbol + ' || ' + file def check_comment(lines): - ifndef_symbol, _ = get_ifndef_symbol(lines) + ifndef_symbol, _ = get_ifndef_symbol(lines) - index = [i for i,s in enumerate(lines) if '#endif' in s] - endif_line = lines[index[-1]].strip() + index = [i for i,s in enumerate(lines) if '#endif' in s] + endif_line = lines[index[-1]].strip() - if endif_line != '#endif // ' + ifndef_symbol: - print(ifndef_symbol) - print(endif_line) - return '#endif line is not correctly formatted' - else: - return '' + if endif_line != '#endif // ' + ifndef_symbol: + print(ifndef_symbol) + print(endif_line) + return '#endif line is not correctly formatted' + else: + return '' def check_copyright(lines): - index = [i for i,s in enumerate(lines[0:23]) if 'Copyright' in s] + index = [i for i,s in enumerate(lines[0:23]) if 'Copyright' in s] - if len(index) == 0: - return 'No copyright header found' + if len(index) == 0: + return 'No copyright header found' - beginning_string = ' * Copyright (c) 2012-' - # * Copyright (c) 2014- + beginning_string = ' * Copyright (c) 2012-' + # * Copyright (c) 2014- - year = lines[index[0]][len(beginning_string) : len(beginning_string) + 4] + year = lines[index[0]][len(beginning_string) : len(beginning_string) + 4] - if lines[index[0] + 1][0] != ' ': - return 'Copyright header is not correctly indented' + if lines[index[0] + 1][0] != ' ': + return 'Copyright header is not correctly indented' - if year != current_year: - return 'Out of date copyright notice ' + year + ' || ' + current_year + if year != current_year: + return 'Out of date copyright notice ' + year + ' || ' + current_year - return '' + return '' def check_byte_order_mark_character(lines): - c = lines[0][0] - if c == 'ï': - return 'File contains UTF-8 byte mark order character' + c = lines[0][0] + if c == 'ï': + return 'File contains UTF-8 byte mark order character' - return '' + return '' def check_naming_convention_component(lines, component): - ifndef_symbol, _ = get_ifndef_symbol(lines) + ifndef_symbol, _ = get_ifndef_symbol(lines) - component_part = ifndef_symbol[2:2 + len(component)] + component_part = ifndef_symbol[2:2 + len(component)] - if component_part != component.upper(): - return '#ifndef naming convention broken: ' + ifndef_symbol + ' || ' + component.upper() - else: - return '' + if component_part != component.upper(): + return '#ifndef naming convention broken: ' + ifndef_symbol + ' || ' + component.upper() + else: + return '' def check_naming_convention_subcomponent(lines, component, file): - ifndef_symbol, _ = get_ifndef_symbol(lines) + ifndef_symbol, _ = get_ifndef_symbol(lines) - if component == "ghoul" or component == "openspace_core": - return + if component == "ghoul" or component == "openspace_core": + return - subcomponent_part = ifndef_symbol[2 + len(component) + 1 :] - subcomponent_part = subcomponent_part[: subcomponent_part.find('_')] + subcomponent_part = ifndef_symbol[2 + len(component) + 1 :] + subcomponent_part = subcomponent_part[: subcomponent_part.find('_')] - path_part = file.split('/')[1] - second_path_part = file.split('/')[2] + path_part = file.split('/')[1] + second_path_part = file.split('/')[2] - - if (path_part.upper() != subcomponent_part) and (second_path_part.upper() != subcomponent_part): - return 'Subcomponent naming convention broken: ' + ifndef_symbol - else: - return '' + if (path_part.upper() != subcomponent_part) and (second_path_part.upper() != subcomponent_part): + return 'Subcomponent naming convention broken: ' + ifndef_symbol + else: + return '' def check_duplicates(lines, previousSymbols): - ifndef_symbol, _ = get_ifndef_symbol(lines) + ifndef_symbol, _ = get_ifndef_symbol(lines) - if ifndef_symbol in previousSymbols: - return False, ifndef_symbol - else: - return True, ifndef_symbol + if ifndef_symbol in previousSymbols: + return False, ifndef_symbol + else: + return True, ifndef_symbol def check_glm_header(lines, file): - Allowed_Files = [ - 'ghoul/glm.h' - ] + Allowed_Files = [ + 'ghoul/glm.h' + ] - for f in Allowed_Files: - if f in file.replace('\\', '/'): - return '' + for f in Allowed_Files: + if f in file.replace('\\', '/'): + return '' - index = [i for i,s in enumerate(lines) - if '#include ' in s or - '#include "glm/glm.hpp>"' in s] + index = [i for i,s in enumerate(lines) + if '#include ' in s or + '#include "glm/glm.hpp>"' in s] - if len(index) > 0: - return 'File used wrong glm include. Use "#include " instead' - else: - return '' + if len(index) > 0: + return 'File used wrong glm include. Use "#include " instead' + else: + return '' def check_core_dependency(lines, component): - if component != "openspace_core": - return '' + if component != "openspace_core": + return '' - index = [i for i,s in enumerate(lines) if 'OPENSPACE_MODULE_' in s] + index = [i for i,s in enumerate(lines) if 'OPENSPACE_MODULE_' in s] - if len(index) > 0: - return lines[index[0]][:-1] - else: - return '' + if len(index) > 0: + return lines[index[0]][:-1] + else: + return '' def check_using_namespace(lines): - index = [i for i,s in enumerate(lines) if "using namespace" in s.strip()] + index = [i for i,s in enumerate(lines) if "using namespace" in s.strip()] - if len(index) > 0: - return lines[index[0]] - else: - return '' + if len(index) > 0: + return lines[index[0]] + else: + return '' def check_end_of_line(lines): - if lines[-1][-1] != '\n': - return lines[-1][-1] - else: - return '' + if lines[-1][-1] != '\n': + return lines[-1][-1] + else: + return '' def check_empty_only_line(lines): - # Disable this check in non-strict mode - if not is_strict_mode: - return '' + # Disable this check in non-strict mode + if not is_strict_mode: + return '' - index = [i + 1 for i, s in enumerate(lines) if s.translate({ord(c): None for c in '\n\r'}).isspace()] - if len(index) > 0: - return index - else: - return '' + index = [i + 1 for i, s in enumerate(lines) if s.translate({ord(c): None for c in '\n\r'}).isspace()] + if len(index) > 0: + return index + else: + return '' def check_assert_usage(lines): - # _assert checks for both ghoul_assert and static_assert, which are both reasonable - index = [i + 1 for i,s in enumerate(lines) if ('assert(' in s and not '_assert(' in s) and s.strip()[0:2] != '//'] - if len(index) > 0: - return index - else: - return ''; + # _assert checks for both ghoul_assert and static_assert, which are both reasonable + index = [i + 1 for i,s in enumerate(lines) if ('assert(' in s and not '_assert(' in s) and s.strip()[0:2] != '//'] + if len(index) > 0: + return index + else: + return ''; def check_line_length(lines): - # Disable this check in non-strict mode - if not is_strict_mode: - return '' + # Disable this check in non-strict mode + if not is_strict_mode: + return '' - index = [i + 1 for i, s in enumerate(lines) if len(s) > (90 + 1)] - if len(index) > 0: - return index - else: - return '' + index = [i + 1 for i, s in enumerate(lines) if len(s) > (90 + 1)] + if len(index) > 0: + return index + else: + return '' def check_empty_character_at_end(lines): - # Disable this check in non-strict mode - if not is_strict_mode: - return '' + # Disable this check in non-strict mode + if not is_strict_mode: + return '' - index = [i + 1 for i, s in enumerate(lines) if len(s) > 1 and s[-2] == ' ' and not s.strip() == ''] - if len(index) > 0: - return index - else: - return '' + index = [i + 1 for i, s in enumerate(lines) if len(s) > 1 and s[-2] == ' ' and not s.strip() == ''] + if len(index) > 0: + return index + else: + return '' def check_for_tab(lines): - index = [i + 1 for i, s in enumerate(lines) if '\t' in s] - if len(index) > 0: - return index - else: - return '' + index = [i + 1 for i, s in enumerate(lines) if '\t' in s] + if len(index) > 0: + return index + else: + return '' previousSymbols = {} def check_header_file(file, component): - with open(file, 'r+', encoding="utf8") as f: - lines = f.readlines() + with open(file, 'r+', encoding="utf8") as f: + lines = f.readlines() - correctness = check_correctness(lines) - if correctness: - print(file, '\t', 'Correctness check failed', '\t', correctness) - return + correctness = check_correctness(lines) + if correctness: + print(file, '\t', 'Correctness check failed', '\t', correctness) + return - equality = check_equality(lines) - if equality: - print(file, '\t', 'Equality check failed', '\t', equality) - return + equality = check_equality(lines) + if equality: + print(file, '\t', 'Equality check failed', '\t', equality) + return - styling = check_styling(lines) - if styling: - print(file, '\t', 'Styling check failed', '\t', styling) - return + styling = check_styling(lines) + if styling: + print(file, '\t', 'Styling check failed', '\t', styling) + return - styling_filename = check_styling_filename(lines, file) - if styling_filename: - print(file, '\t', 'Filename styling check failed', '\t', styling_filename) - return + styling_filename = check_styling_filename(lines, file) + if styling_filename: + print(file, '\t', 'Filename styling check failed', '\t', styling_filename) + return - comment = check_comment(lines) - if comment: - print(file, '\t', 'Comment check failed', '\t', comment) - return + comment = check_comment(lines) + if comment: + print(file, '\t', 'Comment check failed', '\t', comment) + return - copyright = check_copyright(lines) - if copyright: - print(file, '\t', 'Copyright check failed', '\t', copyright) - return + copyright = check_copyright(lines) + if copyright: + print(file, '\t', 'Copyright check failed', '\t', copyright) + return - naming_component = check_naming_convention_component(lines, component) - if naming_component: - print(file, '\t', 'Naming convention broken', '\t', naming_component) - return + naming_component = check_naming_convention_component(lines, component) + if naming_component: + print(file, '\t', 'Naming convention broken', '\t', naming_component) + return - naming_subcomponent = check_naming_convention_subcomponent(lines, component, file) - if naming_subcomponent: - print(file, '\t', 'Naming convention broken', '\t', naming_subcomponent) - return + naming_subcomponent = check_naming_convention_subcomponent(lines, component, file) + if naming_subcomponent: + print(file, '\t', 'Naming convention broken', '\t', naming_subcomponent) + return - end_of_line = check_end_of_line(lines) - if end_of_line: - print(file, '\t', 'Last line does not contain a newline character: ', end_of_line) - return + end_of_line = check_end_of_line(lines) + if end_of_line: + print(file, '\t', 'Last line does not contain a newline character: ', end_of_line) + return - duplicates, symbol = check_duplicates(lines, previousSymbols) - if not duplicates: - print(file, '\t', 'Duplicate include guard', symbol, 'first in', previousSymbols[symbol]) - return - else: - previousSymbols[symbol] = file + duplicates, symbol = check_duplicates(lines, previousSymbols) + if not duplicates: + print(file, '\t', 'Duplicate include guard', symbol, 'first in', previousSymbols[symbol]) + return + else: + previousSymbols[symbol] = file - header = check_glm_header(lines, file) - if header: - print(file, '\t', 'Illegal glm header include', header) - return + header = check_glm_header(lines, file) + if header: + print(file, '\t', 'Illegal glm header include', header) + return - core_dependency = check_core_dependency(lines, component) - if core_dependency: - print(file, '\t', 'Wrong dependency (core depends on module)', core_dependency) + core_dependency = check_core_dependency(lines, component) + if core_dependency: + print(file, '\t', 'Wrong dependency (core depends on module)', core_dependency) - if (not 'ghoul_gl.h' in file): - # ghoul_gl.h is allowed to use 'using namespace' to pull the gl namespace in - using_namespaces = check_using_namespace(lines) - if using_namespaces: - print(file, '\t', 'Using namespace found in header file') + if (not 'ghoul_gl.h' in file): + # ghoul_gl.h is allowed to use 'using namespace' to pull the gl namespace in + using_namespaces = check_using_namespace(lines) + if using_namespaces: + print(file, '\t', 'Using namespace found in header file') - bom = check_byte_order_mark_character(lines) - if bom: - print(file, '\t', 'Byte order mark failed:', bom) + bom = check_byte_order_mark_character(lines) + if bom: + print(file, '\t', 'Byte order mark failed:', bom) - empty_only_lines = check_empty_only_line(lines) - if empty_only_lines: - print(file, '\t', 'Empty only line: ', empty_only_lines) + empty_only_lines = check_empty_only_line(lines) + if empty_only_lines: + print(file, '\t', 'Empty only line: ', empty_only_lines) - line_length = check_line_length(lines) - if line_length: - print(file, '\t', 'Line length exceeded: ', line_length) + line_length = check_line_length(lines) + if line_length: + print(file, '\t', 'Line length exceeded: ', line_length) - empty_character_at_end = check_empty_character_at_end(lines) - if empty_character_at_end: - print(file, '\t', 'Empty character at end: ', empty_character_at_end) + empty_character_at_end = check_empty_character_at_end(lines) + if empty_character_at_end: + print(file, '\t', 'Empty character at end: ', empty_character_at_end) - assert_usage = check_assert_usage(lines) - if assert_usage: - print(file, '\t', 'Wrong assert usage: ', assert_usage) + assert_usage = check_assert_usage(lines) + if assert_usage: + print(file, '\t', 'Wrong assert usage: ', assert_usage) - tabs = check_for_tab(lines) - if tabs: - print(file, '\t', 'TABs found: ', tabs) + tabs = check_for_tab(lines) + if tabs: + print(file, '\t', 'TABs found: ', tabs) def check_inline_file(file, component): - with open(file, 'r+', encoding="utf8") as f: - lines = f.readlines() + with open(file, 'r+', encoding="utf8") as f: + lines = f.readlines() - copyright = check_copyright(lines) - if copyright: - print(file, '\t', 'Copyright check failed', '\t', copyright) + copyright = check_copyright(lines) + if copyright: + print(file, '\t', 'Copyright check failed', '\t', copyright) - header = check_glm_header(lines, file) - if header: - print(file, '\t', 'Illegal glm header include', header) + header = check_glm_header(lines, file) + if header: + print(file, '\t', 'Illegal glm header include', header) - core_dependency = check_core_dependency(lines, component) - if core_dependency: - print(file, '\t', 'Wrong dependency (core depends on module)', core_dependency) + core_dependency = check_core_dependency(lines, component) + if core_dependency: + print(file, '\t', 'Wrong dependency (core depends on module)', core_dependency) - end_of_line = check_end_of_line(lines) - if end_of_line: - print(file, '\t', 'Last line does not contain a newline character: ', end_of_line) - return + end_of_line = check_end_of_line(lines) + if end_of_line: + print(file, '\t', 'Last line does not contain a newline character: ', end_of_line) + return - bom = check_byte_order_mark_character(lines) - if bom: - print(file, '\t', 'Byte order mark failed:', bom) + bom = check_byte_order_mark_character(lines) + if bom: + print(file, '\t', 'Byte order mark failed:', bom) - empty_only_lines = check_empty_only_line(lines) - if empty_only_lines: - print(file, '\t', 'Empty only line: ', empty_only_lines) + empty_only_lines = check_empty_only_line(lines) + if empty_only_lines: + print(file, '\t', 'Empty only line: ', empty_only_lines) - line_length = check_line_length(lines) - if line_length: - print(file, '\t', 'Line length exceeded: ', line_length) + line_length = check_line_length(lines) + if line_length: + print(file, '\t', 'Line length exceeded: ', line_length) - if (not '_doc.inl' in file): - # The _doc.inl files are allowed to use using namespace as they are inclued - # from the cpp files and thus don't leak it - using_namespaces = check_using_namespace(lines) - if using_namespaces: - print(file, '\t', 'Using namespace found in inline file') + if (not '_doc.inl' in file and not '_lua.inl'): + # The _doc.inl files are allowed to use using namespace as they are inclued + # from the cpp files and thus don't leak it + using_namespaces = check_using_namespace(lines) + if using_namespaces: + print(file, '\t', 'Using namespace found in inline file') - line_length = check_line_length(lines) - if line_length: - print(file, '\t', 'Line length exceeded: ', line_length) + line_length = check_line_length(lines) + if line_length: + print(file, '\t', 'Line length exceeded: ', line_length) - empty_character_at_end = check_empty_character_at_end(lines) - if empty_character_at_end: - print(file, '\t', 'Empty character at end: ', empty_character_at_end) + empty_character_at_end = check_empty_character_at_end(lines) + if empty_character_at_end: + print(file, '\t', 'Empty character at end: ', empty_character_at_end) - assert_usage = check_assert_usage(lines) - if assert_usage: - print(file, '\t', 'Wrong assert usage: ', assert_usage) + assert_usage = check_assert_usage(lines) + if assert_usage: + print(file, '\t', 'Wrong assert usage: ', assert_usage) - tabs = check_for_tab(lines) - if tabs: - print(file, '\t', 'TABs found: ', tabs) + tabs = check_for_tab(lines) + if tabs: + print(file, '\t', 'TABs found: ', tabs) def check_source_file(file, component): - with open(file, 'r+', encoding="utf8") as f: - lines = f.readlines() + with open(file, 'r+', encoding="utf8") as f: + lines = f.readlines() - header = check_glm_header(lines, file) - if header: - print(file, '\t', 'Illegal glm header include', header) + header = check_glm_header(lines, file) + if header: + print(file, '\t', 'Illegal glm header include', header) - core_dependency = check_core_dependency(lines, component) - if core_dependency: - print(file, '\t' 'Wrong core dependency', core_dependency) + core_dependency = check_core_dependency(lines, component) + if core_dependency: + print(file, '\t' 'Wrong core dependency', core_dependency) - end_of_line = check_end_of_line(lines) - if end_of_line: - print(file, '\t', 'Last line does not contain a newline character: ', end_of_line) - return + end_of_line = check_end_of_line(lines) + if end_of_line: + print(file, '\t', 'Last line does not contain a newline character: ', end_of_line) + return - copyright = check_copyright(lines) - if copyright: - print(file, '\t', 'Copyright check failed', '\t', copyright) + copyright = check_copyright(lines) + if copyright: + print(file, '\t', 'Copyright check failed', '\t', copyright) - bom = check_byte_order_mark_character(lines) - if bom: - print(file, '\t', 'Byte order mark failed:', bom) + bom = check_byte_order_mark_character(lines) + if bom: + print(file, '\t', 'Byte order mark failed:', bom) - empty_only_lines = check_empty_only_line(lines) - if empty_only_lines: - print(file, '\t', 'Empty only line: ', empty_only_lines) + empty_only_lines = check_empty_only_line(lines) + if empty_only_lines: + print(file, '\t', 'Empty only line: ', empty_only_lines) - line_length = check_line_length(lines) - if line_length: - print(file, '\t', 'Line length exceeded: ', line_length) + line_length = check_line_length(lines) + if line_length: + print(file, '\t', 'Line length exceeded: ', line_length) - empty_character_at_end = check_empty_character_at_end(lines) - if empty_character_at_end: - print(file, '\t', 'Empty character at end: ', empty_character_at_end) + empty_character_at_end = check_empty_character_at_end(lines) + if empty_character_at_end: + print(file, '\t', 'Empty character at end: ', empty_character_at_end) - assert_usage = check_assert_usage(lines) - if assert_usage: - print(file, '\t', 'Wrong assert usage: ', assert_usage) + assert_usage = check_assert_usage(lines) + if assert_usage: + print(file, '\t', 'Wrong assert usage: ', assert_usage) - tabs = check_for_tab(lines) - if tabs: - print(file, '\t', 'TABs found: ', tabs) + tabs = check_for_tab(lines) + if tabs: + print(file, '\t', 'TABs found: ', tabs) def check_files(positiveList, negativeList, component, check_function): - files = [] - for p in positiveList: - f = glob.glob(p, recursive=True) - f = [fi.replace('\\', '/') for fi in f] - files.extend(f) + files = [] + for p in positiveList: + f = glob.glob(p, recursive=True) + f = [fi.replace('\\', '/') for fi in f] + files.extend(f) - negativeFiles = [] - for n in negativeList: - f = glob.glob(n, recursive=True) - f = [fi.replace('\\', '/') for fi in f] - negativeFiles.extend(f) + negativeFiles = [] + for n in negativeList: + f = glob.glob(n, recursive=True) + f = [fi.replace('\\', '/') for fi in f] + negativeFiles.extend(f) - filtered_files = [f for f in files if f not in negativeFiles] + filtered_files = [f for f in files if f not in negativeFiles] - for file in filtered_files: - check_function(file, component) + for file in filtered_files: + check_function(file, component) @@ -572,116 +571,116 @@ def check_files(positiveList, negativeList, component, check_function): basePath = './' if len(sys.argv) > 1: - if sys.argv[1] != "strict": - basePath = sys.argv[1] + '/' + if sys.argv[1] != "strict": + basePath = sys.argv[1] + '/' for a in sys.argv: - if a == "strict": - is_strict_mode = True - if a == "silent": - is_silent_mode = True + if a == "strict": + is_strict_mode = True + if a == "silent": + is_silent_mode = True # Check header files if not is_silent_mode: - print("Checking header files") - print("=====================") + print("Checking header files") + print("=====================") check_files( - [basePath + 'include/**/*.h'], - [], - 'openspace_core', - check_header_file + [basePath + 'include/**/*.h'], + [], + 'openspace_core', + check_header_file ) check_files( - [basePath + 'apps/**/*.h'], - [basePath + 'apps/**/ext/**/*.h'], - 'openspace_app', - check_header_file + [basePath + 'apps/**/*.h'], + [basePath + 'apps/**/ext/**/*.h'], + 'openspace_app', + check_header_file ) check_files( - [basePath + 'modules/**/*.h'], - [ - basePath + 'modules/**/ext/**/*.h', - basePath + 'modules/**/node_modules/**/*.h', - basePath + 'modules/webbrowser/resource.h' - ], - 'openspace_module', - check_header_file + [basePath + 'modules/**/*.h'], + [ + basePath + 'modules/**/ext/**/*.h', + basePath + 'modules/**/node_modules/**/*.h', + basePath + 'modules/webbrowser/resource.h' + ], + 'openspace_module', + check_header_file ) check_files( - [basePath + 'ext/ghoul/include/**/*.h'], - [], - 'ghoul', - check_header_file + [basePath + 'ext/ghoul/include/**/*.h'], + [], + 'ghoul', + check_header_file ) if not is_silent_mode: - print("") - print("Checking inline files") - print("=====================") + print("") + print("Checking inline files") + print("=====================") check_files( - [basePath + 'include/**/*.inl'], - [], - 'openspace_core', - check_inline_file + [basePath + 'include/**/*.inl'], + [], + 'openspace_core', + check_inline_file ) check_files( - [basePath + 'src/**/*.inl'], - [], - 'openspace_core', - check_inline_file + [basePath + 'src/**/*.inl'], + [], + 'openspace_core', + check_inline_file ) check_files( - [basePath + 'apps/**/*.inl'], - [basePath + 'apps/**/ext/**/*.inl'], - 'openspace_app', - check_inline_file + [basePath + 'apps/**/*.inl'], + [basePath + 'apps/**/ext/**/*.inl'], + 'openspace_app', + check_inline_file ) check_files( - [basePath + 'modules/**/*.inl'], - [basePath + 'modules/**/ext/**/*.h'], - 'openspace_module', - check_inline_file + [basePath + 'modules/**/*.inl'], + [basePath + 'modules/**/ext/**/*.h'], + 'openspace_module', + check_inline_file ) check_files( - [basePath + 'ext/ghoul/include/**/*.inl'], - [], - 'ghoul', - check_inline_file + [basePath + 'ext/ghoul/include/**/*.inl'], + [], + 'ghoul', + check_inline_file ) if not is_silent_mode: - print("") - print("Checking source files") - print("=====================") + print("") + print("Checking source files") + print("=====================") check_files( - [basePath + 'src/**/*.cpp'], - [basePath + 'src/**/*_codegen.cpp'], - 'openspace_core', - check_source_file + [basePath + 'src/**/*.cpp'], + [basePath + 'src/**/*_codegen.cpp'], + 'openspace_core', + check_source_file ) check_files( - [basePath + 'apps/**/*.cpp'], - [basePath + 'apps/**/ext/**/*.cpp', basePath + 'apps/**/*_codegen.cpp'], - 'openspace_app', - check_source_file + [basePath + 'apps/**/*.cpp'], + [basePath + 'apps/**/ext/**/*.cpp', basePath + 'apps/**/*_codegen.cpp'], + 'openspace_app', + check_source_file ) check_files( - [basePath + 'modules/**/*.cpp'], - [ - basePath + 'modules/**/ext/**/*.cpp', - basePath + 'modules/**/node_modules/**/*.cpp', - basePath + 'modules/**/*_codegen.cpp' - ], - 'openspace_module', - check_source_file + [basePath + 'modules/**/*.cpp'], + [ + basePath + 'modules/**/ext/**/*.cpp', + basePath + 'modules/**/node_modules/**/*.cpp', + basePath + 'modules/**/*_codegen.cpp' + ], + 'openspace_module', + check_source_file ) check_files( - [basePath + 'ext/ghoul/src/**/*.cpp'], - [], - 'ghoul', - check_source_file + [basePath + 'ext/ghoul/src/**/*.cpp'], + [], + 'ghoul', + check_source_file )