diff --git a/.hgtags b/.hgtags index 78b62c927..ab29fd263 100644 --- a/.hgtags +++ b/.hgtags @@ -1,3 +1,4 @@ +5603634972d94323c11198c54fbaa390c6aee59e stable-2020-06 caab74eb7c5188e368c293c1b32fb516b0a3b95e simdis10.0_SR7 caab74eb7c5188e368c293c1b32fb516b0a3b95e simdissdk-1.12 14518462105ba7e265e3e6bb970c127656302861 stable-2019-12 diff --git a/CMakeImport/ImportQt5.cmake b/CMakeImport/ImportQt5.cmake index def04d925..01f55fb10 100644 --- a/CMakeImport/ImportQt5.cmake +++ b/CMakeImport/ImportQt5.cmake @@ -136,7 +136,8 @@ macro(install_qtplugins dir) DESTINATION ${INSTALLSETTINGS_RUNTIME_DIR}/ OPTIONAL COMPONENT ThirdPartyLibs - FILES_MATCHING PATTERN *.dll) + FILES_MATCHING PATTERN *.dll + PATTERN *d.dll EXCLUDE) else() # Note that Qt requires the Linux shared objects in the executable's subdirectory (e.g. bin) INSTALL(DIRECTORY ${_qt5Gui_install_prefix}/plugins/${dir} diff --git a/CMakeModules/HelperFunctions.cmake b/CMakeModules/HelperFunctions.cmake index 523fe1464..78f03fa0b 100644 --- a/CMakeModules/HelperFunctions.cmake +++ b/CMakeModules/HelperFunctions.cmake @@ -432,6 +432,23 @@ function(vsi_install_target TARGET COMPONENT) endif() endfunction() +# vsi_write_basic_package_config_file(TARGET DEPS) +# +# Given a library TARGET that is being exported, generates a Config.cmake +# file in the build directory for use in vsi_install_export(). This is particularly +# useful in cases where the dependencies of the target are variable and cannot +# be easily hardcoded into a Config.cmake. +function(vsi_write_basic_package_config_file TARGET DEPS) + file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/${TARGET}Config.cmake" + "include(CMakeFindDependencyMacro)\n" + "set(DEPS \"${DEPS}\")\n" + "foreach(DEP IN LISTS DEPS)\n" + " find_dependency(\${DEP})\n" + "endforeach()\n" + "include(\"\${CMAKE_CURRENT_LIST_DIR}/${TARGET}Targets.cmake\")\n" + ) +endfunction() + # vsi_install_export(TARGET VERSION COMPATIBILITY) # # Given a library TARGET that is being exported, installs a generated Targets.cmake diff --git a/Examples/ASIViewer/ASIViewer.cpp b/Examples/ASIViewer/ASIViewer.cpp index 70c3c1de0..d2bf829f6 100644 --- a/Examples/ASIViewer/ASIViewer.cpp +++ b/Examples/ASIViewer/ASIViewer.cpp @@ -162,7 +162,7 @@ struct AppData osgEarth::DateTime refDateTime_; explicit AppData(simData::DataStore *ds, simVis::View* view) - : timeSlider_(NULL), + : timeSlider_(nullptr), ds_(ds), view_(view), startTime_(0.0), diff --git a/Examples/AngleTest/AngleTestExample.cpp b/Examples/AngleTest/AngleTestExample.cpp index c8b9da38c..1696718a8 100644 --- a/Examples/AngleTest/AngleTestExample.cpp +++ b/Examples/AngleTest/AngleTestExample.cpp @@ -198,7 +198,7 @@ int main(int argc, char **argv) viewer->getMainView()->addOverlayControl(createHelp()); /// Prime it - SetUpdate().onValueChanged(NULL, 0.0); + SetUpdate().onValueChanged(nullptr, 0.0); /// add some stock OSG handlers viewer->installDebugHandlers(); diff --git a/Examples/AnimatedLine/ExampleAnimatedLine.cpp b/Examples/AnimatedLine/ExampleAnimatedLine.cpp index 227b6f6cf..7aebd4c3a 100644 --- a/Examples/AnimatedLine/ExampleAnimatedLine.cpp +++ b/Examples/AnimatedLine/ExampleAnimatedLine.cpp @@ -326,7 +326,7 @@ int main(int argc, char **argv) // Make the lines: addAnimatedLines(node1.get(), node2.get(), scene->getScenario(), scene->getMapNode()); addAnimatedLines(node3.get(), node4.get(), scene->getScenario(), scene->getMapNode()); - addAnimatedLines(NULL, NULL, scene->getScenario(), scene->getMapNode()); + addAnimatedLines(nullptr, nullptr, scene->getScenario(), scene->getMapNode()); // tick the sim dataStore.update(0); diff --git a/Examples/AntennaPattern/ExampleAntennaPattern.cpp b/Examples/AntennaPattern/ExampleAntennaPattern.cpp index 337b11f9a..663ce6c62 100644 --- a/Examples/AntennaPattern/ExampleAntennaPattern.cpp +++ b/Examples/AntennaPattern/ExampleAntennaPattern.cpp @@ -70,23 +70,23 @@ struct AppData AppData() : platformId(0), beamId(0), - algorithm(NULL), - algorithmLabel(NULL), - polarity(NULL), - polarityLabel(NULL), - sensitivity(NULL), - frequency(NULL), - gain(NULL), - fov(NULL), - detail(NULL), - power(NULL), - width(NULL), - height(NULL), - scale(NULL), - weighting(NULL), - colorscale(NULL), - blending(NULL), - lighting(NULL) + algorithm(nullptr), + algorithmLabel(nullptr), + polarity(nullptr), + polarityLabel(nullptr), + sensitivity(nullptr), + frequency(nullptr), + gain(nullptr), + fov(nullptr), + detail(nullptr), + power(nullptr), + width(nullptr), + height(nullptr), + scale(nullptr), + weighting(nullptr), + colorscale(nullptr), + blending(nullptr), + lighting(nullptr) { algs.push_back(std::make_pair(simData::BeamPrefs_AntennaPattern_Algorithm_PEDESTAL, "PEDESTAL")); algs.push_back(std::make_pair(simData::BeamPrefs_AntennaPattern_Algorithm_GAUSS, "GAUSS")); diff --git a/Examples/ArticulatedModel/ExampleArticulatedModel.cpp b/Examples/ArticulatedModel/ExampleArticulatedModel.cpp index fa359c75e..895a9a21a 100644 --- a/Examples/ArticulatedModel/ExampleArticulatedModel.cpp +++ b/Examples/ArticulatedModel/ExampleArticulatedModel.cpp @@ -125,7 +125,7 @@ class FindNodeByName : public osg::NodeVisitor explicit FindNodeByName(const std::string& name) : osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN), searchFor_(name), - node_(NULL) + node_(nullptr) { } @@ -137,7 +137,7 @@ class FindNodeByName : public osg::NodeVisitor traverse(node); } - /** Retrieves the node from visitation, possibly NULL */ + /** Retrieves the node from visitation, possibly nullptr */ osg::Node* node() const { return node_.get(); @@ -155,8 +155,8 @@ class TankNode { public: TankNode() - : gun_(NULL), - turret_(NULL) + : gun_(nullptr), + turret_(nullptr) { } virtual ~TankNode() @@ -187,48 +187,48 @@ class TankNode void setGunPitch(double pitchDeg) { - if (gun_ != NULL) + if (gun_ != nullptr) gun_->updateCurrentHPR(osg::Vec3f(0.0f, simCore::DEG2RAD * pitchDeg, 0.0f)); } float gunPitch() const { - if (gun_ != NULL) + if (gun_ != nullptr) return simCore::RAD2DEG * gun_->getCurrentHPR().y(); return 0.0f; } float gunMinimumPitch() const { - if (gun_ != NULL) + if (gun_ != nullptr) return simCore::RAD2DEG * gun_->getMinHPR().y(); return 0.0f; } float gunMaximumPitch() const { - if (gun_ != NULL) + if (gun_ != nullptr) return simCore::RAD2DEG * gun_->getMaxHPR().y(); return 0.0f; } void setTurretYaw(double yawDeg) { - if (turret_ != NULL) + if (turret_ != nullptr) turret_->updateCurrentHPR(osg::Vec3f(simCore::DEG2RAD * yawDeg, 0.0f, 0.0f)); } float turretYaw() const { - if (turret_ != NULL) + if (turret_ != nullptr) return simCore::RAD2DEG * turret_->getCurrentHPR().x(); return 0.0f; } float turretMinimumYaw() const { - if (turret_ != NULL) + if (turret_ != nullptr) return simCore::RAD2DEG * turret_->getMinHPR().x(); return 0.0f; } float turretMaximumYaw() const { - if (turret_ != NULL) + if (turret_ != nullptr) return simCore::RAD2DEG * turret_->getMaxHPR().x(); return 0.0f; } diff --git a/Examples/BeamTest/BeamTest.cpp b/Examples/BeamTest/BeamTest.cpp index bec9cac40..0bfab766e 100644 --- a/Examples/BeamTest/BeamTest.cpp +++ b/Examples/BeamTest/BeamTest.cpp @@ -112,35 +112,35 @@ struct AppData double t_; AppData() - : typeSlider_(NULL), - typeLabel_(NULL), - modeSlider_(NULL), - modeLabel_(NULL), - rangeSlider_(NULL), - rangeLabel_(NULL), - horizSlider_(NULL), - horizLabel_(NULL), - vertSlider_(NULL), - vertLabel_(NULL), - azimuthSlider_(NULL), - azimuthLabel_(NULL), - elevSlider_(NULL), - elevLabel_(NULL), - colorSlider_(NULL), - colorLabel_(NULL), - capResSlider_(NULL), - capResLabel_(NULL), - coneResSlider_(NULL), - coneResLabel_(NULL), - useOffsetIconCheck_(NULL), - shadedCheck_(NULL), - blendedCheck_(NULL), - renderConeCheck_(NULL), - animateCheck_(NULL), - ds_(NULL), + : typeSlider_(nullptr), + typeLabel_(nullptr), + modeSlider_(nullptr), + modeLabel_(nullptr), + rangeSlider_(nullptr), + rangeLabel_(nullptr), + horizSlider_(nullptr), + horizLabel_(nullptr), + vertSlider_(nullptr), + vertLabel_(nullptr), + azimuthSlider_(nullptr), + azimuthLabel_(nullptr), + elevSlider_(nullptr), + elevLabel_(nullptr), + colorSlider_(nullptr), + colorLabel_(nullptr), + capResSlider_(nullptr), + capResLabel_(nullptr), + coneResSlider_(nullptr), + coneResLabel_(nullptr), + useOffsetIconCheck_(nullptr), + shadedCheck_(nullptr), + blendedCheck_(nullptr), + renderConeCheck_(nullptr), + animateCheck_(nullptr), + ds_(nullptr), hostId_(0), beamId_(0), - view_(NULL), + view_(nullptr), t_(0.0) { types_.push_back(std::make_pair(simData::BeamProperties_BeamType_ABSOLUTE_POSITION, "ABSOLUTE")); diff --git a/Examples/CustomRenderingTest/CustomRenderingTest.cpp b/Examples/CustomRenderingTest/CustomRenderingTest.cpp index 0c0780fc3..49c4650b7 100644 --- a/Examples/CustomRenderingTest/CustomRenderingTest.cpp +++ b/Examples/CustomRenderingTest/CustomRenderingTest.cpp @@ -219,7 +219,7 @@ class RenderEngine : public simVis::CustomRenderingNode::UpdateCallback // Adjust the coordinates of the locator to match that of the host auto host = node_->host(); - if (host != NULL) + if (host != nullptr) { simCore::Coordinate coord; host->getLocator()->getCoordinate(&coord); @@ -319,7 +319,7 @@ class AttachRenderGraphics : public simData::DataStore::DefaultListener // Pick out the node from the scene (created by the ScenarioDataStoreAdapter automatically) simVis::CustomRenderingNode* node = manager_->find(newId); - if (node != NULL) + if (node != nullptr) { // A real render engine would need to account for multiple Custom Rendering nodes here, // either by creating a separate updater per entity, or configuring the updater to diff --git a/Examples/EciTrackHistoryTest/EciTrackHistoryTest.cpp b/Examples/EciTrackHistoryTest/EciTrackHistoryTest.cpp index 66ef9dc9e..1e2fc3a51 100644 --- a/Examples/EciTrackHistoryTest/EciTrackHistoryTest.cpp +++ b/Examples/EciTrackHistoryTest/EciTrackHistoryTest.cpp @@ -83,21 +83,21 @@ struct AppData osg::ref_ptr simHandler_; AppData(simData::DataStore* ds, simData::ObjectId hostId) - : modeSlider_(NULL), - timeTicksSlider_(NULL), - modeLabel_(NULL), - sizeLabel_(NULL), - timeTicksLabel_(NULL), - rewind1_(NULL), - rewind2_(NULL), - ff1_(NULL), - ff2_(NULL), - timeSlider_(NULL), - tether_(NULL), + : modeSlider_(nullptr), + timeTicksSlider_(nullptr), + modeLabel_(nullptr), + sizeLabel_(nullptr), + timeTicksLabel_(nullptr), + rewind1_(nullptr), + rewind2_(nullptr), + ff1_(nullptr), + ff2_(nullptr), + timeSlider_(nullptr), + tether_(nullptr), ds_(ds), hostId_(hostId), - view_(NULL), - platformModel_(NULL) + view_(nullptr), + platformModel_(nullptr) { modes_.push_back(std::make_pair(simData::TrackPrefs_Mode_OFF, "OFF")); modes_.push_back(std::make_pair(simData::TrackPrefs_Mode_POINT, "POINT")); @@ -156,7 +156,7 @@ struct AppData void tether() { - view_->tetherCamera(NULL); + view_->tetherCamera(nullptr); view_->tetherCamera(platformModel_.get()); view_->setFocalOffsets(45, -45, 2e4); } diff --git a/Examples/GOGReader/GOGReader.cpp b/Examples/GOGReader/GOGReader.cpp index 6123540d6..79b49ebfb 100644 --- a/Examples/GOGReader/GOGReader.cpp +++ b/Examples/GOGReader/GOGReader.cpp @@ -27,6 +27,7 @@ * Demonstrates the loading and display of SIMDIS .gog format vector overlay data. */ +#include #include "osgEarth/Controls" #include "osgEarth/LabelNode" #include "osgEarth/MouseCoordsTool" @@ -85,7 +86,7 @@ class LatLonElevListener : public simUtil::MousePositionManipulator::Listener // latitude in degrees double lat() const { return lastLat_; } - // logintude in degrees + // longitude in degrees double lon() const { return lastLon_; } // elevation in meters double elev() const { return lastElev_; } @@ -128,7 +129,7 @@ class MouseAndMenuHandler : public osgGA::GUIEventHandler { centeredGogIndex_.init(0); mouseDispatcher_.reset(new simUtil::MouseDispatcher); - mouseDispatcher_->setViewManager(NULL); + mouseDispatcher_->setViewManager(nullptr); latLonElevListener_.reset(new LatLonElevListener()); setUpMouseManip_(viewer_.get()); updateStatusAndLabel_(); @@ -201,9 +202,9 @@ class MouseAndMenuHandler : public osgGA::GUIEventHandler simVis::Viewpoint eyePos = focusedView->getViewpoint(); // update the eye position's focal point - focusedView->tetherCamera(NULL); + focusedView->tetherCamera(nullptr); eyePos.focalPoint() = osgEarth::GeoPoint(osgEarth::SpatialReference::create("wgs84"), position); - eyePos.setNode(NULL); + eyePos.setNode(nullptr); focusedView->setViewpoint(eyePos); updateStatusAndLabel_(); @@ -321,7 +322,7 @@ class MouseAndMenuHandler : public osgGA::GUIEventHandler void setUpMouseManip_(simVis::Viewer* viewer) { - if (viewer == NULL || viewer->getSceneManager() == NULL || !mouseDispatcher_) + if (viewer == nullptr || viewer->getSceneManager() == nullptr || !mouseDispatcher_) return; mouseManip_.reset(new simUtil::MousePositionManipulator(viewer->getSceneManager()->getMapNode(), viewer->getSceneManager()->getOrCreateAttachPoint("Map Callbacks"))); mouseManip_->setTerrainResolution(0.0001); @@ -411,6 +412,31 @@ simData::ObjectId addPlatform(simData::DataStore &dataStore, const std::string& return platformId; } +/** Process changes on the opacity slider. */ +class OpacitySliderCallback : public ui::ControlEventHandler +{ +public: + void setLabel(ui::LabelControl* label) + { + label_ = label; + } + + virtual void onValueChanged(ui::Control* control, float value) override + { + // Write the percentage to the label + osg::ref_ptr label; + if (label_.lock(label)) + label->setText(std::to_string(static_cast((value * 100) + 0.5f)) + "%"); + + // Set the override color on all nodes based on the provided opacity + for (const auto& overlay : s_overlayNodes) + overlay->setOpacity(value); + } + +private: + osg::observer_ptr label_; +}; + int main(int argc, char** argv) { simCore::checkVersionThrow(); @@ -440,16 +466,24 @@ int main(int argc, char** argv) bool showElevation = ap.read("--showElevation"); bool attach = ap.read("--attach"); + // parse the remaining args + std::vector gogFiles; + std::string iconFile = EXAMPLE_IMAGE_ICON; + for (int i = 1; i < argc; ++i) + { + std::string arg = argv[i]; + if (arg == "--iconFile" && argc > i) + iconFile = argv[++i]; + else + gogFiles.push_back(arg); + } + osg::ref_ptr pin; if (mark) pin = URI("http://www.osgearth.org/chrome/site/pushpin_yellow.png").getImage(); GeoPoint go; - - std::string iconFile = EXAMPLE_IMAGE_ICON; - - /// data source which will provide positions for the platform - /// based on the simulation time. + // data source that provides positions for the platform based on the simulation time simData::MemoryDataStore dataStore; scene->getScenario()->bind(&dataStore); @@ -460,15 +494,8 @@ int main(int argc, char** argv) osg::Group* group = new osg::Group(); // add the gog file vector layers. - for (int i = 1; i < argc; ++i) + for (const std::string& gogFile : gogFiles) { - std::string arg = argv[i]; - if (arg == "--iconFile" && argc > i) - { - iconFile = argv[++i]; - continue; - } - simVis::GOG::Parser::OverlayNodeVector gogs; std::vector followData; simVis::GOG::Parser parser(scene->getMapNode()); @@ -476,11 +503,11 @@ int main(int argc, char** argv) // sets a default reference location for relative GOGs: parser.setReferenceLocation(simVis::GOG::BSTUR); - std::ifstream is(arg.c_str()); + std::ifstream is(gogFile.c_str()); if (!is.is_open()) { - std::string fileName(argv[i]); - SIM_ERROR <<"Could not open GOG file " << fileName << "\n"; + std::string fileName(gogFile); + SIM_ERROR <<"Could not open GOG file " << gogFile << "\n"; return 1; } @@ -545,7 +572,7 @@ int main(int argc, char** argv) } else { - SIM_WARN << "Unable to load GOG data from \"" << argv[i] << "\"" << std::endl; + SIM_WARN << "Unable to load GOG data from \"" << gogFile << "\"" << std::endl; } } @@ -580,6 +607,20 @@ int main(int argc, char** argv) vbox->addControl(new ui::LabelControl(s_help, 14, simVis::Color::Silver)); ui::LabelControl* statusLabel = new ui::LabelControl("STATUS", 14, simVis::Color::Silver); vbox->addControl(statusLabel); + + // Add a section to control the opacity + vbox->addControl(new ui::LabelControl("Opacity:", 14)); + OpacitySliderCallback* sliderCallback = new OpacitySliderCallback; + ui::HSliderControl* opacitySlider = new ui::HSliderControl(0.f, 1.f, 1.f, sliderCallback); + opacitySlider->setHorizFill(false); + opacitySlider->setWidth(250.f); + ui::LabelControl* opacityPercent = new ui::LabelControl("100%", 14); + sliderCallback->setLabel(opacityPercent); + ui::HBox* hbox = new ui::HBox(); + hbox->addControl(opacitySlider); + hbox->addControl(opacityPercent); + vbox->addControl(hbox); + mainView->addOverlayControl(vbox); // Install a handler to respond to the demo keys in this sample. @@ -589,9 +630,8 @@ int main(int argc, char** argv) statusLabel, dataStore, showElevation, - attach ? platform.get() : NULL); + attach ? platform.get() : nullptr); mainView->getCamera()->addEventCallback(mouseHandler); viewer->run(); } - diff --git a/Examples/GateTest/GateTest.cpp b/Examples/GateTest/GateTest.cpp index 54219e08c..6213be583 100644 --- a/Examples/GateTest/GateTest.cpp +++ b/Examples/GateTest/GateTest.cpp @@ -113,32 +113,32 @@ struct AppData double t_; AppData() - : typeSlider_(NULL), - typeLabel_(NULL), - modeSlider_(NULL), - modeLabel_(NULL), - fillPatternSlider_(NULL), - fillPatternLabel_(NULL), - rangeMinSlider_(NULL), - rangeMinLabel_(NULL), - rangeMaxSlider_(NULL), - rangeMaxLabel_(NULL), - horizSlider_(NULL), - horizLabel_(NULL), - vertSlider_(NULL), - vertLabel_(NULL), - azimuthSlider_(NULL), - azimuthLabel_(NULL), - elevSlider_(NULL), - elevLabel_(NULL), - colorSlider_(NULL), - colorLabel_(NULL), - centroidCheck_(NULL), - lightedCheck_(NULL), - ds_(NULL), + : typeSlider_(nullptr), + typeLabel_(nullptr), + modeSlider_(nullptr), + modeLabel_(nullptr), + fillPatternSlider_(nullptr), + fillPatternLabel_(nullptr), + rangeMinSlider_(nullptr), + rangeMinLabel_(nullptr), + rangeMaxSlider_(nullptr), + rangeMaxLabel_(nullptr), + horizSlider_(nullptr), + horizLabel_(nullptr), + vertSlider_(nullptr), + vertLabel_(nullptr), + azimuthSlider_(nullptr), + azimuthLabel_(nullptr), + elevSlider_(nullptr), + elevLabel_(nullptr), + colorSlider_(nullptr), + colorLabel_(nullptr), + centroidCheck_(nullptr), + lightedCheck_(nullptr), + ds_(nullptr), hostId_(0), gateId_(0), - view_(NULL), + view_(nullptr), t_(0.0) { types_.push_back(std::make_pair(simData::GateProperties_GateType_ABSOLUTE_POSITION, "ABSOLUTE")); diff --git a/Examples/ImageIcons/ImageIcons.cpp b/Examples/ImageIcons/ImageIcons.cpp index 47643c34c..a46d1b4e0 100644 --- a/Examples/ImageIcons/ImageIcons.cpp +++ b/Examples/ImageIcons/ImageIcons.cpp @@ -65,10 +65,10 @@ static simData::IconRotation s_iconRotation = simData::IR_2D_YAW; static const std::string s_title = "Image Icons Example"; /// keep a handle, for toggling -static osg::ref_ptr s_helpControl = NULL; +static osg::ref_ptr s_helpControl = nullptr; /// label displaying the name of the current calculation -static osg::ref_ptr s_iconRotationLabel = NULL; +static osg::ref_ptr s_iconRotationLabel = nullptr; //---------------------------------------------------------------------------- diff --git a/Examples/LoadEarthFile/LoadEarthFile.cpp b/Examples/LoadEarthFile/LoadEarthFile.cpp index 904f7fe1e..fbe640c44 100644 --- a/Examples/LoadEarthFile/LoadEarthFile.cpp +++ b/Examples/LoadEarthFile/LoadEarthFile.cpp @@ -139,12 +139,12 @@ struct MenuHandler : public osgGA::GUIEventHandler MenuHandler(simVis::Viewer* viewer, simVis::CreateInsetEventHandler* handler, LabelControl* elevationLabel, simUtil::MouseDispatcher* mouseDispatcher) : viewer_(viewer), handler_(handler), - latLonElevListener_(NULL), + latLonElevListener_(nullptr), showLatLonElevation_(false) { latLonElevListener_ = new LatLonElevationListener(elevationLabel); mouseDispatcher_ = mouseDispatcher; - mouseDispatcher_->setViewManager(NULL); + mouseDispatcher_->setViewManager(nullptr); setUpMouseManip_(viewer_.get()); } diff --git a/Examples/Ocean/Ocean.cpp b/Examples/Ocean/Ocean.cpp index 38be0b97c..08cc93877 100644 --- a/Examples/Ocean/Ocean.cpp +++ b/Examples/Ocean/Ocean.cpp @@ -193,7 +193,7 @@ struct MenuHandler : public osgGA::GUIEventHandler case '0': { osg::observer_ptr ship = scene_->getScenario()->find(s_shipId); - if (ship != NULL) + if (ship != nullptr) { viewer_->getMainView()->tetherCamera(ship.get()); viewer_->getMainView()->setFocalOffsets(0, -10.0, 20000.0, 2.5); @@ -205,7 +205,7 @@ struct MenuHandler : public osgGA::GUIEventHandler break; } case '1': - viewer_->getMainView()->tetherCamera(NULL); + viewer_->getMainView()->tetherCamera(nullptr); break; case 'h': if (menuControl_) diff --git a/Examples/Overhead/OverheadExample.cpp b/Examples/Overhead/OverheadExample.cpp index 305d1f9a6..9cdd78c2c 100644 --- a/Examples/Overhead/OverheadExample.cpp +++ b/Examples/Overhead/OverheadExample.cpp @@ -126,7 +126,7 @@ struct MouseAndMenuHandler : public osgGA::GUIEventHandler labelsOn_(true), border_(0) { - mouseDispatcher_->setViewManager(NULL); + mouseDispatcher_->setViewManager(nullptr); latLonElevListener_.reset(new LatLonElevListener()); setUpMouseManip_(viewer_.get()); updateStatusAndLabel_(); @@ -316,12 +316,12 @@ struct MouseAndMenuHandler : public osgGA::GUIEventHandler simData::ObjectId getCenteredPlatformId_(const simVis::View* view) const { osg::Node* tether = view->getCameraTether(); - if (tether == NULL) + if (tether == nullptr) return 0; else { simVis::PlatformModelNode* model = dynamic_cast(tether); - assert(model != NULL); + assert(model != nullptr); std::vector parents = model->getParents(); for (auto iter = parents.begin(); iter != parents.end(); ++iter) @@ -336,7 +336,7 @@ struct MouseAndMenuHandler : public osgGA::GUIEventHandler void setUpMouseManip_(simVis::Viewer* viewer) { - if (viewer == NULL || viewer->getSceneManager() == NULL || !mouseDispatcher_) + if (viewer == nullptr || viewer->getSceneManager() == nullptr || !mouseDispatcher_) return; mouseManip_.reset(new simUtil::MousePositionManipulator(viewer->getSceneManager()->getMapNode(), viewer->getSceneManager()->getOrCreateAttachPoint("Map Callbacks"))); mouseManip_->setTerrainResolution(0.0001); diff --git a/Examples/Periscope/PeriscopeExample.cpp b/Examples/Periscope/PeriscopeExample.cpp index 514bf1cd0..8fb2b23d8 100644 --- a/Examples/Periscope/PeriscopeExample.cpp +++ b/Examples/Periscope/PeriscopeExample.cpp @@ -342,7 +342,7 @@ int main(int argc, char** argv) // remove the default manipulator; we will set the camera manually viewer->getMainView()->setUpViewInWindow(20, 20, width, height, 0); - viewer->getMainView()->setCameraManipulator(NULL); + viewer->getMainView()->setCameraManipulator(nullptr); // apply the reticle overlay. simUtil::HudManager hudManager(viewer->getMainView(), viewer->getMainView()->getOrCreateHUD()); diff --git a/Examples/Picking/CustomRender.h b/Examples/Picking/CustomRender.h index 394b7b965..e7ff1f2f8 100644 --- a/Examples/Picking/CustomRender.h +++ b/Examples/Picking/CustomRender.h @@ -50,11 +50,11 @@ class RenderEngine : public simVis::CustomRenderingNode::UpdateCallback virtual bool update(const simData::DataSliceBase* updateSlice, bool force = false) { // Break out if the node isn't currently valid - if (node_ == NULL) + if (node_ == nullptr) return false; // Create the geometry if it hasn't been created yet - if (transform_ == NULL) + if (transform_ == nullptr) { simVis::LocatorNode* locatorNode = node_->locatorNode(); locatorNode->removeChildren(0, locatorNode->getNumChildren()); @@ -84,7 +84,7 @@ class RenderEngine : public simVis::CustomRenderingNode::UpdateCallback // Adjust the coordinates of the locator to match that of the host const simVis::EntityNode* host = node_->host(); - if (host != NULL) + if (host != nullptr) { simCore::Coordinate coord; host->getLocator()->getCoordinate(&coord); @@ -169,7 +169,7 @@ class AttachRenderGraphics : public simData::DataStore::DefaultListener // Pick out the node from the scene (created by the ScenarioDataStoreAdapter automatically) simVis::CustomRenderingNode* node = manager_->find(newId); - if (node != NULL) + if (node != nullptr) { // A real render engine would need to account for multiple Custom Render nodes here, // either by creating a separate updater per entity, or configuring the updater to diff --git a/Examples/Picking/ExamplePicking.cpp b/Examples/Picking/ExamplePicking.cpp index 6af374670..049da59ce 100644 --- a/Examples/Picking/ExamplePicking.cpp +++ b/Examples/Picking/ExamplePicking.cpp @@ -194,10 +194,10 @@ class MenuHandler : public osgGA::GUIEventHandler if (app_.insetRttView) { app_.mainView->removeInset(app_.insetRttView.get()); - app_.insetRttView = NULL; + app_.insetRttView = nullptr; } app_.mainView->removeInset(app_.insetView.get()); - app_.insetView = NULL; + app_.insetView = nullptr; } break; diff --git a/Examples/PlanetariumViewTest/PlanetariumViewTest.cpp b/Examples/PlanetariumViewTest/PlanetariumViewTest.cpp index 69e9fa94a..db5662b3e 100644 --- a/Examples/PlanetariumViewTest/PlanetariumViewTest.cpp +++ b/Examples/PlanetariumViewTest/PlanetariumViewTest.cpp @@ -319,7 +319,7 @@ int main(int argc, char **argv) app.platformId = addPlatform(app.dataStore, EXAMPLE_SHIP_ICON); // place some random beams. - ::srand(time(NULL)); + ::srand(time(nullptr)); for (int i=0; igetCameraTether(); - view_->tetherCamera(NULL); + view_->tetherCamera(nullptr); s_action->setText(Stringify() << "Tether OFF"); } else @@ -897,8 +897,8 @@ struct MyPopupCallback : public simVis::PopupContentCallback return osgEarth::Stringify() << std::fixed - << "Lat: " << llf.format(pos.y(), 2) << '\n' - << "Lon: " << llf.format(pos.x(), 2) << '\n' + << "Lat: " << llf.format(osgEarth::Angle(pos.y(), srs_->getUnits()), 2) << '\n' + << "Lon: " << llf.format(osgEarth::Angle(pos.x(), srs_->getUnits()), 2) << '\n' << std::setprecision(altP) << "Alt: " << pos.z() << "m" << '\n' << "MGRS: " << mgrs.format(pos); } diff --git a/Examples/Qt/ExampleQt.cpp b/Examples/Qt/ExampleQt.cpp index 784b1355f..5b9bdc197 100644 --- a/Examples/Qt/ExampleQt.cpp +++ b/Examples/Qt/ExampleQt.cpp @@ -75,7 +75,7 @@ struct FrameRateAction : public QAction // custom action for File->Exit menu :) struct ExitAction : public QAction { - explicit ExitAction(QMainWindow* win) : QAction(tr("Exit"), NULL), win_(win) + explicit ExitAction(QMainWindow* win) : QAction(tr("Exit"), nullptr), win_(win) { connect(this, SIGNAL(triggered()), win_, SLOT(close())); } diff --git a/Examples/Qt/MyMainWindow.h b/Examples/Qt/MyMainWindow.h index d580073c6..60d918bea 100644 --- a/Examples/Qt/MyMainWindow.h +++ b/Examples/Qt/MyMainWindow.h @@ -44,7 +44,7 @@ class MyMainWindow : public QMainWindow public: explicit MyMainWindow(simVis::ViewManager* viewMan) - : glWindow_(NULL) + : glWindow_(nullptr) { viewMan_ = viewMan; diff --git a/Examples/QtCategoryFilterTest/CategoryFilterTest.cpp b/Examples/QtCategoryFilterTest/CategoryFilterTest.cpp index 051c70a7b..c09121b95 100644 --- a/Examples/QtCategoryFilterTest/CategoryFilterTest.cpp +++ b/Examples/QtCategoryFilterTest/CategoryFilterTest.cpp @@ -145,7 +145,7 @@ int main(int argc, char* argv[]) QApplication app(argc, argv); simData::MemoryDataStore* dataStore = new simData::MemoryDataStore(); - MainWindow* window = new MainWindow(dataStore, NULL); + MainWindow* window = new MainWindow(dataStore, nullptr); window->show(); int rv = app.exec(); diff --git a/Examples/QtColorWidgetTest/main.cpp b/Examples/QtColorWidgetTest/main.cpp index 7a16e990b..6719e0bbf 100644 --- a/Examples/QtColorWidgetTest/main.cpp +++ b/Examples/QtColorWidgetTest/main.cpp @@ -27,7 +27,7 @@ int main(int argc, char* argv[]) { QApplication app(argc, argv); - TestColorWidget* colorWidget = new TestColorWidget(NULL); + TestColorWidget* colorWidget = new TestColorWidget(nullptr); colorWidget->show(); int rv = app.exec(); diff --git a/Examples/QtConsoleDataModel/Console.h b/Examples/QtConsoleDataModel/Console.h index 1a7035f53..6cba367fd 100644 --- a/Examples/QtConsoleDataModel/Console.h +++ b/Examples/QtConsoleDataModel/Console.h @@ -37,7 +37,7 @@ class Console : public QWidget Q_OBJECT; public: - Console(simQt::ConsoleDataModel& dataModel, QWidget* parent=NULL); + Console(simQt::ConsoleDataModel& dataModel, QWidget* parent=nullptr); virtual ~Console(); private slots: diff --git a/Examples/QtDataTableViewTest/DataTableViewTest.cpp b/Examples/QtDataTableViewTest/DataTableViewTest.cpp index 2e41f3e0f..726d6e7c4 100644 --- a/Examples/QtDataTableViewTest/DataTableViewTest.cpp +++ b/Examples/QtDataTableViewTest/DataTableViewTest.cpp @@ -151,7 +151,7 @@ namespace DataTableViewTest ui_->setupUi(this); // set up entity tree view - entityTreeModel_ = new simQt::EntityTreeModel(NULL, ds); + entityTreeModel_ = new simQt::EntityTreeModel(nullptr, ds); entityTreeComposite_ = ui_->EntityTreeComposite; entityTreeComposite_->setModel(entityTreeModel_); connect(entityTreeComposite_, SIGNAL(itemsSelected(QList)), this, SLOT(itemsSelected(QList))); @@ -180,16 +180,16 @@ namespace DataTableViewTest MainWindow::~MainWindow() { - // need to set providers to NULL - ui_->DataTableComboBox->setProviders(NULL); + // need to set providers to nullptr + ui_->DataTableComboBox->setProviders(nullptr); delete ui_; - ui_ = NULL; + ui_ = nullptr; delete entityTreeModel_; - entityTreeModel_ = NULL; + entityTreeModel_ = nullptr; delete tableModel_; - tableModel_ = NULL; + tableModel_ = nullptr; delete testHelper_; - testHelper_ = NULL; + testHelper_ = nullptr; } void MainWindow::addTable_() @@ -208,7 +208,7 @@ namespace DataTableViewTest void MainWindow::addRow_() { simData::DataTable* table = ui_->DataTableComboBox->currentSelection(); - if (table == NULL) + if (table == nullptr) return; simData::TableRow row; // use column visitor to get all the columns @@ -229,7 +229,7 @@ namespace DataTableViewTest void MainWindow::addColumn_() { simData::DataTable* table = ui_->DataTableComboBox->currentSelection(); - if (table == NULL) + if (table == nullptr) return; // give the new column a unique name std::ostringstream os; @@ -242,7 +242,7 @@ namespace DataTableViewTest void MainWindow::removeTable_() { simData::DataTable* table = ui_->DataTableComboBox->currentSelection(); - if (table == NULL) + if (table == nullptr) return; testHelper_->dataStore()->dataTableManager().deleteTable(table->tableId()); } @@ -311,7 +311,7 @@ int main(int argc, char* argv[]) { QApplication app(argc, argv); - DataTableViewTest::MainWindow* window = new DataTableViewTest::MainWindow(NULL); + DataTableViewTest::MainWindow* window = new DataTableViewTest::MainWindow(nullptr); window->show(); int rv = app.exec(); diff --git a/Examples/QtDockableViews/QtDockableViews.cpp b/Examples/QtDockableViews/QtDockableViews.cpp index ac4622b28..b3bc67d01 100644 --- a/Examples/QtDockableViews/QtDockableViews.cpp +++ b/Examples/QtDockableViews/QtDockableViews.cpp @@ -126,7 +126,7 @@ MyMainWindow::~MyMainWindow() void MyMainWindow::paintEvent(QPaintEvent* e) { // refresh all the views -- only repaint if the last created GL window was exposed (or got deleted). - // This repaints on NULL because it the flag (in this app) can only be NULL if user closed an open + // This repaints on nullptr because the flag (in this app) can only be nullptr if user closed an open // window, and other windows that are still open are almost certainly still exposed. We do check // for isExposed() on the last created window, under the presumption that once it is exposed, we // can safely draw on all windows. diff --git a/Examples/QtEntityLineEditTest/EntityLineEditTest.cpp b/Examples/QtEntityLineEditTest/EntityLineEditTest.cpp index abb4f1c3d..28ad27b32 100644 --- a/Examples/QtEntityLineEditTest/EntityLineEditTest.cpp +++ b/Examples/QtEntityLineEditTest/EntityLineEditTest.cpp @@ -110,7 +110,7 @@ MainWindow::MainWindow(QWidget *parent, simData::DataStore* dataStore) : QDialog connect(mainWindowGui_->deleteButton, SIGNAL(clicked()), this, SLOT(delete_())); connect(mainWindowGui_->renameButton, SIGNAL(clicked()), this, SLOT(rename_())); - entityTreeModel_ = new simQt::EntityTreeModel(NULL, dataStore_); + entityTreeModel_ = new simQt::EntityTreeModel(nullptr, dataStore_); entityTreeModel_->setToListView(); mainWindowGui_->entityLine->setModel(entityTreeModel_, simData::PLATFORM); connect(mainWindowGui_->entityLine, SIGNAL(itemSelected(uint64_t)), this, SLOT(itemSelected_(uint64_t))); @@ -122,7 +122,7 @@ void MainWindow::itemSelected_(uint64_t id) MainWindow::~MainWindow() { - mainWindowGui_->entityLine->setModel(NULL, simData::PLATFORM); + mainWindowGui_->entityLine->setModel(nullptr, simData::PLATFORM); delete mainWindowGui_; delete entityTreeModel_; } @@ -171,7 +171,7 @@ int main(int argc, char* argv[]) QApplication app(argc, argv); simData::MemoryDataStore* dataStore = new simData::MemoryDataStore(); - MainWindow* window = new MainWindow(NULL, dataStore); + MainWindow* window = new MainWindow(nullptr, dataStore); window->show(); int rv = app.exec(); diff --git a/Examples/QtEntityViewTest/EntityViewTest.cpp b/Examples/QtEntityViewTest/EntityViewTest.cpp index 52f1906fa..7a360e944 100644 --- a/Examples/QtEntityViewTest/EntityViewTest.cpp +++ b/Examples/QtEntityViewTest/EntityViewTest.cpp @@ -130,7 +130,7 @@ MainWindow::MainWindow(QWidget *parent) : QDialog(parent) connect(mainWindowGui_->testButton, SIGNAL(clicked()), this, SLOT(test_())); connect(mainWindowGui_->deleteButton, SIGNAL(clicked()), this, SLOT(deleteEntity_())); - entityTreeModel_ = new simQt::EntityTreeModel(NULL, dataStore_); + entityTreeModel_ = new simQt::EntityTreeModel(nullptr, dataStore_); entityTreeComposite_ = mainWindowGui_->entityTreeComposite; entityTreeComposite_->addEntityFilter(new simQt::EntityTypeFilter(*dataStore_, simData::ALL, true)); entityTreeComposite_->setModel(entityTreeModel_); @@ -198,7 +198,7 @@ int main(int argc, char* argv[]) { QApplication app(argc, argv); - MainWindow* window = new MainWindow(NULL); + MainWindow* window = new MainWindow(nullptr); window->show(); int rv = app.exec(); diff --git a/Examples/QtFileSelectorTest/main.cpp b/Examples/QtFileSelectorTest/main.cpp index 0573db11d..e1f3c5f1f 100644 --- a/Examples/QtFileSelectorTest/main.cpp +++ b/Examples/QtFileSelectorTest/main.cpp @@ -27,7 +27,7 @@ int main(int argc, char* argv[]) { QApplication app(argc, argv); - TestFileSelectorWidget fileSelectorWidget(NULL); + TestFileSelectorWidget fileSelectorWidget(nullptr); fileSelectorWidget.show(); return app.exec(); diff --git a/Examples/QtThreadExample/DataGenerator.cpp b/Examples/QtThreadExample/DataGenerator.cpp index 3748b680b..a7816da23 100644 --- a/Examples/QtThreadExample/DataGenerator.cpp +++ b/Examples/QtThreadExample/DataGenerator.cpp @@ -28,7 +28,7 @@ namespace SdkQThreadExample DataGenerator::DataGenerator() : QObject(), - timer_(NULL), + timer_(nullptr), done_(false), lat_(0.0), lon_(0.0), @@ -67,7 +67,7 @@ void DataGenerator::update_() // Stop the timer timer_->stop(); delete timer_; - timer_ = NULL; + timer_ = nullptr; // Send out signal indicating the thread is done emit finished(); return; diff --git a/Examples/QtThreadExample/Gui.h b/Examples/QtThreadExample/Gui.h index a11241117..0f85ad228 100644 --- a/Examples/QtThreadExample/Gui.h +++ b/Examples/QtThreadExample/Gui.h @@ -36,7 +36,7 @@ class Gui : public QDialog Q_OBJECT; public: - explicit Gui(QWidget* parent = NULL); + explicit Gui(QWidget* parent = nullptr); virtual ~Gui(); /** Update the text for the number of updates processed */ diff --git a/Examples/QtThreadExample/MyMainWindow.cpp b/Examples/QtThreadExample/MyMainWindow.cpp index dd3ed77c9..1b1201ab4 100644 --- a/Examples/QtThreadExample/MyMainWindow.cpp +++ b/Examples/QtThreadExample/MyMainWindow.cpp @@ -33,8 +33,8 @@ namespace SdkQThreadExample{ MyMainWindow::MyMainWindow(simVis::ViewManager* viewMan, simData::DataStore& dataStore) : viewManager_(viewMan), dataStore_(dataStore), - reader_(NULL), - generatorDialog_(NULL) + reader_(nullptr), + generatorDialog_(nullptr) { // disable the default ESC-to-quit event: viewManager_->getViewer()->setKeyEventSetsDone(0); @@ -83,18 +83,18 @@ void MyMainWindow::paintEvent(QPaintEvent* e) redrawTimer_.start(); // Update the GUI at the slow rate of the paintEvent instead of at the data rate - if ((reader_ != NULL) && (generatorDialog_ != NULL)) + if ((reader_ != nullptr) && (generatorDialog_ != nullptr)) generatorDialog_->updateNumberProcessed(reader_->numberProcessed()); } void MyMainWindow::showGenerateDialog() { - if (reader_ == NULL) + if (reader_ == nullptr) { reader_ = new Reader(dataStore_); } - if (generatorDialog_ == NULL) + if (generatorDialog_ == nullptr) { generatorDialog_ = new Gui(this); // When the user click the Start button signal the reader to start diff --git a/Examples/QtThreadExample/Reader.cpp b/Examples/QtThreadExample/Reader.cpp index ff0d3cd0c..718f23f25 100644 --- a/Examples/QtThreadExample/Reader.cpp +++ b/Examples/QtThreadExample/Reader.cpp @@ -35,7 +35,7 @@ namespace SdkQThreadExample Reader::Reader(simData::DataStore& dataStore) : dataStore_(dataStore), - threadedDataGen_(NULL), + threadedDataGen_(nullptr), id_(0), numberProcessed_(0) { @@ -48,7 +48,7 @@ Reader::~Reader() void Reader::start() { - if (threadedDataGen_ != NULL) + if (threadedDataGen_ != nullptr) return; @@ -70,7 +70,7 @@ void Reader::start() void Reader::stop() { - if (threadedDataGen_ != NULL) + if (threadedDataGen_ != nullptr) { // Disconnect before shutting down to prevent race condition disconnect(threadedDataGen_, SIGNAL(newData(double, double, double)), this, SLOT(addDataPoint_(double, double, double))); @@ -78,7 +78,7 @@ void Reader::stop() } // thread_ gets deleted automatically with deleteLater() signal - threadedDataGen_ = NULL; + threadedDataGen_ = nullptr; id_ = 0; } diff --git a/Examples/QtTimeWidgetTest/TimeWidgetTest.cpp b/Examples/QtTimeWidgetTest/TimeWidgetTest.cpp index 4ba0fa39f..4901b56f9 100644 --- a/Examples/QtTimeWidgetTest/TimeWidgetTest.cpp +++ b/Examples/QtTimeWidgetTest/TimeWidgetTest.cpp @@ -27,7 +27,7 @@ int main(int argc, char* argv[]) { QApplication app(argc, argv); - MainWindow* window = new MainWindow(NULL); + MainWindow* window = new MainWindow(nullptr); window->show(); int rv = app.exec(); diff --git a/Examples/QtUnitsWidgetTest/UnitsComboBoxTest.h b/Examples/QtUnitsWidgetTest/UnitsComboBoxTest.h index b9b967e52..ca125d651 100644 --- a/Examples/QtUnitsWidgetTest/UnitsComboBoxTest.h +++ b/Examples/QtUnitsWidgetTest/UnitsComboBoxTest.h @@ -40,7 +40,7 @@ class UnitsComboBoxTest : public QWidget { Q_OBJECT; public: - explicit UnitsComboBoxTest(QWidget* parent = NULL); + explicit UnitsComboBoxTest(QWidget* parent = nullptr); virtual ~UnitsComboBoxTest(); private slots: diff --git a/Examples/QtViewManagerDataModel/TestViewManagerQt.cpp b/Examples/QtViewManagerDataModel/TestViewManagerQt.cpp index 46f5e2258..943cc3a58 100644 --- a/Examples/QtViewManagerDataModel/TestViewManagerQt.cpp +++ b/Examples/QtViewManagerDataModel/TestViewManagerQt.cpp @@ -234,7 +234,7 @@ void MainWindow::removeView() { QVariant data = topTreeView_->model()->data(topTreeView_->currentIndex(), simQt::ViewManagerDataModel::VIEW_ROLE); simVis::View* selectedView = static_cast(data.value()); - if (selectedView == NULL || mainViews_.empty()) + if (selectedView == nullptr || mainViews_.empty()) return; simVis::View* hostView = selectedView->getHostView(); diff --git a/Examples/RFProp/RFProp.cpp b/Examples/RFProp/RFProp.cpp index 6aef02a05..4519509a9 100644 --- a/Examples/RFProp/RFProp.cpp +++ b/Examples/RFProp/RFProp.cpp @@ -135,7 +135,7 @@ double getBearingAngle(const std::string& infilename) return simCore::angFix2PI(bearing * simCore::DEG2RAD); } -static osg::ref_ptr s_controlGrid = NULL; +static osg::ref_ptr s_controlGrid = nullptr; static bool s_autoBearing = false; static float s_alphaValue = 1.f; @@ -594,7 +594,7 @@ int main(int argc, char** argv) simExamples::addDefaultSkyNode(viewer.get()); osg::ref_ptr root = new osg::Group(); - osg::ref_ptr profileManager = new simRF::ProfileManager(); + osg::ref_ptr profileManager = new simRF::ProfileManager(nullptr); // min & max loss values for gradient color setting in dB; valid loss data is [0,300] const double minFSL = 0; diff --git a/Examples/RadialLOS/ExampleRadialLOS.cpp b/Examples/RadialLOS/ExampleRadialLOS.cpp index b3328af94..45170cad4 100644 --- a/Examples/RadialLOS/ExampleRadialLOS.cpp +++ b/Examples/RadialLOS/ExampleRadialLOS.cpp @@ -70,16 +70,16 @@ namespace struct AppData { AppData() - : altitude(NULL), - azim_center(NULL), - fov(NULL), - azim_res(NULL), - range_max(NULL), - range_res(NULL), - p2p_result(NULL), - los(NULL), - mapNode(NULL), - p2pFeature(NULL) + : altitude(nullptr), + azim_center(nullptr), + fov(nullptr), + azim_res(nullptr), + range_max(nullptr), + range_res(nullptr), + p2p_result(nullptr), + los(nullptr), + mapNode(nullptr), + p2pFeature(nullptr) { } diff --git a/Examples/RangeTool/ExampleRangeTool.cpp b/Examples/RangeTool/ExampleRangeTool.cpp index 3224a6603..65067330d 100644 --- a/Examples/RangeTool/ExampleRangeTool.cpp +++ b/Examples/RangeTool/ExampleRangeTool.cpp @@ -59,7 +59,7 @@ using namespace osgEarth::Util::Controls; //---------------------------------------------------------------------------- // global association to manipulate -static osg::ref_ptr s_association = NULL; +static osg::ref_ptr s_association = nullptr; // list of calculations to cycle through static simVis::RangeTool::CalculationVector s_lineCalcs; @@ -76,11 +76,11 @@ static int s_lineCalcIndex = -1, s_angleCalcIndex = -1; static const std::string s_title = "Range Tool Example"; /// keep a handle, for toggling -static osg::ref_ptr s_helpControl = NULL; +static osg::ref_ptr s_helpControl = nullptr; /// label displaying the name of the current calculation -static osg::ref_ptr s_lineCalcLabel = NULL; -static osg::ref_ptr s_angleCalcLabel = NULL; +static osg::ref_ptr s_lineCalcLabel = nullptr; +static osg::ref_ptr s_angleCalcLabel = nullptr; // callback to toggle depth testing flag diff --git a/Examples/RocketBurn/RocketBurn.cpp b/Examples/RocketBurn/RocketBurn.cpp index a65eefcbb..bea5c10f6 100644 --- a/Examples/RocketBurn/RocketBurn.cpp +++ b/Examples/RocketBurn/RocketBurn.cpp @@ -48,8 +48,8 @@ class TimeListener : public simData::DataStore::DefaultListener { } - /// current time has been changed - virtual void onTimeChange(simData::DataStore *source) + /// data store has changed + virtual void onChange(simData::DataStore *source) { rbStorage_.update(source->updateTime()); vtStorage_.update(source->updateTime()); diff --git a/Examples/SimpleServer/ViewerApp.cpp b/Examples/SimpleServer/ViewerApp.cpp index 100cfbdf7..1e4984e90 100644 --- a/Examples/SimpleServer/ViewerApp.cpp +++ b/Examples/SimpleServer/ViewerApp.cpp @@ -144,11 +144,11 @@ class Shortcuts : public osgGA::GUIEventHandler ////////////////////////////////////////////////////////////////// ViewerApp::ViewerApp(osg::ArgumentParser& args) - : clock_(NULL), + : clock_(nullptr), textReplacer_(new simCore::TextReplacer), - dataStore_(NULL), - interpolator_(NULL), - timeVariable_(NULL), + dataStore_(nullptr), + interpolator_(nullptr), + timeVariable_(nullptr), declutterOn_(false), colorIndex_(0) { @@ -157,7 +157,7 @@ ViewerApp::ViewerApp(osg::ArgumentParser& args) ViewerApp::~ViewerApp() { - engine_ = NULL; + engine_ = nullptr; delete dataStore_; } @@ -362,7 +362,7 @@ void ViewerApp::centerNext() simVis::View* view = viewManager_->getView(0); simVis::EntityNode* tetherNode = view->getEntityNode(view->getCameraTether()); simData::ObjectId lastTetherId = 0; - if (tetherNode != NULL) + if (tetherNode != nullptr) { lastTetherId = tetherNode->getId(); } @@ -390,7 +390,7 @@ void ViewerApp::toggleCockpit() // Figure out what the current tether node is simVis::View* view = viewManager_->getView(0); simVis::EntityNode* tetherNode = view->getEntityNode(view->getCameraTether()); - if (tetherNode == NULL) + if (tetherNode == nullptr) return; if (view->getCameraTether() && !view->isCockpitEnabled()) @@ -404,7 +404,7 @@ void ViewerApp::toggleCockpit() view->setViewpoint(vp); return; } - view->enableCockpitMode(NULL); + view->enableCockpitMode(nullptr); } void ViewerApp::playPause() @@ -433,7 +433,7 @@ void ViewerApp::toggleLogDb() void ViewerApp::cycleTimeFormat() { - if (timeVariable_ == NULL) + if (timeVariable_ == nullptr) return; timeVariable_->cycleFormat(); } diff --git a/Examples/SkyModel/ExampleSkyModel.cpp b/Examples/SkyModel/ExampleSkyModel.cpp index 755cdd16f..f3e962854 100644 --- a/Examples/SkyModel/ExampleSkyModel.cpp +++ b/Examples/SkyModel/ExampleSkyModel.cpp @@ -96,7 +96,7 @@ struct AppData { float mag = ambient->getValue(); - if (sceneManager->getSkyNode() != NULL) + if (sceneManager->getSkyNode() != nullptr) sceneManager->getSkyNode()->getSunLight()->setAmbient(osg::Vec4f(mag, mag, mag, 1.f)); } diff --git a/Examples/TimestampedLayer/ExampleTimestampedLayer.cpp b/Examples/TimestampedLayer/ExampleTimestampedLayer.cpp index 72853fbda..ec98fc6a2 100644 --- a/Examples/TimestampedLayer/ExampleTimestampedLayer.cpp +++ b/Examples/TimestampedLayer/ExampleTimestampedLayer.cpp @@ -40,9 +40,9 @@ namespace ui = osgEarth::Util::Controls; struct App { App() - : timeSlider_(NULL), - clockLabel_(NULL), - activeLayer_(NULL), + : timeSlider_(nullptr), + clockLabel_(nullptr), + activeLayer_(nullptr), firstTime_(INT_MAX), lastTime_(0), now_(0) @@ -140,7 +140,7 @@ bool loadEarthFile(const std::string& earthFile, simVis::Viewer* viewer) { osg::ref_ptr node = osgDB::readNodeFile(earthFile); osgEarth::MapNode* mapNode = osgEarth::MapNode::get(node.get()); - if (mapNode == NULL) + if (mapNode == nullptr) return false; viewer->setMapNode(mapNode); diff --git a/Examples/TrackHistoryTest/TrackHistoryTest.cpp b/Examples/TrackHistoryTest/TrackHistoryTest.cpp index 7794115d1..816ecc892 100644 --- a/Examples/TrackHistoryTest/TrackHistoryTest.cpp +++ b/Examples/TrackHistoryTest/TrackHistoryTest.cpp @@ -103,29 +103,29 @@ struct AppData osg::ref_ptr simHandler_; AppData(simData::DataStore* ds, simData::ObjectId hostId) - : modeSlider_(NULL), - sizeSlider_(NULL), - colorSlider_(NULL), - overrideColorSlider_(NULL), - maxLengthSlider_(NULL), - multiColorCheck_(NULL), - platformColorCheck_(NULL), - generateColorCommandsCheck_(NULL), - modeLabel_(NULL), - sizeLabel_(NULL), - colorLabel_(NULL), - overrideColorLabel_(NULL), - maxLengthLabel_(NULL), - rewind1_(NULL), - rewind2_(NULL), - ff1_(NULL), - ff2_(NULL), - timeSlider_(NULL), - tether_(NULL), + : modeSlider_(nullptr), + sizeSlider_(nullptr), + colorSlider_(nullptr), + overrideColorSlider_(nullptr), + maxLengthSlider_(nullptr), + multiColorCheck_(nullptr), + platformColorCheck_(nullptr), + generateColorCommandsCheck_(nullptr), + modeLabel_(nullptr), + sizeLabel_(nullptr), + colorLabel_(nullptr), + overrideColorLabel_(nullptr), + maxLengthLabel_(nullptr), + rewind1_(nullptr), + rewind2_(nullptr), + ff1_(nullptr), + ff2_(nullptr), + timeSlider_(nullptr), + tether_(nullptr), ds_(ds), hostId_(hostId), - view_(NULL), - platformModel_(NULL) + view_(nullptr), + platformModel_(nullptr) { modes_.push_back(std::make_pair(simData::TrackPrefs_Mode_OFF, "OFF")); modes_.push_back(std::make_pair(simData::TrackPrefs_Mode_POINT, "POINT")); @@ -220,7 +220,7 @@ struct AppData void tether() { - view_->tetherCamera(NULL); + view_->tetherCamera(nullptr); view_->tetherCamera(platformModel_.get()); view_->setFocalOffsets(45, -45, 2e4); } @@ -231,12 +231,12 @@ struct AppData simData::DataTable* table = ds_->dataTableManager().findTable(hostId_, simData::INTERNAL_TRACK_HISTORY_TABLE); simData::TableColumnId colId = 0; bool foundColumn = false; - if (table == NULL) + if (table == nullptr) { simData::TableStatus status = ds_->dataTableManager().addDataTable(hostId_, simData::INTERNAL_TRACK_HISTORY_TABLE, &table); if (!status.isError()) { - simData::TableColumn* newColumn = NULL; + simData::TableColumn* newColumn = nullptr; if (!table->addColumn(simData::INTERNAL_TRACK_HISTORY_COLOR_COLUMN, simData::VT_UINT32, 0, &newColumn).isError()) { colId = newColumn->columnId(); @@ -277,7 +277,7 @@ struct AppData void removeColorCommands_() { simData::DataTable* table = ds_->dataTableManager().findTable(hostId_, simData::INTERNAL_TRACK_HISTORY_TABLE); - if (table != NULL) + if (table != nullptr) ds_->dataTableManager().deleteTable(table->tableId()); } diff --git a/Plugins/QtDesignerWidgets/CategoryDataBreadcrumbsPlugin.cpp b/Plugins/QtDesignerWidgets/CategoryDataBreadcrumbsPlugin.cpp index 3919cb278..33960d498 100644 --- a/Plugins/QtDesignerWidgets/CategoryDataBreadcrumbsPlugin.cpp +++ b/Plugins/QtDesignerWidgets/CategoryDataBreadcrumbsPlugin.cpp @@ -29,7 +29,7 @@ CategoryDataBreadcrumbsPlugin::CategoryDataBreadcrumbsPlugin(QObject *parent) : QObject(parent), - dataStore_(NULL) + dataStore_(nullptr) { } @@ -47,7 +47,7 @@ void CategoryDataBreadcrumbsPlugin::initialize(QDesignerFormEditorInterface *) bool CategoryDataBreadcrumbsPlugin::isInitialized() const { - return dataStore_ != NULL; + return dataStore_ != nullptr; } QWidget *CategoryDataBreadcrumbsPlugin::createWidget(QWidget *parent) @@ -55,7 +55,7 @@ QWidget *CategoryDataBreadcrumbsPlugin::createWidget(QWidget *parent) simQt::CategoryDataBreadcrumbs* rv = new simQt::CategoryDataBreadcrumbs(parent); // Create a filter for user to see - if (dataStore_ == NULL) + if (dataStore_ == nullptr) dataStore_ = new simData::MemoryDataStore; simData::CategoryNameManager& nameManager = dataStore_->categoryNameManager(); simData::CategoryFilter filter(dataStore_); diff --git a/Plugins/QtDesignerWidgets/CategoryFilterWidgetPlugin.cpp b/Plugins/QtDesignerWidgets/CategoryFilterWidgetPlugin.cpp index b28afe8ad..03ec1dd0d 100644 --- a/Plugins/QtDesignerWidgets/CategoryFilterWidgetPlugin.cpp +++ b/Plugins/QtDesignerWidgets/CategoryFilterWidgetPlugin.cpp @@ -29,7 +29,7 @@ CategoryFilterWidgetPlugin::CategoryFilterWidgetPlugin(QObject *parent) : QObject(parent), - dataStore_(NULL) + dataStore_(nullptr) { } @@ -48,14 +48,14 @@ void CategoryFilterWidgetPlugin::initialize(QDesignerFormEditorInterface *) bool CategoryFilterWidgetPlugin::isInitialized() const { - return dataStore_ != NULL; + return dataStore_ != nullptr; } QWidget *CategoryFilterWidgetPlugin::createWidget(QWidget *parent) { simQt::CategoryFilterWidget* rv = new simQt::CategoryFilterWidget(parent); // Create the data store, adding default categories - initialize(NULL); + initialize(nullptr); rv->setDataStore(dataStore_); // Create a filter for user to see diff --git a/Plugins/QtDesignerWidgets/EntityLineEditPlugin.cpp b/Plugins/QtDesignerWidgets/EntityLineEditPlugin.cpp index fca1ec136..43240a7f9 100644 --- a/Plugins/QtDesignerWidgets/EntityLineEditPlugin.cpp +++ b/Plugins/QtDesignerWidgets/EntityLineEditPlugin.cpp @@ -45,7 +45,7 @@ bool EntityLineEditPlugin::isInitialized() const QWidget *EntityLineEditPlugin::createWidget(QWidget *parent) { - simQt::EntityLineEdit* rv = new simQt::EntityLineEdit(parent, NULL); + simQt::EntityLineEdit* rv = new simQt::EntityLineEdit(parent, nullptr); return rv; } diff --git a/Plugins/QtDesignerWidgets/EntityTreeCompositePlugin.cpp b/Plugins/QtDesignerWidgets/EntityTreeCompositePlugin.cpp index ee7540208..493a67f2d 100644 --- a/Plugins/QtDesignerWidgets/EntityTreeCompositePlugin.cpp +++ b/Plugins/QtDesignerWidgets/EntityTreeCompositePlugin.cpp @@ -46,7 +46,7 @@ bool EntityTreeCompositePlugin::isInitialized() const QWidget *EntityTreeCompositePlugin::createWidget(QWidget *parent) { simQt::EntityTreeComposite* rv = new simQt::EntityTreeComposite(parent); - rv->setModel(new QtDesignerDisplayTree(NULL)); + rv->setModel(new QtDesignerDisplayTree(nullptr)); return rv; } diff --git a/Plugins/QtDesignerWidgets/simQtDesignerPlugins.h b/Plugins/QtDesignerWidgets/simQtDesignerPlugins.h index 2b46e9e05..86e7df4eb 100644 --- a/Plugins/QtDesignerWidgets/simQtDesignerPlugins.h +++ b/Plugins/QtDesignerWidgets/simQtDesignerPlugins.h @@ -36,7 +36,7 @@ class simQtDesignerPlugins : public QObject, public QDesignerCustomWidgetCollect #endif public: - explicit simQtDesignerPlugins(QObject* parent = NULL); + explicit simQtDesignerPlugins(QObject* parent = nullptr); public: // QDesignerCustomWidgetCollectionInterface API virtual QList customWidgets() const; diff --git a/SDK/simCore/Calc/Calculations.cpp b/SDK/simCore/Calc/Calculations.cpp index edcdd34cb..d29f847b7 100644 --- a/SDK/simCore/Calc/Calculations.cpp +++ b/SDK/simCore/Calc/Calculations.cpp @@ -323,7 +323,7 @@ void calculateDRCRDownValue(const Vec3 &fromLla, const double &yaw, const Vec3 & // get the true azimuth and elevation from "fromLla" to "toLla" double trueAzimuth = 0; double trueElevation = 0; - calculateAbsAzEl(fromLla, toLla, &trueAzimuth, &trueElevation, NULL, model, &cc); + calculateAbsAzEl(fromLla, toLla, &trueAzimuth, &trueElevation, nullptr, model, &cc); // get the down value if (downValue) @@ -410,7 +410,7 @@ double calculateRangeRate(const Vec3 &fromLla, const Vec3 &fromOriLla, const Vec } double bearing = 0; - calculateRelAzEl(fromLla, fromOriLla, toLla, &bearing, NULL, NULL, model, &cc); + calculateRelAzEl(fromLla, fromOriLla, toLla, &bearing, nullptr, nullptr, model, &cc); return v3Length(fromVel) * cos(fromOriLla[0] - bearing) - (v3Length(toVel) * cos(toOriLla[0] - bearing)); } @@ -430,7 +430,7 @@ double calculateBearingRate(const Vec3 &fromLla, const Vec3 &fromOriLla, const V } double bearing = 0; - calculateRelAzEl(fromLla, fromOriLla, toLla, &bearing, NULL, NULL, model, &cc); + calculateRelAzEl(fromLla, fromOriLla, toLla, &bearing, nullptr, nullptr, model, &cc); const double range = calculateGroundDist(fromLla, toLla, model, &cc); const double tspd = v3Length(toVel); @@ -935,7 +935,7 @@ bool convertLocations(const Coordinate &fromState, const Coordinate &toState, co } /** -* Converts the given perfect sphere earth XYZ values to ENU Tangent Plane values, given +* Converts the given perfect sphere earth XYZ values to X-East Tangent Plane values, given * the tangent plane's latitude, longitude, and altitude. Note: If tangent plane's perfect * sphere Earth XYZ values are available, they can be given for a faster calculation. */ @@ -962,20 +962,20 @@ void sphere2TangentPlane(const Vec3& llaVec, const Vec3& sphereVec, Vec3& tpVec, // get the delta spherical XYZ from the tangent plane to the given sphereVec point v3Subtract(sphereVec, tempSphereXYZ, tempSphereXYZ); - // figure out the the tangent plane ENU values if the tangent plane + // figure out the the X-East tangent plane values if the tangent plane // was at Lat = 0, Lon = 0 tpVec[0] = -tempSphereXYZ[1]; tpVec[1] = tempSphereXYZ[2]; tpVec[2] = -tempSphereXYZ[0]; // Correctly rotate at end of sphere2TangentPlane() - // adjusts the tangent plane ENU values based on the given tangent plane Lat and Lon values + // adjusts the X-East tangent plane values based on the given tangent plane Lat and Lon values v3RotY(tpVec, -llaVec[1], tpVec); v3RotX(tpVec, llaVec[0], tpVec); } /** -* Converts the given ENU Tangent Plane values to perfect sphere Earth XYZ values, given +* Converts the given X-East Tangent Plane values to perfect sphere Earth XYZ values, given * the tangent planes latitude, longitude, and altitude. Note: If tangent plane's perfect * sphere Earth XYZ values are available, they can be given for a faster calculation. */ @@ -989,7 +989,7 @@ void tangentPlane2Sphere(const Vec3 &llaVec, const Vec3 &tpVec, Vec3& sphereVec, } Vec3 tempTpENU(tpVec); - // move the given ENU values from the given tangent plane to the + // move the given X-East values from the given tangent plane to the // tangent plane at Lat = 0, Lon = 0 v3RotX(tempTpENU, -llaVec[0], tempTpENU); v3RotY(tempTpENU, llaVec[1], tempTpENU); @@ -1558,7 +1558,7 @@ bool positionInGate(const simCore::Vec3& gateHostLLA, const simCore::Vec3& posit double rae[3]; // gets the azimuth, elevation, and length from the host platform to the position of interest - simCore::calculateAbsAzEl(gateHostLLA, positionLLA, &rae[1], &rae[2], NULL, earthModel, &cc); + simCore::calculateAbsAzEl(gateHostLLA, positionLLA, &rae[1], &rae[2], nullptr, earthModel, &cc); rae[0] = simCore::calculateSlant(gateHostLLA, positionLLA, earthModel, &cc); const double halfW = widthRad / 2.0; diff --git a/SDK/simCore/Calc/Calculations.h b/SDK/simCore/Calc/Calculations.h index be75e7888..57a5e5db6 100644 --- a/SDK/simCore/Calc/Calculations.h +++ b/SDK/simCore/Calc/Calculations.h @@ -235,10 +235,10 @@ namespace simCore * sphere Earth XYZ values are available, they can be given for a faster calculation. * @param[in ] llaVec Latitude, longitude, and altitude values of the tangent plane origin * @param[in ] sphereVec Given XYZ values to convert to an ENU location - * @param[out] tpVec Distance in XYZ that the sphereVec is from the llaVec location + * @param[out] tpVec Distance in X-East that the sphereVec is from the llaVec location * @param[in ] sphereTpOrigin Perfect sphere coordinates of the tangent plane origin, if known. If this value is not known, it will be calculated from llaVec. Calculation is faster if this is provided. */ - SDKCORE_EXPORT void sphere2TangentPlane(const Vec3& llaVec, const Vec3& sphereVec, Vec3& tpVec, const Vec3* sphereTpOrigin=NULL); + SDKCORE_EXPORT void sphere2TangentPlane(const Vec3& llaVec, const Vec3& sphereVec, Vec3& tpVec, const Vec3* sphereTpOrigin=nullptr); /** * @brief Converts the given X-East Tangent Plane position to a perfect sphere earth XYZ position @@ -247,11 +247,11 @@ namespace simCore * the tangent planes latitude, longitude, and altitude. Note: If tangent plane's perfect * sphere Earth XYZ values are available, they can be given for a faster calculation. * @param[in ] llaVec Latitude, longitude, and altitude values of the tangent plane origin - * @param[in ] tpVec Given distance in XYZ that the sphereVec is from the llaVec location - * @param[out] sphereVec XYZ values to convert to an ENU location + * @param[in ] tpVec Given X-East values to convert to a perfect sphere XYZ location + * @param[out] sphereVec XYZ vector generated by conversion from the X-East location * @param[in ] sphereTpOrigin Perfect sphere coordinates of the tangent plane origin, if known. If this value is not known, it will be calculated from llaVec. Calculation is faster if this is provided. */ - SDKCORE_EXPORT void tangentPlane2Sphere(const Vec3 &llaVec, const Vec3 &tpVec, Vec3& sphereVec, const Vec3* sphereTpOrigin=NULL); + SDKCORE_EXPORT void tangentPlane2Sphere(const Vec3 &llaVec, const Vec3 &tpVec, Vec3& sphereVec, const Vec3* sphereTpOrigin=nullptr); /** * @brief Converts a geodetic position into a perfect sphere XYZ position @@ -314,7 +314,7 @@ namespace simCore * @param[out] azbck Backward azimuth from second point to reference (rad) * @pre one of the lat, lon or azbck params must be valid */ - SDKCORE_EXPORT void sodanoDirect(const double refLat, const double refLon, const double refAlt, const double dist, const double azfwd, double *latOut, double *lonOut, double *azbck=NULL); + SDKCORE_EXPORT void sodanoDirect(const double refLat, const double refLon, const double refAlt, const double dist, const double azfwd, double *latOut, double *lonOut, double *azbck=nullptr); /** * @brief Calculates the geodesic length, forward and backward azimuth using Sodano's indirect solution @@ -328,11 +328,11 @@ namespace simCore * @param[in ] refAlt Height above ellipsoid of reference point (m) * @param[in ] lat Geodetic latitude of point 2 (rad) * @param[in ] lon Geodetic longitude of point 2 (rad) - * @param[out] azfwd Forward azimuth from reference to second point clockwise from North (rad), not calculated if NULL - * @param[out] azbck Backward azimuth from second point to reference (rad), not calculated if NULL + * @param[out] azfwd Forward azimuth from reference to second point clockwise from North (rad), not calculated if nullptr + * @param[out] azbck Backward azimuth from second point to reference (rad), not calculated if nullptr * @return dist, Geodesic length or distance from reference to second point (m) */ - SDKCORE_EXPORT double sodanoInverse(const double refLat, const double refLon, const double refAlt, const double lat, const double lon, double *azfwd=NULL, double *azbck=NULL); + SDKCORE_EXPORT double sodanoInverse(const double refLat, const double refLon, const double refAlt, const double lat, const double lon, double *azfwd=nullptr, double *azbck=nullptr); /** * @brief Calculates the Earth's radius at the given latitude @@ -512,9 +512,9 @@ namespace simCore * (for example) the optimum center position for fitting both points in a 3D view. * @param[out] midpoint Geodetic center position calculated by averaging the geodetic values. The altitude is given as the average of the input * altitudes and will not cut through the earth (unless one or more input values is below 0.0 altitude). - * @param[out] wrapsDateline Set to true if non-null and if the area wraps the antimeridian (dateline). NULL is acceptable. + * @param[out] wrapsDateline Set to true if non-null and if the area wraps the antimeridian (dateline). nullptr is acceptable. */ - SDKCORE_EXPORT void calculateGeodeticMidPoint(const Vec3& llaBgnPos, const Vec3& llaEndPos, bool highResolution, simCore::Vec3& midpoint, bool* wrapsDateline=NULL); + SDKCORE_EXPORT void calculateGeodeticMidPoint(const Vec3& llaBgnPos, const Vec3& llaEndPos, bool highResolution, simCore::Vec3& midpoint, bool* wrapsDateline=nullptr); /** * @brief Calculates flight path angles from an ENU geodetic velocity vector diff --git a/SDK/simCore/Calc/DatumConvert.cpp b/SDK/simCore/Calc/DatumConvert.cpp index 7ddb8868c..8f937d6ca 100644 --- a/SDK/simCore/Calc/DatumConvert.cpp +++ b/SDK/simCore/Calc/DatumConvert.cpp @@ -44,7 +44,7 @@ MagneticDatumConvert::MagneticDatumConvert() MagneticDatumConvert::~MagneticDatumConvert() { delete wmm_; - wmm_ = NULL; + wmm_ = nullptr; } double MagneticDatumConvert::convertMagneticDatum(const Vec3& lla, const TimeStamp& timeStamp, double bearingRad, diff --git a/SDK/simCore/Calc/Gars.h b/SDK/simCore/Calc/Gars.h index 3a8c7c2c6..ae91e0dce 100644 --- a/SDK/simCore/Calc/Gars.h +++ b/SDK/simCore/Calc/Gars.h @@ -55,7 +55,7 @@ class SDKCORE_EXPORT Gars * @param[out] key5 Optional int pointer set to 5 minute key specified in the GARS coordinate, if available * @return true if valid GARS coordinate string, false otherwise */ - static bool isValidGars(const std::string& gars, std::string* err = NULL, int* lonBand = NULL, int* latPrimaryIdx = NULL, int* latSecondaryIdx = NULL, int* quad15 = NULL, int* key5 = NULL); + static bool isValidGars(const std::string& gars, std::string* err = nullptr, int* lonBand = nullptr, int* latPrimaryIdx = nullptr, int* latSecondaryIdx = nullptr, int* quad15 = nullptr, int* key5 = nullptr); /** * Converts a GARS coordinate to geodetic coordinates. The resulting latitude/longitude @@ -66,7 +66,7 @@ class SDKCORE_EXPORT Gars * @param[out] err Optional pointer to error string * @return 0 if conversion is successful, non-zero otherwise */ - static int convertGarsToGeodetic(const std::string& gars, double& latRad, double& lonRad, std::string* err = NULL); + static int convertGarsToGeodetic(const std::string& gars, double& latRad, double& lonRad, std::string* err = nullptr); /** * Converts geodetic goordinates to a GARS coordinate. @@ -77,7 +77,7 @@ class SDKCORE_EXPORT Gars * @param[out] err Optional pointer to error string * @return 0 if conversion is successful, non-zero otherwise */ - static int convertGeodeticToGars(double latRad, double lonRad, std::string& garsOut, Level level = GARS_5, std::string* err = NULL); + static int convertGeodeticToGars(double latRad, double lonRad, std::string& garsOut, Level level = GARS_5, std::string* err = nullptr); }; } diff --git a/SDK/simCore/Calc/MagneticVariance.cpp b/SDK/simCore/Calc/MagneticVariance.cpp index 0a66c8bbf..4647db16a 100644 --- a/SDK/simCore/Calc/MagneticVariance.cpp +++ b/SDK/simCore/Calc/MagneticVariance.cpp @@ -740,12 +740,12 @@ WorldMagneticModel::WorldMagneticModel() WorldMagneticModel::~WorldMagneticModel() { delete geomag_; - geomag_ = NULL; + geomag_ = nullptr; } int WorldMagneticModel::calculateMagneticVariance(const simCore::Vec3& lla, int ordinalDay, int year, double& varianceRad) { - if (geomag_ == NULL) + if (geomag_ == nullptr) return 1; return geomag_->calculateVariance(lla, ordinalDay, year, varianceRad); } diff --git a/SDK/simCore/Calc/Math.cpp b/SDK/simCore/Calc/Math.cpp index 78a4621af..f5d44df70 100644 --- a/SDK/simCore/Calc/Math.cpp +++ b/SDK/simCore/Calc/Math.cpp @@ -87,9 +87,9 @@ void simCore::d3MMmult(const double a[][3], const double b[][3], double c[][3]) assert(b); assert(c); - if ((a == NULL) || (b == NULL) || (c == NULL)) + if ((a == nullptr) || (b == nullptr) || (c == nullptr)) { - if (c != NULL) + if (c != nullptr) { for (size_t ii = 0; ii < 3; ++ii) { @@ -126,7 +126,7 @@ void simCore::d3Mv3Mult(const double a[][3], const Vec3 &u, Vec3 &v) } assert(a); - if (a == NULL) + if (a == nullptr) { v.zero(); return; @@ -148,7 +148,7 @@ void simCore::d3MTv3Mult(const double a[][3], const Vec3 &u, Vec3 &v) } assert(a); - if (a == NULL) + if (a == nullptr) { v.zero(); return; @@ -166,9 +166,9 @@ void simCore::d3MMTmult(const double a[][3], const double b[][3], double c[][3]) assert(b); assert(c); - if ((a == NULL) || (b == NULL) || (c == NULL)) + if ((a == nullptr) || (b == nullptr) || (c == nullptr)) { - if (c != NULL) + if (c != nullptr) { for (size_t ii = 0; ii < 3; ++ii) { @@ -265,7 +265,7 @@ void simCore::d3DCMtoEuler(const double dcm[][3], Vec3 &ea) // asin returns in the range -pi/2 to pi/2 assert(dcm); - if (dcm == NULL) + if (dcm == nullptr) { ea.zero(); return; @@ -311,7 +311,7 @@ void simCore::d3EulertoDCM(const Vec3 &ea, double dcm[][3]) // theta, and finally a rotation about the body z through the yaw angle psi. assert(dcm); - if (dcm == NULL) + if (dcm == nullptr) return; // psi/yaw components @@ -361,7 +361,7 @@ void simCore::d3EulertoQ(const Vec3 &ea, double q[4]) // Results verified by Matlab: http://www.mathworks.com/matlabcentral/fileexchange/27653 assert(q); - if (q == NULL) + if (q == nullptr) return; // psi/yaw components @@ -406,7 +406,7 @@ void simCore::d3QtoEuler(const double q[4], Vec3 &ea) // Function expects a normalized quaternion in the form: q0 + q1i + q2j + q3k assert(q); - if (q == NULL) + if (q == nullptr) { ea.zero(); return; diff --git a/SDK/simCore/Calc/Math.h b/SDK/simCore/Calc/Math.h index 4253bade3..ba0cee86a 100644 --- a/SDK/simCore/Calc/Math.h +++ b/SDK/simCore/Calc/Math.h @@ -200,7 +200,7 @@ namespace simCore * Breaks up value into a mantissa (or significand) and exponent value, for base 10 * values. Returns mantissa such that mantissa * pow(10.0, exp) == value. * @param value Argument to represent in scientific notation. - * @param exp If non-NULL, will receive the exponent portion of the value. + * @param exp If not nullptr, will receive the exponent portion of the value. * @return Mantissa value. Will be 0.0 for input of 0.0. Otherwise, is a value with * an absolute value between [+1.0, +10.0) with a sign set appropriately. Negative * input values result in a negative return value. diff --git a/SDK/simCore/Calc/Mgrs.h b/SDK/simCore/Calc/Mgrs.h index 50891bfc9..5314693d0 100644 --- a/SDK/simCore/Calc/Mgrs.h +++ b/SDK/simCore/Calc/Mgrs.h @@ -53,7 +53,7 @@ class SDKCORE_EXPORT Mgrs * @param[out] err Optional pointer to error string * @return 0 if conversion is successful, non-zero otherwise */ - static int convertMgrsToGeodetic(const std::string& mgrs, double& lat, double& lon, std::string* err = NULL); + static int convertMgrsToGeodetic(const std::string& mgrs, double& lat, double& lon, std::string* err = nullptr); /** * Breaks an MGRS coordinate string into its components. @@ -67,7 +67,7 @@ class SDKCORE_EXPORT Mgrs * @return 0 if conversion is successful, non-zero otherwise */ static int breakMgrsString(const std::string& mgrs, int& zone, std::string& gzdLetters, double& easting, - double& northing, std::string* err = NULL); + double& northing, std::string* err = nullptr); /** * Converts an MGRS coordinate to geodetic coordinates. @@ -85,7 +85,7 @@ class SDKCORE_EXPORT Mgrs * @return 0 if conversion is successful, non-zero otherwise */ static int convertMgrsToUtm(int zone, const std::string& gzdLetters, double mgrsEasting, double mgrsNorthing, - bool& northPole, double& utmEasting, double& utmNorthing, std::string* err = NULL); + bool& northPole, double& utmEasting, double& utmNorthing, std::string* err = nullptr); /** * Converts a UTM coordinate to geodetic coordinates. @@ -102,7 +102,7 @@ class SDKCORE_EXPORT Mgrs * @param[out] err Optional pointer to error string * @return 0 if conversion is successful, non-zero otherwise */ - static int convertUtmToGeodetic(int zone, bool northPole, double easting, double northing, double& lat, double& lon, std::string* err = NULL); + static int convertUtmToGeodetic(int zone, bool northPole, double easting, double northing, double& lat, double& lon, std::string* err = nullptr); /** * Converts an MGRS coordinate to UPS coordinates. @@ -119,7 +119,7 @@ class SDKCORE_EXPORT Mgrs * @return 0 if conversion is successful, non-zero otherwise */ static int convertMgrsToUps(const std::string& gzdLetters, double mgrsEasting, double mgrsNorthing, - bool& northPole, double& upsEasting, double& upsNorthing, std::string* err = NULL); + bool& northPole, double& upsEasting, double& upsNorthing, std::string* err = nullptr); /** * Converts a UPS coordinate to geodetic coordinates. @@ -134,7 +134,7 @@ class SDKCORE_EXPORT Mgrs * @param[out] err Optional pointer to error string * @return 0 if conversion is successful, non-zero otherwise */ - static int convertUpsToGeodetic(bool northPole, double easting, double northing, double& lat, double& lon, std::string* err = NULL); + static int convertUpsToGeodetic(bool northPole, double easting, double northing, double& lat, double& lon, std::string* err = nullptr); private: diff --git a/SDK/simCore/Calc/SquareMatrix.cpp b/SDK/simCore/Calc/SquareMatrix.cpp index eae61ccb4..c7f10f866 100644 --- a/SDK/simCore/Calc/SquareMatrix.cpp +++ b/SDK/simCore/Calc/SquareMatrix.cpp @@ -149,7 +149,7 @@ std::vector SquareMatrix::column(unsigned int col) const const double* SquareMatrix::data() const { if (dimension_ < 2) - return NULL; + return nullptr; return matrix_.data(); } diff --git a/SDK/simCore/Calc/SquareMatrix.h b/SDK/simCore/Calc/SquareMatrix.h index 9649488cd..9c9c75acc 100644 --- a/SDK/simCore/Calc/SquareMatrix.h +++ b/SDK/simCore/Calc/SquareMatrix.h @@ -110,7 +110,7 @@ class SDKCORE_EXPORT SquareMatrix /** * Returns a pointer to the matrix data - * @return A pointer to the matrix data or a NULL pointer if the matrix is invalid + * @return A pointer to the matrix data or a nullptr if the matrix is invalid */ const double* data() const; diff --git a/SDK/simCore/Calc/UnitContext.cpp b/SDK/simCore/Calc/UnitContext.cpp index dfc4645aa..627ab54a2 100644 --- a/SDK/simCore/Calc/UnitContext.cpp +++ b/SDK/simCore/Calc/UnitContext.cpp @@ -228,7 +228,7 @@ void UnitContextAdapter::setReferenceYear(int refYear) void UnitContextAdapter::setDatumConvert(simCore::DatumConvertPtr datumConvert) { - if (datumConvert == NULL) + if (datumConvert == nullptr) datumConvert_.reset(new MagneticDatumConvert); else datumConvert_ = datumConvert; diff --git a/SDK/simCore/Calc/UnitContext.h b/SDK/simCore/Calc/UnitContext.h index 6be3107a7..eeb791d22 100644 --- a/SDK/simCore/Calc/UnitContext.h +++ b/SDK/simCore/Calc/UnitContext.h @@ -66,7 +66,7 @@ class SDKCORE_EXPORT UnitContext virtual MagneticVariance magneticVariance() const = 0; virtual VerticalDatum verticalDatum() const = 0; virtual int referenceYear() const = 0; - /** Note that return value may be NULL */ + /** Note that return value may be nullptr */ virtual simCore::DatumConvertPtr datumConvert() const = 0; ///@} diff --git a/SDK/simCore/Calc/Vec3.h b/SDK/simCore/Calc/Vec3.h index 1fa556520..270e9550a 100644 --- a/SDK/simCore/Calc/Vec3.h +++ b/SDK/simCore/Calc/Vec3.h @@ -51,7 +51,7 @@ namespace simCore */ explicit Vec3(const double v[3]) { - if (v == NULL) + if (v == nullptr) { zero(); return; @@ -101,7 +101,7 @@ namespace simCore /// Copy contents to a double[3] pointer void toD3(double dVec[3]) const { - if (dVec == NULL) return; + if (dVec == nullptr) return; dVec[0] = v[0]; dVec[1] = v[1]; dVec[2] = v[2]; } diff --git a/SDK/simCore/Common/Common.h b/SDK/simCore/Common/Common.h index d7e774624..63f5fc420 100644 --- a/SDK/simCore/Common/Common.h +++ b/SDK/simCore/Common/Common.h @@ -51,26 +51,6 @@ #define SDK_DEPRECATE(METHOD, TEXT) SDK_DEPRECATED_PRE(TEXT) METHOD SDK_DEPRECATED_POST(TEXT) -#ifdef USE_DEPRECATED_SIMDISSDK_API - -// set up define for whether member templates are supported by VisualStudio compilers. -#ifdef _MSC_VER - #if(_MSC_VER >= 1300) - #define __STL_MEMBER_TEMPLATES - #endif -#endif - -// Define NULL pointer value -#ifndef NULL - #ifdef __cplusplus - #define NULL 0 - #else - #define NULL ((void *)0) - #endif -#endif - -#endif /* USE_DEPRECATED_SIMDISSDK_API */ - #ifdef WIN32 #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN diff --git a/SDK/simCore/EM/AntennaPattern.cpp b/SDK/simCore/EM/AntennaPattern.cpp index 1e755a587..ca49b9bf3 100644 --- a/SDK/simCore/EM/AntennaPattern.cpp +++ b/SDK/simCore/EM/AntennaPattern.cpp @@ -131,7 +131,7 @@ AntennaPatternType antennaPatternType(const std::string& antPatStr) AntennaPattern* loadPatternFile(const std::string& filename, float freqMHz) { if (filename.empty()) - return NULL; + return nullptr; // algorithm keywords are all uppercase const std::string& algorithm = upperCase(filename); @@ -154,7 +154,7 @@ AntennaPattern* loadPatternFile(const std::string& filename, float freqMHz) if (antTable->readPat(filename) == 0) return antTable; delete antTable; - return NULL; + return nullptr; } if (extension == ANTENNA_STRING_EXTENSION_RELATIVE) { @@ -162,7 +162,7 @@ AntennaPattern* loadPatternFile(const std::string& filename, float freqMHz) if (antTable->readPat(filename) == 0) return antTable; delete antTable; - return NULL; + return nullptr; } if (extension == ANTENNA_STRING_EXTENSION_BILINEAR) { @@ -170,7 +170,7 @@ AntennaPattern* loadPatternFile(const std::string& filename, float freqMHz) if (bilinear->readPat(filename, (freqMHz*1e6)) == 0) return bilinear; delete bilinear; - return NULL; + return nullptr; } if (extension == ANTENNA_STRING_EXTENSION_CRUISE) { @@ -178,7 +178,7 @@ AntennaPattern* loadPatternFile(const std::string& filename, float freqMHz) if (antTable->readPat(filename) == 0) return antTable; delete antTable; - return NULL; + return nullptr; } if (extension == ANTENNA_STRING_EXTENSION_MONOPULSE) { @@ -186,7 +186,7 @@ AntennaPattern* loadPatternFile(const std::string& filename, float freqMHz) if (monopulse->readPat(filename, (freqMHz*1e6)) == 0) return monopulse; delete monopulse; - return NULL; + return nullptr; } if (extension == ANTENNA_STRING_EXTENSION_NSMA) { @@ -194,7 +194,7 @@ AntennaPattern* loadPatternFile(const std::string& filename, float freqMHz) if (antTable->readPat(filename) == 0) return antTable; delete antTable; - return NULL; + return nullptr; } if (extension == ANTENNA_STRING_EXTENSION_EZNEC) { @@ -202,7 +202,7 @@ AntennaPattern* loadPatternFile(const std::string& filename, float freqMHz) if (antTable->readPat(filename) == 0) return antTable; delete antTable; - return NULL; + return nullptr; } if (extension == ANTENNA_STRING_EXTENSION_XFDTD) { @@ -210,9 +210,9 @@ AntennaPattern* loadPatternFile(const std::string& filename, float freqMHz) if (antTable->readPat(filename) == 0) return antTable; delete antTable; - return NULL; + return nullptr; } - return NULL; + return nullptr; } // ---------------------------------------------------------------------------- @@ -1209,9 +1209,9 @@ AntennaPatternCRUISE::AntennaPatternCRUISE() elevMin_(0), azimStep_(0), elevStep_(0), - freqData_(NULL), - azimData_(NULL), - elevData_(NULL) + freqData_(nullptr), + azimData_(nullptr), + elevData_(nullptr) {} void AntennaPatternCRUISE::reset_() @@ -1238,9 +1238,9 @@ void AntennaPatternCRUISE::reset_() elevMin_= 0; azimStep_= 0; elevStep_= 0; - freqData_ = NULL; - azimData_ = NULL; - elevData_ = NULL; + freqData_ = nullptr; + azimData_ = nullptr; + elevData_ = nullptr; minGain_ = -SMALL_DB_VAL; maxGain_ = SMALL_DB_VAL; } diff --git a/SDK/simCore/EM/Decibel.h b/SDK/simCore/EM/Decibel.h index 601b1cf48..bce73ef9e 100644 --- a/SDK/simCore/EM/Decibel.h +++ b/SDK/simCore/EM/Decibel.h @@ -24,8 +24,8 @@ #define SIMCORE_EM_DECIBEL_H #include -#include #include +#include "simCore/Calc/MathConstants.h" namespace simCore { diff --git a/SDK/simCore/EM/Propagation.cpp b/SDK/simCore/EM/Propagation.cpp index 5501caa43..69e28264b 100644 --- a/SDK/simCore/EM/Propagation.cpp +++ b/SDK/simCore/EM/Propagation.cpp @@ -237,9 +237,9 @@ void getFreqMhzRange(FrequencyBandUsEcm usEcm, double* minFreqMhz, double* maxFr break; } - if (minFreqMhz != NULL) + if (minFreqMhz != nullptr) *minFreqMhz = minFreq; - if (maxFreqMhz != NULL) + if (maxFreqMhz != nullptr) *maxFreqMhz = maxFreq; return; @@ -367,9 +367,9 @@ void getFreqMhzRange(FrequencyBandIEEE ieeeEcm, double* minFreqMhz, double* maxF break; } - if (minFreqMhz != NULL) + if (minFreqMhz != nullptr) *minFreqMhz = minFreq; - if (maxFreqMhz != NULL) + if (maxFreqMhz != nullptr) *maxFreqMhz = maxFreq; return; diff --git a/SDK/simCore/EM/RadarCrossSection.cpp b/SDK/simCore/EM/RadarCrossSection.cpp index fdd0f36e5..9cedd278c 100644 --- a/SDK/simCore/EM/RadarCrossSection.cpp +++ b/SDK/simCore/EM/RadarCrossSection.cpp @@ -218,8 +218,8 @@ RCSLUT::RCSLUT() for (unsigned int i = 0; i < 2; ++i) { lastElev_[i] = std::numeric_limits::max(); - loTable_[i] = NULL; - hiTable_[i] = NULL; + loTable_[i] = nullptr; + hiTable_[i] = nullptr; } } @@ -238,9 +238,9 @@ RCSTable *RCSLUT::getTable_(float freq, float elev, PolarityType pol, bool creat POLARITY_FREQ_ELEV_MAP::iterator pfeiter; FREQ_ELEV_MAP::iterator feiter; ELEV_RCSTABLE_MAP::iterator eiter; - RCSTable *rcsTable = NULL; - FREQMAP* fm = NULL; - ELEVMAP* em = NULL; + RCSTable *rcsTable = nullptr; + FREQMAP* fm = nullptr; + ELEVMAP* em = nullptr; // look for specified polarization pfeiter = rcsMap_.find(pol); @@ -308,8 +308,8 @@ float RCSLUT::calcTableRCS_(float freq, double azim, double elev, PolarityType p return final_rcs; } - RCSTable *rcstabLo = NULL; - RCSTable *rcstabHi = NULL; + RCSTable *rcstabLo = nullptr; + RCSTable *rcstabHi = nullptr; bool foundInCache = false; if (simCore::areEqual(lastFreq_, freq, 0.1) && pol == lastPolarity_) { @@ -429,8 +429,8 @@ float RCSLUT::calcTableRCS_(float freq, double azim, double elev, PolarityType p else { // freq or polarization changed, cached elev/table values are no longer valid - loTable_[1] = NULL; - hiTable_[1] = NULL; + loTable_[1] = nullptr; + hiTable_[1] = nullptr; lastElev_[1] = std::numeric_limits::max(); } @@ -443,9 +443,9 @@ float RCSLUT::calcTableRCS_(float freq, double azim, double elev, PolarityType p } // either both tables are NULL, or both are non-NULL - assert((rcstabLo == NULL && rcstabHi == NULL) || (rcstabLo && rcstabHi)); + assert((rcstabLo == nullptr && rcstabHi == nullptr) || (rcstabLo && rcstabHi)); - if (rcstabLo == NULL && rcstabHi == NULL) + if (rcstabLo == nullptr && rcstabHi == nullptr) { // we didn't find any matching tables final_rcs = dB2Linear(mean_); @@ -534,7 +534,7 @@ float RCSLUT::RCSsm(float freq, double azim, double elev, PolarityType pol) int RCSLUT::loadXPATCHRCSFile_(std::istream &inFile) { int rv = 1; - RCSTable *rcsTable = NULL; + RCSTable *rcsTable = nullptr; std::vector medianVec; float freq = 0; float elev = 0; @@ -1229,7 +1229,7 @@ void RCSLUT::computeStatistics_(std::vector* medianVec) { if (!medianVec) { - // the argument cannot be NULL + // the argument cannot be nullptr assert(0); return; } @@ -1288,8 +1288,8 @@ void RCSLUT::reset_() for (unsigned int i = 0; i < 2; ++i) { lastElev_[i] = std::numeric_limits::max(); - loTable_[i] = NULL; - hiTable_[i] = NULL; + loTable_[i] = nullptr; + hiTable_[i] = nullptr; } mean_ = 0.; median_ = SMALL_DB_VAL; @@ -1354,13 +1354,13 @@ int RCSLUT::loadRCSFile(std::istream& istream) RadarCrossSection* RcsFileParser::loadRCSFile(const std::string& fname) { if (fname.empty()) - return NULL; + return nullptr; RCSLUT* rcsdata = new RCSLUT(); if (rcsdata->loadRCSFile(fname) != 0) { delete rcsdata; - rcsdata = NULL; + rcsdata = nullptr; } return rcsdata; diff --git a/SDK/simCore/EM/RadarCrossSection.h b/SDK/simCore/EM/RadarCrossSection.h index 9f2aefae6..a331d27d7 100644 --- a/SDK/simCore/EM/RadarCrossSection.h +++ b/SDK/simCore/EM/RadarCrossSection.h @@ -387,7 +387,7 @@ namespace simCore /** * This method opens a file stream and parses the RCS data * @param[in ] fname Input file name - * @return valid RadarCrossSection on success, NULL otherwise. + * @return valid RadarCrossSection on success, nullptr otherwise. */ static RadarCrossSection* loadRCSFile(const std::string& fname); }; diff --git a/SDK/simCore/String/FilePatterns.h b/SDK/simCore/String/FilePatterns.h index 8d2222f40..1821b57a6 100644 --- a/SDK/simCore/String/FilePatterns.h +++ b/SDK/simCore/String/FilePatterns.h @@ -293,19 +293,27 @@ static const std::string UDP_CAPTURE_FILE_PATTERNS = "Data Storage (*.dstor)\n" "All Files (*)"; -/** Dialog-oriented user-friendly list of SIMDIS 10 Settings files */ +/** Dialog-oriented user-friendly list of SIMDIS 10 Settings files, for loading */ +static const std::string SIMDIS10_SETTINGS_FILE_LOAD_PATTERNS = + "SIMDIS 10 Configuration Files (*.ini, *.ini.bak)\n" + "All Files (*)"; +/** Dialog-oriented user-friendly list of SIMDIS 10 Settings files, for saving */ static const std::string SIMDIS10_SETTINGS_FILE_PATTERNS = "SIMDIS 10 Configuration Files (*.ini)\n" "All Files (*)"; -/** Dialog-oriented user-friendly list of Plot-XY Settings files */ +/** Dialog-oriented user-friendly list of Plot-XY Settings files, for loading */ +static const std::string PLOT_SETTINGS_FILE_LOAD_PATTERNS = + "Plot-XY Configuration Files (*.ini, *.ini.bak)\n" + "All Files (*)"; +/** Dialog-oriented user-friendly list of Plot-XY Settings files, for saving */ static const std::string PLOT_SETTINGS_FILE_PATTERNS = "Plot-XY Configuration Files (*.ini)\n" "All Files (*)"; /** Combination of all data file patterns */ static const std::string ALL_DATA_FILE_PATTERNS = ALL_SIMDIS_FILE_PATTERNS + - std::string(",.prefs,.rul,.view,.rcs,.hdf5,") + + std::string(",*.prefs,*.rul,*.view,*.svml,*.rcs,*.hdf5,") + ALL_GOG_FILE_PATTERNS + std::string(",") + ALL_SIMDIS_TEXTURE_FILE_PATTERNS + std::string(",") + ALL_MEDIA_FILE_PATTERNS + std::string(",") + diff --git a/SDK/simCore/String/Format.cpp b/SDK/simCore/String/Format.cpp index e4b697069..147d5debe 100644 --- a/SDK/simCore/String/Format.cpp +++ b/SDK/simCore/String/Format.cpp @@ -22,6 +22,7 @@ */ #include #include +#include #include #include #include @@ -125,15 +126,22 @@ std::string buildString(const std::string &prefix, double value, size_t width, s const size_t realPrecision = simCore::sdkMin(precision, static_cast(16)); // scientific notation limit const double sciNoteGT2 = simCore::sdkMin(1e+80, sciNoteGT); - if ((value > sciNoteGT2) || (value < -sciNoteGT2) || - (value != 0.0 && value < sciNoteLT && value > -sciNoteLT)) - { + const bool useScientific = (value > sciNoteGT2) || (value < -sciNoteGT2) || + (value != 0.0 && value < sciNoteLT&& value > -sciNoteLT); + if (useScientific) strVal.setf(std::ios::scientific, std::ios::floatfield); - } else - { strVal.setf(std::ios::fixed, std::ios::floatfield); + +#if defined(NDEBUG) && defined(_MSC_VER) && _MSC_VER > 1922 + // Avoid processing in https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/printf-printf-l-wprintf-wprintf-l?view=vs-2019 + // due to bug reported in https://developercommunity.visualstudio.com/content/problem/1085732/different-printf-double-rounding-behaviour-between.html + if (!useScientific) + { + const double multFactor = std::pow(10.0, realPrecision); + value = simCore::rint(value * multFactor) / multFactor; } +#endif if (padZero) strVal << std::setfill('0') << std::setw(width) << std::setprecision(realPrecision) << value; diff --git a/SDK/simCore/String/UnitContextFormatter.cpp b/SDK/simCore/String/UnitContextFormatter.cpp index c893646c1..83ed15fef 100644 --- a/SDK/simCore/String/UnitContextFormatter.cpp +++ b/SDK/simCore/String/UnitContextFormatter.cpp @@ -36,7 +36,7 @@ namespace simCore { UnitContextFormatter::UnitContextFormatter(const UnitContext* unitsProvider) : unitsProvider_(unitsProvider) { - // If units provider is NULL, nothing in this class works + // If units provider is nullptr, nothing in this class works assert(unitsProvider_); } @@ -84,7 +84,7 @@ std::string UnitContextFormatter::formatAngle(double val, AngleExtents angleForm double UnitContextFormatter::rawAzimuth(const Vec3& lla, const simCore::TimeStamp& timeStamp, double az, CoordinateSystem coordSystem, double offset) const { - if (unitsProvider_->datumConvert() != NULL) + if (unitsProvider_->datumConvert() != nullptr) return unitsProvider_->datumConvert()->convertMagneticDatum(lla, timeStamp, az, coordSystem, MAGVAR_TRUE, unitsProvider_->magneticVariance(), offset); return az; } @@ -109,7 +109,7 @@ std::string UnitContextFormatter::formatAltitude(double alt) const double UnitContextFormatter::rawAltitude(const Vec3& lla, const TimeStamp& timeStamp, CoordinateSystem coordSystem, double offset, VerticalDatum outputDatum) const { - if (unitsProvider_->datumConvert() != NULL) + if (unitsProvider_->datumConvert() != nullptr) return unitsProvider_->datumConvert()->convertVerticalDatum(lla, timeStamp, coordSystem, VERTDATUM_WGS84, outputDatum, offset); return lla.alt(); } diff --git a/SDK/simCore/String/ValidNumber.cpp b/SDK/simCore/String/ValidNumber.cpp index e9e7b0dce..06beb7f66 100644 --- a/SDK/simCore/String/ValidNumber.cpp +++ b/SDK/simCore/String/ValidNumber.cpp @@ -94,9 +94,9 @@ bool isValidNumber(const std::string& token, uint64_t& val, bool permitSign) errno = 0; #ifdef WIN32 - val = _strtoui64(token.c_str(), NULL, 10); + val = _strtoui64(token.c_str(), nullptr, 10); #else - val = strtoull(token.c_str(), NULL, 10); + val = strtoull(token.c_str(), nullptr, 10); #endif if (errno != 0) { @@ -113,7 +113,7 @@ bool isValidNumber(const std::string& token, uint32_t& val, bool permitPlusToken errno = 0; unsigned long longVal = strtoul(token.c_str(), &end, 10); - // Error conditions are: Failed to convert, failed to end on a NULL, or having leading white space or leading minus sign + // Error conditions are: Failed to convert, failed to end on a nullptr, or having leading white space or leading minus sign if ((errno != 0) || (end == start) || (*end != '\0') || isspace(*start) || (*start == '-')) { val = 0; @@ -179,7 +179,7 @@ bool isValidNumber(const std::string& token, int64_t& val, bool permitPlusToken) #ifdef WIN32 val = _atoi64(token.c_str()); #else - val = strtoll(token.c_str(), NULL, 10); + val = strtoll(token.c_str(), nullptr, 10); #endif if (errno != 0) { @@ -196,7 +196,7 @@ bool isValidNumber(const std::string& token, int32_t& val, bool permitPlusToken) errno = 0; long longVal = strtol(token.c_str(), &end, 10); - // Error conditions are: Failed to convert, failed to end on a NULL, or having leading white space + // Error conditions are: Failed to convert, failed to end on a nullptr, or having leading white space if ((errno != 0) || (end == start) || (*end != '\0') || isspace(*start)) { val = 0; @@ -258,7 +258,7 @@ bool isValidNumber(const std::string& token, double& val, bool permitPlusToken) char* end; val = std::strtod(start, &end); - // Error conditions are: Failed to convert, failed to end on a NULL, or having leading white space + // Error conditions are: Failed to convert, failed to end on a nullptr, or having leading white space if ((end == start) || (*end != '\0') || (isspace(*start))) { val = 0.0; @@ -316,7 +316,7 @@ bool isValidHexNumber(const std::string& token, uint32_t& val, bool require0xPre errno = 0; unsigned long longVal = strtoul(token.c_str(), &end, 16); - // Error conditions are: Failed to convert, failed to end on a NULL, or having leading white space or leading minus sign + // Error conditions are: Failed to convert, failed to end on a nullptr, or having leading white space or leading minus sign if ((errno != 0) || (end == start) || (*end != '\0') || isspace(*start) || (*start == '-') || (*start == '+')) { val = 0; diff --git a/SDK/simCore/Time/ClockImpl.cpp b/SDK/simCore/Time/ClockImpl.cpp index 8981495ad..486562b16 100644 --- a/SDK/simCore/Time/ClockImpl.cpp +++ b/SDK/simCore/Time/ClockImpl.cpp @@ -1082,7 +1082,7 @@ void VisualizationClock::registerModeChangeCallback(Clock::ModeChangeObserverPtr { ClockWithObservers::registerModeChangeCallback(p); auto replayPtr = std::dynamic_pointer_cast(p); - if (replayPtr != NULL) + if (replayPtr != nullptr) { auto i = std::find(visClockObservers_.begin(), visClockObservers_.end(), p); if (i == visClockObservers_.end()) @@ -1094,7 +1094,7 @@ void VisualizationClock::removeModeChangeCallback(Clock::ModeChangeObserverPtr p { ClockWithObservers::removeModeChangeCallback(p); auto replayPtr = std::dynamic_pointer_cast(p); - if (replayPtr != NULL) + if (replayPtr != nullptr) { auto i = std::find(visClockObservers_.begin(), visClockObservers_.end(), replayPtr); if (i != visClockObservers_.end()) diff --git a/SDK/simCore/Time/Julian.cpp b/SDK/simCore/Time/Julian.cpp index dc4585ffa..50157aea5 100644 --- a/SDK/simCore/Time/Julian.cpp +++ b/SDK/simCore/Time/Julian.cpp @@ -41,7 +41,7 @@ int simCore::julianDay() time_t t(tp.tv_sec); pTime = gmtime(&t); - if (pTime == NULL) + if (pTime == nullptr) return std::numeric_limits::max(); // tm struct year days range from 0 to 365, Julian days are 1 to 366 diff --git a/SDK/simCore/Time/String.cpp b/SDK/simCore/Time/String.cpp index e82ea73f8..0a7c21f5a 100644 --- a/SDK/simCore/Time/String.cpp +++ b/SDK/simCore/Time/String.cpp @@ -678,14 +678,14 @@ TimeFormatterRegistry::~TimeFormatterRegistry() void TimeFormatterRegistry::registerCustomFormatter(TimeFormatterPtr formatter) { - if (formatter != NULL) + if (formatter != nullptr) foreignFormatters_.push_back(formatter); } const TimeFormatter& TimeFormatterRegistry::formatter(simCore::TimeFormat format) const { std::map::const_iterator i = knownFormatters_.find(format); - if (i != knownFormatters_.end() && i->second != NULL) + if (i != knownFormatters_.end() && i->second != nullptr) return *i->second; return *nullFormatter_; } diff --git a/SDK/simCore/Time/Utils.cpp b/SDK/simCore/Time/Utils.cpp index 5994a6014..df916d683 100644 --- a/SDK/simCore/Time/Utils.cpp +++ b/SDK/simCore/Time/Utils.cpp @@ -47,7 +47,7 @@ int simCore::currentYear() const time_t t(tp.tv_sec); const struct tm* pTime = gmtime(&t); - if (pTime == NULL) + if (pTime == nullptr) return std::numeric_limits::max(); // years are stored as values since 1900 @@ -81,7 +81,7 @@ double simCore::systemTimeToSecsBgnYr() const time_t t(tp.tv_sec); const struct tm* pTime = gmtime(&t); - if (pTime == NULL) + if (pTime == nullptr) return std::numeric_limits::max(); // assemble a UTC "system time" @@ -107,7 +107,7 @@ void simCore::systemTimeToSecsBgnYr(unsigned int &pSecs, unsigned short &pMillis const time_t t(tp.tv_sec); const struct tm* pTime = gmtime(&t); - if (pTime == NULL) + if (pTime == nullptr) { pSecs = std::numeric_limits::max(); pMillisec = std::numeric_limits::max(); @@ -138,7 +138,7 @@ double simCore::systemTimeToSecsBgnDay() time_t t(tp.tv_sec); struct tm* pTime = gmtime(&t); - if (pTime == NULL) + if (pTime == nullptr) return std::numeric_limits::max(); // assemble a UTC "system time" @@ -160,7 +160,7 @@ void simCore::timeSinceJan1970ToSecsBgnYr(double timeSinceJan1970, unsigned int time_t t(seconds); const struct tm* pTime = gmtime(&t); - if (pTime == NULL) + if (pTime == nullptr) { // timeSinceJan1970 is invalid pSecs = 0; @@ -526,7 +526,7 @@ std::string simCore::getTimeComponents(double time, unsigned int *day, unsigned } //------------------------------------------------------------------------ -#ifdef USE_DEPRECATED_SIMDISSDK_API + void simCore::normalizeTime(int &refYear, double &secondsSinceRefYear) { assert(refYear > 1900); @@ -571,7 +571,6 @@ void simCore::normalizeTime(int &refYear, double &secondsSinceRefYear) secondsSinceRefYear = simCore::getTimeStructDifferenceInSeconds(epochTime, timeval); } } -#endif double simCore::getNextTimeStep(bool faster, double lastStep) { diff --git a/SDK/simCore/Time/Utils.h b/SDK/simCore/Time/Utils.h index 2df20da5d..4a85f7b2b 100644 --- a/SDK/simCore/Time/Utils.h +++ b/SDK/simCore/Time/Utils.h @@ -273,9 +273,7 @@ namespace simCore * @pre refYear and secondsSinceRefYear valid params * @deprecated */ -#ifdef USE_DEPRECATED_SIMDISSDK_API SDK_DEPRECATE(SDKCORE_EXPORT void normalizeTime(int &refYear, double &secondsSinceRefYear), "Method will be removed in a future SDK release"); -#endif /** * Algorithm to get a new time step based on a step up or step down from a given step value * Calculates the proper step to use when stepping up or down from a time step diff --git a/SDK/simData/CategoryData/CategoryFilter.cpp b/SDK/simData/CategoryData/CategoryFilter.cpp index a95ad01c3..972cbfc1f 100644 --- a/SDK/simData/CategoryData/CategoryFilter.cpp +++ b/SDK/simData/CategoryData/CategoryFilter.cpp @@ -92,8 +92,8 @@ CategoryFilter::CategoryFilter(simData::DataStore* dataStore, bool autoUpdate) if (autoUpdate_) { // Does nothing without a datastore - assert(dataStore != NULL); - if (dataStore_ == NULL) + assert(dataStore != nullptr); + if (dataStore_ == nullptr) return; buildCategoryFilter_(true, true, true, true); @@ -120,7 +120,7 @@ CategoryFilter::CategoryFilter(const CategoryFilter& other) CategoryFilter::~CategoryFilter() { - if ((dataStore_ != NULL) && (listenerPtr_ != NULL)) + if ((dataStore_ != nullptr) && (listenerPtr_ != nullptr)) dataStore_->categoryNameManager().removeListener(listenerPtr_); } @@ -135,7 +135,7 @@ CategoryFilter& CategoryFilter::assign(const CategoryFilter& other, bool copyAut return *this; // Clear the listener pointer unconditionally - if ((dataStore_ != NULL) && (listenerPtr_ != NULL)) + if ((dataStore_ != nullptr) && (listenerPtr_ != nullptr)) { dataStore_->categoryNameManager().removeListener(listenerPtr_); listenerPtr_.reset(); @@ -146,10 +146,10 @@ CategoryFilter& CategoryFilter::assign(const CategoryFilter& other, bool copyAut categoryCheck_ = other.categoryCheck_; categoryRegExp_ = other.categoryRegExp_; - if (dataStore_ != NULL && autoUpdate_) + if (dataStore_ != nullptr && autoUpdate_) { // re-add observers/listeners - assert(listenerPtr_ == NULL); + assert(listenerPtr_ == nullptr); listenerPtr_.reset(new CategoryFilterListener(this)); dataStore_->categoryNameManager().addListener(listenerPtr_); } @@ -373,13 +373,13 @@ void CategoryFilter::setCategoryRegExp(int nameInt, const simData::RegExpFilterP // new entry, add to the map if this is a non-empty string if (nameIter == categoryRegExp_.end()) { - if (regExp != NULL && !regExp->pattern().empty()) + if (regExp != nullptr && !regExp->pattern().empty()) categoryRegExp_[nameInt] = regExp; return; } // update the expression if non-empty, remove if empty - if (regExp != NULL && !regExp->pattern().empty()) + if (regExp != nullptr && !regExp->pattern().empty()) nameIter->second = regExp; else removeName(nameInt); @@ -387,7 +387,7 @@ void CategoryFilter::setCategoryRegExp(int nameInt, const simData::RegExpFilterP bool CategoryFilter::match(uint64_t entityId) const { - if (dataStore_ == NULL) + if (dataStore_ == nullptr) return true; CurrentCategoryValues curCategoryData; CategoryFilter::getCurrentCategoryValues(*dataStore_, entityId, curCategoryData); @@ -499,7 +499,7 @@ bool CategoryFilter::matchData(const CurrentCategoryValues& curCategoryData) con bool CategoryFilter::matchRegExpFilter_(const CurrentCategoryValues& curCategoryData) const { // no failure if no regular expressions - if (categoryRegExp_.empty() || dataStore_ == NULL) + if (categoryRegExp_.empty() || dataStore_ == nullptr) return true; CurrentCategoryValues::const_iterator curCategoryDataIter; // first, check the reg exp, since this is likely to be more comprehensive @@ -528,7 +528,7 @@ bool CategoryFilter::matchRegExpFilter_(const CurrentCategoryValues& curCategory std::string CategoryFilter::serialize(bool simplify) const { - if (dataStore_ == NULL) + if (dataStore_ == nullptr) return " "; simData::CategoryNameManager& catNameMgr = dataStore_->categoryNameManager(); @@ -554,7 +554,7 @@ std::string CategoryFilter::serialize(bool simplify) const for (auto regIter = categoryRegExpCopy.begin(); regIter != categoryRegExpCopy.end(); ++regIter) { // Skip this regexp if it's not valid - if (regIter->second == NULL || regIter->second->pattern().empty()) + if (regIter->second == nullptr || regIter->second->pattern().empty()) continue; auto catIter = categoryCheckCopy.find(regIter->first); @@ -633,7 +633,7 @@ std::string CategoryFilter::serialize(bool simplify) const ///@return false on fail bool CategoryFilter::deserialize(const std::string &checksString, bool skipEmptyCategories, RegExpFilterFactory* regExpFactory) { - if (dataStore_ == NULL) + if (dataStore_ == nullptr) return false; categoryCheck_.clear(); @@ -897,7 +897,7 @@ void CategoryFilter::simplifyRegExp_(CategoryFilter::CategoryRegExp& regExps) co { for (auto i = regExps.begin(); i != regExps.end(); /* no increment */) { - if (i->second == NULL || i->second->pattern().empty()) + if (i->second == nullptr || i->second->pattern().empty()) regExps.erase(i++); else ++i; @@ -909,7 +909,7 @@ void CategoryFilter::simplify_(CategoryFilter::CategoryCheck& checks) const // Remove all categories that have a non-empty regular expression for (auto i = categoryRegExp_.begin(); i != categoryRegExp_.end(); ++i) { - if (i->second != NULL && !i->second->pattern().empty()) + if (i->second != nullptr && !i->second->pattern().empty()) checks.erase(i->first); } simplifyValues_(checks); @@ -926,7 +926,7 @@ void CategoryFilter::simplify(int categoryName) if (refIter != categoryRegExp_.end()) { // Clean up categoryRegExp_ first - if (refIter->second == NULL || refIter->second->pattern().empty()) + if (refIter->second == nullptr || refIter->second->pattern().empty()) categoryRegExp_.erase(refIter); else if (i != categoryCheck_.end()) { @@ -1046,7 +1046,7 @@ void CategoryFilter::getValues(int nameInt, ValuesCheck& checks) const const simData::RegExpFilter* CategoryFilter::getRegExp(int nameInt) const { auto i = categoryRegExp_.find(nameInt); - return (i == categoryRegExp_.end() ? NULL : i->second.get()); + return (i == categoryRegExp_.end() ? nullptr : i->second.get()); } std::string CategoryFilter::getRegExpPattern(int nameInt) const diff --git a/SDK/simData/CategoryData/CategoryFilter.h b/SDK/simData/CategoryData/CategoryFilter.h index b735991d6..1200b8dcf 100644 --- a/SDK/simData/CategoryData/CategoryFilter.h +++ b/SDK/simData/CategoryData/CategoryFilter.h @@ -240,7 +240,7 @@ class SDKDATA_EXPORT CategoryFilter /** * Set the regExp for the specified category name. This regular expression will be used to match against the value - * for this category name. Pass in NULL or a RegExp with empty string to remove the entry for the specified category + * for this category name. Pass in nullptr or a RegExp with empty string to remove the entry for the specified category * name. Note that when a regular expression is set for a category, the regular expression supersedes * any category checkmarks for that category name. * @param[in] nameInt int value of the category name @@ -275,7 +275,7 @@ class SDKDATA_EXPORT CategoryFilter * @param checksString serialization of the category filter * @param skipEmptyCategories if true, optimize filter by skipping unchecked categories * @param regExpFactory Factory to use for generating regular expressions in the checks string. If - * NULL, then filters with regular expressions will not be parsed properly. + * nullptr, then filters with regular expressions will not be parsed properly. * @return true on success, false if there is any problem */ bool deserialize(const std::string &checksString, bool skipEmptyCategories, RegExpFilterFactory* regExpFactory); @@ -309,7 +309,7 @@ class SDKDATA_EXPORT CategoryFilter void getNames(std::vector& names) const; /** Retrieves the values associated with the name. This may be empty if a regular expression is applied to the name. */ void getValues(int nameInt, ValuesCheck& checks) const; - /** Retrieves the values regular expression for the given name int. May be NULL if not set. */ + /** Retrieves the values regular expression for the given name int. May be nullptr if not set. */ const simData::RegExpFilter* getRegExp(int nameInt) const; /** Retrieves the values regular expression string for the given name int. May be empty string if not set. */ std::string getRegExpPattern(int nameInt) const; diff --git a/SDK/simData/CategoryData/MemoryCategoryDataSlice.cpp b/SDK/simData/CategoryData/MemoryCategoryDataSlice.cpp index 2ba5806a7..05987ba8b 100644 --- a/SDK/simData/CategoryData/MemoryCategoryDataSlice.cpp +++ b/SDK/simData/CategoryData/MemoryCategoryDataSlice.cpp @@ -534,7 +534,7 @@ class MemoryCategoryDataSlice::Iterator : public CategoryDataSlice::IteratorImpl //---------------------------------------------------------------------------- MemoryCategoryDataSlice::MemoryCategoryDataSlice(double timeStamp) : lastUpdateTime_(timeStamp), - categoryNameManager_(NULL), + categoryNameManager_(nullptr), sliceSize_(0) { } diff --git a/SDK/simData/DataSlice.h b/SDK/simData/DataSlice.h index f668b8555..2d9563168 100644 --- a/SDK/simData/DataSlice.h +++ b/SDK/simData/DataSlice.h @@ -186,9 +186,9 @@ class DataSlice : public VisitableDataSlice /** * Retrieve the bounds used to compute the interpolated value * The bounds are represented as a std::pair containing const pointers - * If the value is not interpolated, the values in the pair could be NULL + * If the value is not interpolated, the values in the pair could be nullptr */ - virtual Bounds interpolationBounds() const { return Bounds(static_cast(NULL), static_cast(NULL)); } + virtual Bounds interpolationBounds() const { return Bounds(static_cast(nullptr), static_cast(nullptr)); } /// Earliest time in the update slice, or DBL_MAX if none virtual double firstTime() const = 0; diff --git a/SDK/simData/DataSliceUpdaters.h b/SDK/simData/DataSliceUpdaters.h index 99c74adff..4b3440896 100644 --- a/SDK/simData/DataSliceUpdaters.h +++ b/SDK/simData/DataSliceUpdaters.h @@ -150,7 +150,7 @@ class Interpolator; /** * Update slices to the specified time, using interpolation as needed. - * All pointers must point to valid values, NULL values are not valid. + * All pointers must point to valid values, nullptr values are not valid. */ template @@ -161,8 +161,8 @@ T *computeTimeUpdate(ForwardIterator begin, ForwardIterator& currentIt, ForwardI if (begin == end) { *isInterpolated = false; - *bounds = B(static_cast(NULL), static_cast(NULL)); - return NULL; + *bounds = B(static_cast(nullptr), static_cast(nullptr)); + return nullptr; } currentIt = computeUpperBound(begin, currentIt, end, time); @@ -175,7 +175,7 @@ T *computeTimeUpdate(ForwardIterator begin, ForwardIterator& currentIt, ForwardI // Closest update is the last point T *current = *(--currentIt); *isInterpolated = false; - *bounds = B(static_cast(NULL), static_cast(NULL)); + *bounds = B(static_cast(nullptr), static_cast(nullptr)); return current; } @@ -183,8 +183,8 @@ T *computeTimeUpdate(ForwardIterator begin, ForwardIterator& currentIt, ForwardI if (currentIt == begin) { *isInterpolated = false; - *bounds = B(static_cast(NULL), static_cast(NULL)); - return NULL; + *bounds = B(static_cast(nullptr), static_cast(nullptr)); + return nullptr; } // time is between points @@ -195,7 +195,7 @@ T *computeTimeUpdate(ForwardIterator begin, ForwardIterator& currentIt, ForwardI if (simCore::areEqual(time, (*currentIt)->time())) { *isInterpolated = false; - *bounds = B(static_cast(NULL), static_cast(NULL)); + *bounds = B(static_cast(nullptr), static_cast(nullptr)); return (*currentIt); } diff --git a/SDK/simData/DataStore.cpp b/SDK/simData/DataStore.cpp index 059c94977..36fdc9e6e 100644 --- a/SDK/simData/DataStore.cpp +++ b/SDK/simData/DataStore.cpp @@ -52,7 +52,7 @@ DataStore::Transaction& DataStore::Transaction::operator=(const Transaction &rhs void DataStore::Transaction::commit() { - assert(transaction_.get() != NULL); + assert(transaction_.get() != nullptr); transaction_->commit(); } diff --git a/SDK/simData/DataStore.h b/SDK/simData/DataStore.h index bba1003cc..5b200fbe6 100644 --- a/SDK/simData/DataStore.h +++ b/SDK/simData/DataStore.h @@ -105,7 +105,7 @@ class SDKDATA_EXPORT DataStore * committed or has gone out of scope. An attempt to enforce this behavior * has been made by requiring the reference to the object associated with the * transaction to be provided as an argument when releasing or canceling a - * transaction, so that it may be set to NULL. + * transaction, so that it may be set to nullptr. */ class SDKDATA_EXPORT Transaction { @@ -130,9 +130,9 @@ class SDKDATA_EXPORT DataStore template void release(T **operand) { - assert(transaction_.get() != NULL); + assert(transaction_.get() != nullptr); transaction_->release(); - *operand = NULL; + *operand = nullptr; } /// complete the transaction by committing it and releasing it; equivalent to commit followed by release @@ -166,7 +166,10 @@ class SDKDATA_EXPORT DataStore virtual void onPrefsChange(DataStore *source, ObjectId id) = 0; /// current time has been changed - virtual void onTimeChange(DataStore *source) = 0; + SDK_DEPRECATE(virtual void onTimeChange(DataStore *source) {}, "Method has been replaced with onChange()"); + + /// data store has changed, this includes both time change and/or data change; called a max of once per frame + virtual void onChange(DataStore *source) = 0; /// something has changed in the entity category data virtual void onCategoryDataChange(DataStore *source, ObjectId changedId, simData::ObjectType ot) = 0; @@ -200,8 +203,8 @@ class SDKDATA_EXPORT DataStore /// prefs for the given entity have been changed virtual void onPrefsChange(DataStore *source, ObjectId id) {} - /// current time has been changed - virtual void onTimeChange(DataStore *source) {} + /// data store has changed + virtual void onChange(DataStore *source) {} /// something has changed in the entity category data virtual void onCategoryDataChange(DataStore *source, ObjectId changedId, simData::ObjectType ot) {} @@ -394,7 +397,7 @@ class SDKDATA_EXPORT DataStore /// Specify the interpolator to use virtual void setInterpolator(Interpolator *interpolator) = 0; - /// Get the current interpolator (NULL if disabled) + /// Get the current interpolator (nullptr if disabled) virtual Interpolator* interpolator() const = 0; ///@} @@ -439,14 +442,14 @@ class SDKDATA_EXPORT DataStore ///@} /**@name Scenario Properties - * @note should always return a valid object (never NULL) + * @note should always return a valid object (never nullptr) * @{ */ virtual const ScenarioProperties* scenarioProperties(Transaction *transaction) const = 0; virtual ScenarioProperties* mutable_scenarioProperties(Transaction *transaction) = 0; /**@name Object Properties - * @note will return NULL if no object is associated with the specified id + * @note will return nullptr if no object is associated with the specified id * @{ */ virtual const PlatformProperties* platformProperties(ObjectId id, Transaction *transaction) const = 0; @@ -466,7 +469,7 @@ class SDKDATA_EXPORT DataStore ///@} /**@name Object Preferences - * @note will return NULL if no object is associated with the specified id + * @note will return nullptr if no object is associated with the specified id * @{ */ virtual const PlatformPrefs* platformPrefs(ObjectId id, Transaction *transaction) const = 0; @@ -549,7 +552,7 @@ class SDKDATA_EXPORT DataStore virtual int removeGenericDataTag(ObjectId id, const std::string& tag) = 0; /**@name Add data update, command, generic data, or category data - *@note Returns NULL if platform for specified ID does not exist + *@note Returns nullptr if platform for specified ID does not exist * @{ */ virtual PlatformUpdate * addPlatformUpdate(ObjectId id, Transaction *transaction) = 0; @@ -626,7 +629,7 @@ class SDKDATA_EXPORT DataStore /**@name NewUpdatesListener * @{ */ - /// Sets a listener for when entity updates are added; use NULL to remove. + /// Sets a listener for when entity updates are added; use nullptr to remove. virtual void setNewUpdatesListener(NewUpdatesListenerPtr callback) = 0; ///@} diff --git a/SDK/simData/DataStoreHelpers.cpp b/SDK/simData/DataStoreHelpers.cpp index 4dee0f52b..a725963d2 100644 --- a/SDK/simData/DataStoreHelpers.cpp +++ b/SDK/simData/DataStoreHelpers.cpp @@ -29,7 +29,7 @@ namespace simData { std::string DataStoreHelpers::nameFromId(const ObjectId& objectId, const simData::DataStore* dataStore) { - if (dataStore == NULL) + if (dataStore == nullptr) return ""; simData::DataStore::Transaction transaction; const simData::CommonPrefs* prefs = dataStore->commonPrefs(objectId, &transaction); @@ -38,7 +38,7 @@ std::string DataStoreHelpers::nameFromId(const ObjectId& objectId, const simData std::string DataStoreHelpers::aliasFromId(const ObjectId& objectId, const simData::DataStore* dataStore) { - if (dataStore == NULL) + if (dataStore == nullptr) return ""; simData::DataStore::Transaction transaction; const simData::CommonPrefs* prefs = dataStore->commonPrefs(objectId, &transaction); @@ -47,12 +47,12 @@ std::string DataStoreHelpers::aliasFromId(const ObjectId& objectId, const simDat std::string DataStoreHelpers::nameOrAliasFromId(const ObjectId& objectId, const simData::DataStore* dataStore, bool allowBlankAlias) { - if (dataStore == NULL) + if (dataStore == nullptr) return ""; simData::DataStore::Transaction transaction; const simData::CommonPrefs* prefs = dataStore->commonPrefs(objectId, &transaction); - if (prefs == NULL) + if (prefs == nullptr) return ""; if (prefs->usealias()) @@ -125,7 +125,7 @@ std::string DataStoreHelpers::typeToString(simData::ObjectType entityType) std::string DataStoreHelpers::typeFromId(ObjectId objectId, const simData::DataStore* dataStore) { - if (dataStore == NULL) + if (dataStore == nullptr) return ""; return typeToString(dataStore->objectType(objectId)); } @@ -158,7 +158,7 @@ std::string DataStoreHelpers::fullTypeToString(simData::ObjectType entityType) std::string DataStoreHelpers::fullTypeFromId(ObjectId objectId, const simData::DataStore* dataStore) { - if (dataStore == NULL) + if (dataStore == nullptr) return ""; simData::DataStore::Transaction transaction; return fullTypeToString(dataStore->objectType(objectId)); @@ -166,7 +166,7 @@ std::string DataStoreHelpers::fullTypeFromId(ObjectId objectId, const simData::D uint64_t DataStoreHelpers::originalIdFromId(ObjectId objectId, const simData::DataStore* dataStore) { - if (dataStore == NULL) + if (dataStore == nullptr) return 0; simData::ObjectType objType = dataStore->objectType(objectId); simData::DataStore::Transaction transaction; @@ -224,7 +224,7 @@ uint64_t DataStoreHelpers::originalIdFromId(ObjectId objectId, const simData::Da ObjectId DataStoreHelpers::idByName(const std::string& objectName, const simData::DataStore* dataStore) { - if (dataStore == NULL) + if (dataStore == nullptr) return 0; simData::DataStore::IdList ids; dataStore->idListByName(objectName, &ids); @@ -235,7 +235,7 @@ ObjectId DataStoreHelpers::idByName(const std::string& objectName, const simData ObjectId DataStoreHelpers::getPlatformHostId(ObjectId objectId, const simData::DataStore* dataStore) { - if (dataStore == NULL) + if (dataStore == nullptr) return 0; while (dataStore->objectType(objectId) != simData::PLATFORM) @@ -251,7 +251,7 @@ ObjectId DataStoreHelpers::getPlatformHostId(ObjectId objectId, const simData::D std::string DataStoreHelpers::description(const simData::DataStore* dataStore) { - if (dataStore == NULL) + if (dataStore == nullptr) return 0; simData::DataStore::Transaction transaction; return dataStore->scenarioProperties(&transaction)->description(); @@ -282,12 +282,12 @@ google::protobuf::Message* DataStoreHelpers::makeMessage(simData::ObjectType ent } assert(false); - return NULL; + return nullptr; } int DataStoreHelpers::addMediaFile(const std::string& fileName, simData::DataStore* dataStore) { - if (dataStore == NULL) + if (dataStore == nullptr) return 1; if (fileName.empty()) @@ -295,7 +295,7 @@ int DataStoreHelpers::addMediaFile(const std::string& fileName, simData::DataSto simData::DataStore::Transaction transaction; simData::ScenarioProperties* props = dataStore->mutable_scenarioProperties(&transaction); - if (props != NULL) + if (props != nullptr) { // Prevent duplicates. for (int ii = 0; ii < props->mediafile_size(); ++ii) @@ -319,18 +319,18 @@ int DataStoreHelpers::addMediaFile(const std::string& fileName, simData::DataSto simData::DataTable* DataStoreHelpers::getOrCreateDataTable(ObjectId objectId, const std::string& tableName, simData::DataStore* dataStore) { - if ((dataStore->objectType(objectId) == simData::NONE) || tableName.empty() || (dataStore == NULL)) - return NULL; + if ((dataStore->objectType(objectId) == simData::NONE) || tableName.empty() || (dataStore == nullptr)) + return nullptr; simData::DataTableManager& tableManager = dataStore->dataTableManager(); simData::DataTable* table = tableManager.findTable(objectId, tableName); // if failed to find the table, create the table. - if (table == NULL) + if (table == nullptr) { simData::TableStatus status = tableManager.addDataTable(objectId, tableName, &table); if (status.isError()) - return NULL; + return nullptr; } return table; @@ -339,7 +339,7 @@ simData::DataTable* DataStoreHelpers::getOrCreateDataTable(ObjectId objectId, co int DataStoreHelpers::getOrCreateColumn(simData::DataTable* table, const std::string& columnName, VariableType storageType, UnitType unitType, simData::DataStore* dataStore, simData::TableColumnId& id) { - if ((table == NULL) || columnName.empty() || (dataStore == NULL)) + if ((table == nullptr) || columnName.empty() || (dataStore == nullptr)) return 1; simData::TableColumn* column = table->column(columnName); @@ -350,7 +350,7 @@ int DataStoreHelpers::getOrCreateColumn(simData::DataTable* table, const std::st } // if failed to find the column, create the column - simData::TableColumn* newColumn = NULL; + simData::TableColumn* newColumn = nullptr; if (table->addColumn(columnName, storageType, unitType, &newColumn).isError()) return 1; @@ -367,7 +367,7 @@ namespace { { simData::DataStore::Transaction txn; const simData::CommonPrefs* prefs = dataStore.commonPrefs(objectId, &txn); - if (prefs != NULL) + if (prefs != nullptr) { return prefs->datadraw(); } @@ -376,7 +376,7 @@ namespace { } const simData::PlatformUpdateSlice* slice = dataStore.platformUpdateSlice(objectId); - if (slice == NULL) + if (slice == nullptr) return false; // static platforms are always active @@ -399,7 +399,7 @@ namespace { return false; const simData::BeamCommandSlice* slice = dataStore.beamCommandSlice(objectId); - if (slice == NULL) + if (slice == nullptr) return false; // Check the draw state @@ -449,7 +449,7 @@ namespace { return false; const simData::GateCommandSlice* slice = dataStore.gateCommandSlice(objectId); - if (slice == NULL) + if (slice == nullptr) return false; // Check the draw state @@ -477,7 +477,7 @@ namespace { return false; const simData::LaserCommandSlice* slice = dataStore.laserCommandSlice(objectId); - if (slice == NULL) + if (slice == nullptr) return false; // Check the draw state @@ -519,7 +519,7 @@ bool isCustomRenderingActive(const simData::DataStore& dataStore, simData::Objec return false; const auto* slice = dataStore.customRenderingCommandSlice(objectId); - if (slice == NULL) + if (slice == nullptr) return false; // Check the draw state @@ -584,7 +584,7 @@ double DataStoreHelpers::getUserVerticalDatum(const simData::DataStore& dataStor { simData::DataStore::Transaction transaction; auto sp = dataStore.scenarioProperties(&transaction); - if ((sp != NULL) && sp->has_coordinateframe()) + if ((sp != nullptr) && sp->has_coordinateframe()) return sp->coordinateframe().verticaldatumuservalue(); return 0.0; } @@ -592,7 +592,7 @@ double DataStoreHelpers::getUserVerticalDatum(const simData::DataStore& dataStor simData::ObjectId platformId = simData::DataStoreHelpers::getPlatformHostId(id, &dataStore); simData::DataStore::Transaction transaction; const simData::PlatformProperties* prop = dataStore.platformProperties(platformId, &transaction); - if (prop != NULL) + if (prop != nullptr) return prop->coordinateframe().verticaldatumuservalue(); return 0.0; } diff --git a/SDK/simData/DataStoreHelpers.h b/SDK/simData/DataStoreHelpers.h index b6e425abc..803687e22 100644 --- a/SDK/simData/DataStoreHelpers.h +++ b/SDK/simData/DataStoreHelpers.h @@ -66,7 +66,7 @@ class SDKDATA_EXPORT DataStoreHelpers static std::string description(const simData::DataStore* dataStore); /// Adds a media file if not already in the dataStore, the argument fileName must be full path. Returns zero on success. static int addMediaFile(const std::string& fileName, simData::DataStore* dataStore); - /// Gets or creates a table for the given object with the given name; returns NULL on error + /// Gets or creates a table for the given object with the given name; returns nullptr on error static simData::DataTable* getOrCreateDataTable(ObjectId objectId, const std::string& tableName, simData::DataStore* dataStore); /// Gets or creates a column for the given table with the given name; return 0 on success static int getOrCreateColumn(simData::DataTable* table, const std::string& columnName, VariableType storageType, UnitType unitType, simData::DataStore* dataStore, simData::TableColumnId& id); diff --git a/SDK/simData/DataStoreProxy.cpp b/SDK/simData/DataStoreProxy.cpp index eda79e632..cd5551ed5 100644 --- a/SDK/simData/DataStoreProxy.cpp +++ b/SDK/simData/DataStoreProxy.cpp @@ -29,7 +29,7 @@ namespace simData DataStoreProxy::DataStoreProxy(DataStore* dataStore) : dataStore_(dataStore), - interpolator_(NULL) + interpolator_(nullptr) { assert(dataStore_); } @@ -40,7 +40,7 @@ void DataStoreProxy::reset(DataStore* newDataStore) return; // only capture old internals if there is somewhere new to put them - InternalsMemento *oldInternals = newDataStore ? dataStore_->createInternalsMemento() : NULL; + InternalsMemento *oldInternals = newDataStore ? dataStore_->createInternalsMemento() : nullptr; DataStore *const oldDataStore = dataStore_; dataStore_ = newDataStore; @@ -72,7 +72,7 @@ void DataStoreProxy::setInterpolator(Interpolator *interpolator) Interpolator* DataStoreProxy::interpolator() const { - return isInterpolationEnabled() ? interpolator_ : NULL; + return isInterpolationEnabled() ? interpolator_ : nullptr; } void DataStoreProxy::addListener(DataStore::ListenerPtr callback) diff --git a/SDK/simData/DataStoreProxy.h b/SDK/simData/DataStoreProxy.h index 5916d7b31..617d816fa 100644 --- a/SDK/simData/DataStoreProxy.h +++ b/SDK/simData/DataStoreProxy.h @@ -120,7 +120,7 @@ class SDKDATA_EXPORT DataStoreProxy : public DataStore /// Specify the interpolator to use virtual void setInterpolator(Interpolator *interpolator); - /// Get the current interpolator (NULL if disabled) + /// Get the current interpolator (nullptr if disabled) virtual Interpolator* interpolator() const; ///@} @@ -165,14 +165,14 @@ class SDKDATA_EXPORT DataStoreProxy : public DataStore ///@} /**@name Scenario Properties - * @note should always return a valid object (never NULL) + * @note should always return a valid object (never nullptr) * @{ */ virtual const ScenarioProperties* scenarioProperties(Transaction *transaction) const {return dataStore_->scenarioProperties(transaction);} virtual ScenarioProperties* mutable_scenarioProperties(Transaction *transaction) {return dataStore_->mutable_scenarioProperties(transaction);} /**@name Object Properties - * @note will return NULL if no object is associated with the specified id + * @note will return nullptr if no object is associated with the specified id * @{ */ virtual const PlatformProperties* platformProperties(ObjectId id, Transaction *transaction) const {return dataStore_->platformProperties(id, transaction);} @@ -192,7 +192,7 @@ class SDKDATA_EXPORT DataStoreProxy : public DataStore ///@} /**@name Object Preferences - * @note will return NULL if no object is associated with the specified id + * @note will return nullptr if no object is associated with the specified id * @{ */ virtual const PlatformPrefs* platformPrefs(ObjectId id, Transaction *transaction) const {return dataStore_->platformPrefs(id, transaction);} @@ -268,7 +268,7 @@ class SDKDATA_EXPORT DataStoreProxy : public DataStore virtual int removeGenericDataTag(ObjectId id, const std::string& tag) { return dataStore_->removeGenericDataTag(id, tag); } /**@name Add data update, command, generic data, or category data - *@note Returns NULL if platform for specified ID does not exist + *@note Returns nullptr if platform for specified ID does not exist * @{ */ virtual PlatformUpdate * addPlatformUpdate(ObjectId id, Transaction *transaction) {return dataStore_->addPlatformUpdate(id, transaction);} @@ -335,7 +335,7 @@ class SDKDATA_EXPORT DataStoreProxy : public DataStore /**@name NewUpdatesListener * @{ */ - /// Sets a listener for when entity updates are added; use NULL to remove. + /// Sets a listener for when entity updates are added; use nullptr to remove. virtual void setNewUpdatesListener(NewUpdatesListenerPtr callback); ///@} diff --git a/SDK/simData/DataTable.cpp b/SDK/simData/DataTable.cpp index 4eadde1eb..a88e20d40 100644 --- a/SDK/simData/DataTable.cpp +++ b/SDK/simData/DataTable.cpp @@ -138,7 +138,7 @@ class TableCellT : public TableCell virtual bool equals(const TableCell& b) const { const TableCellT* cellThisType = dynamic_cast*>(&b); - if (cellThisType == NULL) + if (cellThisType == nullptr) return false; ValueType tmpValue; cellThisType->value(tmpValue); @@ -213,7 +213,7 @@ namespace TableStatus getCellValue(const std::vector& vec, TableColumnId columnId, T& value) { std::vector::const_iterator i = std::lower_bound(vec.begin(), vec.end(), ColumnCellPair(columnId, NullTableCell)); - if (i == vec.end() || i->second == NULL || i->first != columnId) + if (i == vec.end() || i->second == nullptr || i->first != columnId) return TableStatus::Error("Cell not found."); return i->second->value(value); } @@ -234,7 +234,7 @@ namespace { // Found an entry, cell already exists TableCellT* cellTyped = dynamic_cast*>(iter1->second); - if (cellTyped != NULL) + if (cellTyped != nullptr) { // existing cell is same type as cellValue, is okay to just set it cellTyped->setValue(value); diff --git a/SDK/simData/DataTable.h b/SDK/simData/DataTable.h index 47a025a10..fb7d1065f 100644 --- a/SDK/simData/DataTable.h +++ b/SDK/simData/DataTable.h @@ -119,7 +119,7 @@ class SDKDATA_EXPORT DataTableManager * if the table name already exists. * @param ownerId Owner ID of the table. * @param tableName Table name unique to the entity owner ID, must be non-empty. - * @param newTable Pointer to a data table, or NULL if there was an error. This table may have been + * @param newTable Pointer to a data table, or nullptr if there was an error. This table may have been * created by this call, or created by a previous call if the name is not unique. The return value * will indicate isError() if the table already existed. * @return Status indicating success for a new table creation, or error if an existing table was @@ -171,7 +171,7 @@ class SDKDATA_EXPORT DataTableManager * exist for a given owner ID and table name combination. * @param ownerId Owner of the table being searched for * @param tableName Name of the table being searched for - * @return Table value associated with the owner ID and string name, or NULL if none found. + * @return Table value associated with the owner ID and string name, or nullptr if none found. */ virtual DataTable* findTable(simData::ObjectId ownerId, const std::string& tableName) const = 0; @@ -236,7 +236,7 @@ class TableList /** Entity owner ID associated with the list of tables */ virtual simData::ObjectId ownerId() const = 0; - /** Retrieves the table (or NULL) associated with the given name. */ + /** Retrieves the table (or nullptr) associated with the given name. */ virtual DataTable* findTable(const std::string& tableName) const = 0; /** Returns the total number of tables in this list. */ virtual size_t tableCount() const = 0; @@ -273,7 +273,7 @@ class DelayedFlushContainerComposite : public DelayedFlushContainer /** Saves a flush container for later deletion. */ void push_back(DelayedFlushContainerPtr ptr) { - if (ptr.get() != NULL) + if (ptr.get() != nullptr) deque_.push_back(ptr); } private: @@ -282,7 +282,7 @@ class DelayedFlushContainerComposite : public DelayedFlushContainer /** * Data tables can contain any time stamped data in column arrangement, and permit both out-of- - * order addition of elements and NULL cells. Columns can be added after table creation, and + * order addition of elements and nullptr cells. Columns can be added after table creation, and * can also be added even after some rows are added. Tables should be created using the * DataTableManager::addDataTable() factory function. */ @@ -358,14 +358,14 @@ class SDKDATA_EXPORT DataTable /** * Retrieves the column associated with the particular column ID provided. Column IDs * are unique within the context of a single DataTable and will not change. - * @return NULL if column not found, or pointer to the column ID requested. + * @return nullptr if column not found, or pointer to the column ID requested. */ virtual TableColumn* column(TableColumnId id) const = 0; /** * Retrieves the column associated with the particular column name provided. Column names * are unique within the context of a single DataTable. - * @return NULL if column not found, or pointer to the column with the name requested. + * @return nullptr if column not found, or pointer to the column with the name requested. */ virtual TableColumn* column(const std::string& name) const = 0; @@ -600,7 +600,7 @@ class TableColumn * Retrieves the value of the column at a given time, using the interpolator provided. * @param value Will contain the value interpolated at the requested time. * @param time Time value to seek for interpolating values. - * @param interpolator Instance of interpolator to calculate values; if NULL, then linearly interpolate. + * @param interpolator Instance of interpolator to calculate values; if nullptr, then linearly interpolate. * @return Status return value. This function will not extrapolate, so * searching for a value before the beginning or after the end is an error. */ diff --git a/SDK/simData/GenericIterator.h b/SDK/simData/GenericIterator.h index 25d69e932..c63e112db 100644 --- a/SDK/simData/GenericIterator.h +++ b/SDK/simData/GenericIterator.h @@ -36,14 +36,14 @@ class GenericIteratorImpl virtual ~GenericIteratorImpl() {} /** Retrieves next element and increments iterator to position after that element * @return Element after original iterator position, - * or NULL if no such element + * or nullptr if no such element */ virtual const ValueType next() = 0; /** Retrieves next element and does not change iterator position */ virtual const ValueType peekNext() const = 0; /** Retrieves previous element and decrements iterator to position before that element * @return Element before original iterator position, - * or NULL if no such element + * or nullptr if no such element */ virtual const ValueType previous() = 0; /** Retrieves previous element and does not change iterator position */ @@ -111,14 +111,14 @@ class GenericIterator /** Retrieves next element and increments iterator to position after that element * @return Element after original iterator position, - * or NULL if no such element + * or nullptr if no such element */ const ValueType next() {return impl_->next();} /** Retrieves next element and does not change iterator position */ const ValueType peekNext() const {return impl_->peekNext();} /** Retrieves previous element and decrements iterator to position before that element * @return Element before original iterator position, - * or NULL if no such element + * or nullptr if no such element */ const ValueType previous() {return impl_->previous();} /** Retrieves previous element and does not change iterator position */ diff --git a/SDK/simData/LobGroupMemoryDataSlice.cpp b/SDK/simData/LobGroupMemoryDataSlice.cpp index efbf49795..b27f77c90 100644 --- a/SDK/simData/LobGroupMemoryDataSlice.cpp +++ b/SDK/simData/LobGroupMemoryDataSlice.cpp @@ -95,13 +95,13 @@ void LobGroupMemoryDataSlice::update(double time) // only pass in the currentUpdate if it has data points if (currentUpdate->datapoints_size()) { - current_ = NULL; + current_ = nullptr; setCurrent(currentUpdate); } - else // set current to NULL, need to call setCurrent to trigger update flag + else // set current to nullptr, need to call setCurrent to trigger update flag { delete currentUpdate; - setCurrent(NULL); + setCurrent(nullptr); } } @@ -110,7 +110,7 @@ void LobGroupMemoryDataSlice::flush(bool keepStatic) if (MemorySliceHelper::flush(updates_, keepStatic) == 0) { delete current_; - current_ = NULL; + current_ = nullptr; } dirty_ = true; } diff --git a/SDK/simData/MemoryDataSlice-inl.h b/SDK/simData/MemoryDataSlice-inl.h index 2657dbf65..42c1a1e43 100644 --- a/SDK/simData/MemoryDataSlice-inl.h +++ b/SDK/simData/MemoryDataSlice-inl.h @@ -37,7 +37,7 @@ namespace MemorySliceHelper { template SafeDequeIterator::SafeDequeIterator() -: deque_(NULL), +: deque_(nullptr), val_(0) { } @@ -52,7 +52,7 @@ SafeDequeIterator::SafeDequeIterator(typename std::deque* deque, typename template void SafeDequeIterator::invalidate() { - if (deque_ != NULL) + if (deque_ != nullptr) val_ = static_cast::difference_type>(deque_->size()); else val_ = 0; @@ -61,7 +61,7 @@ void SafeDequeIterator::invalidate() template typename std::deque::iterator SafeDequeIterator::get() const { - if (deque_ == NULL) + if (deque_ == nullptr) return typename std::deque::iterator(); if (val_ > static_cast::difference_type>(deque_->size())) @@ -145,7 +145,7 @@ template const T* const VectorIterator::next() { if (!hasNext()) - return NULL; + return nullptr; return (*vec_)[nextIndex_++]; } @@ -154,7 +154,7 @@ template const T* const VectorIterator::peekNext() const { if (!hasNext()) - return NULL; + return nullptr; return (*vec_)[nextIndex_]; } @@ -163,7 +163,7 @@ template const T* const VectorIterator::previous() { if (!hasPrevious()) - return NULL; + return nullptr; return (*vec_)[--nextIndex_]; } @@ -172,7 +172,7 @@ template const T* const VectorIterator::peekPrevious() const { if (!hasPrevious()) - return NULL; + return nullptr; return (*vec_)[(nextIndex_ - 1)]; } @@ -219,9 +219,9 @@ template MemoryDataSlice::MemoryDataSlice() : mdsHasChanged_(false), dirty_(false), - current_(NULL), + current_(nullptr), interpolated_(false), - bounds_(static_cast(NULL), static_cast(NULL)), + bounds_(static_cast(nullptr), static_cast(nullptr)), fastUpdate_(&updates_, updates_.end()) { } @@ -236,7 +236,7 @@ template void MemoryDataSlice::flush(bool keepStatic) { if (MemorySliceHelper::flush(updates_, keepStatic) == 0) - current_ = NULL; + current_ = nullptr; dirty_ = true; } @@ -356,7 +356,7 @@ void MemoryDataSlice::update(double time) clearChanged(); // early out when there are no changes to this slice - if (!dirty_ && (current_ != NULL) && ((current_->time() == time) || (current_->time() == -1.0))) + if (!dirty_ && (current_ != nullptr) && ((current_->time() == time) || (current_->time() == -1.0))) return; dirty_ = false; @@ -366,7 +366,7 @@ void MemoryDataSlice::update(double time) if (fastUpdate_.get() != updates_.end()) setCurrent(*fastUpdate_.get()); else - setCurrent(NULL); + setCurrent(nullptr); } template @@ -376,7 +376,7 @@ void MemoryDataSlice::update(double time, Interpolator *interpolator) clearChanged(); // early out when there are no changes to this slice - if (!dirty_ && (current_ != NULL) && ((current_->time() == time) || (current_->time() == -1.0))) + if (!dirty_ && (current_ != nullptr) && ((current_->time() == time) || (current_->time() == -1.0))) return; // update is processing the changes to the slice, clear the flag @@ -405,7 +405,7 @@ void MemoryDataSlice::insert(T *data) { // NULL the current ptr, if we are replacing the update it aliases; current will become valid upon update if (current_ == *iter) - setCurrent(NULL); + setCurrent(nullptr); delete *iter; *iter = data; @@ -520,7 +520,7 @@ const CommandType* MemoryCommandSlice::current() const typename std::deque::const_iterator i = std::upper_bound(updates_.begin(), updates_.end(), lastUpdateTime_, UpdateComp()); - return (i != updates_.begin()) ? *(i-1) : NULL; + return (i != updates_.begin()) ? *(i-1) : nullptr; } template @@ -656,9 +656,9 @@ void MemoryCommandSlice::update(DataStore *ds, ObjectId i // process all command updates in one prefs transaction DataStore::Transaction t; - PrefType* prefs = NULL; + PrefType* prefs = nullptr; simData::getPreference(ds, id, &prefs, &t); - if (prefs == NULL) + if (prefs == nullptr) return; const CommandType *lastCommand = current(); diff --git a/SDK/simData/MemoryDataSlice.h b/SDK/simData/MemoryDataSlice.h index a45599360..dc2c3f565 100644 --- a/SDK/simData/MemoryDataSlice.h +++ b/SDK/simData/MemoryDataSlice.h @@ -257,7 +257,7 @@ class MemoryDataSlice : public DataSlice /** The time delta between the given time and the data point before the given time; return -1 if no previous point */ virtual double deltaTime(double time) const; - /** Retrieves the current interpolated T, or NULL if none */ + /** Retrieves the current interpolated T, or nullptr if none */ T* currentInterpolated(); protected: diff --git a/SDK/simData/MemoryDataStore.cpp b/SDK/simData/MemoryDataStore.cpp index f82c06d9f..960c305c2 100644 --- a/SDK/simData/MemoryDataStore.cpp +++ b/SDK/simData/MemoryDataStore.cpp @@ -110,7 +110,7 @@ EntryType* getEntry(ObjectId id, const EntryMapType *store) return iter->second; } - return NULL; + return nullptr; } /** @@ -210,7 +210,7 @@ class DataStoreLimits : public MemoryTable::DataLimitsProvider template TableStatus setLimitValues_(const T* prefs, size_t& pointsLimit, double& secondsLimit) const { - if (prefs == NULL) + if (prefs == nullptr) return TableStatus::Error("No preferences for table's owner entity ID."); // Limit by points pointsLimit = prefs->datalimitpoints(); @@ -331,13 +331,13 @@ MemoryDataStore::MemoryDataStore() lastUpdateTime_(0.0), hasChanged_(false), interpolationEnabled_(false), - interpolator_(NULL), + interpolator_(nullptr), newUpdatesListener_(new DefaultNewUpdatesListener), dataLimiting_(false), categoryNameManager_(new CategoryNameManager), - dataLimitsProvider_(NULL), - dataTableManager_(NULL), - boundClock_(NULL), + dataLimitsProvider_(nullptr), + dataTableManager_(nullptr), + boundClock_(nullptr), entityNameCache_(new EntityNameCache()) { dataLimitsProvider_ = new DataStoreLimits(*this); @@ -352,13 +352,13 @@ MemoryDataStore::MemoryDataStore(const ScenarioProperties &properties) lastUpdateTime_(0.0), hasChanged_(false), interpolationEnabled_(false), - interpolator_(NULL), + interpolator_(nullptr), newUpdatesListener_(new DefaultNewUpdatesListener), dataLimiting_(false), categoryNameManager_(new CategoryNameManager), - dataLimitsProvider_(NULL), - dataTableManager_(NULL), - boundClock_(NULL), + dataLimitsProvider_(nullptr), + dataTableManager_(nullptr), + boundClock_(nullptr), entityNameCache_(new EntityNameCache()) { dataLimitsProvider_ = new DataStoreLimits(*this); @@ -373,13 +373,13 @@ MemoryDataStore::~MemoryDataStore() { clear(); delete categoryNameManager_; - categoryNameManager_ = NULL; + categoryNameManager_ = nullptr; delete dataTableManager_; - dataTableManager_ = NULL; + dataTableManager_ = nullptr; delete dataLimitsProvider_; - dataLimitsProvider_ = NULL; + dataLimitsProvider_ = nullptr; delete entityNameCache_; - entityNameCache_ = NULL; + entityNameCache_ = nullptr; } void MemoryDataStore::clear() @@ -425,13 +425,13 @@ bool MemoryDataStore::canInterpolate() const * Enable or disable interpolation, if supported * Will only succeed if the DataStore implementation supports interpolation and * contains a valid interpolator object - * TODO(millman): this seems like an unnecessary interface, can we just use setInterpolator(NULL) to disable? + * TODO(millman): this seems like an unnecessary interface, can we just use setInterpolator(nullptr) to disable? * @return the state of interpolation */ bool MemoryDataStore::enableInterpolation(bool state) { // interpolation can only be enabled if there is an interpolator - if (state && interpolator_ != NULL) + if (state && interpolator_ != nullptr) { if (!interpolationEnabled_) { @@ -455,7 +455,7 @@ bool MemoryDataStore::enableInterpolation(bool state) ///Indicates that interpolation is either enabled or disabled bool MemoryDataStore::isInterpolationEnabled() const { - return interpolationEnabled_ && interpolator_ != NULL; + return interpolationEnabled_ && interpolator_ != nullptr; } ///Specifies the interpolator @@ -468,10 +468,10 @@ void MemoryDataStore::setInterpolator(Interpolator *interpolator) } } -/// Get the current interpolator (NULL if disabled) +/// Get the current interpolator (nullptr if disabled) Interpolator* MemoryDataStore::interpolator() const { - return (interpolationEnabled_) ? interpolator_ : NULL; + return (interpolationEnabled_) ? interpolator_ : nullptr; } void MemoryDataStore::updatePlatforms_(double time) @@ -488,8 +488,8 @@ void MemoryDataStore::updatePlatforms_(double time) if (!platform->preferences()->commonprefs().datadraw()) { - // until we have datadraw, send NULL; once we have datadraw, we'll immediately update with valid data - platform->updates()->setCurrent(NULL); + // until we have datadraw, send nullptr; once we have datadraw, we'll immediately update with valid data + platform->updates()->setCurrent(nullptr); continue; } @@ -502,7 +502,7 @@ void MemoryDataStore::updatePlatforms_(double time) if (!staticPlatform && (time < firstTime || time > slice->lastTime())) { // platform is not valid/has expired - platform->updates()->setCurrent(NULL); + platform->updates()->setCurrent(nullptr); continue; } } @@ -519,53 +519,53 @@ void MemoryDataStore::updateTargetBeam_(ObjectId id, BeamEntry* beam, double tim // Get the two platforms, if available if (!beam->properties()->has_hostid()) { - beam->updates()->setCurrent(NULL); + beam->updates()->setCurrent(nullptr); return; } if (!beam->preferences()->has_targetid()) { - beam->updates()->setCurrent(NULL); + beam->updates()->setCurrent(nullptr); return; } Platforms::iterator plat = platforms_.find(beam->properties()->hostid()); - if ((plat == platforms_.end()) || (plat->second == NULL)) + if ((plat == platforms_.end()) || (plat->second == nullptr)) { - beam->updates()->setCurrent(NULL); + beam->updates()->setCurrent(nullptr); return; } PlatformEntry* sourcePlatform = plat->second; const PlatformUpdate* sourceUpdate = sourcePlatform->updates()->current(); - if ((sourceUpdate == NULL) || (!sourceUpdate->has_position())) + if ((sourceUpdate == nullptr) || (!sourceUpdate->has_position())) { - beam->updates()->setCurrent(NULL); + beam->updates()->setCurrent(nullptr); return; } plat = platforms_.find(beam->preferences()->targetid()); - if ((plat == platforms_.end()) || (plat->second == NULL)) + if ((plat == platforms_.end()) || (plat->second == nullptr)) { - beam->updates()->setCurrent(NULL); + beam->updates()->setCurrent(nullptr); return; } PlatformEntry* destPlatform = plat->second; const PlatformUpdate* destUpdate = destPlatform->updates()->current(); - if ((destUpdate == NULL) || (!destUpdate->has_position())) + if ((destUpdate == nullptr) || (!destUpdate->has_position())) { - beam->updates()->setCurrent(NULL); + beam->updates()->setCurrent(nullptr); return; } // target beam has no updates; it uses the currentInterpolated() to deliver info to simVis::Beam BeamUpdate* update = beam->updates()->currentInterpolated(); - // simVis::Beam will calculate the RAE whenever it gets a non-NULL update with hasChanged flag set + // simVis::Beam will calculate the RAE whenever it gets a non-nullptr update with hasChanged flag set // update only when there is a time change or this is a NULL->non-NULL transition - if (beam->updates()->current() == NULL || update->time() != time) + if (beam->updates()->current() == nullptr || update->time() != time) { update->set_time(time); update->set_azimuth(0.0); @@ -587,9 +587,9 @@ void MemoryDataStore::updateBeams_(double time) // apply commands beamEntry->commands()->update(this, iter->first, time); - // until we have datadraw, send NULL; once we have datadraw, we'll immediately update with valid data + // until we have datadraw, send nullptr; once we have datadraw, we'll immediately update with valid data if (!beamEntry->preferences()->commonprefs().datadraw()) - beamEntry->updates()->setCurrent(NULL); + beamEntry->updates()->setCurrent(nullptr); else if (beamEntry->properties()->type() == BeamProperties_BeamType_TARGET) updateTargetBeam_(iter->first, beamEntry, time); else if (isInterpolationEnabled() && beamEntry->preferences()->interpolatebeampos()) @@ -602,8 +602,8 @@ void MemoryDataStore::updateBeams_(double time) simData::MemoryDataStore::BeamEntry* MemoryDataStore::getBeamForGate_(google::protobuf::uint64 gateID) { Beams::iterator beamIt = beams_.find(gateID); - if ((beamIt == beams_.end()) || (beamIt->second == NULL)) - return NULL; + if ((beamIt == beams_.end()) || (beamIt->second == nullptr)) + return nullptr; return beamIt->second; } @@ -616,7 +616,7 @@ void MemoryDataStore::updateTargetGate_(GateEntry* gate, double time) // Get the host beam for this gate if (!gate->properties()->has_hostid()) { - gate->updates()->setCurrent(NULL); + gate->updates()->setCurrent(nullptr); return; } @@ -625,41 +625,41 @@ void MemoryDataStore::updateTargetGate_(GateEntry* gate, double time) assert(beam->properties()->type() == BeamProperties_BeamType_TARGET); if (!beam || !beam->properties()->has_hostid() || beam->properties()->type() != BeamProperties_BeamType_TARGET || !beam->preferences()->has_targetid()) { - gate->updates()->setCurrent(NULL); + gate->updates()->setCurrent(nullptr); return; } Platforms::iterator plat = platforms_.find(beam->properties()->hostid()); - if ((plat == platforms_.end()) || (plat->second == NULL)) + if ((plat == platforms_.end()) || (plat->second == nullptr)) { - gate->updates()->setCurrent(NULL); + gate->updates()->setCurrent(nullptr); return; } PlatformEntry* sourcePlatform = plat->second; const PlatformUpdate* sourceUpdate = sourcePlatform->updates()->current(); - if ((sourceUpdate == NULL) || (!sourceUpdate->has_position())) + if ((sourceUpdate == nullptr) || (!sourceUpdate->has_position())) { - gate->updates()->setCurrent(NULL); + gate->updates()->setCurrent(nullptr); return; } plat = platforms_.find(beam->preferences()->targetid()); - if ((plat == platforms_.end()) || (plat->second == NULL)) + if ((plat == platforms_.end()) || (plat->second == nullptr)) { - gate->updates()->setCurrent(NULL); + gate->updates()->setCurrent(nullptr); return; } PlatformEntry* destPlatform = plat->second; const PlatformUpdate* destUpdate = destPlatform->updates()->current(); - if ((destUpdate == NULL) || (!destUpdate->has_position())) + if ((destUpdate == nullptr) || (!destUpdate->has_position())) { - gate->updates()->setCurrent(NULL); + gate->updates()->setCurrent(nullptr); return; } - const bool gateWasOff = (gate->updates()->current() == NULL); + const bool gateWasOff = (gate->updates()->current() == nullptr); // target gates use the MemoryDataSlice::currentInterpolated_ to hold the modified update GateUpdate* update = gate->updates()->currentInterpolated(); @@ -672,7 +672,7 @@ void MemoryDataStore::updateTargetGate_(GateEntry* gate, double time) else gate->updates()->update(time); const GateUpdate* currentUpdate = gate->updates()->current(); - if (currentUpdate == NULL) + if (currentUpdate == nullptr) return; // update only when gate was off, there is a time change, or if we depend on beam for height/width @@ -703,7 +703,7 @@ void MemoryDataStore::updateTargetGate_(GateEntry* gate, double time) bool MemoryDataStore::gateUsesBeamBeamwidth_(GateEntry* gate) const { const GateUpdate* currentUpdate = gate->updates()->current(); - return (currentUpdate != NULL && gate->properties()->has_hostid() && + return (currentUpdate != nullptr && gate->properties()->has_hostid() && (currentUpdate->height() <= 0.0 || currentUpdate->width() <= 0.0)); } @@ -715,9 +715,9 @@ void MemoryDataStore::updateGates_(double time) // apply commands gateEntry->commands()->update(this, iter->first, time); - // until we have datadraw, send NULL; once we have datadraw, we'll immediately update with valid data + // until we have datadraw, send nullptr; once we have datadraw, we'll immediately update with valid data if (!gateEntry->preferences()->commonprefs().datadraw()) - gateEntry->updates()->setCurrent(NULL); + gateEntry->updates()->setCurrent(nullptr); else if (gateEntry->properties()->type() == GateProperties_GateType_TARGET) updateTargetGate_(gateEntry, time); else @@ -748,9 +748,9 @@ void MemoryDataStore::updateLasers_(double time) // apply commands laserEntry->commands()->update(this, iter->first, time); - // until we have datadraw, send NULL; once we have datadraw, we'll immediately update with valid data + // until we have datadraw, send nullptr; once we have datadraw, we'll immediately update with valid data if (!laserEntry->preferences()->commonprefs().datadraw()) - laserEntry->updates()->setCurrent(NULL); + laserEntry->updates()->setCurrent(nullptr); // laser interpolation is on, there is no preference; but off if we have no interpolator else if (isInterpolationEnabled()) laserEntry->updates()->update(time, interpolator_); @@ -887,7 +887,7 @@ void MemoryDataStore::flushDataTables_(ObjectId id) // Visit all tables and flush them const simData::TableList* ownerTables = dataTableManager().tablesForOwner(id); - if (ownerTables != NULL) + if (ownerTables != nullptr) { FlushVisitor flushVisitor; ownerTables->accept(flushVisitor); @@ -941,7 +941,7 @@ void MemoryDataStore::update(double time) for (ListenerList::const_iterator j = localCopy.begin(); j != localCopy.end(); ++j) { - if (*j != NULL) + if (*j != nullptr) { (**j).onCategoryDataChange(this, i->first, ot); checkForRemoval_(localCopy); @@ -961,9 +961,9 @@ void MemoryDataStore::update(double time) for (ListenerList::const_iterator i = localCopy.begin(); i != localCopy.end(); ++i) { - if (*i != NULL) + if (*i != nullptr) { - (**i).onTimeChange(this); + (**i).onChange(this); checkForRemoval_(localCopy); } } @@ -1028,7 +1028,7 @@ void MemoryDataStore::flush(ObjectId flushId, FlushType flushType) // now send out notification to listeners for (ListenerList::const_iterator i = localCopy.begin(); i != localCopy.end(); ++i) { - if (*i != NULL) + if (*i != nullptr) { (*i)->onFlush(this, flushId); checkForRemoval_(localCopy); @@ -1147,8 +1147,8 @@ void MemoryDataStore::idList(IdList *ids, simData::ObjectType type) const void MemoryDataStore::idListByName(const std::string& name, IdList* ids, simData::ObjectType type) const { // If null someone is call this routine before entityNameCache_ is made in the constructor - assert(entityNameCache_ != NULL); - if (entityNameCache_ == NULL) + assert(entityNameCache_ != nullptr); + if (entityNameCache_ == nullptr) return; std::vector entries; @@ -1468,7 +1468,7 @@ void MemoryDataStore::removeEntity(ObjectId id) justRemoved_.clear(); for (ListenerList::const_iterator i = localCopy.begin(); i != localCopy.end(); ++i) { - if (*i != NULL) + if (*i != nullptr) { (**i).onRemoveEntity(this, id, ot); checkForRemoval_(localCopy); @@ -1561,7 +1561,7 @@ void MemoryDataStore::fireOnPostRemoveEntity_(ObjectId id, ObjectType ot) justRemoved_.clear(); for (ListenerList::const_iterator i = localCopy.begin(); i != localCopy.end(); ++i) { - if (*i != NULL) + if (*i != nullptr) { (**i).onPostRemoveEntity(this, id, ot); checkForRemoval_(localCopy); @@ -1593,102 +1593,102 @@ int MemoryDataStore::removeGenericDataTag(ObjectId id, const std::string& tag) const PlatformProperties* MemoryDataStore::platformProperties(ObjectId id, Transaction *transaction) const { const PlatformEntry *entry = getEntry(id, &platforms_, transaction); - return entry ? entry->properties() : NULL; + return entry ? entry->properties() : nullptr; } /// mutable version PlatformProperties* MemoryDataStore::mutable_platformProperties(ObjectId id, Transaction *transaction) { PlatformEntry *entry = getEntry(id, &platforms_, transaction); - return entry ? entry->mutable_properties() : NULL; + return entry ? entry->mutable_properties() : nullptr; } ///@return const properties of beam with 'id' const BeamProperties *MemoryDataStore::beamProperties(ObjectId id, Transaction *transaction) const { const BeamEntry *entry = getEntry(id, &beams_, transaction); - return entry ? entry->properties() : NULL; + return entry ? entry->properties() : nullptr; } /// mutable version BeamProperties *MemoryDataStore::mutable_beamProperties(ObjectId id, Transaction *transaction) { BeamEntry *entry = getEntry(id, &beams_, transaction); - return entry ? entry->mutable_properties() : NULL; + return entry ? entry->mutable_properties() : nullptr; } ///@return const properties of gate with 'id' const GateProperties *MemoryDataStore::gateProperties(ObjectId id, Transaction *transaction) const { const GateEntry *entry = getEntry(id, &gates_, transaction); - return entry ? entry->properties() : NULL; + return entry ? entry->properties() : nullptr; } /// mutable version GateProperties *MemoryDataStore::mutable_gateProperties(ObjectId id, Transaction *transaction) { GateEntry *entry = getEntry(id, &gates_, transaction); - return entry ? entry->mutable_properties() : NULL; + return entry ? entry->mutable_properties() : nullptr; } ///@return const properties of laser with 'id' const LaserProperties* MemoryDataStore::laserProperties(ObjectId id, Transaction *transaction) const { const LaserEntry *entry = getEntry(id, &lasers_, transaction); - return entry ? entry->properties() : NULL; + return entry ? entry->properties() : nullptr; } /// mutable version LaserProperties* MemoryDataStore::mutable_laserProperties(ObjectId id, Transaction *transaction) { LaserEntry *entry = getEntry(id, &lasers_, transaction); - return entry ? entry->mutable_properties() : NULL; + return entry ? entry->mutable_properties() : nullptr; } ///@return const properties of projector with 'id' const ProjectorProperties* MemoryDataStore::projectorProperties(ObjectId id, Transaction *transaction) const { const ProjectorEntry *entry = getEntry(id, &projectors_, transaction); - return entry ? entry->properties() : NULL; + return entry ? entry->properties() : nullptr; } /// mutable version ProjectorProperties* MemoryDataStore::mutable_projectorProperties(ObjectId id, Transaction *transaction) { ProjectorEntry *entry = getEntry(id, &projectors_, transaction); - return entry ? entry->mutable_properties() : NULL; + return entry ? entry->mutable_properties() : nullptr; } ///@return const properties of lobGroup with 'id' const LobGroupProperties* MemoryDataStore::lobGroupProperties(ObjectId id, Transaction *transaction) const { const LobGroupEntry *entry = getEntry(id, &lobGroups_, transaction); - return entry ? entry->properties() : NULL; + return entry ? entry->properties() : nullptr; } /// mutable version LobGroupProperties* MemoryDataStore::mutable_lobGroupProperties(ObjectId id, Transaction *transaction) { LobGroupEntry *entry = getEntry(id, &lobGroups_, transaction); - return entry ? entry->mutable_properties() : NULL; + return entry ? entry->mutable_properties() : nullptr; } const CustomRenderingProperties* MemoryDataStore::customRenderingProperties(ObjectId id, Transaction *transaction) const { const CustomRenderingEntry *entry = getEntry(id, &customRenderings_, transaction); - return entry ? entry->properties() : NULL; + return entry ? entry->properties() : nullptr; } CustomRenderingProperties* MemoryDataStore::mutable_customRenderingProperties(ObjectId id, Transaction *transaction) { CustomRenderingEntry *entry = getEntry(id, &customRenderings_, transaction); - return entry ? entry->mutable_properties() : NULL; + return entry ? entry->mutable_properties() : nullptr; } const PlatformPrefs* MemoryDataStore::platformPrefs(ObjectId id, Transaction *transaction) const { const PlatformEntry *entry = getEntry(id, &platforms_, transaction); - return entry ? entry->preferences() : NULL; + return entry ? entry->preferences() : nullptr; } PlatformPrefs* MemoryDataStore::mutable_platformPrefs(ObjectId id, Transaction *transaction) @@ -1704,13 +1704,13 @@ PlatformPrefs* MemoryDataStore::mutable_platformPrefs(ObjectId id, Transaction * } // Platform associated with specified id was not found - return NULL; + return nullptr; } const BeamPrefs* MemoryDataStore::beamPrefs(ObjectId id, Transaction *transaction) const { const BeamEntry *entry = getEntry(id, &beams_, transaction); - return entry ? entry->preferences() : NULL; + return entry ? entry->preferences() : nullptr; } BeamPrefs* MemoryDataStore::mutable_beamPrefs(ObjectId id, Transaction *transaction) @@ -1726,13 +1726,13 @@ BeamPrefs* MemoryDataStore::mutable_beamPrefs(ObjectId id, Transaction *transact } // Beam associated with specified id was not found - return NULL; + return nullptr; } const GatePrefs* MemoryDataStore::gatePrefs(ObjectId id, Transaction *transaction) const { const GateEntry *entry = getEntry(id, &gates_, transaction); - return entry ? entry->preferences() : NULL; + return entry ? entry->preferences() : nullptr; } GatePrefs* MemoryDataStore::mutable_gatePrefs(ObjectId id, Transaction *transaction) @@ -1748,13 +1748,13 @@ GatePrefs* MemoryDataStore::mutable_gatePrefs(ObjectId id, Transaction *transact } // Gate associated with specified id was not found - return NULL; + return nullptr; } const LaserPrefs* MemoryDataStore::laserPrefs(ObjectId id, Transaction *transaction) const { const LaserEntry *entry = getEntry(id, &lasers_, transaction); - return entry ? entry->preferences() : NULL; + return entry ? entry->preferences() : nullptr; } LaserPrefs* MemoryDataStore::mutable_laserPrefs(ObjectId id, Transaction *transaction) @@ -1770,13 +1770,13 @@ LaserPrefs* MemoryDataStore::mutable_laserPrefs(ObjectId id, Transaction *transa } // Laser associated with specified id was not found - return NULL; + return nullptr; } const ProjectorPrefs* MemoryDataStore::projectorPrefs(ObjectId id, Transaction *transaction) const { const ProjectorEntry *entry = getEntry(id, &projectors_, transaction); - return entry ? entry->preferences() : NULL; + return entry ? entry->preferences() : nullptr; } ProjectorPrefs* MemoryDataStore:: mutable_projectorPrefs(ObjectId id, Transaction *transaction) @@ -1792,13 +1792,13 @@ ProjectorPrefs* MemoryDataStore:: mutable_projectorPrefs(ObjectId id, Transactio } // Projector associated with specified id was not found - return NULL; + return nullptr; } const LobGroupPrefs* MemoryDataStore::lobGroupPrefs(ObjectId id, Transaction *transaction) const { const LobGroupEntry *entry = getEntry(id, &lobGroups_, transaction); - return entry ? entry->preferences() : NULL; + return entry ? entry->preferences() : nullptr; } LobGroupPrefs* MemoryDataStore::mutable_lobGroupPrefs(ObjectId id, Transaction *transaction) @@ -1814,13 +1814,13 @@ LobGroupPrefs* MemoryDataStore::mutable_lobGroupPrefs(ObjectId id, Transaction * } // LobGroup associated with specified id was not found - return NULL; + return nullptr; } const CustomRenderingPrefs* MemoryDataStore::customRenderingPrefs(ObjectId id, Transaction *transaction) const { const CustomRenderingEntry *entry = getEntry(id, &customRenderings_, transaction); - return entry ? entry->preferences() : NULL; + return entry ? entry->preferences() : nullptr; } CustomRenderingPrefs* MemoryDataStore::mutable_customRenderingPrefs(ObjectId id, Transaction *transaction) @@ -1835,63 +1835,63 @@ CustomRenderingPrefs* MemoryDataStore::mutable_customRenderingPrefs(ObjectId id, return impl->settings(); } - return NULL; + return nullptr; } const CommonPrefs* MemoryDataStore::commonPrefs(ObjectId id, Transaction* transaction) const { const PlatformPrefs* plat = platformPrefs(id, transaction); - if (plat != NULL) + if (plat != nullptr) return &plat->commonprefs(); const BeamPrefs* beam = beamPrefs(id, transaction); - if (beam != NULL) + if (beam != nullptr) return &beam->commonprefs(); const GatePrefs* gate = gatePrefs(id, transaction); - if (gate != NULL) + if (gate != nullptr) return &gate->commonprefs(); const LaserPrefs* laser = laserPrefs(id, transaction); - if (laser != NULL) + if (laser != nullptr) return &laser->commonprefs(); const LobGroupPrefs* lobGroup = lobGroupPrefs(id, transaction); - if (lobGroup != NULL) + if (lobGroup != nullptr) return &lobGroup->commonprefs(); const ProjectorPrefs* proj = projectorPrefs(id, transaction); - if (proj != NULL) + if (proj != nullptr) return &proj->commonprefs(); const CustomRenderingPrefs* custom = customRenderingPrefs(id, transaction); - if (custom != NULL) + if (custom != nullptr) return &custom->commonprefs(); - return NULL; + return nullptr; } CommonPrefs* MemoryDataStore::mutable_commonPrefs(ObjectId id, Transaction* transaction) { PlatformPrefs* plat = mutable_platformPrefs(id, transaction); - if (plat != NULL) + if (plat != nullptr) return plat->mutable_commonprefs(); BeamPrefs* beam = mutable_beamPrefs(id, transaction); - if (beam != NULL) + if (beam != nullptr) return beam->mutable_commonprefs(); GatePrefs* gate = mutable_gatePrefs(id, transaction); - if (gate != NULL) + if (gate != nullptr) return gate->mutable_commonprefs(); LaserPrefs* laser = mutable_laserPrefs(id, transaction); - if (laser != NULL) + if (laser != nullptr) return laser->mutable_commonprefs(); LobGroupPrefs* lobGroup = mutable_lobGroupPrefs(id, transaction); - if (lobGroup != NULL) + if (lobGroup != nullptr) return lobGroup->mutable_commonprefs(); ProjectorPrefs* proj = mutable_projectorPrefs(id, transaction); - if (proj != NULL) + if (proj != nullptr) return proj->mutable_commonprefs(); CustomRenderingPrefs* custom = mutable_customRenderingPrefs(id, transaction); - if (custom != NULL) + if (custom != nullptr) return custom->mutable_commonprefs(); - return NULL; + return nullptr; } -///@return NULL if platform for specified 'id' does not exist +///@return nullptr if platform for specified 'id' does not exist PlatformUpdate* MemoryDataStore::addPlatformUpdate(ObjectId id, Transaction *transaction) { assert(transaction); @@ -1899,7 +1899,7 @@ PlatformUpdate* MemoryDataStore::addPlatformUpdate(ObjectId id, Transaction *tra PlatformEntry *entry = getEntry(id, &platforms_); if (!entry) { - return NULL; + return nullptr; } PlatformUpdate *update = new PlatformUpdate(); @@ -1911,7 +1911,7 @@ PlatformUpdate* MemoryDataStore::addPlatformUpdate(ObjectId id, Transaction *tra return update; } -///@return NULL if platform for specified 'id' does not exist +///@return nullptr if platform for specified 'id' does not exist PlatformCommand *MemoryDataStore::addPlatformCommand(ObjectId id, Transaction *transaction) { assert(transaction); @@ -1919,7 +1919,7 @@ PlatformCommand *MemoryDataStore::addPlatformCommand(ObjectId id, Transaction *t PlatformEntry *entry = getEntry(id, &platforms_); if (!entry) { - return NULL; + return nullptr; } PlatformCommand *command = new PlatformCommand(); @@ -1932,7 +1932,7 @@ PlatformCommand *MemoryDataStore::addPlatformCommand(ObjectId id, Transaction *t return command; } -///@return NULL if beam for specified 'id' does not exist +///@return nullptr if beam for specified 'id' does not exist BeamUpdate* MemoryDataStore::addBeamUpdate(ObjectId id, Transaction *transaction) { assert(transaction); @@ -1940,7 +1940,7 @@ BeamUpdate* MemoryDataStore::addBeamUpdate(ObjectId id, Transaction *transaction BeamEntry *entry = getEntry(id, &beams_); if (!entry) { - return NULL; + return nullptr; } BeamUpdate *update = new BeamUpdate(); @@ -1952,7 +1952,7 @@ BeamUpdate* MemoryDataStore::addBeamUpdate(ObjectId id, Transaction *transaction return update; } -///@return NULL if beam for specified 'id' does not exist +///@return nullptr if beam for specified 'id' does not exist BeamCommand *MemoryDataStore::addBeamCommand(ObjectId id, Transaction *transaction) { assert(transaction); @@ -1960,7 +1960,7 @@ BeamCommand *MemoryDataStore::addBeamCommand(ObjectId id, Transaction *transacti BeamEntry *entry = getEntry(id, &beams_); if (!entry) { - return NULL; + return nullptr; } BeamCommand *command = new BeamCommand(); @@ -1973,7 +1973,7 @@ BeamCommand *MemoryDataStore::addBeamCommand(ObjectId id, Transaction *transacti return command; } -///@return NULL if gate for specified 'id' does not exist +///@return nullptr if gate for specified 'id' does not exist GateUpdate* MemoryDataStore::addGateUpdate(ObjectId id, Transaction *transaction) { assert(transaction); @@ -1981,7 +1981,7 @@ GateUpdate* MemoryDataStore::addGateUpdate(ObjectId id, Transaction *transaction GateEntry *entry = getEntry(id, &gates_); if (!entry) { - return NULL; + return nullptr; } GateUpdate *update = new GateUpdate(); @@ -1993,7 +1993,7 @@ GateUpdate* MemoryDataStore::addGateUpdate(ObjectId id, Transaction *transaction return update; } -///@return NULL if gate for specified 'id' does not exist +///@return nullptr if gate for specified 'id' does not exist GateCommand *MemoryDataStore::addGateCommand(ObjectId id, Transaction *transaction) { assert(transaction); @@ -2001,7 +2001,7 @@ GateCommand *MemoryDataStore::addGateCommand(ObjectId id, Transaction *transacti GateEntry *entry = getEntry(id, &gates_); if (!entry) { - return NULL; + return nullptr; } GateCommand *command = new GateCommand(); @@ -2014,7 +2014,7 @@ GateCommand *MemoryDataStore::addGateCommand(ObjectId id, Transaction *transacti return command; } -///@return NULL if laser for specified 'id' does not exist +///@return nullptr if laser for specified 'id' does not exist LaserUpdate* MemoryDataStore::addLaserUpdate(ObjectId id, Transaction *transaction) { assert(transaction); @@ -2022,7 +2022,7 @@ LaserUpdate* MemoryDataStore::addLaserUpdate(ObjectId id, Transaction *transacti LaserEntry *entry = getEntry(id, &lasers_); if (!entry) { - return NULL; + return nullptr; } LaserUpdate *update = new LaserUpdate(); @@ -2034,7 +2034,7 @@ LaserUpdate* MemoryDataStore::addLaserUpdate(ObjectId id, Transaction *transacti return update; } -///@return NULL if laser for specified 'id' does not exist +///@return nullptr if laser for specified 'id' does not exist LaserCommand *MemoryDataStore::addLaserCommand(ObjectId id, Transaction *transaction) { assert(transaction); @@ -2042,7 +2042,7 @@ LaserCommand *MemoryDataStore::addLaserCommand(ObjectId id, Transaction *transac LaserEntry *entry = getEntry(id, &lasers_); if (!entry) { - return NULL; + return nullptr; } LaserCommand *command = new LaserCommand(); @@ -2055,7 +2055,7 @@ LaserCommand *MemoryDataStore::addLaserCommand(ObjectId id, Transaction *transac return command; } -///@return NULL if projector for specified 'id' does not exist +///@return nullptr if projector for specified 'id' does not exist ProjectorUpdate* MemoryDataStore::addProjectorUpdate(ObjectId id, Transaction *transaction) { assert(transaction); @@ -2063,7 +2063,7 @@ ProjectorUpdate* MemoryDataStore::addProjectorUpdate(ObjectId id, Transaction *t ProjectorEntry *entry = getEntry(id, &projectors_); if (!entry) { - return NULL; + return nullptr; } ProjectorUpdate *update = new ProjectorUpdate(); @@ -2075,7 +2075,7 @@ ProjectorUpdate* MemoryDataStore::addProjectorUpdate(ObjectId id, Transaction *t return update; } -///@return NULL if projector for specified 'id' does not exist +///@return nullptr if projector for specified 'id' does not exist ProjectorCommand *MemoryDataStore::addProjectorCommand(ObjectId id, Transaction *transaction) { assert(transaction); @@ -2083,7 +2083,7 @@ ProjectorCommand *MemoryDataStore::addProjectorCommand(ObjectId id, Transaction ProjectorEntry *entry = getEntry(id, &projectors_); if (!entry) { - return NULL; + return nullptr; } ProjectorCommand *command = new ProjectorCommand(); @@ -2096,7 +2096,7 @@ ProjectorCommand *MemoryDataStore::addProjectorCommand(ObjectId id, Transaction return command; } -///@return NULL if lobGroup for specified 'id' does not exist +///@return nullptr if lobGroup for specified 'id' does not exist LobGroupUpdate* MemoryDataStore::addLobGroupUpdate(ObjectId id, Transaction *transaction) { assert(transaction); @@ -2104,7 +2104,7 @@ LobGroupUpdate* MemoryDataStore::addLobGroupUpdate(ObjectId id, Transaction *tra LobGroupEntry *entry = getEntry(id, &lobGroups_); if (!entry) { - return NULL; + return nullptr; } LobGroupUpdate *update = new LobGroupUpdate(); @@ -2116,7 +2116,7 @@ LobGroupUpdate* MemoryDataStore::addLobGroupUpdate(ObjectId id, Transaction *tra return update; } -///@return NULL if lobGroup for specified 'id' does not exist +///@return nullptr if lobGroup for specified 'id' does not exist LobGroupCommand *MemoryDataStore::addLobGroupCommand(ObjectId id, Transaction *transaction) { assert(transaction); @@ -2124,7 +2124,7 @@ LobGroupCommand *MemoryDataStore::addLobGroupCommand(ObjectId id, Transaction *t LobGroupEntry *entry = getEntry(id, &lobGroups_); if (!entry) { - return NULL; + return nullptr; } LobGroupCommand *command = new LobGroupCommand(); @@ -2144,7 +2144,7 @@ CustomRenderingCommand* MemoryDataStore::addCustomRenderingCommand(ObjectId id, auto *entry = getEntry(id, &customRenderings_); if (!entry) { - return NULL; + return nullptr; } auto *command = new CustomRenderingCommand(); @@ -2157,7 +2157,7 @@ CustomRenderingCommand* MemoryDataStore::addCustomRenderingCommand(ObjectId id, return command; } -///@return NULL if generic data for specified 'id' does not exist +///@return nullptr if generic data for specified 'id' does not exist GenericData* MemoryDataStore::addGenericData(ObjectId id, Transaction *transaction) { assert(transaction); @@ -2165,7 +2165,7 @@ GenericData* MemoryDataStore::addGenericData(ObjectId id, Transaction *transacti MemoryGenericDataSlice *slice = getEntry(id, &genericData_); if (!slice) { - return NULL; + return nullptr; } GenericData *data = new GenericData(); @@ -2179,7 +2179,7 @@ GenericData* MemoryDataStore::addGenericData(ObjectId id, Transaction *transacti return data; } -///@return NULL if category data for specified 'id' does not exist +///@return nullptr if category data for specified 'id' does not exist CategoryData* MemoryDataStore::addCategoryData(ObjectId id, Transaction *transaction) { assert(transaction); @@ -2187,7 +2187,7 @@ CategoryData* MemoryDataStore::addCategoryData(ObjectId id, Transaction *transac MemoryCategoryDataSlice *slice = getEntry (id, &categoryData_); if (!slice) { - return NULL; + return nullptr; } CategoryData *data = new CategoryData(); @@ -2202,79 +2202,79 @@ CategoryData* MemoryDataStore::addCategoryData(ObjectId id, Transaction *transac const PlatformUpdateSlice* MemoryDataStore::platformUpdateSlice(ObjectId id) const { PlatformEntry *entry = getEntry(id, &platforms_); - return entry ? entry->updates() : NULL; + return entry ? entry->updates() : nullptr; } const PlatformCommandSlice* MemoryDataStore::platformCommandSlice(ObjectId id) const { PlatformEntry *entry = getEntry(id, &platforms_); - return entry ? entry->commands() : NULL; + return entry ? entry->commands() : nullptr; } const BeamUpdateSlice* MemoryDataStore::beamUpdateSlice(ObjectId id) const { BeamEntry *entry = getEntry(id, &beams_); - return entry ? entry->updates() : NULL; + return entry ? entry->updates() : nullptr; } const BeamCommandSlice* MemoryDataStore::beamCommandSlice(ObjectId id) const { BeamEntry *entry = getEntry(id, &beams_); - return entry ? entry->commands() : NULL; + return entry ? entry->commands() : nullptr; } const GateUpdateSlice* MemoryDataStore::gateUpdateSlice(ObjectId id) const { GateEntry *entry = getEntry(id, &gates_); - return entry ? entry->updates() : NULL; + return entry ? entry->updates() : nullptr; } const GateCommandSlice* MemoryDataStore::gateCommandSlice(ObjectId id) const { GateEntry *entry = getEntry(id, &gates_); - return entry ? entry->commands() : NULL; + return entry ? entry->commands() : nullptr; } const LaserUpdateSlice* MemoryDataStore::laserUpdateSlice(ObjectId id) const { LaserEntry *entry = getEntry(id, &lasers_); - return entry ? entry->updates() : NULL; + return entry ? entry->updates() : nullptr; } const LaserCommandSlice* MemoryDataStore::laserCommandSlice(ObjectId id) const { LaserEntry *entry = getEntry(id, &lasers_); - return entry ? entry->commands() : NULL; + return entry ? entry->commands() : nullptr; } const ProjectorUpdateSlice* MemoryDataStore::projectorUpdateSlice(ObjectId id) const { ProjectorEntry *entry = getEntry(id, &projectors_); - return entry ? entry->updates() : NULL; + return entry ? entry->updates() : nullptr; } const ProjectorCommandSlice* MemoryDataStore::projectorCommandSlice(ObjectId id) const { ProjectorEntry *entry = getEntry(id, &projectors_); - return entry ? entry->commands() : NULL; + return entry ? entry->commands() : nullptr; } const LobGroupUpdateSlice* MemoryDataStore::lobGroupUpdateSlice(ObjectId id) const { LobGroupEntry *entry = getEntry(id, &lobGroups_); - return entry ? entry->updates() : NULL; + return entry ? entry->updates() : nullptr; } const LobGroupCommandSlice* MemoryDataStore::lobGroupCommandSlice(ObjectId id) const { LobGroupEntry *entry = getEntry(id, &lobGroups_); - return entry ? entry->commands() : NULL; + return entry ? entry->commands() : nullptr; } const CustomRenderingCommandSlice* MemoryDataStore::customRenderingCommandSlice(ObjectId id) const { CustomRenderingEntry *entry = getEntry(id, &customRenderings_); - return entry ? entry->commands() : NULL; + return entry ? entry->commands() : nullptr; } const GenericDataSlice* MemoryDataStore::genericDataSlice(ObjectId id) const @@ -2294,7 +2294,7 @@ int MemoryDataStore::modifyPlatformCommandSlice(ObjectId id, VisitableDataSlice< case simData::PLATFORM: { PlatformEntry *entry = getEntry(id, &platforms_); - if (entry == NULL) + if (entry == nullptr) return 1; PlatformCommandSlice* commands = entry->commands(); commands->modify(modifier); @@ -2315,7 +2315,7 @@ int MemoryDataStore::modifyCustomRenderingCommandSlice(ObjectId id, VisitableDat case simData::CUSTOM_RENDERING: { CustomRenderingEntry *entry = getEntry(id, &customRenderings_); - if (entry == NULL) + if (entry == nullptr) return 1; CustomRenderingCommandSlice* commands = entry->commands(); commands->modify(modifier); @@ -2394,7 +2394,7 @@ void MemoryDataStore::setNewUpdatesListener(NewUpdatesListenerPtr callback) std::shared_ptr newRowListener; // If clearing out the updates listener, then also clear out the memory table's listener for performance - if (callback == NULL) + if (callback == nullptr) newUpdatesListener_.reset(new DefaultNewUpdatesListener); else { @@ -2507,11 +2507,11 @@ void MemoryDataStore::MutableSettingsTransactionImpl::release() // Raise notifications for settings changes after internal data structures are updated for (ListenerList::const_iterator i = localCopy.begin(); i != localCopy.end(); ++i) { - if (*i != NULL) + if (*i != nullptr) { (*i)->onPrefsChange(store_, id_); store_->checkForRemoval_(localCopy); - if ((*i != NULL) && (nameChange_)) + if ((*i != nullptr) && (nameChange_)) { (*i)->onNameChange(store_, id_); store_->checkForRemoval_(localCopy); @@ -2526,7 +2526,7 @@ MemoryDataStore::MutableSettingsTransactionImpl::~MutableSettingsTransactionI { release(); delete modifiedSettings_; - modifiedSettings_ = NULL; + modifiedSettings_ = nullptr; } MemoryDataStore::ScenarioSettingsTransactionImpl::ScenarioSettingsTransactionImpl(ScenarioProperties *settings, MemoryDataStore *store, ScenarioListenerList *observers) @@ -2578,7 +2578,7 @@ MemoryDataStore::ScenarioSettingsTransactionImpl::~ScenarioSettingsTransactionIm { release(); delete modifiedSettings_; - modifiedSettings_ = NULL; + modifiedSettings_ = nullptr; } //---------------------------------------------------------------------------- @@ -2590,9 +2590,9 @@ void MemoryDataStore::NewEntryTransactionImpl::commit() { committed_ = true; - assert(entries_ != NULL); - assert(entry_ != NULL); - assert(entry_->properties() != NULL); + assert(entries_ != nullptr); + assert(entry_ != nullptr); + assert(entry_->properties() != nullptr); // Not allows to change the ID assert(initialId_ == entry_->properties()->id()); @@ -2607,7 +2607,7 @@ void MemoryDataStore::NewEntryTransactionImpl::commit() { // Attempting to create an entity with same ID SIM_DEBUG << "Replacing entity with ID " << entry_->properties()->id() << "\n"; - assert(i->second != NULL); + assert(i->second != nullptr); delete i->second; i->second = entry_; } @@ -2631,7 +2631,7 @@ void MemoryDataStore::NewEntryTransactionImpl::release() { // Delete the uncommitted entry delete entry_; - entry_ = NULL; + entry_ = nullptr; } else { @@ -2648,7 +2648,7 @@ void MemoryDataStore::NewEntryTransactionImpl::release() store_->justRemoved_.clear(); for (ListenerList::const_iterator i = localCopy.begin(); i != localCopy.end(); ++i) { - if (*i != NULL) + if (*i != nullptr) { (*i)->onAddEntity(store_, id, ot); store_->checkForRemoval_(localCopy); @@ -2717,7 +2717,7 @@ void MemoryDataStore::NewUpdateTransactionImpl::release() { // Delete the uncommitted update delete update_; - update_ = NULL; + update_ = nullptr; } } @@ -2758,7 +2758,7 @@ void MemoryDataStore::NewScenarioGenericUpdateTransactionImpl::rel { // Delete the uncommitted update delete update_; - update_ = NULL; + update_ = nullptr; } } diff --git a/SDK/simData/MemoryDataStore.h b/SDK/simData/MemoryDataStore.h index 4d52b1df3..d7b6c1ced 100644 --- a/SDK/simData/MemoryDataStore.h +++ b/SDK/simData/MemoryDataStore.h @@ -112,7 +112,7 @@ class SDKDATA_EXPORT MemoryDataStore : public DataStore /// Specify the interpolator to use virtual void setInterpolator(Interpolator *interpolator); - /// Get the current interpolator (NULL if disabled) + /// Get the current interpolator (nullptr if disabled) virtual Interpolator* interpolator() const; ///@} @@ -159,7 +159,7 @@ class SDKDATA_EXPORT MemoryDataStore : public DataStore ///@} /**@name Properties - * @note should always return a valid object (never NULL) + * @note should always return a valid object (never nullptr) * @{ */ virtual const ScenarioProperties *scenarioProperties(Transaction *transaction) const; @@ -182,7 +182,7 @@ class SDKDATA_EXPORT MemoryDataStore : public DataStore ///@} /**@name Object Preferences - * @note will return NULL if no object is associated with the specified id + * @note will return nullptr if no object is associated with the specified id * @{ */ virtual const PlatformPrefs *platformPrefs(ObjectId id, Transaction *transaction) const; @@ -240,7 +240,7 @@ class SDKDATA_EXPORT MemoryDataStore : public DataStore virtual int removeGenericDataTag(ObjectId id, const std::string& tag); /**@name Add data update, command, generic data, or category data - *@note Returns NULL if platform for specified ID does not exist + *@note Returns nullptr if platform for specified ID does not exist * @{ */ virtual PlatformUpdate *addPlatformUpdate(ObjectId id, Transaction *transaction); @@ -316,7 +316,7 @@ class SDKDATA_EXPORT MemoryDataStore : public DataStore /**@name NewUpdatesListener * @{ */ - /// Sets a listener for when entity updates are added; use NULL to remove. + /// Sets a listener for when entity updates are added; use nullptr to remove. virtual void setNewUpdatesListener(NewUpdatesListenerPtr callback); /// Retrieves the listener for new updates (internal) NewUpdatesListener& newUpdatesListener() const; diff --git a/SDK/simData/MemoryGenericDataSlice.cpp b/SDK/simData/MemoryGenericDataSlice.cpp index 949c1472e..c1d7a85af 100644 --- a/SDK/simData/MemoryGenericDataSlice.cpp +++ b/SDK/simData/MemoryGenericDataSlice.cpp @@ -428,8 +428,8 @@ bool MemoryGenericDataSlice::update(double time) void MemoryGenericDataSlice::insert(GenericData* data, bool ignoreDuplicates) { // Should always pass data in - assert(data != NULL); - if (data == NULL) + assert(data != nullptr); + if (data == nullptr) return; for (int k = 0; k < data->entry_size(); ++k) @@ -486,7 +486,7 @@ bool MemoryGenericDataSlice::isDirty() const void MemoryGenericDataSlice::visit(Visitor *visitor) const { - if (visitor == NULL) + if (visitor == nullptr) return; if (genericData_.empty()) diff --git a/SDK/simData/MemoryTable/DataColumn.cpp b/SDK/simData/MemoryTable/DataColumn.cpp index 65afe7c38..3e47659a2 100644 --- a/SDK/simData/MemoryTable/DataColumn.cpp +++ b/SDK/simData/MemoryTable/DataColumn.cpp @@ -289,8 +289,8 @@ class DataContainerT : public DataContainer /** Instantiates a new data column. */ DataColumn::DataColumn(TimeContainer* timeContainer, const std::string& columnName, TableId tableId, TableColumnId columnId, VariableType storageType, UnitType unitType) : timeContainer_(timeContainer), - freshData_(NULL), - staleData_(NULL), + freshData_(nullptr), + staleData_(nullptr), name_(columnName), tableId_(tableId), id_(columnId), @@ -298,14 +298,14 @@ DataColumn::DataColumn(TimeContainer* timeContainer, const std::string& columnNa unitType_(unitType) { // Assertion failure means invalid precondition - assert(timeContainer_ != NULL); + assert(timeContainer_ != nullptr); freshData_ = newDataContainer_(variableType_); staleData_ = newDataContainer_(variableType_); // Assertion means we didn't make a data container, which would only happen if // someone added a new variable type. Note this would show up as a Linux // compile time warning as well, as long as switch() doesn't have a default case. - assert(freshData_ != NULL); - assert(staleData_ != NULL); + assert(freshData_ != nullptr); + assert(staleData_ != nullptr); } /** Columns contain no dynamic memory */ @@ -346,8 +346,8 @@ class DataColumn::FlushContainer : public simData::DelayedFlushContainer { delete freshData_; delete staleData_; - freshData_ = NULL; - staleData_ = NULL; + freshData_ = nullptr; + staleData_ = nullptr; } private: DataContainer* freshData_; @@ -447,7 +447,7 @@ TableStatus DataColumn::interpolate(double& value, double time, const Interpolat void DataColumn::replaceTimeContainer(TimeContainer* newTimes) { // Assertion failure means invalid precondition - assert(newTimes != NULL); + assert(newTimes != nullptr); timeContainer_ = newTimes; } @@ -505,7 +505,7 @@ DataContainer* DataColumn::newDataContainer_(simData::VariableType variableType) case VT_DOUBLE: return new DataContainerT(); case VT_STRING: return new DataContainerT(); } - return NULL; + return nullptr; } void DataColumn::swapFreshStaleData() diff --git a/SDK/simData/MemoryTable/DoubleBufferTimeContainer.cpp b/SDK/simData/MemoryTable/DoubleBufferTimeContainer.cpp index 40d67f0b0..32e2151fb 100644 --- a/SDK/simData/MemoryTable/DoubleBufferTimeContainer.cpp +++ b/SDK/simData/MemoryTable/DoubleBufferTimeContainer.cpp @@ -71,8 +71,8 @@ class DoubleBufferTimeContainer::FlushContainer : public DelayedFlushContainer public: /** Construct a new FlushContainer */ FlushContainer(TimeIndexDeque& timesA, TimeIndexDeque& timesB) - : timesA_(NULL), - timesB_(NULL) + : timesA_(nullptr), + timesB_(nullptr) { // Optimize the case where vectors are empty if (!timesA.empty()) @@ -89,9 +89,9 @@ class DoubleBufferTimeContainer::FlushContainer : public DelayedFlushContainer virtual ~FlushContainer() { delete timesA_; - timesA_ = NULL; + timesA_ = nullptr; delete timesB_; - timesB_ = NULL; + timesB_ = nullptr; } private: TimeIndexDeque* timesA_; @@ -114,7 +114,7 @@ class DoubleBufferTimeContainer::DoubleBufferIterator : public TimeContainer::It DoubleBufferIterator() : binIndex_(BIN_INVALID) { - ownerBins_[BIN_STALE] = ownerBins_[BIN_FRESH] = NULL; + ownerBins_[BIN_STALE] = ownerBins_[BIN_FRESH] = nullptr; // Order here doesn't really matter since the bins are invalid iter_[BIN_STALE] = &iterA_; iter_[BIN_FRESH] = &iterB_; @@ -235,7 +235,7 @@ class DoubleBufferTimeContainer::DoubleBufferIterator : public TimeContainer::It // Make a copy of iterators to prevent change TimeIndexDeque::iterator freshIter = freshIter_(); TimeIndexDeque::iterator staleIter = staleIter_(); - return previous_(freshIter, staleIter, NULL); + return previous_(freshIter, staleIter, nullptr); } /** Resets the iterator to the front of the data structure, before the first element */ @@ -317,7 +317,7 @@ class DoubleBufferTimeContainer::DoubleBufferIterator : public TimeContainer::It bool isValid_() const { - return staleTimes_() != NULL && freshTimes_() != NULL && + return staleTimes_() != nullptr && freshTimes_() != nullptr && (binIndex_ == BIN_STALE || binIndex_ == BIN_FRESH); } size_t otherBin_() const @@ -578,7 +578,7 @@ TimeContainer::Iterator DoubleBufferTimeContainer::findOrAddTime(double timeValu void DoubleBufferTimeContainer::erase(TimeContainer::Iterator iter, TimeContainer::EraseBehavior eraseBehavior) { DoubleBufferIterator* dbIter = dynamic_cast(iter.impl()); - if (dbIter != NULL) + if (dbIter != nullptr) dbIter->erase(eraseBehavior); } @@ -607,7 +607,7 @@ DoubleBufferTimeContainer::TimeIndexDeque::iterator DoubleBufferTimeContainer::l { LessThan lessThan; TimeIndexDeque::iterator i = std::lower_bound(deq.begin(), deq.end(), timeValue, lessThan); - if (exactMatch != NULL) + if (exactMatch != nullptr) *exactMatch = ((i != deq.end()) && (i->first == timeValue)); return i; } @@ -640,7 +640,7 @@ DoubleBufferTimeContainer::TimeIndexDeque& DoubleBufferTimeContainer::staleTimes void DoubleBufferTimeContainer::swapFreshStaleData(DataTable* table, const std::vector& observers) { // Before clearing out the stale bin, announce that all those times are being removed - if (table != NULL && !times_[BIN_STALE]->empty()) + if (table != nullptr && !times_[BIN_STALE]->empty()) { // Loop through each observer for (std::vector::const_iterator oiter = observers.begin(); oiter != observers.end(); ++oiter) diff --git a/SDK/simData/MemoryTable/DoubleBufferTimeContainer.h b/SDK/simData/MemoryTable/DoubleBufferTimeContainer.h index 94f13d73f..9277b91e5 100644 --- a/SDK/simData/MemoryTable/DoubleBufferTimeContainer.h +++ b/SDK/simData/MemoryTable/DoubleBufferTimeContainer.h @@ -62,7 +62,7 @@ class SDKDATA_EXPORT DoubleBufferTimeContainer : public TimeContainer virtual TimeContainer::Iterator upper_bound(double timeValue); virtual TimeContainer::Iterator findTimeAtOrBeforeGivenTime(double timeValue); virtual TimeContainer::Iterator find(double timeValue); - virtual TimeContainer::Iterator findOrAddTime(double timeValue, bool* exactMatch=NULL); + virtual TimeContainer::Iterator findOrAddTime(double timeValue, bool* exactMatch=nullptr); virtual void erase(Iterator iter, EraseBehavior eraseBehavior); virtual DelayedFlushContainerPtr flush(); @@ -85,7 +85,7 @@ class SDKDATA_EXPORT DoubleBufferTimeContainer : public TimeContainer typedef std::pair RowTimeToIndex; // pTimeIndex typedef std::deque TimeIndexDeque; - TimeIndexDeque::iterator lowerBound_(TimeIndexDeque& deq, double timeValue, bool* exactMatch=NULL) const; + TimeIndexDeque::iterator lowerBound_(TimeIndexDeque& deq, double timeValue, bool* exactMatch=nullptr) const; TimeIndexDeque::iterator upperBound_(TimeIndexDeque& deq, double timeValue) const; TimeContainer::Iterator newIterator_(size_t whichBin, TimeIndexDeque::iterator staleIter, TimeIndexDeque::iterator freshIter); diff --git a/SDK/simData/MemoryTable/SubTable.cpp b/SDK/simData/MemoryTable/SubTable.cpp index 7bf4ca5df..124e47d95 100644 --- a/SDK/simData/MemoryTable/SubTable.cpp +++ b/SDK/simData/MemoryTable/SubTable.cpp @@ -91,7 +91,7 @@ class SubTable::AddRowTransactionImpl : public SubTable::AddRowTransaction TableStatus setCellValue_(TableColumnId columnId, T& value) { DataColumn* column = subTable_.findColumn_(columnId); - if (column == NULL) + if (column == nullptr) return TableStatus::Error("Column does not exist in subtable."); if (!insertRow_) return column->replace(isFreshBin_, rowIndex_, value); @@ -149,7 +149,7 @@ class SubTable::AddRowTransactionImpl : public SubTable::AddRowTransaction void notifyObserver_(SubTable* newTable, const std::vector& startingColumns) { - if (splitObserver_.get() == NULL) + if (splitObserver_.get() == nullptr) { // Indicates we have a memory leak because no one is available // to take ownership of the newly created subtable. @@ -275,7 +275,7 @@ SubTable::SubTable(TimeContainer* newTimeContainer, TableId tableId) tableId_(tableId) { // Assertion failure means the caller gave us a bad time container to use - assert(timeContainer_ != NULL && timeContainer_->size() == 0); + assert(timeContainer_ != nullptr && timeContainer_->size() == 0); } SubTable::SubTable(const TimeContainer& copyTimes, const std::vector& withColumns, double withoutTimeStamp, TableId tableId) @@ -329,7 +329,7 @@ TableStatus SubTable::addColumn(const std::string& columnName, TableColumnId col return TableStatus::Error("Attempting to add column to a non-empty subtable, violates NULL-less state."); DataColumn* newColumn = new DataColumn(timeContainer_, columnName, tableId_, columnId, storageType, unitType); columns_.push_back(newColumn); - if (newCol != NULL) *newCol = newColumn; + if (newCol != nullptr) *newCol = newColumn; // Assertion failure means reuse of IDs assert(columnMap_.find(columnId) == columnMap_.end()); @@ -398,7 +398,7 @@ simData::DelayedFlushContainerPtr SubTable::flush(TableColumnId id, SplitObserve } // Complex case: Flushing one column among many - if (splitObserver.get() == NULL) + if (splitObserver.get() == nullptr) { // Split observer is required when flushing a single column. // Without it, no one will take ownership of the new sub table @@ -406,7 +406,7 @@ simData::DelayedFlushContainerPtr SubTable::flush(TableColumnId id, SplitObserve return DelayedFlushContainerPtr(deq); } - DataColumn* removedCol = NULL; + DataColumn* removedCol = nullptr; for (std::vector::const_iterator i = columns_.begin(); i != columns_.end(); ++i) { if ((*i)->columnId() == id) @@ -418,7 +418,7 @@ simData::DelayedFlushContainerPtr SubTable::flush(TableColumnId id, SplitObserve } // Didn't find the column in this sub table. Nothing to do, return - if (removedCol == NULL) + if (removedCol == nullptr) return DelayedFlushContainerPtr(deq); // Split off the flushed column to a new subtable @@ -437,14 +437,14 @@ DataColumn* SubTable::findColumn_(TableColumnId columnId) const { std::map::const_iterator i = columnMap_.find(columnId); if (i == columnMap_.end()) - return NULL; + return nullptr; return i->second; } TableStatus SubTable::interpolate(TableColumnId columnId, double time, double& value, const TableColumn::Interpolator* interpolator) const { TableColumn* column = findColumn_(columnId); - if (column == NULL) + if (column == nullptr) return TableStatus::Error("Invalid column index."); return column->interpolate(value, time, interpolator); } diff --git a/SDK/simData/MemoryTable/SubTable.h b/SDK/simData/MemoryTable/SubTable.h index cca114c90..302848831 100644 --- a/SDK/simData/MemoryTable/SubTable.h +++ b/SDK/simData/MemoryTable/SubTable.h @@ -203,7 +203,7 @@ class SDKDATA_EXPORT SubTable /// Initializes a subtable using the columns provided, with our time map (minus "withoutTimeStamp") SubTable(const TimeContainer& copyTimes, const std::vector& withColumns, double withoutTimeStamp, TableId tableId); - /// Finds a column based on ID, returning NULL if none + /// Finds a column based on ID, returning nullptr if none DataColumn* findColumn_(TableColumnId columnId) const; /// Removes but does not delete, used in splits to maintain null-less table TableStatus removeColumn_(TableColumnId columnId); diff --git a/SDK/simData/MemoryTable/Table.cpp b/SDK/simData/MemoryTable/Table.cpp index d1550a138..81579a1c6 100644 --- a/SDK/simData/MemoryTable/Table.cpp +++ b/SDK/simData/MemoryTable/Table.cpp @@ -125,7 +125,7 @@ class Table::TransferCellsToSubTables : public TableRow::CellVisitor return; // Find the appropriate subtable for the column SubTable* subTable = owner_.subTableForId_(columnId); - if (subTable == NULL) + if (subTable == nullptr) { visitStatus_ = TableStatus::Error("Table column ID not found."); return; @@ -205,7 +205,7 @@ TableColumn* Table::column(TableColumnId id) const std::map::const_iterator i = columns_.find(id); if (i != columns_.end()) return i->second.second; - return NULL; + return nullptr; } TableColumn* Table::column(const std::string& name) const @@ -214,41 +214,41 @@ TableColumn* Table::column(const std::string& name) const if (i != columnsByName_.end()) return i->second; - return NULL; + return nullptr; } SubTable* Table::subTableForId_(TableColumnId columnId) const { std::map::const_iterator i = columns_.find(columnId); if (i == columns_.end()) - return NULL; + return nullptr; return i->second.first; } TableStatus Table::addColumn(const std::string& columnName, VariableType storageType, UnitType unitType, TableColumn** newColumn) { if (columnName.empty()) - return TableStatus::Error("Unable to create table with empty name."); + return TableStatus::Error("Unable to create column with empty name."); // Check for existing name TableColumn* existing = column(columnName); if (existing) { if (newColumn) *newColumn = existing; - return TableStatus::Error("Table name already exists."); + return TableStatus::Error("Column name already exists."); } // Find an empty subtable to add the new column - SubTable* emptyTable = NULL; + SubTable* emptyTable = nullptr; for (std::vector::const_iterator i = subtables_.begin(); - i != subtables_.end() && emptyTable == NULL; ++i) + i != subtables_.end() && emptyTable == nullptr; ++i) { if ((*i)->empty()) emptyTable = *i; } // Create the subtable if we have to - TableColumn* returnColumn = NULL; - if (emptyTable == NULL) + TableColumn* returnColumn = nullptr; + if (emptyTable == nullptr) { // Create an empty table with a new time container emptyTable = new SubTable(new DoubleBufferTimeContainer(), tableId_); @@ -272,12 +272,12 @@ TableStatus Table::addColumn(const std::string& columnName, VariableType storage } // At this point, we've used nextId_ and we have a valid column - assert(returnColumn != NULL); + assert(returnColumn != nullptr); // Save the column, and do any callbacks columns_[nextId_++] = std::make_pair(emptyTable, returnColumn); columnsByName_[columnName] = returnColumn; // Assertion failure means we somehow forgot to set newColumn return value - assert(newColumn == NULL || *newColumn == returnColumn); + assert(newColumn == nullptr || *newColumn == returnColumn); // notify observers of new column fireOnAddColumn_(*returnColumn); return TableStatus::Success(); @@ -292,7 +292,7 @@ TableStatus Table::removeColumn(const std::string& columnName) TableColumn* column = colByNameIter->second; if (!column) { - // Shouldn't be storing a NULL column + // Shouldn't be storing a nullptr column assert(0); return TableStatus::Error("Column \"" + columnName + "\" does not exist."); } @@ -308,7 +308,7 @@ TableStatus Table::removeColumn(const std::string& columnName) auto subtable = columnsIter->second.first; if (!subtable) { - // Shouldn't be storing a NULL subtable pointer + // Shouldn't be storing a nullptr subtable pointer assert(0); return TableStatus::Error("Column \"" + columnName + "\" does not exist."); } @@ -480,7 +480,7 @@ TableStatus Table::addRow(const TableRow& row) // Do data limiting when rows are added // TODO: This could feasibly be optimized across the data store with a parallel for-each // that does data limiting at preset intervals - if (dataLimits_ != NULL) + if (dataLimits_ != nullptr) { size_t pointsLimit = 0; double secondsLimit = 0.0; diff --git a/SDK/simData/MemoryTable/Table.h b/SDK/simData/MemoryTable/Table.h index 48a68dee7..69cb1d93b 100644 --- a/SDK/simData/MemoryTable/Table.h +++ b/SDK/simData/MemoryTable/Table.h @@ -40,7 +40,7 @@ class DataLimitsProvider; * a single entity (or the scenario, if owner ID is 0). A single entity may have multiple tables * (represented by a simData::TableList), but a single data table is associated with only one owner. * - * Tables might have NULL values. For performance, the in-memory solution subdivides itself into SubTable + * Tables might have nullptr values. For performance, the in-memory solution subdivides itself into SubTable * instances. Each SubTable is null-less. So this Table implementation is a collection of SubTable * instances. */ diff --git a/SDK/simData/MemoryTable/TableManager.cpp b/SDK/simData/MemoryTable/TableManager.cpp index 3b7894716..821205f59 100644 --- a/SDK/simData/MemoryTable/TableManager.cpp +++ b/SDK/simData/MemoryTable/TableManager.cpp @@ -61,7 +61,7 @@ class TableManager::MemTableList : public simData::TableList virtual DataTable* findTable(const std::string& tableName) const { std::map::const_iterator i = tables_.find(tableName); - return (i == tables_.end()) ? NULL : i->second; + return (i == tables_.end()) ? nullptr : i->second; } // Inherits parent's documentation @@ -136,22 +136,22 @@ TableStatus TableManager::addDataTable(ObjectId ownerId, const std::string& tabl // Don't allow empty string if (tableName.empty()) { - if (newTable != NULL) *newTable = NULL; + if (newTable != nullptr) *newTable = nullptr; return TableStatus::Error("Empty name not permitted for new data tables."); } // Make sure we don't add duplicates std::map::const_iterator i = listsByOwner_.find(ownerId); - MemTableList* list = NULL; + MemTableList* list = nullptr; if (i != listsByOwner_.end()) { list = i->second; // Assertion failure means internal code forgot to erase() an iterator, shouldn't happen - assert(list != NULL); + assert(list != nullptr); DataTable* table = list->findTable(tableName); - if (table != NULL) - { // NULL == table already exists - if (newTable != NULL) *newTable = table; + if (table != nullptr) + { // nullptr == table already exists + if (newTable != nullptr) *newTable = table; return TableStatus::Error("Table with name already exists for specified entity."); } } @@ -168,7 +168,7 @@ TableStatus TableManager::addDataTable(ObjectId ownerId, const std::string& tabl // Assertion failure means reuse of IDs or invalidly saved ID in constructor assert(tablesById_.find(table->tableId()) == tablesById_.end()); tablesById_[table->tableId()] = table; - if (newTable != NULL) *newTable = table; + if (newTable != nullptr) *newTable = table; // notify observers table was added fireOnAddTable_(table); @@ -191,7 +191,7 @@ TableStatus TableManager::deleteTable(TableId tableId) void TableManager::removeTable(MemoryTable::Table* table) { - if (table == NULL) + if (table == nullptr) return; // notify observers table is being removed @@ -199,14 +199,14 @@ void TableManager::removeTable(MemoryTable::Table* table) std::map::iterator tableIter = tablesById_.find(table->tableId()); // Table not found - if (tableIter == tablesById_.end() || tableIter->second == NULL) + if (tableIter == tablesById_.end() || tableIter->second == nullptr) return; // Find the entry in the listsByOwner_ std::map::iterator listIter = listsByOwner_.find(table->ownerId()); // Assertion failure means the list got out of sync with our maps - assert(listIter != listsByOwner_.end() && listIter->second != NULL); - if (listIter != listsByOwner_.end() && listIter->second != NULL) + assert(listIter != listsByOwner_.end() && listIter->second != nullptr); + if (listIter != listsByOwner_.end() && listIter->second != nullptr) { MemTableList* list = listIter->second; // Assertion failure means we lost sync with the list @@ -229,7 +229,7 @@ void TableManager::removeTable(MemoryTable::Table* table) void TableManager::setNewRowDataListener(TableManager::NewRowDataListenerPtr listener) { - if (listener == NULL) + if (listener == nullptr) newRowDataListener_.reset(new DefaultNewRowDataListener); else newRowDataListener_ = listener; @@ -281,7 +281,7 @@ class DeleteTablesInList : public TableList::Visitor void TableManager::deleteTablesByOwner(ObjectId ownerId) { std::map::iterator listIter = listsByOwner_.find(ownerId); - if (listIter == listsByOwner_.end() || listIter->second == NULL) + if (listIter == listsByOwner_.end() || listIter->second == nullptr) return; // nothing to do MemTableList* list = listIter->second; // TODO: Test this; might have iterator invalidation issues @@ -301,19 +301,19 @@ size_t TableManager::tableCount() const const TableList* TableManager::tablesForOwner(ObjectId ownerId) const { std::map::const_iterator i = listsByOwner_.find(ownerId); - return (i == listsByOwner_.end()) ? NULL : i->second; + return (i == listsByOwner_.end()) ? nullptr : i->second; } DataTable* TableManager::getTable(simData::TableId tableId) const { std::map::const_iterator i = tablesById_.find(tableId); - return (i == tablesById_.end() ? NULL : i->second); + return (i == tablesById_.end() ? nullptr : i->second); } DataTable* TableManager::findTable(ObjectId ownerId, const std::string& tableName) const { const TableList* list = tablesForOwner(ownerId); - return (list != NULL) ? list->findTable(tableName) : NULL; + return (list != nullptr) ? list->findTable(tableName) : nullptr; } void TableManager::fireOnAddTable_(DataTable* table) const diff --git a/SDK/simData/MemoryTable/TableManager.h b/SDK/simData/MemoryTable/TableManager.h index 5cff9f8f2..510976f5e 100644 --- a/SDK/simData/MemoryTable/TableManager.h +++ b/SDK/simData/MemoryTable/TableManager.h @@ -89,7 +89,7 @@ class SDKDATA_EXPORT TableManager : public simData::DataTableManager virtual void onNewRowData(simData::DataTable& table, simData::ObjectId id, double dataTime) {} }; - /** Sets the new-row data listener for when new table rows are added; use NULL to remove. */ + /** Sets the new-row data listener for when new table rows are added; use nullptr to remove. */ void setNewRowDataListener(NewRowDataListenerPtr listener); /** Internal method for Table to use to alert on new row data */ diff --git a/SDK/simData/MemoryTable/TimeContainer.h b/SDK/simData/MemoryTable/TimeContainer.h index 3b6427ecd..5ec2bcc6d 100644 --- a/SDK/simData/MemoryTable/TimeContainer.h +++ b/SDK/simData/MemoryTable/TimeContainer.h @@ -155,9 +155,9 @@ class SDKDATA_EXPORT TimeContainer * Either returns the iterator representing the time value, or adds the time * value and returns an iterator such that its next() is the new time value. * @param timeValue Time to find, or add if it didn't exist - * @param exactMatch If non-NULL, will be set to false if added row, or true if found row + * @param exactMatch If non-nullptr, will be set to false if added row, or true if found row */ - virtual Iterator findOrAddTime(double timeValue, bool* exactMatch=NULL) = 0; + virtual Iterator findOrAddTime(double timeValue, bool* exactMatch=nullptr) = 0; /** * Performs data limiting for the container and associated columns diff --git a/SDK/simData/MessageVisitor/Message.cpp b/SDK/simData/MessageVisitor/Message.cpp index c4c8ddf99..76087a813 100644 --- a/SDK/simData/MessageVisitor/Message.cpp +++ b/SDK/simData/MessageVisitor/Message.cpp @@ -39,13 +39,13 @@ int getField(google::protobuf::Message& message, std::pairGetDescriptor(); lastDesc = msgDesc->FindFieldByName(tokens[i]); - if (lastDesc == NULL) + if (lastDesc == nullptr) { // The given path does not match the definition of the protobuf return 2; @@ -59,7 +59,7 @@ int getField(google::protobuf::Message& message, std::pairGetReflection()->MutableMessage(const_cast(currentMessage), lastDesc); - if (currentMessage == NULL) // Safety catch + if (currentMessage == nullptr) // Safety catch return 4; } else if (i != tokens.size() - 1) @@ -69,10 +69,10 @@ int getField(google::protobuf::Message& message, std::pairGetReflection(); diff --git a/SDK/simData/NearestNeighborInterpolator.cpp b/SDK/simData/NearestNeighborInterpolator.cpp index ad0992a42..e6bb048fe 100644 --- a/SDK/simData/NearestNeighborInterpolator.cpp +++ b/SDK/simData/NearestNeighborInterpolator.cpp @@ -28,7 +28,7 @@ namespace template bool compute(double time, const T &prev, const T &next, T *result) { - assert(result != NULL && prev.time() <= time && time <= next.time()); + assert(result != nullptr && prev.time() <= time && time <= next.time()); double midPoint = (next.time() + prev.time()) / 2.0; if (time < midPoint) diff --git a/SDK/simData/PrefRulesManager.h b/SDK/simData/PrefRulesManager.h index b0e52f9e1..30c521aa6 100644 --- a/SDK/simData/PrefRulesManager.h +++ b/SDK/simData/PrefRulesManager.h @@ -48,7 +48,7 @@ class PrefRule /** * Apply this rule to the specified entity, if all conditions are met. * (Gathers all the required data from the DataStore in this call, which can be expensive.) - * @param[in] entityId id of the entity + * @param[in] entityId id of the entity. 0 is not a valid value and will not match any entities. * @param[in] ds handle to the data store * @return 0 on successful application, non-zero on error */ @@ -66,7 +66,8 @@ class PrefRulesManager virtual ~PrefRulesManager() {} /** - * Load the rules in the specified pref rule file, adding them to the currently loaded rules + * Load the rules in the specified pref rule file, adding them to the currently loaded rules. Rules are always + * force applied when added. * @param ruleFile the pref rule file to load * @return 0 on success, non-zero on error */ @@ -76,7 +77,7 @@ class PrefRulesManager * Enforce the pref value specified by tagStack and entityType on the specified entity. This means that the pref value will * not be updated by normal processing. Only components with authority to override the pref value enforcement will do so. * This is useful for cases where a pref update from one source should be flagged to take priority over updates from other sources. - * @param id the data store entity id + * @param id the data store entity id. 0 is not a valid value and will not match any entities. * @param tagStack the protobuf message field numbers that identify the pref (fully qualified from PlatformPrefs, BeamPrefs, etc.) * @param enforce If true, then turn on enforcing, preventing rules from changing the value. If false, disables the enforcement, * allowing preference rules to work with the value again. @@ -86,14 +87,14 @@ class PrefRulesManager /** * Returns true if the preference value is set to enforcing. Enforced prefs cannot be changed by Preference Rules. For * more details, see enforcePrefValue(). - * @param id the data store entity id + * @param id the data store entity id. 0 is not a valid value and will not match any entities. * @param tagStack the protobuf message field numbers that identify the pref (fully qualified from PlatformPrefs, BeamPrefs, etc.) * @return True if the value is marked for enforcement, false otherwise */ virtual bool isPrefValueEnforced(simData::ObjectId id, const std::deque& tagStack) const = 0; /** - * Load the rules in the specified pref rule files. + * Load the rules in the specified pref rule files. Rules are always force applied when added. * Note that the last file in the vector is the one saved to the scenario as the current pref rule file. * @param ruleFiles list of the pref rule files to load * @param removeOldRules if true, all rules will be removed and replaced with those in the ruleFiles param @@ -122,7 +123,7 @@ class PrefRulesManager virtual int serializeRules(std::ostream& os) = 0; /** - * Deserializes the rules passed in the istream + * Deserializes the rules passed in the istream. Rules are always force applied when added. * @param[in] rules rules to deserialize * @return 0 on total success, non-zero if there were any problems loading rules. Note that non-zero return can still indicate partial success */ @@ -131,6 +132,7 @@ class PrefRulesManager /** * Add a preference rule. PrefRuleManager will deserialize the string into a pref rule, or multiple * rules if the pref rule is compound. The latest version of the preference rules format is presumed. + * Rules are always force applied when added. * @param[out] rules that resulted from the serialized string (rule could be compound) * @param[in] serializedRule a string representing a serialized pref rule * @param[in] fileFormatVersion an int representing the pref .rul file format version the pref rule is formatted in @@ -162,7 +164,7 @@ class PrefRulesManager /** * Applies all the rules to the specified entity - * @param[in] id the specified entity + * @param[in] id the specified entity. 0 is not a valid value and will not match any entities. * @return 0 on success, non-zero on error */ virtual int applyRules(uint64_t id) = 0; diff --git a/SDK/simNotify/Notify.cpp b/SDK/simNotify/Notify.cpp index 133fd668d..cfb651515 100644 --- a/SDK/simNotify/Notify.cpp +++ b/SDK/simNotify/Notify.cpp @@ -76,7 +76,7 @@ namespace simNotify severityLimit_ = severity; } - /** Retrieves the handler for the given severity, never NULL */ + /** Retrieves the handler for the given severity, never nullptr */ NotifyHandlerPtr handler(NotifySeverity severity) const { assert(severity >= simNotify::NOTIFY_ALWAYS && severity <= simNotify::NOTIFY_DEBUG_FP); @@ -91,8 +91,8 @@ namespace simNotify assert(severity >= simNotify::NOTIFY_ALWAYS && severity <= simNotify::NOTIFY_DEBUG_FP); if (severity >= simNotify::NOTIFY_ALWAYS && severity <= simNotify::NOTIFY_DEBUG_FP) { - // Avoid NULL assignments - if (handler == NULL) + // Avoid nullptr assignments + if (handler == nullptr) handler = nullNotifyHandler_; handlers_[severity] = handler; } @@ -101,8 +101,8 @@ namespace simNotify /** Changes the handler for all severities */ void setNotifyHandlers(NotifyHandlerPtr handler) { - assert(handler != NULL); - if (handler == NULL) + assert(handler != nullptr); + if (handler == nullptr) return; for (std::vector::iterator i = handlers_.begin(); i != handlers_.end(); ++i) *i = handler; @@ -176,7 +176,10 @@ namespace simNotify NotifyHandlerPtr notifyHandler(NotifySeverity severity) { - return notifyContext_->handler(severity); + NotifyHandlerPtr rv = notifyContext_->handler(severity); + if (rv) + rv->setSeverity(severity); + return rv; } void setNotifyHandler(NotifySeverity severity, NotifyHandlerPtr handler) @@ -195,7 +198,7 @@ namespace simNotify if (isNotifyEnabled(severity)) { NotifyHandlerPtr handler = notifyContext_->handler(severity); - if (handler != NULL) + if (handler != nullptr) { handler->setSeverity(severity); handler->notifyPrefix(); @@ -264,7 +267,7 @@ namespace simNotify void installNotifyContext(NotifyContext* const context) { - if (context != NULL) + if (context != nullptr) notifyContext_ = context; } diff --git a/SDK/simQt.h b/SDK/simQt.h index 386428d9d..dc431a0ba 100644 --- a/SDK/simQt.h +++ b/SDK/simQt.h @@ -70,7 +70,6 @@ #include "simQt/FontWidget.h" #include "simQt/GanttChartView.h" #include "simQt/Gl3FormatGuesser.h" -#include "simQt/IncrementalCompileSettings.h" #include "simQt/MapDataModel.h" #include "simQt/MonospaceItemDelegate.h" #include "simQt/MruList.h" @@ -103,6 +102,7 @@ #include "simQt/Toast.h" #include "simQt/UnitContext.h" #include "simQt/UnitsComboBox.h" +#include "simQt/ValueMerge.h" #include "simQt/ViewManagerDataModel.h" #include "simQt/ViewWidget.h" #include "simQt/WeightedMenuManager.h" diff --git a/SDK/simQt/ActionItemModel.cpp b/SDK/simQt/ActionItemModel.cpp index 8171f3d46..0ed78e944 100644 --- a/SDK/simQt/ActionItemModel.cpp +++ b/SDK/simQt/ActionItemModel.cpp @@ -105,7 +105,7 @@ class ActionItemModel::GroupItem : public ActionItemModel::TreeItem /**@name tree actions *@{ */ - virtual TreeItem* parent() const { return NULL; } + virtual TreeItem* parent() const { return nullptr; } virtual TreeItem* child(int row) const { return children_[row]; } virtual int indexOf(TreeItem* child) const { return children_.indexOf(child); } virtual int numChildren() const { return children_.size(); } @@ -120,16 +120,16 @@ class ActionItemModel::GroupItem : public ActionItemModel::TreeItem /// find an item corresponding to the given action virtual TreeItem* find(const Action* action) const { - if (action != NULL && action->group() == name_) + if (action != nullptr && action->group() == name_) { // Search children for (auto it = children_.begin(); it != children_.end(); ++it) { TreeItem* child = (*it)->find(action); - if (child != NULL) + if (child != nullptr) return child; } } - return NULL; + return nullptr; } //--- local functions @@ -163,7 +163,7 @@ class ActionItemModel::GroupItem : public ActionItemModel::TreeItem * Finds the child with the given name *@param name name to match *@param rowIndex row containing the match (-1 on no match) - *@return the item corresponding to the given name, will return NULL on no match + *@return the item corresponding to the given name, will return nullptr on no match */ TreeItem* findChild(const QString& name, int& rowIndex) const { @@ -178,7 +178,7 @@ class ActionItemModel::GroupItem : public ActionItemModel::TreeItem k++; } rowIndex = -1; - return NULL; + return nullptr; } private: @@ -210,7 +210,7 @@ class ActionItemModel::ActionItem : public ActionItemModel::TreeItem } virtual QVariant decoration(int col) const { - if (col == 0 && action_->action() != NULL) + if (col == 0 && action_->action() != nullptr) { return action_->action()->icon(); } @@ -256,7 +256,7 @@ class ActionItemModel::ActionItem : public ActionItemModel::TreeItem *@{ */ virtual TreeItem* parent() const { return parent_; } - virtual TreeItem* child(int row) const { return NULL; } + virtual TreeItem* child(int row) const { return nullptr; } virtual int indexOf(TreeItem* child) const { return -1; } virtual int numChildren() const { return 0; } @@ -264,7 +264,7 @@ class ActionItemModel::ActionItem : public ActionItemModel::TreeItem ///@} /// find an item corresponding to the given action - virtual TreeItem* find(const Action* action) const { return (action == action_) ? const_cast(this) : NULL; } + virtual TreeItem* find(const Action* action) const { return (action == action_) ? const_cast(this) : nullptr; } private: ActionItemModel::GroupItem* parent_; @@ -274,7 +274,7 @@ class ActionItemModel::ActionItem : public ActionItemModel::TreeItem ////////////////////////////////////////////////////////////////////// ActionItemModel::ActionItemModel(QObject* parent) : QAbstractItemModel(parent), - registry_(NULL), + registry_(nullptr), readOnly_(false) { } @@ -315,7 +315,7 @@ QModelIndex ActionItemModel::index(int row, int column, const QModelIndex &paren return createIndex(row, column, groups_[row]); TreeItem* parentItem = static_cast(parent.internalPointer()); // Item was not made correctly, check index() - assert(parentItem != NULL); + assert(parentItem != nullptr); return createIndex(row, column, parentItem->child(row)); } @@ -326,12 +326,12 @@ QModelIndex ActionItemModel::parent(const QModelIndex &child) const TreeItem *childItem = static_cast(child.internalPointer()); // Item was not made correctly, check index() - assert(childItem != NULL); - if (childItem == NULL) + assert(childItem != nullptr); + if (childItem == nullptr) return QModelIndex(); // parentItem should be pointing to a group item GroupItem *parentItem = dynamic_cast(childItem->parent()); - if (parentItem == NULL) + if (parentItem == nullptr) return QModelIndex(); return createIndex(groups_.indexOf(parentItem), 0, parentItem); } @@ -343,7 +343,7 @@ int ActionItemModel::rowCount(const QModelIndex &parent) const if (parent.column() != 0) return 0; TreeItem* parentItem = static_cast(parent.internalPointer()); - return (parentItem == NULL) ? 0 : parentItem->numChildren(); + return (parentItem == nullptr) ? 0 : parentItem->numChildren(); } return groups_.size(); } @@ -380,7 +380,7 @@ Qt::ItemFlags ActionItemModel::flags(const QModelIndex& index) const if (index.isValid()) { TreeItem* item = static_cast(index.internalPointer()); - if (item != NULL) + if (item != nullptr) { Qt::ItemFlags rv = item->flags(index.column()); // Remove the editable flag if needed @@ -398,7 +398,7 @@ bool ActionItemModel::setData(const QModelIndex& index, const QVariant& value, i if (index.isValid() && role == Qt::EditRole) { TreeItem* item = static_cast(index.internalPointer()); - if (item != NULL) + if (item != nullptr) return item->setData(index.column(), value); } return QAbstractItemModel::setData(index, value, role); @@ -426,7 +426,7 @@ QVariant ActionItemModel::headerData(int section, Qt::Orientation orientation, i void ActionItemModel::connect_(ActionRegistry* newRegistry) { - if (newRegistry == NULL) + if (newRegistry == nullptr) return; connect(newRegistry, SIGNAL(actionAdded(simQt::Action*)), this, SLOT(actionAdded(simQt::Action*))); connect(newRegistry, SIGNAL(actionRemoved(const simQt::Action*)), this, SLOT(actionRemoved(const simQt::Action*))); @@ -435,7 +435,7 @@ void ActionItemModel::connect_(ActionRegistry* newRegistry) void ActionItemModel::disconnect_(ActionRegistry* oldRegistry) { - if (oldRegistry == NULL) + if (oldRegistry == nullptr) return; disconnect(oldRegistry, SIGNAL(actionAdded(simQt::Action*)), this, SLOT(actionAdded(simQt::Action*))); disconnect(oldRegistry, SIGNAL(actionRemoved(const simQt::Action*)), this, SLOT(actionRemoved(const simQt::Action*))); @@ -444,7 +444,7 @@ void ActionItemModel::disconnect_(ActionRegistry* oldRegistry) void ActionItemModel::createGroupedList_(QList& groups) const { - if (registry_ == NULL) + if (registry_ == nullptr) return; // Query the registry and sort into groups @@ -480,11 +480,11 @@ void ActionItemModel::createGroupedList_(QList& groups) const void ActionItemModel::actionAdded(Action* action) { - if (action == NULL) + if (action == nullptr) return; GroupItem* group = findGroup_(action->group()); // New group to create? - if (group == NULL) + if (group == nullptr) { // Find newPosition, the index pointing to the alphabetical insertion point int newPosition; @@ -515,7 +515,7 @@ void ActionItemModel::actionAdded(Action* action) void ActionItemModel::actionRemoved(const Action* action) { TreeItem* item = findAction_(action); - if (item == NULL || item->parent() == NULL) + if (item == nullptr || item->parent() == nullptr) return; // Case 1: last item in the list, let's just remove the whole group TreeItem* parent = item->parent(); @@ -551,21 +551,21 @@ ActionItemModel::GroupItem* ActionItemModel::findGroup_(const QString& name) con if ((*it)->title() == name) return *it; } - return NULL; + return nullptr; } ActionItemModel::TreeItem* ActionItemModel::findAction_(const Action* action) const { - if (action == NULL) - return NULL; + if (action == nullptr) + return nullptr; GroupItem* group = findGroup_(action->group()); - return (group == NULL) ? NULL : group->find(action); + return (group == nullptr) ? nullptr : group->find(action); } QModelIndex ActionItemModel::indexOfAction_(Action* action) const { TreeItem* treeItem = findAction_(action); - if (treeItem != NULL) + if (treeItem != nullptr) return createIndex(treeItem->row(), 0, treeItem); return QModelIndex(); } @@ -692,7 +692,7 @@ ActionItemModelDelegate::~ActionItemModelDelegate() void ActionItemModelDelegate::closeAndCommitEditor_() { KeySequenceEdit* editor = qobject_cast(sender()); - assert(editor != NULL); + assert(editor != nullptr); emit commitData(editor); emit closeEditor(editor); } @@ -710,7 +710,7 @@ void ActionItemModelDelegate::setEditorData(QWidget* editWidget, const QModelInd if (!index.isValid()) return; KeySequenceEdit* editor = qobject_cast(editWidget); - assert(editor != NULL); + assert(editor != nullptr); // Pull out the QVariant data from the data model QVariant itemData = index.model()->data(index, Qt::DisplayRole); if (itemData.isValid()) @@ -724,7 +724,7 @@ void ActionItemModelDelegate::setModelData(QWidget* editWidget, QAbstractItemMod return; // Set the data in the model from our data KeySequenceEdit* editor = qobject_cast(editWidget); - assert(editor != NULL); + assert(editor != nullptr); model->setData(index, editor->key(), Qt::EditRole); } @@ -734,8 +734,8 @@ bool ActionItemModelDelegate::eventFilter(QObject* editor, QEvent* evt) { const QKeyEvent* keyEvent = static_cast(evt); KeySequenceEdit* edit = qobject_cast(editor); - assert(edit != NULL); - if (edit != NULL) + assert(edit != nullptr); + if (edit != nullptr) { // Preprocess the key; don't give the filters a chance to handle the key. // This prevents weird focus problems with keys like Tab, and avoids issues diff --git a/SDK/simQt/ActionItemModel.h b/SDK/simQt/ActionItemModel.h index a720e65fd..f33a2e5dd 100644 --- a/SDK/simQt/ActionItemModel.h +++ b/SDK/simQt/ActionItemModel.h @@ -41,7 +41,7 @@ class SDKQT_EXPORT ActionItemModel : public QAbstractItemModel Q_OBJECT; public: /// constructor - explicit ActionItemModel(QObject* parent=NULL); + explicit ActionItemModel(QObject* parent=nullptr); virtual ~ActionItemModel(); /// Changes the registry that is represented in the item model @@ -106,7 +106,7 @@ class SDKQT_EXPORT KeySequenceEdit : public QLineEdit Q_OBJECT; public: /// constructor - explicit KeySequenceEdit(QWidget* parent=NULL); + explicit KeySequenceEdit(QWidget* parent=nullptr); virtual ~KeySequenceEdit(); ///@return most recent key set by this widget @@ -154,7 +154,7 @@ class SDKQT_EXPORT ActionItemModelDelegate : public QStyledItemDelegate Q_OBJECT; public: /// constructor - explicit ActionItemModelDelegate(QObject* parent=NULL); + explicit ActionItemModelDelegate(QObject* parent=nullptr); virtual ~ActionItemModelDelegate(); /// Override createEditor() to return our KeySequenceEdit diff --git a/SDK/simQt/ActionRegistry.cpp b/SDK/simQt/ActionRegistry.cpp index ba6d0f95f..c5118156a 100644 --- a/SDK/simQt/ActionRegistry.cpp +++ b/SDK/simQt/ActionRegistry.cpp @@ -72,7 +72,7 @@ ToolTipUpdater::ToolTipUpdater(QObject* parent) void ToolTipUpdater::addPending(simQt::Action* action) { - if (action == NULL) + if (action == nullptr) return; pendingActions_.push_back(action); @@ -86,6 +86,9 @@ void ToolTipUpdater::updateToolTips_() for (auto it = pendingActions_.begin(); it != pendingActions_.end(); ++it) { QAction* action = (*it)->action(); + if (!action) + continue; + QString tt = action->property(ORIGINAL_TOOL_TIP_PROPERTY).toString(); // Get the original tool tip from the property if (tt.isEmpty()) { @@ -296,7 +299,7 @@ class ActionRegistry::MementoImpl : public ActionRegistry::SettingsMemento if (!visitedDescs.contains(i.key())) { // Failure of assertion means visitedDesc got constructed improperly - assert(registry.findWithoutAliases_(i.key()) == NULL); + assert(registry.findWithoutAliases_(i.key()) == nullptr); if (i.value().empty()) { // Save empty unknown values so that empty hotkeys can work fine @@ -326,7 +329,7 @@ class ActionRegistry::MementoImpl : public ActionRegistry::SettingsMemento { Action* action = registry.findWithoutAliases_(i.key()); - if (action == NULL) + if (action == nullptr) { // The action does not exist; add a new one (will show up as Unknown) if (i.value().empty()) @@ -380,7 +383,7 @@ ActionRegistry::~ActionRegistry() delete *it; delete toolTipUpdater_; - toolTipUpdater_ = NULL; + toolTipUpdater_ = nullptr; } Action* ActionRegistry::registerAction(const QString &group, const QString &description, QAction *action) @@ -388,7 +391,7 @@ Action* ActionRegistry::registerAction(const QString &group, const QString &desc assertActionsByKeyValid_(); Action* newAct = findWithoutAliases_(description); - if (newAct != NULL) + if (newAct != nullptr) { // This occurs when more than one action has the same name. The description must be // unique, so this means you have duplicates and need to resolve this issue. @@ -429,7 +432,7 @@ Action* ActionRegistry::registerAction(const QString &group, const QString &desc int ActionRegistry::registerAlias(const QString& actionDesc, const QString& alias) { Action* action = findWithoutAliases_(actionDesc); - if (action == NULL) + if (action == nullptr) return 1; if (aliases_.find(alias) != aliases_.end()) @@ -460,7 +463,7 @@ void ActionRegistry::assertActionsByKeyValid_() const for (auto it = keys.begin(); it != keys.end(); ++it) { const Action* action = actionsByKey_.value(*it); - assert(action != NULL && action->hotkeys().contains(*it)); + assert(action != nullptr && action->hotkeys().contains(*it)); } // Loop through the hotkeys in all known actions and make sure there's an entry and it's us @@ -468,7 +471,7 @@ void ActionRegistry::assertActionsByKeyValid_() const for (auto it = actions.begin(); it != actions.end(); ++it) { const Action* action = *it; - assert(action != NULL); + assert(action != nullptr); auto hotkeys = action->hotkeys(); for (auto hotkeyIt = hotkeys.begin(); hotkeyIt != hotkeys.end(); ++hotkeyIt) { @@ -484,7 +487,7 @@ int ActionRegistry::removeAction(const QString& desc) assertActionsByKeyValid_(); Action* action = findWithoutAliases_(desc); - if (action == NULL) + if (action == nullptr) return 1; // Remove from actions maps @@ -526,7 +529,7 @@ int ActionRegistry::removeAction(const QString& desc) aliases_.remove(*it); // Remove it from the main window's action list - if (mainWindow_) + if (mainWindow_ && action->action()) mainWindow_->removeAction(action->action()); emit(actionRemoved(action)); @@ -554,26 +557,26 @@ Action* ActionRegistry::findAction(const QString& desc) const { assertActionsByKeyValid_(); Action* action = findWithoutAliases_(desc); - if (action != NULL) + if (action != nullptr) return action; QMap::const_iterator it = aliases_.find(desc); if (it != aliases_.end()) return findWithoutAliases_(*it); - return NULL; + return nullptr; } Action* ActionRegistry::findWithoutAliases_(const QString& desc) const { QMap::const_iterator i = actionsByDesc_.find(desc); - return (i == actionsByDesc_.end()) ? NULL : *i; + return (i == actionsByDesc_.end()) ? nullptr : *i; } Action* ActionRegistry::findAction(QKeySequence hotKey) const { QMap::const_iterator i = actionsByKey_.find(hotKey); - return (i == actionsByKey_.end()) ? NULL : *i; + return (i == actionsByKey_.end()) ? nullptr : *i; } QList ActionRegistry::actions() const @@ -587,7 +590,7 @@ QList ActionRegistry::actions() const int ActionRegistry::removeHotKey(Action* action, unsigned int bindingNum) { - if (action == NULL) + if (action == nullptr) return 1; QList newKeys = action->hotkeys(); if (bindingNum < static_cast(newKeys.size())) @@ -601,7 +604,7 @@ int ActionRegistry::removeHotKey(Action* action, unsigned int bindingNum) int ActionRegistry::setHotKey(Action* action, QKeySequence hotkey) { - if (action == NULL) + if (action == nullptr) return 1; QList newKeys; newKeys += hotkey; @@ -611,7 +614,7 @@ int ActionRegistry::setHotKey(Action* action, QKeySequence hotkey) int ActionRegistry::addHotKey(const QString& actionDesc, QKeySequence hotkey) { Action* action = findAction(actionDesc); - if (action != NULL) + if (action != nullptr) { QList newKeys = action->hotkeys(); newKeys += hotkey; @@ -644,7 +647,7 @@ int ActionRegistry::addHotKey(const QString& actionDesc, QKeySequence hotkey) // Save as an unknown action, store hotkey for later QMap::const_iterator i = unknownActions_.find(actionDesc); - UnknownAction* unknown = NULL; + UnknownAction* unknown = nullptr; if (i == unknownActions_.end()) { unknown = new UnknownAction; @@ -665,7 +668,7 @@ int ActionRegistry::addHotKey(const QString& actionDesc, QKeySequence hotkey) int ActionRegistry::setHotKeys(Action* action, const QList& hotkeys) { - if (action == NULL) + if (action == nullptr) return 1; const QList uniqueHotkeys = makeUnique_(hotkeys); @@ -683,7 +686,7 @@ int ActionRegistry::setHotKeys(Action* action, const QList& hotkey QKeySequence key = *it; // We do not need to remove the binding for our own action (no-op) Action* oldAction = findAction(key); - if (oldAction != NULL && action != oldAction) + if (oldAction != nullptr && action != oldAction) removeBinding_(oldAction, key, true); // Store association of binding to new action (unconditionally) actionsByKey_[key] = action; @@ -704,7 +707,8 @@ int ActionRegistry::setHotKeys(Action* action, const QList& hotkey } // Update the actual QAction - action->action()->setShortcuts(uniqueHotkeys); + if (action->action()) + action->action()->setShortcuts(uniqueHotkeys); // Assertion failure means setShortcuts() failed in an unknown way assert(uniqueHotkeys == action->hotkeys()); // Assertion failure means our hotkeys list lost sync with action-by-key map @@ -759,7 +763,7 @@ void ActionRegistry::combineAndSetKeys_(Action* action, const QListaction()) return 1; QMap::iterator i = actionsByKey_.find(key); if (i != actionsByKey_.end()) diff --git a/SDK/simQt/ActionRegistry.h b/SDK/simQt/ActionRegistry.h index 707ed623b..0ed14533d 100644 --- a/SDK/simQt/ActionRegistry.h +++ b/SDK/simQt/ActionRegistry.h @@ -23,11 +23,12 @@ #ifndef SIMQT_ACTIONREGISTRY_H #define SIMQT_ACTIONREGISTRY_H -#include -#include +#include #include #include -#include +#include +#include +#include #include "simCore/Common/Common.h" class QAction; @@ -45,7 +46,7 @@ class ToolTipUpdater : public QObject { Q_OBJECT public: - explicit ToolTipUpdater(QObject* parent = NULL); + explicit ToolTipUpdater(QObject* parent = nullptr); public slots: /** Add an action to the list of actions waiting to have their tool tip updated. */ void addPending(simQt::Action* action); @@ -95,7 +96,7 @@ class SDKQT_EXPORT Action ActionRegistry* registry_; QString group_; QString description_; - QAction* action_; + QPointer action_; }; /// Manager for all registered actions diff --git a/SDK/simQt/CMakeLists.txt b/SDK/simQt/CMakeLists.txt index 25de94d4e..d58e8bf25 100644 --- a/SDK/simQt/CMakeLists.txt +++ b/SDK/simQt/CMakeLists.txt @@ -57,6 +57,7 @@ set(SIMQT_HEADERS ${SIMQT_INC}Settings.h ${SIMQT_INC}SettingsGroup.h ${SIMQT_INC}StartupLayoutManager.h + ${SIMQT_INC}ValueMerge.h ${SIMQT_INC}WeightedMenuManager.h ${SIMQT_INC}WidgetSettings.h ) @@ -93,11 +94,13 @@ if(TARGET simVis) list(APPEND SIMQT_HEADERS_TO_MOC ${SIMQT_INC}CenterEntity.h ${SIMQT_INC}EntityLineEdit.h - ${SIMQT_INC}IncrementalCompileSettings.h ${SIMQT_INC}MapDataModel.h ${SIMQT_INC}TimestampedLayerManager.h ${SIMQT_INC}ViewManagerDataModel.h ) + if(ENABLE_DEPRECATED_SIMDISSDK_API) + list(APPEND SIMQT_HEADERS_TO_MOC ${SIMQT_INC}IncrementalCompileSettings.h) + endif() list(APPEND SIMQT_HEADERS ${SIMQT_INC}FillItemModelWithNodeVisitor.h ) @@ -179,6 +182,7 @@ set(SIMQT_SOURCES ${SIMQT_SRC}Toast.cpp ${SIMQT_SRC}UnitsComboBox.cpp ${SIMQT_SRC}UnitContext.cpp + ${SIMQT_SRC}ValueMerge.cpp ${SIMQT_SRC}WeightedMenuManager.cpp ${SIMQT_SRC}WidgetSettings.cpp ) @@ -212,11 +216,13 @@ if(TARGET simVis) ${SIMQT_SRC}CenterEntity.cpp ${SIMQT_SRC}EntityLineEdit.cpp ${SIMQT_SRC}FillItemModelWithNodeVisitor.cpp - ${SIMQT_SRC}IncrementalCompileSettings.cpp ${SIMQT_SRC}MapDataModel.cpp ${SIMQT_SRC}TimestampedLayerManager.cpp ${SIMQT_SRC}ViewManagerDataModel.cpp ) + if(ENABLE_DEPRECATED_SIMDISSDK_API) + list(APPEND SIMQT_SOURCES ${SIMQT_SRC}IncrementalCompileSettings.cpp) + endif() # Parts of simQt depend on both simVis and osgQt if (TARGET OSGQT) diff --git a/SDK/simQt/CategoryDataBreadcrumbs.cpp b/SDK/simQt/CategoryDataBreadcrumbs.cpp index dd6f708bb..8bf2c3188 100644 --- a/SDK/simQt/CategoryDataBreadcrumbs.cpp +++ b/SDK/simQt/CategoryDataBreadcrumbs.cpp @@ -291,7 +291,7 @@ bool CloseableItemDelegate::editorEvent(QEvent* evt, QAbstractItemModel* model, { // We only care about mouse events QMouseEvent* mouseEvent = dynamic_cast(evt); - if (mouseEvent == NULL) + if (mouseEvent == nullptr) return false; // Farm off to helper functions @@ -360,7 +360,7 @@ class CategoryDataBreadcrumbs::FilterClearListener : public simData::CategoryNam CategoryDataBreadcrumbs::CategoryDataBreadcrumbs(QWidget* parent) : QWidget(parent), - filter_(NULL), + filter_(nullptr), minimumGroupSize_(3), hideWhenEmpty_(true), emptyText_(tr("No active category filter")), @@ -600,8 +600,8 @@ QString CategoryDataBreadcrumbs::buildValuesHtmlList_(const simData::CategoryNam void CategoryDataBreadcrumbs::addNameToList_(int nameIndex, bool useAltFillColor) { - // Break out to avoid NULL problems - if (filter_ == NULL || filter_->getDataStore() == NULL) + // Break out to avoid nullptr problems + if (filter_ == nullptr || filter_->getDataStore() == nullptr) return; // Initialize by getting the name manager, name, and current set of checks @@ -752,7 +752,7 @@ void CategoryDataBreadcrumbs::clearFilter() // Clear out content delete filter_; - filter_ = NULL; + filter_ = nullptr; listWidget_->clear(); // Resize @@ -1052,8 +1052,9 @@ void CategoryDataBreadcrumbs::synchronizeToSenderFilter_() simQt::EntityCategoryFilter* from = dynamic_cast(sender()); // Assertion failure means that this method was called by something that wasn't an entity category // filter, which shouldn't be possible because it's a private slot. - assert(from != NULL); - setFilter(from->categoryFilter()); + assert(from != nullptr); + if (from) + setFilter(from->categoryFilter()); } } diff --git a/SDK/simQt/CategoryDataBreadcrumbs.h b/SDK/simQt/CategoryDataBreadcrumbs.h index 1af0446b5..67e1668ca 100644 --- a/SDK/simQt/CategoryDataBreadcrumbs.h +++ b/SDK/simQt/CategoryDataBreadcrumbs.h @@ -79,7 +79,7 @@ class SDKQT_EXPORT CloseableItemDelegate : public QStyledItemDelegate }; /** Constructor and destructor */ - explicit CloseableItemDelegate(QObject* parent=NULL); + explicit CloseableItemDelegate(QObject* parent=nullptr); virtual ~CloseableItemDelegate(); /** Overrides from QStyledItemDelegate */ @@ -155,7 +155,7 @@ class SDKQT_EXPORT CategoryDataBreadcrumbs : public QWidget Q_PROPERTY(QString emptyText READ emptyText WRITE setEmptyText); public: - explicit CategoryDataBreadcrumbs(QWidget* parent=NULL); + explicit CategoryDataBreadcrumbs(QWidget* parent=nullptr); virtual ~CategoryDataBreadcrumbs(); /** Override to return a reasonable minimum height based on content */ diff --git a/SDK/simQt/CategoryFilterCounter.cpp b/SDK/simQt/CategoryFilterCounter.cpp index d7df496e8..2179e2cc7 100644 --- a/SDK/simQt/CategoryFilterCounter.cpp +++ b/SDK/simQt/CategoryFilterCounter.cpp @@ -174,7 +174,7 @@ void CategoryFilterCounter::testCategory_(int nameInt, CategoryCountResults::Val AsyncCategoryCounter::AsyncCategoryCounter(QObject* parent) : QObject(parent), - counter_(NULL), + counter_(nullptr), retestPending_(false) { } @@ -192,7 +192,7 @@ void AsyncCategoryCounter::setFilter(const simData::CategoryFilter& filter) void AsyncCategoryCounter::asyncCountEntities() { - if (counter_ != NULL) + if (counter_ != nullptr) { retestPending_ = true; return; @@ -205,7 +205,7 @@ void AsyncCategoryCounter::asyncCountEntities() QFutureWatcher* watcher = new QFutureWatcher(); counter_ = new CategoryFilterCounter(watcher); - if (nextFilter_ != NULL) + if (nextFilter_ != nullptr) counter_->setFilter(*nextFilter_); counter_->prepare(); @@ -223,8 +223,8 @@ void AsyncCategoryCounter::emitResults_() lastResults_ = counter_->results(); emit resultsReady(lastResults_); - // just set to NULL, the deleteLater() for watcher will do the actual delete - counter_ = NULL; + // just set to nullptr, the deleteLater() for watcher will do the actual delete + counter_ = nullptr; // Retest now that it's safe to do so if (retestPending_) diff --git a/SDK/simQt/CategoryFilterCounter.h b/SDK/simQt/CategoryFilterCounter.h index 8a5833266..d5843b1dd 100644 --- a/SDK/simQt/CategoryFilterCounter.h +++ b/SDK/simQt/CategoryFilterCounter.h @@ -58,7 +58,7 @@ class SDKQT_EXPORT CategoryFilterCounter : public QObject Q_OBJECT; public: /** Default constructor */ - explicit CategoryFilterCounter(QObject* parent = NULL); + explicit CategoryFilterCounter(QObject* parent = nullptr); /** Sets the category filter to use */ void setFilter(const simData::CategoryFilter& filter); @@ -129,7 +129,7 @@ class SDKQT_EXPORT AsyncCategoryCounter : public QObject Q_OBJECT; public: /** Default constructor */ - explicit AsyncCategoryCounter(QObject* parent = NULL); + explicit AsyncCategoryCounter(QObject* parent = nullptr); virtual ~AsyncCategoryCounter(); diff --git a/SDK/simQt/CategoryTreeModel.cpp b/SDK/simQt/CategoryTreeModel.cpp index 79ad05729..aacde0d2d 100644 --- a/SDK/simQt/CategoryTreeModel.cpp +++ b/SDK/simQt/CategoryTreeModel.cpp @@ -260,7 +260,7 @@ class CategoryTreeModel::ValueItem : public TreeItem ///////////////////////////////////////////////////////////////////////// TreeItem::TreeItem() - : parent_(NULL) + : parent_(nullptr) { } @@ -276,7 +276,7 @@ TreeItem* TreeItem::parent() const int TreeItem::rowInParent() const { - if (parent_ == NULL) + if (parent_ == nullptr) { // Caller is getting an invalid value assert(0); @@ -303,9 +303,9 @@ int TreeItem::childCount() const void TreeItem::addChild(TreeItem* item) { // Assertion failure means developer is doing something weird. - assert(item != NULL); + assert(item != nullptr); // Assertion failure means that item is inserted more than once. - assert(item->parent() == NULL); + assert(item->parent() == nullptr); // Set the parent and save the item in our children vector. item->parent_ = this; @@ -319,7 +319,7 @@ CategoryTreeModel::CategoryItem::CategoryItem(const simData::CategoryNameManager nameInt_(nameInt), unlistedValue_(false), contributesToFilter_(false), - font_(NULL), + font_(nullptr), locked_(false) { } @@ -474,7 +474,7 @@ bool CategoryTreeModel::CategoryItem::setChildChecks_(const simData::RegExpFilte { // Test the EditRole, which is used because it omits the # count (e.g. "Friendly (1)") ValueItem* valueItem = static_cast(child(k)); - const bool matches = reFilter != NULL && reFilter->match(valueItem->valueString().toStdString()); + const bool matches = reFilter != nullptr && reFilter->match(valueItem->valueString().toStdString()); if (matches != valueItem->isChecked()) { valueItem->setChecked(matches); @@ -489,7 +489,7 @@ int CategoryTreeModel::CategoryItem::updateTo(const simData::CategoryFilter& fil // Update the category if it has a RegExp const QString oldRegExp = regExpString_; const auto* regExpObject = filter.getRegExp(nameInt_); - regExpString_ = (regExpObject != NULL ? QString::fromStdString(filter.getRegExpPattern(nameInt_)) : ""); + regExpString_ = (regExpObject != nullptr ? QString::fromStdString(filter.getRegExpPattern(nameInt_)) : ""); // If the RegExp string is different, we definitely have some sort of change bool hasChange = (regExpString_ != oldRegExp); @@ -760,9 +760,9 @@ bool CategoryTreeModel::ValueItem::setData(const QVariant& value, int role, simD // Internally handle check/uncheck value. For ROLE_REGEXP and ROLE_LOCKED_STATE, rely on category parent if (role == Qt::CheckStateRole) return setCheckStateData_(value, filter, filterChanged); - else if (role == ROLE_REGEXP_STRING && parent() != NULL) + else if (role == ROLE_REGEXP_STRING && parent() != nullptr) return parent()->setData(value, role, filter, filterChanged); - else if (role == ROLE_LOCKED_STATE && parent() != NULL) + else if (role == ROLE_LOCKED_STATE && parent() != nullptr) return parent()->setData(value, role, filter, filterChanged); filterChanged = false; return false; @@ -823,7 +823,8 @@ bool CategoryTreeModel::ValueItem::setCheckStateData_(const QVariant& value, sim // Update the parent too, which fixes the GUI for whether it contributes CategoryItem* parentTree = dynamic_cast(parent()); - parentTree->recalcContributionTo(filter); + if (parentTree) + parentTree->recalcContributionTo(filter); filterChanged = true; return true; @@ -957,10 +958,10 @@ bool CategoryProxyModel::filterAcceptsRow(int sourceRow, const QModelIndex &sour CategoryTreeModel::CategoryTreeModel(QObject* parent) : QAbstractItemModel(parent), - dataStore_(NULL), - filter_(new simData::CategoryFilter(NULL)), + dataStore_(nullptr), + filter_(new simData::CategoryFilter(nullptr)), categoryFont_(new QFont), - settings_(NULL) + settings_(nullptr) { listener_.reset(new CategoryFilterListener(*this)); @@ -974,9 +975,9 @@ CategoryTreeModel::~CategoryTreeModel() categories_.deleteAll(); categoryIntToItem_.clear(); delete categoryFont_; - categoryFont_ = NULL; + categoryFont_ = nullptr; delete filter_; - filter_ = NULL; + filter_ = nullptr; if (dataStore_) dataStore_->categoryNameManager().removeListener(listener_); } @@ -991,7 +992,7 @@ QModelIndex CategoryTreeModel::index(int row, int column, const QModelIndex &par // Has a parent: must be a value item TreeItem* parentItem = static_cast(parent.internalPointer()); // Item was not made correctly, check index() - assert(parentItem != NULL); + assert(parentItem != nullptr); return createIndex(row, column, parentItem->child(row)); } @@ -1003,7 +1004,7 @@ QModelIndex CategoryTreeModel::parent(const QModelIndex &child) const // Child could be a category (no parent) or a value (category parent) const TreeItem* childItem = static_cast(child.internalPointer()); TreeItem* parentItem = childItem->parent(); - if (parentItem == NULL) // child is a category; no parent + if (parentItem == nullptr) // child is a category; no parent return QModelIndex(); return createIndex(categories_.indexOf(static_cast(parentItem)), 0, parentItem); } @@ -1015,7 +1016,7 @@ int CategoryTreeModel::rowCount(const QModelIndex &parent) const if (parent.column() != 0) return 0; TreeItem* parentItem = static_cast(parent.internalPointer()); - return (parentItem == NULL) ? 0 : parentItem->childCount(); + return (parentItem == nullptr) ? 0 : parentItem->childCount(); } return categories_.size(); } @@ -1063,7 +1064,7 @@ bool CategoryTreeModel::setData(const QModelIndex& idx, const QVariant& value, i if (!idx.isValid() || !idx.internalPointer()) return QAbstractItemModel::setData(idx, value, role); - // NULL filter means the tree should be empty, so we shouldn't get setData()... + // nullptr filter means the tree should be empty, so we shouldn't get setData()... TreeItem* item = static_cast(idx.internalPointer()); assert(filter_ && item); bool wasEdited = false; @@ -1119,11 +1120,11 @@ void CategoryTreeModel::setFilter(const simData::CategoryFilter& filter) // Avoid no-op simData::CategoryFilter simplified(filter); simplified.simplify(); - if (filter_ != NULL && simplified == *filter_) + if (filter_ != nullptr && simplified == *filter_) return; // Do a two step assignment so that we don't automatically get auto-update - if (filter_ == NULL) + if (filter_ == nullptr) filter_ = new simData::CategoryFilter(filter.getDataStore()); filter_->assign(simplified, false); @@ -1165,7 +1166,7 @@ void CategoryTreeModel::setFilter(const simData::CategoryFilter& filter) const simData::CategoryFilter& CategoryTreeModel::categoryFilter() const { - // Precondition of this method is that data store was set; filter must be non-NULL + // Precondition of this method is that data store was set; filter must be non-nullptr assert(filter_); return *filter_; } @@ -1176,10 +1177,10 @@ void CategoryTreeModel::setDataStore(simData::DataStore* dataStore) return; // Update the listeners on name manager as we change it - if (dataStore_ != NULL) + if (dataStore_ != nullptr) dataStore_->categoryNameManager().removeListener(listener_); dataStore_ = dataStore; - if (dataStore_ != NULL) + if (dataStore_ != nullptr) dataStore_->categoryNameManager().addListener(listener_); beginResetModel(); @@ -1189,9 +1190,9 @@ void CategoryTreeModel::setDataStore(simData::DataStore* dataStore) categoryIntToItem_.clear(); // Clear out the internal filter object - const bool hadFilter = (filter_ != NULL && !filter_->isEmpty()); + const bool hadFilter = (filter_ != nullptr && !filter_->isEmpty()); delete filter_; - filter_ = NULL; + filter_ = nullptr; if (dataStore_) { filter_ = new simData::CategoryFilter(dataStore_); @@ -1269,7 +1270,7 @@ void CategoryTreeModel::clearTree_() void CategoryTreeModel::addName_(int nameInt) { - assert(dataStore_ != NULL); + assert(dataStore_ != nullptr); // Create the tree item for the category const auto& nameManager = dataStore_->categoryNameManager(); @@ -1305,7 +1306,7 @@ void CategoryTreeModel::addName_(int nameInt) CategoryTreeModel::CategoryItem* CategoryTreeModel::findNameTree_(int nameInt) const { auto i = categoryIntToItem_.find(nameInt); - return (i == categoryIntToItem_.end()) ? NULL : i->second; + return (i == categoryIntToItem_.end()) ? nullptr : i->second; } void CategoryTreeModel::updateLockedState_(const QStringList& lockedCategories, CategoryItem& category) @@ -1322,7 +1323,7 @@ void CategoryTreeModel::addValue_(int nameInt, int valueInt) TreeItem* nameItem = findNameTree_(nameInt); // Means we got a category that we don't know about; shouldn't happen. assert(nameItem); - if (nameItem == NULL) + if (nameItem == nullptr) return; // Create the value item @@ -1951,7 +1952,7 @@ class CategoryFilterWidget::DataStoreListener : public simData::DataStore::Liste virtual void onNameChange(simData::DataStore *source, simData::ObjectId changeId) {} virtual void onScenarioDelete(simData::DataStore* source) {} virtual void onPrefsChange(simData::DataStore *source, simData::ObjectId id) {} - virtual void onTimeChange(simData::DataStore *source) {} + virtual void onChange(simData::DataStore *source) {} virtual void onFlush(simData::DataStore* source, simData::ObjectId id) {} private: @@ -1964,8 +1965,8 @@ CategoryFilterWidget::CategoryFilterWidget(QWidget* parent) : QWidget(parent), activeFiltering_(false), showEntityCount_(false), - counter_(NULL), - setRegExpAction_(NULL), + counter_(nullptr), + setRegExpAction_(nullptr), countDirty_(true) { setWindowTitle("Category Data Filter"); @@ -2114,7 +2115,7 @@ void CategoryFilterWidget::setShowEntityCount(bool fl) // Clear out the old counter delete counter_; - counter_ = NULL; + counter_ = nullptr; // Create a new counter and configure it if (showEntityCount_) @@ -2233,7 +2234,7 @@ void CategoryFilterWidget::setRegularExpression_() { // Make sure we have a sender and can pull out the index. If not, return QObject* senderObject = sender(); - if (senderObject == NULL) + if (senderObject == nullptr) return; QModelIndex index = senderObject->property("index").toModelIndex(); if (index.isValid()) @@ -2281,7 +2282,7 @@ void CategoryFilterWidget::clearRegularExpression_() { // Make sure we have a sender and can pull out the index. If not, return QObject* senderObject = sender(); - if (senderObject == NULL) + if (senderObject == nullptr) return; QModelIndex index = senderObject->property("index").toModelIndex(); if (!index.isValid()) @@ -2296,7 +2297,7 @@ void CategoryFilterWidget::toggleLockCategory_() { // Make sure we have a sender and can pull out the index. If not, return QObject* senderObject = sender(); - if (senderObject == NULL) + if (senderObject == nullptr) return; QModelIndex index = senderObject->property("index").toModelIndex(); if (!index.isValid()) diff --git a/SDK/simQt/CategoryTreeModel.h b/SDK/simQt/CategoryTreeModel.h index f8450976e..a556a93c6 100644 --- a/SDK/simQt/CategoryTreeModel.h +++ b/SDK/simQt/CategoryTreeModel.h @@ -112,7 +112,7 @@ class SDKQT_EXPORT CategoryTreeModel : public QAbstractItemModel { Q_OBJECT; public: - explicit CategoryTreeModel(QObject* parent = NULL); + explicit CategoryTreeModel(QObject* parent = nullptr); virtual ~CategoryTreeModel(); /** Changes the data store, updating what categories and values are shown. */ @@ -222,7 +222,7 @@ class SDKQT_EXPORT CategoryTreeItemDelegate : public QStyledItemDelegate { Q_OBJECT; public: - explicit CategoryTreeItemDelegate(QObject* parent = NULL); + explicit CategoryTreeItemDelegate(QObject* parent = nullptr); virtual ~CategoryTreeItemDelegate(); /** Overrides from QStyledItemDelegate */ diff --git a/SDK/simQt/CenterEntity.cpp b/SDK/simQt/CenterEntity.cpp index beee1d7e3..cf893ee18 100644 --- a/SDK/simQt/CenterEntity.cpp +++ b/SDK/simQt/CenterEntity.cpp @@ -43,16 +43,6 @@ CenterEntity::CenterEntity(simVis::FocusManager& focusManager, simVis::ScenarioM { } -#ifdef USE_DEPRECATED_SIMDISSDK_API -CenterEntity::CenterEntity(simVis::FocusManager& focusManager, simVis::ScenarioManager& scenarioManager, EntityTreeComposite& tree) - : QObject(&tree), - focusManager_(&focusManager), - scenarioManager_(&scenarioManager) -{ - bindTo(tree); -} -#endif - CenterEntity::~CenterEntity() { } @@ -86,24 +76,16 @@ void CenterEntity::centerOnSelection(const QList& ids) } } -#ifdef USE_DEPRECATED_SIMDISSDK_API -void CenterEntity::bindTo(EntityTreeComposite& tree) -{ - connect(&tree, SIGNAL(itemDoubleClicked(uint64_t)), this, SLOT(centerOnEntity(uint64_t))); - tree.setExpandsOnDoubleClick(false); /// Turns off the tree expansion on double click. -} -#endif - -void CenterEntity::centerOnEntity(uint64_t id) +void CenterEntity::centerOnEntity(uint64_t id, bool force) { // Need the scenario and focus manager to continue if (!scenarioManager_ || !focusManager_) return; simVis::EntityNode* node = getViewCenterableNode(id); - if ((node != NULL) && node->isActive() && node->isVisible()) + if ((node != nullptr) && (force || (node->isActive() && node->isVisible()))) { - if (focusManager_->getFocusedView() != NULL) + if (focusManager_->getFocusedView() != nullptr) { focusManager_->getFocusedView()->tetherCamera(node); } @@ -118,24 +100,10 @@ void CenterEntity::setCentroidManager(simVis::CentroidManager* centroidManager) simVis::EntityNode* CenterEntity::getViewCenterableNode(uint64_t id) const { if (!scenarioManager_ || !focusManager_) - return NULL; - - simVis::EntityNode* node = scenarioManager_->find(id); - - // tetherCamera works only with platforms, custom renderings and gates, so work up the chain until - // a platform, custom rendering or gate is found. - while ((node != NULL) && (dynamic_cast(node) == NULL) && - (dynamic_cast(node) == NULL) && - (dynamic_cast(node) == NULL)) - { - uint64_t parentId; - if (node->getHostId(parentId)) - node = scenarioManager_->find(parentId); - else - node = NULL; - } + return nullptr; - return node; + auto node = focusManager_->getFocusedView()->getModelNodeForTether(scenarioManager_->find(id)); + return focusManager_->getFocusedView()->getEntityNode(node); } //-------------------------------------------------------------------------------------------------- @@ -194,7 +162,7 @@ void BindCenterEntityToEntityTreeComposite::updateCenterEnable_() for (auto it = ids.begin(); it != ids.end(); ++it) { auto node = centerEntity_.getViewCenterableNode(*it); - if ((node == NULL) || (node->isActive() && !node->isVisible())) + if ((node == nullptr) || (node->isActive() && !node->isVisible())) { tree_.setUseCenterAction(false, tr("Inactive entity selected")); return; @@ -211,7 +179,7 @@ void BindCenterEntityToEntityTreeComposite::updateCenterEnable_() } // Make sure time controls are enabled and that the scenario is in file mode - if ((dataStore_.getBoundClock() == NULL) || dataStore_.getBoundClock()->controlsDisabled() || dataStore_.getBoundClock()->isLiveMode()) + if ((dataStore_.getBoundClock() == nullptr) || dataStore_.getBoundClock()->controlsDisabled() || dataStore_.getBoundClock()->isLiveMode()) { tree_.setUseCenterAction(false, tr("Inactive entity selected")); return; @@ -257,10 +225,11 @@ void BindCenterEntityToEntityTreeComposite::updateCenterEnable_() void BindCenterEntityToEntityTreeComposite::centerOnEntity_(uint64_t id) { - if ((newTime_ != -1.0) && (dataStore_.getBoundClock() != NULL) && !dataStore_.getBoundClock()->controlsDisabled() && !dataStore_.getBoundClock()->isLiveMode()) + if ((newTime_ != -1.0) && (dataStore_.getBoundClock() != nullptr) && !dataStore_.getBoundClock()->controlsDisabled() && !dataStore_.getBoundClock()->isLiveMode()) dataStore_.getBoundClock()->setTime(simCore::TimeStamp(dataStore_.referenceYear(), newTime_)); - centerEntity_.centerOnEntity(id); + // Need to force the center because the setTime has not been process so the entity may not yet be valid + centerEntity_.centerOnEntity(id, true); } double BindCenterEntityToEntityTreeComposite::getPlatformNearestTime_(uint64_t id) const @@ -268,13 +237,13 @@ double BindCenterEntityToEntityTreeComposite::getPlatformNearestTime_(uint64_t i // First check the visible flag simData::DataStore::Transaction trans; auto pref = dataStore_.platformPrefs(id, &trans); - if ((pref == NULL) || !pref->commonprefs().draw() || !pref->commonprefs().datadraw()) + if ((pref == nullptr) || !pref->commonprefs().draw() || !pref->commonprefs().datadraw()) return -1.0; trans.release(&pref); // Next check data points auto slice = dataStore_.platformUpdateSlice(id); - if ((slice == NULL) || (slice->numItems() == 0)) + if ((slice == nullptr) || (slice->numItems() == 0)) return -1.0; const auto time = dataStore_.updateTime(); @@ -282,10 +251,10 @@ double BindCenterEntityToEntityTreeComposite::getPlatformNearestTime_(uint64_t i // Since there is a check above for at least one point, previous or next must be set - if (iter.peekNext() == NULL) + if (iter.peekNext() == nullptr) return iter.peekPrevious()->time(); - if (iter.peekPrevious() == NULL) + if (iter.peekPrevious() == nullptr) return iter.peekNext()->time(); const double nextDelta = iter.peekNext()->time() - time; @@ -299,12 +268,12 @@ double BindCenterEntityToEntityTreeComposite::getCustomRenderingNearestTime_(uin // First check the visible flag simData::DataStore::Transaction trans; auto pref = dataStore_.customRenderingPrefs(id, &trans); - if ((pref == NULL) || !pref->commonprefs().draw()) + if ((pref == nullptr) || !pref->commonprefs().draw()) return -1.0; trans.release(&pref); auto commands = dataStore_.customRenderingCommandSlice(id); - if ((commands == NULL) || (commands->numItems() == 0)) + if ((commands == nullptr) || (commands->numItems() == 0)) return -1.0; const auto time = dataStore_.updateTime(); @@ -331,7 +300,7 @@ double BindCenterEntityToEntityTreeComposite::getCustomRenderingEarlierTime_(dou auto iter = slice->upper_bound(searchTime); // Custom Render code enforces no repeats on data draw, so this is safe - while (iter.peekPrevious() != NULL) + while (iter.peekPrevious() != nullptr) { auto previous = iter.previous(); if (previous->has_updateprefs() && @@ -355,7 +324,7 @@ double BindCenterEntityToEntityTreeComposite::getCustomRenderingLaterTime_(doubl auto iter = slice->upper_bound(searchTime); // Custom Render code enforces no repeats on data draw, so this is safe - while (iter.peekNext() != NULL) + while (iter.peekNext() != nullptr) { auto next = iter.next(); if (next->has_updateprefs() && diff --git a/SDK/simQt/CenterEntity.h b/SDK/simQt/CenterEntity.h index 4f5450fea..ee7ce5351 100644 --- a/SDK/simQt/CenterEntity.h +++ b/SDK/simQt/CenterEntity.h @@ -59,17 +59,9 @@ class SDKQT_EXPORT CenterEntity : public QObject public: /** Constructor for a generic parent */ - CenterEntity(simVis::FocusManager& focusManager, simVis::ScenarioManager& scenarioManager, QObject* parent=NULL); + CenterEntity(simVis::FocusManager& focusManager, simVis::ScenarioManager& scenarioManager, QObject* parent=nullptr); virtual ~CenterEntity(); -// use BindCenterEntityToEntityTreeComposite instead -#ifdef USE_DEPRECATED_SIMDISSDK_API - /** Constructor for EntityTreeComposite parent with an automatic call to bindTo */ - SDK_DEPRECATE(CenterEntity(simVis::FocusManager& focusManager, simVis::ScenarioManager& scenarioManager, EntityTreeComposite& tree), "Method will be removed in a future SDK release"); - /** Auto configures the double click to center on platform and turns off the tree expansion on double click */ - SDK_DEPRECATE(void bindTo(EntityTreeComposite& tree), "Method will be removed in a future SDK release"); -#endif - /** * Sets the centroid manager for centering views * @param centroidManager the centroid manager for centering views @@ -79,13 +71,17 @@ class SDKQT_EXPORT CenterEntity : public QObject /** * Returns the view center-able node for the given id * @param id The entity to get a view center-able node - * @return A node that a view can be centered on; returns NULL on error. + * @return A node that a view can be centered on; returns nullptr on error. */ simVis::EntityNode* getViewCenterableNode(uint64_t id) const; public slots: - /** Center the current view port on the given entity Unique ID */ - void centerOnEntity(uint64_t id); + /** + * Center the current view port on the given entity Unique ID + * @param id The entity to center on + * @param force Center on an invalid entity with the expectation it will soon become valid + */ + void centerOnEntity(uint64_t id, bool force = false); /** Center the current view port on the given list of entity unique IDs */ void centerOnSelection(const QList& ids); @@ -104,7 +100,7 @@ class SDKQT_EXPORT BindCenterEntityToEntityTreeComposite : public QObject Q_OBJECT; public: - BindCenterEntityToEntityTreeComposite(CenterEntity& centerEntity, EntityTreeComposite& tree, simData::DataStore& dataStore, QObject* parent = NULL); + BindCenterEntityToEntityTreeComposite(CenterEntity& centerEntity, EntityTreeComposite& tree, simData::DataStore& dataStore, QObject* parent = nullptr); virtual ~BindCenterEntityToEntityTreeComposite(); /** diff --git a/SDK/simQt/ColorButton.h b/SDK/simQt/ColorButton.h index ab8584f17..e18f07ad1 100644 --- a/SDK/simQt/ColorButton.h +++ b/SDK/simQt/ColorButton.h @@ -42,7 +42,7 @@ class SDKQT_EXPORT ColorButton : public QPushButton public: /// Constructor - ColorButton(QWidget* parent = NULL); + ColorButton(QWidget* parent = nullptr); virtual ~ColorButton(); /** returns the current color selection */ @@ -68,7 +68,7 @@ public slots: signals: /** Emitted when double clicked */ - void doubleClicked(QMouseEvent* evt=NULL); + void doubleClicked(QMouseEvent* evt=nullptr); protected: /** Override the paint event to draw the gradient blending alpha if necessary */ diff --git a/SDK/simQt/ColorGradient.cpp b/SDK/simQt/ColorGradient.cpp index 514ed86be..65a28d7c2 100644 --- a/SDK/simQt/ColorGradient.cpp +++ b/SDK/simQt/ColorGradient.cpp @@ -42,6 +42,8 @@ ColorGradient::ColorGradient() ColorGradient::ColorGradient(const std::map& colors) : function_(new osg::TransferFunction1D) { + // Start with a default "empty" gradient + clearColors(); // setColors will fix values outside [0,1] setColors(colors); } @@ -49,6 +51,8 @@ ColorGradient::ColorGradient(const std::map& colors) ColorGradient::ColorGradient(const std::map& colors) : function_(new osg::TransferFunction1D) { + // Start with a default "empty" gradient + clearColors(); // setColors will fix values outside [0,1] setColors(colors); } @@ -102,17 +106,11 @@ ColorGradient ColorGradient::newDopplerGradient() QColor ColorGradient::colorAt(float zeroToOne) const { - if (empty()) - return Qt::black; - return simQt::getQtColorFromOsg(function_->getColor(zeroToOne)); } osg::Vec4 ColorGradient::osgColorAt(float zeroToOne) const { - if (empty()) - return osg::Vec4(0, 0, 0, 0); - return function_->getColor(zeroToOne); } @@ -132,6 +130,9 @@ int ColorGradient::setColor(float zeroToOne, const osg::Vec4& color) int ColorGradient::removeColor(float zeroToOne) { + if (function_->getColorMap().size() <= 2) + return 1; + auto& colorMap = function_->getColorMap(); auto i = colorMap.find(zeroToOne); if (i == colorMap.end()) @@ -142,8 +143,7 @@ int ColorGradient::removeColor(float zeroToOne) void ColorGradient::clearColors() { - // Manually clear map, since function_->clear() leaves min/max values - function_->getColorMap().clear(); + function_->clear(); } std::map ColorGradient::colors() const @@ -161,38 +161,63 @@ osg::TransferFunction1D::ColorMap ColorGradient::getColorMap() const int ColorGradient::colorCount() const { - return static_cast(function_->getColorMap().size()); -} - -bool ColorGradient::empty() const -{ - return function_->getColorMap().empty(); + const int count = static_cast(function_->getColorMap().size()); + assert(count >= 2); // At least two stops are required + return count; } -void ColorGradient::setColors(const std::map& colors) +int ColorGradient::setColors(const std::map& colors) { - clearColors(); + if (colors.size() < 2) + return 1; auto& colorMap = function_->getColorMap(); + std::map oldColorMap = colorMap; + + // Manually clear map instead of calling clearColors(), since it sets default colors + colorMap.clear(); + for (const auto& stop : colors) { // Remove values before 0. and after 1. if (stop.first >= 0.f && stop.first <= 1.f) colorMap[stop.first] = simQt::getOsgColorFromQt(stop.second); } + + // Restore old colors if new map doesn't have at least two stops + if (colorMap.size() < 2) + { + colorMap = oldColorMap; + return 1; + } + return 0; } -void ColorGradient::setColors(const std::map& colors) +int ColorGradient::setColors(const std::map& colors) { - clearColors(); + if (colors.size() < 2) + return 1; auto& colorMap = function_->getColorMap(); + std::map oldColorMap = colorMap; + + // Manually clear map instead of calling clearColors(), since it sets default colors + colorMap.clear(); + for (const auto& stop : colors) { // Remove values before 0. and after 1. if (stop.first >= 0.f && stop.first <= 1.f) colorMap[stop.first] = stop.second; } + + // Restore old colors if new map doesn't have at least two stops + if (colorMap.size() < 2) + { + colorMap = oldColorMap; + return 1; + } + return 0; } QColor ColorGradient::interpolate(const QColor& lowColor, const QColor& highColor, float low, float val, float high) diff --git a/SDK/simQt/ColorGradient.h b/SDK/simQt/ColorGradient.h index 4a7ddacb0..b39eabcf4 100644 --- a/SDK/simQt/ColorGradient.h +++ b/SDK/simQt/ColorGradient.h @@ -39,6 +39,7 @@ static const QString GRADIENT_STOP_TEMPLATE = "stop: %1 rgba(%2)"; /** * Represents a color gradient between magnitude values 0 and 1. * Wraps osg::TransferFunction1D as underlying implementation. + * This class enforces a minimum of two color stops at all times. */ class SDKQT_EXPORT ColorGradient { @@ -82,9 +83,8 @@ class SDKQT_EXPORT ColorGradient /** Removes a single control color, by its value. Returns 0 on success. */ int removeColor(float zeroToOne); /** - * Removes all configured colors, leaving the map empty. - * Differs from osg::TransferFunction1D::clear() that - * clears all but the min/max values, which it sets to white. + * Removes all configured colors using osg::TransferFunction1D::clear() + * which sets two white stops at 0.f and 1.f. */ void clearColors(); @@ -95,13 +95,19 @@ class SDKQT_EXPORT ColorGradient /** Retrieves count of registered colors. */ int colorCount() const; - /** Returns true if the color map is empty. */ - bool empty() const; - /** Sets all control colors at once, replacing old values. Discards values outside [0,1]. */ - void setColors(const std::map& colors); - /** Sets all control colors at once, replacing old values. Discards values outside [0,1]. */ - void setColors(const std::map& colors); + /** + * Sets all control colors at once, replacing old values. Discards values outside [0,1]. + * New map should provide at least two valid stops. Returns 0 on success, non-zero on error. + * If the given map is invalid, no changes are made to the gradient. + */ + int setColors(const std::map& colors); + /** + * Sets all control colors at once, replacing old values. Discards values outside [0,1]. + * New map should provide at least two valid stops. Returns 0 on success, non-zero on error. + * If the given map is invalid, no changes are made to the gradient. + */ + int setColors(const std::map& colors); /** Comparison operator */ bool operator==(const ColorGradient& rhs) const; diff --git a/SDK/simQt/ColorGradientWidget.cpp b/SDK/simQt/ColorGradientWidget.cpp index 71f5105a9..676dcffe8 100644 --- a/SDK/simQt/ColorGradientWidget.cpp +++ b/SDK/simQt/ColorGradientWidget.cpp @@ -68,7 +68,7 @@ static const QString GRAD_WIDGET_TOOLTIP = QObject::tr("Left-click and drag to m class ColorGradientWidget::ColorGradientModel : public QAbstractTableModel { public: - explicit ColorGradientModel(QObject* parent = NULL) + explicit ColorGradientModel(QObject* parent = nullptr) : QAbstractTableModel(parent) {} @@ -240,12 +240,11 @@ class ColorGradientWidget::ColorGradientModel : public QAbstractTableModel /** Retrieves the current color gradient from the model */ ColorGradient getColorGradient() const { - ColorGradient grad; - grad.clearColors(); - + std::map colors; for (const auto& colorStop : colorStops_) - grad.setColor(colorStop.first, colorStop.second); + colors[colorStop.first] = colorStop.second; + ColorGradient grad(colors); return grad; } @@ -410,10 +409,12 @@ class ColorGradientWidget::ColorGradientModel : public QAbstractTableModel class ColorGradientWidget::GradientDisplayWidget : public QWidget { public: - explicit GradientDisplayWidget(ColorGradientModel& model, QWidget* parent = NULL) + explicit GradientDisplayWidget(ColorGradientModel& model, QWidget* parent = nullptr) : QWidget(parent), model_(model), - dragIndex_(QModelIndex()) + showAlpha_(true), + dragIndex_(QModelIndex()), + pickIndex_(QModelIndex()) { setMinimumHeight(HANDLE_SIZE_PX + HANDLE_THICKNESS_PX + OUTLINE_THICKNESS_PX); // Enable mouse tracking so we get move events with no buttons pressed @@ -424,6 +425,11 @@ class ColorGradientWidget::GradientDisplayWidget : public QWidget connect(&model_, SIGNAL(modelReset()), this, SLOT(update())); } + void setShowAlpha(bool showAlpha) + { + showAlpha_ = showAlpha; + } + virtual void paintEvent(QPaintEvent* event) override { QPainter painter(this); @@ -482,6 +488,12 @@ class ColorGradientWidget::GradientDisplayWidget : public QWidget virtual void mouseReleaseEvent(QMouseEvent* evt) override { dragIndex_ = QModelIndex(); + // If we start a drag inside, but release it outside, clear our pick + if (!underMouse()) + { + pickIndex_ = QModelIndex(); + update(); + } } virtual void mouseMoveEvent(QMouseEvent* evt) override @@ -512,6 +524,15 @@ class ColorGradientWidget::GradientDisplayWidget : public QWidget this); } + virtual void leaveEvent(QEvent* event) override + { + // Don't worry about dragIndex_. Leaving while dragging will not trigger this, + // but it will be triggered when a doubleClick spawns the dialog. + // Fortunately, mouseDoubleClickEvent() will clear the indices when it's finished + pickIndex_ = QModelIndex(); + update(); + } + virtual void mouseDoubleClickEvent(QMouseEvent* evt) override { if (evt->button() != Qt::LeftButton || width() == 0) @@ -589,8 +610,8 @@ class ColorGradientWidget::GradientDisplayWidget : public QWidget ColorGradientWidget::ColorGradientWidget(QWidget* parent) : QWidget(parent), ui_(new Ui_ColorGradientWidget), - tableGroup_(NULL), - treeView_(NULL), + tableGroup_(nullptr), + treeView_(nullptr), showTable_(true), showAlpha_(true), showHelp_(true) @@ -604,15 +625,15 @@ ColorGradientWidget::ColorGradientWidget(QWidget* parent) // Sort by the edit role to avoid "string order" proxyModel_->setSortRole(Qt::EditRole); - auto display = new GradientDisplayWidget(*model_); + display_ = new GradientDisplayWidget(*model_); QSizePolicy policy; policy.setHorizontalPolicy(QSizePolicy::Expanding); policy.setVerticalPolicy(QSizePolicy::Expanding); policy.setHorizontalStretch(10); // Arbitrary number larger than defaults of other items - display->setSizePolicy(policy); - display->setToolTip(simQt::formatTooltip(tr("Color Gradient"), GRAD_WIDGET_TOOLTIP)); + display_->setSizePolicy(policy); + display_->setToolTip(simQt::formatTooltip(tr("Color Gradient"), GRAD_WIDGET_TOOLTIP)); - ui_->gridLayout->addWidget(display, 0, 1); + ui_->gridLayout->addWidget(display_, 0, 1); ui_->helpButton->setVisible(showHelp_); connect(ui_->helpButton, SIGNAL(clicked(bool)), this, SLOT(showHelpDialog_())); @@ -629,6 +650,7 @@ ColorGradientWidget::ColorGradientWidget(QWidget* parent) ColorGradientWidget::~ColorGradientWidget() { + // unique_ptr and Qt parenting take care of memory } void ColorGradientWidget::setColorGradient(const ColorGradient& gradient) @@ -664,6 +686,11 @@ bool ColorGradientWidget::showHelp() const return showHelp_; } +bool ColorGradientWidget::gradientIsValid() const +{ + return model_->rowCount() >= 2; +} + void ColorGradientWidget::setShowTable(bool show) { if (show == showTable_) @@ -684,6 +711,9 @@ void ColorGradientWidget::setShowAlpha(bool show) treeView_->itemDelegateForColumn(ColorGradientModel::COL_COLOR)->deleteLater(); treeView_->setItemDelegateForColumn(ColorGradientModel::COL_COLOR, new ColorWidgetDelegate(showAlpha_, this)); } + + assert(display_); // Dev Error: Should've created at instantiation + display_->setShowAlpha(showAlpha_); } void ColorGradientWidget::setShowHelp(bool show) @@ -712,9 +742,9 @@ void ColorGradientWidget::showOrHideTable_() if (!showTable_) { delete tableGroup_; - tableGroup_ = NULL; + tableGroup_ = nullptr; // treeView_ will be deleted by Qt parentage - treeView_ = NULL; + treeView_ = nullptr; return; } diff --git a/SDK/simQt/ColorGradientWidget.h b/SDK/simQt/ColorGradientWidget.h index e3b92d31d..4a029ddf8 100644 --- a/SDK/simQt/ColorGradientWidget.h +++ b/SDK/simQt/ColorGradientWidget.h @@ -50,7 +50,7 @@ class SDKQT_EXPORT ColorGradientWidget : public QWidget public: /** Constructor */ - explicit ColorGradientWidget(QWidget* parent = NULL); + explicit ColorGradientWidget(QWidget* parent = nullptr); virtual ~ColorGradientWidget(); /** @@ -70,6 +70,9 @@ class SDKQT_EXPORT ColorGradientWidget : public QWidget /** Returns true if the button to spawn a help dialog is shown */ bool showHelp() const; + /** Returns true if the gradient in the widget is currently valid */ + bool gradientIsValid() const; + public slots: /** Sets whether to display the color stops table */ void setShowTable(bool show); @@ -104,6 +107,7 @@ private slots: QSortFilterProxyModel* proxyModel_; class GradientDisplayWidget; + GradientDisplayWidget* display_; bool showTable_; bool showAlpha_; diff --git a/SDK/simQt/ColorWidget.h b/SDK/simQt/ColorWidget.h index 6862bb8b9..50a390a0a 100644 --- a/SDK/simQt/ColorWidget.h +++ b/SDK/simQt/ColorWidget.h @@ -63,7 +63,7 @@ class SDKQT_EXPORT ColorWidget : public QWidget // QDESIGNER_WIDGET_EXPORT public: /** Constructor */ - ColorWidget(QWidget* parent = NULL); + ColorWidget(QWidget* parent = nullptr); virtual ~ColorWidget(); /** returns the current color selection */ diff --git a/SDK/simQt/ColorWidgetDelegate.cpp b/SDK/simQt/ColorWidgetDelegate.cpp index c6ec3bde2..f4f5094f0 100644 --- a/SDK/simQt/ColorWidgetDelegate.cpp +++ b/SDK/simQt/ColorWidgetDelegate.cpp @@ -52,7 +52,8 @@ void ColorWidgetDelegate::setEditorData(QWidget* editor, const QModelIndex& inde simQt::ColorWidget* button = dynamic_cast(editor); // Somehow got an editor other than the one defined in createEditor() assert(button); - button->setColor(dataVar.value()); + if (button) + button->setColor(dataVar.value()); } void ColorWidgetDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const diff --git a/SDK/simQt/ColorWidgetDelegate.h b/SDK/simQt/ColorWidgetDelegate.h index 96378d165..e6695ffe9 100644 --- a/SDK/simQt/ColorWidgetDelegate.h +++ b/SDK/simQt/ColorWidgetDelegate.h @@ -36,7 +36,7 @@ class SDKQT_EXPORT ColorWidgetDelegate : public QStyledItemDelegate { Q_OBJECT; public: - explicit ColorWidgetDelegate(bool showAlpha, QObject* parent = NULL); + explicit ColorWidgetDelegate(bool showAlpha, QObject* parent = nullptr); /** Creates the ColorWidget the user can interact with to change the color */ virtual QWidget* createEditor(QWidget* parent, const QStyleOptionViewItem& option, const QModelIndex& index) const; diff --git a/SDK/simQt/ConsoleChannel.cpp b/SDK/simQt/ConsoleChannel.cpp index 2d8785039..7d358113c 100644 --- a/SDK/simQt/ConsoleChannel.cpp +++ b/SDK/simQt/ConsoleChannel.cpp @@ -36,7 +36,7 @@ void ChannelNotifyHandler::setChannel(ConsoleChannelPtr channel) void ChannelNotifyHandler::notify(const std::string& message) { - if (channel_ == NULL) + if (channel_ == nullptr) return; lockMutex_(); diff --git a/SDK/simQt/ConsoleDataModel.cpp b/SDK/simQt/ConsoleDataModel.cpp index e55ab9180..748c8a0a5 100644 --- a/SDK/simQt/ConsoleDataModel.cpp +++ b/SDK/simQt/ConsoleDataModel.cpp @@ -61,7 +61,7 @@ class ConsoleDataModel::ChannelImpl : public ConsoleChannel */ virtual void addText(simNotify::NotifySeverity severity, const QString& text) { - if (dataModel_ == NULL) + if (dataModel_ == nullptr) return; // Directly call addEntry to avoid a look-up, for performance reasons in the common case. if (QThread::currentThread() == dataModel_->thread()) @@ -127,7 +127,8 @@ ConsoleDataModel::~ConsoleDataModel() { ChannelImpl* impl = dynamic_cast((*it).get()); // Clear out the pointer to "this", in case it survives beyond us - impl->setConsoleDataModel(NULL); + if (impl) + impl->setConsoleDataModel(nullptr); } } @@ -146,7 +147,7 @@ QVariant ConsoleDataModel::data(const QModelIndex& idx, int role) const return QVariant(); LineEntry* line = static_cast(idx.internalPointer()); assert(line); - if (line == NULL) + if (line == nullptr) return QVariant(); switch (role) @@ -331,7 +332,7 @@ void ConsoleDataModel::addPlainEntry_(simNotify::NotifySeverity severity, const return; // Process the entry through filters (if filters are defined) - LineEntry* newEntry = NULL; + LineEntry* newEntry = nullptr; if (!entryFilters_.empty()) { // Put into a struct for processing diff --git a/SDK/simQt/ConsoleDataModel.h b/SDK/simQt/ConsoleDataModel.h index f72af558f..4b00a59b3 100644 --- a/SDK/simQt/ConsoleDataModel.h +++ b/SDK/simQt/ConsoleDataModel.h @@ -92,7 +92,7 @@ class SDKQT_EXPORT ConsoleDataModel : public QAbstractItemModel }; /** Constructor */ - ConsoleDataModel(QObject* parent=NULL); + ConsoleDataModel(QObject* parent=nullptr); virtual ~ConsoleDataModel(); /** From QAbstractItemModel::data */ diff --git a/SDK/simQt/ConsoleLogger.cpp b/SDK/simQt/ConsoleLogger.cpp index 2ffaa6f17..f2cdd953d 100644 --- a/SDK/simQt/ConsoleLogger.cpp +++ b/SDK/simQt/ConsoleLogger.cpp @@ -124,7 +124,7 @@ ConsoleLogger::ConsoleLogger(const QString& filePrefix, QObject* parent) ConsoleLogger::~ConsoleLogger() { delete fileLogger_; - fileLogger_ = NULL; + fileLogger_ = nullptr; } int ConsoleLogger::clean(const DetermineRemovable& removable) const diff --git a/SDK/simQt/ConsoleLogger.h b/SDK/simQt/ConsoleLogger.h index dc497b70f..cc12273de 100644 --- a/SDK/simQt/ConsoleLogger.h +++ b/SDK/simQt/ConsoleLogger.h @@ -76,7 +76,7 @@ class SDKQT_EXPORT ConsoleLogger : public QObject Q_OBJECT; public: /** Constructor */ - ConsoleLogger(const QString& filePrefix="SIMDIS_SDK", QObject* parent=NULL); + ConsoleLogger(const QString& filePrefix="SIMDIS_SDK", QObject* parent=nullptr); virtual ~ConsoleLogger(); /** diff --git a/SDK/simQt/DataTableComboBox.cpp b/SDK/simQt/DataTableComboBox.cpp index a617dc142..40859047d 100644 --- a/SDK/simQt/DataTableComboBox.cpp +++ b/SDK/simQt/DataTableComboBox.cpp @@ -73,7 +73,7 @@ class TableListVisitor : public simData::TableList::Visitor DataTableComboBox::DataTableComboBox(QWidget* parent) :QWidget(parent), entityId_(0), -dataStore_(NULL) +dataStore_(nullptr) { ui_ = new Ui_DataTableComboBox; ui_->setupUi(this); @@ -84,7 +84,7 @@ dataStore_(NULL) DataTableComboBox::~DataTableComboBox() { - if (dataStore_ != NULL) + if (dataStore_ != nullptr) dataStore_->dataTableManager().removeObserver(observer_); delete ui_; } @@ -92,7 +92,7 @@ DataTableComboBox::~DataTableComboBox() simData::DataTable* DataTableComboBox::currentSelection() const { if (ui_->TableComboBox->count() == 0) - return NULL; + return nullptr; return (simData::DataTable*)(ui_->TableComboBox->itemData(ui_->TableComboBox->currentIndex()).toLongLong()); } @@ -100,11 +100,11 @@ void DataTableComboBox::setEntity(simData::ObjectId entityId) { entityId_ = entityId; ui_->TableComboBox->clear(); - if (dataStore_ == NULL) + if (dataStore_ == nullptr) return; // get the table list for all tables owned by this entity const simData::TableList* tableList = dataStore_->dataTableManager().tablesForOwner(entityId_); - if (tableList == NULL) + if (tableList == nullptr) return; // visit the table list to populate the combo box with data tables TableListVisitor listVisitor(ui_->TableComboBox); @@ -114,10 +114,10 @@ void DataTableComboBox::setEntity(simData::ObjectId entityId) void DataTableComboBox::setProviders(simData::DataStore* dataStore) { // remove observer if replacing data store - if (dataStore_ != NULL) + if (dataStore_ != nullptr) dataStore_->dataTableManager().removeObserver(observer_); dataStore_ = dataStore; - if (dataStore_ == NULL) + if (dataStore_ == nullptr) return; // now register new observer dataStore_->dataTableManager().addObserver(observer_); @@ -152,7 +152,7 @@ void DataTableComboBox::removeTable_(simData::DataTable* table) } } if (ui_->TableComboBox->count() == 0) - emit(dataTableSelected(NULL)); + emit(dataTableSelected(nullptr)); } } diff --git a/SDK/simQt/DataTableComboBox.h b/SDK/simQt/DataTableComboBox.h index 666fdb1cb..05a09c1af 100644 --- a/SDK/simQt/DataTableComboBox.h +++ b/SDK/simQt/DataTableComboBox.h @@ -42,7 +42,7 @@ class SDKQT_EXPORT DataTableComboBox : public QWidget Q_OBJECT; public: /** Constructor */ - explicit DataTableComboBox(QWidget* parent = NULL); + explicit DataTableComboBox(QWidget* parent = nullptr); /** Destructor */ virtual ~DataTableComboBox(); @@ -67,7 +67,7 @@ Q_OBJECT; signals: /** - * Emitted when a new table is selected. Will pass NULL if combo box becomes empty + * Emitted when a new table is selected. Will pass nullptr if combo box becomes empty * @param table current selected table */ void dataTableSelected(simData::DataTable* table); diff --git a/SDK/simQt/DataTableModel.cpp b/SDK/simQt/DataTableModel.cpp index d0a97523c..0d22529c9 100644 --- a/SDK/simQt/DataTableModel.cpp +++ b/SDK/simQt/DataTableModel.cpp @@ -84,7 +84,7 @@ class RowValueAccumulator : public simData::DataTable::RowVisitor //---------------------------------------------------------------------------- DataTableModel::DataTableModel(QObject *parent, simData::DataTable* dataTable) :QAbstractItemModel(parent), -dataTable_(NULL), +dataTable_(nullptr), genericPrecision_(3) { setDataTable(dataTable); @@ -96,7 +96,7 @@ DataTableModel::~DataTableModel() QVariant DataTableModel::data(const QModelIndex &index, int role) const { - if (!index.isValid() || dataTable_ == NULL) + if (!index.isValid() || dataTable_ == nullptr) return QVariant(); if (!(columns_.size() > index.column()) || !(rows_.size() > index.row())) return QVariant(); @@ -119,7 +119,7 @@ QVariant DataTableModel::data(const QModelIndex &index, int role) const if (!cell.hasNext()) return EMPTY_CELL; - // return NULL if we found no data at this time + // return nullptr if we found no data at this time if (cell.peekNext()->time() != time) return EMPTY_CELL; @@ -139,7 +139,7 @@ QVariant DataTableModel::data(const QModelIndex &index, int role) const if (!cell.hasNext()) return EMPTY_CELL; - // return NULL if we found no data at this time + // return nullptr if we found no data at this time if (cell.peekNext()->time() != time) return EMPTY_CELL; @@ -153,7 +153,7 @@ QVariant DataTableModel::data(const QModelIndex &index, int role) const return Qt::AlignLeft; const simData::TableColumn* col = columns_[index.column()]; simData::TableColumn::Iterator cell = col->findAtOrBeforeTime(time); - // this is a NULL block, left align + // this is a nullptr block, left align if (cell.next()->time() != time) return Qt::AlignLeft; @@ -233,7 +233,7 @@ void DataTableModel::setDataTable(simData::DataTable* dataTable) dataTable_ = dataTable; // no table, update layout and return - if (dataTable_ == NULL) + if (dataTable_ == nullptr) { endResetModel(); return; @@ -252,7 +252,7 @@ void DataTableModel::setDataTable(simData::DataTable* dataTable) // use size() instead of size() - 1 because of the time column const int lastColIndex = cv.columns().size(); beginInsertColumns(QModelIndex(), 0, lastColIndex); - columns_.push_back(NULL); // time column + columns_.push_back(nullptr); // time column columns_ += cv.columns(); endInsertColumns(); diff --git a/SDK/simQt/DataTableModel.h b/SDK/simQt/DataTableModel.h index cd2ca8240..779789043 100644 --- a/SDK/simQt/DataTableModel.h +++ b/SDK/simQt/DataTableModel.h @@ -46,7 +46,7 @@ namespace simQt { * @param parent * @param dataTable data for the model */ - DataTableModel(QObject *parent = NULL, simData::DataTable* dataTable = NULL); + DataTableModel(QObject *parent = nullptr, simData::DataTable* dataTable = nullptr); /** Destructor */ virtual ~DataTableModel(); @@ -79,7 +79,7 @@ namespace simQt { */ void setDataTable(simData::DataTable* dataTable); - /** Returns the current data table; can be NULL */ + /** Returns the current data table; can be nullptr */ simData::DataTable* dataTable() const; public slots: diff --git a/SDK/simQt/DirectorySelectorWidget.cpp b/SDK/simQt/DirectorySelectorWidget.cpp index a23e5af3b..759bc3a1a 100644 --- a/SDK/simQt/DirectorySelectorWidget.cpp +++ b/SDK/simQt/DirectorySelectorWidget.cpp @@ -33,7 +33,7 @@ namespace simQt { DirectorySelectorWidget::DirectorySelectorWidget(QWidget* parent) : QWidget(parent), registryKey_("Private/directory"), - labelWidget_(NULL), + labelWidget_(nullptr), includeLabel_(false), label_(tr("Directory")), browserTitle_(tr("Select Directory")) @@ -84,7 +84,7 @@ void DirectorySelectorWidget::setIncludeLabel(bool value) { if (value == true) { - if (labelWidget_ == NULL) + if (labelWidget_ == nullptr) { labelWidget_ = new QLabel(label_); } @@ -94,7 +94,7 @@ void DirectorySelectorWidget::setIncludeLabel(bool value) { ui_->horizontalLayout->removeWidget(labelWidget_); delete labelWidget_; - labelWidget_ = NULL; + labelWidget_ = nullptr; } includeLabel_ = value; diff --git a/SDK/simQt/DirectorySelectorWidget.h b/SDK/simQt/DirectorySelectorWidget.h index 4d04c528d..853c86512 100644 --- a/SDK/simQt/DirectorySelectorWidget.h +++ b/SDK/simQt/DirectorySelectorWidget.h @@ -53,7 +53,7 @@ class SDKQT_EXPORT DirectorySelectorWidget : public QWidget public: /** Constructor */ - DirectorySelectorWidget(QWidget* parent=NULL); + DirectorySelectorWidget(QWidget* parent=nullptr); virtual ~DirectorySelectorWidget(); /** Sets the registry key for saving/loading files; defaults to SETTINGS/file */ diff --git a/SDK/simQt/DndTreeView.h b/SDK/simQt/DndTreeView.h index c614c7a91..1bec42cf8 100644 --- a/SDK/simQt/DndTreeView.h +++ b/SDK/simQt/DndTreeView.h @@ -40,7 +40,7 @@ class SDKQT_EXPORT DndTreeView : public QTreeView public: /** Constructor */ - explicit DndTreeView(QWidget* parent = NULL); + explicit DndTreeView(QWidget* parent = nullptr); /** Destructor */ virtual ~DndTreeView(); diff --git a/SDK/simQt/DockWidget.cpp b/SDK/simQt/DockWidget.cpp index d185a7343..ccad394b4 100644 --- a/SDK/simQt/DockWidget.cpp +++ b/SDK/simQt/DockWidget.cpp @@ -138,7 +138,7 @@ class DockWidget::MonochromeIcon : public QObject class DockWidget::DoubleClickFrame : public QFrame { public: - DoubleClickFrame(DockWidget& dockWidget, QWidget* parent=NULL, Qt::WindowFlags flags=0) + DoubleClickFrame(DockWidget& dockWidget, QWidget* parent=nullptr, Qt::WindowFlags flags=0) : QFrame(parent, flags), dockWidget_(dockWidget) { @@ -176,7 +176,7 @@ class DockWidget::DoubleClickFrame : public QFrame class DockWidget::DoubleClickIcon : public QLabel { public: - DoubleClickIcon(DockWidget& dockWidget, QWidget* parent = NULL, Qt::WindowFlags flags = 0) + DoubleClickIcon(DockWidget& dockWidget, QWidget* parent = nullptr, Qt::WindowFlags flags = 0) : QLabel(parent, flags), dockWidget_(dockWidget) { @@ -199,7 +199,7 @@ class DockWidget::DoubleClickIcon : public QLabel DockWidget::DockWidget(QWidget* parent, Qt::WindowFlags flags) : QDockWidget(parent, flags), - globalSettings_(NULL), + globalSettings_(nullptr), mainWindow_(dynamic_cast(parent)) { init_(); @@ -207,7 +207,7 @@ DockWidget::DockWidget(QWidget* parent, Qt::WindowFlags flags) DockWidget::DockWidget(const QString& title, QWidget* parent, Qt::WindowFlags flags) : QDockWidget(title, parent, flags), - globalSettings_(NULL), + globalSettings_(nullptr), mainWindow_(dynamic_cast(parent)) { setObjectName(title); @@ -246,23 +246,23 @@ DockWidget::~DockWidget() disconnect(QApplication::instance(), SIGNAL(focusChanged(QWidget*, QWidget*)), this, SLOT(changeTitleColorsFromFocusChange_(QWidget*, QWidget*))); delete noTitleBar_; - noTitleBar_ = NULL; + noTitleBar_ = nullptr; delete titleBar_; - titleBar_ = NULL; + titleBar_ = nullptr; } void DockWidget::init_() { // default title bar text size to application text size titleBarPointSize_ = QApplication::font().pointSize(); - searchLineEdit_ = NULL; + searchLineEdit_ = nullptr; titleBarWidgetCount_ = 0; extraFeatures_ = DEFAULT_EXTRA_FEATURES; - settingsSaved_ = (settings_ == NULL); // Prevent false asserts when the simQt::Settings is not provided in construction + settingsSaved_ = (settings_ == nullptr); // Prevent false asserts when the simQt::Settings is not provided in construction haveFocus_ = false; isDockable_ = true; - disableAllDocking_ = NULL; - borderThickness_ = NULL; + disableAllDocking_ = nullptr; + borderThickness_ = nullptr; createStylesheets_(); @@ -577,7 +577,7 @@ void DockWidget::dock_() // In some cases, setFloating() may fail to redock. In these cases, we may need // to request a valid dock from the main window. - if (isFloating() && mainWindow_ != NULL) + if (isFloating() && mainWindow_ != nullptr) mainWindow_->addDockWidget(Qt::RightDockWidgetArea, this); // Finally update the state of the enable/disable/visibility @@ -628,7 +628,7 @@ void DockWidget::fixTabIcon_() // Locate the tab bar that contains this window, based on the window title int index = 0; QTabBar* tabBar = findTabWithTitle_(tabBars, windowTitle(), index); - if (tabBar == NULL) + if (tabBar == nullptr) return; // This title matches ours, set the tab icon @@ -642,7 +642,7 @@ void DockWidget::fixTabIcon_() int newIndex = (index == 1 ? 0 : 1); // Set icon from our only other tabified widget DockWidget* firstTab = dynamic_cast(tabifiedWidgets[0]); - if (firstTab != NULL && firstTab->windowTitle() == tabBar->tabText(newIndex)) + if (firstTab != nullptr && firstTab->windowTitle() == tabBar->tabText(newIndex)) { tabBar->setTabIcon(newIndex, firstTab->widget()->windowIcon()); } @@ -715,7 +715,7 @@ void DockWidget::setWidget(QWidget* widget) } QDockWidget::setWidget(widget); - if (widget == NULL) + if (widget == nullptr) return; setWindowIcon(widget->windowIcon()); @@ -784,7 +784,7 @@ void DockWidget::setDockable(bool dockable) bool DockWidget::allDockingDisabled() const { - return (disableAllDocking_ != NULL && disableAllDocking_->value()); + return (disableAllDocking_ != nullptr && disableAllDocking_->value()); } void DockWidget::verifyDockState_(bool floating) @@ -820,7 +820,7 @@ QTabBar* DockWidget::findTabWithTitle_(const QList& fromBars, const QS return tabBar; } } - return NULL; + return nullptr; } QAction* DockWidget::isDockableAction() const @@ -836,7 +836,7 @@ bool DockWidget::isMaximized_() const bool DockWidget::searchEnabled() const { - return searchLineEdit_ != NULL; + return searchLineEdit_ != nullptr; } void DockWidget::setSearchEnabled(bool enable) @@ -854,7 +854,7 @@ void DockWidget::setSearchEnabled(bool enable) if (!enable) { delete searchLineEdit_; - searchLineEdit_ = NULL; + searchLineEdit_ = nullptr; return; } @@ -879,15 +879,15 @@ simQt::SearchLineEdit* DockWidget::searchLineEdit() const int DockWidget::insertTitleBarWidget(int beforeIndex, QWidget* widget) { - if (titleBar_ == NULL || titleBar_->layout() == NULL) + if (titleBar_ == nullptr || titleBar_->layout() == nullptr) return 1; QBoxLayout* layout = dynamic_cast(titleBar_->layout()); - if (layout == NULL) + if (layout == nullptr) return 1; const int numPrev = titleBar_->layout()->count(); // Calculate the actual index -- offset by icon, title, and maybe search edit if it exists - const int actualIndex = beforeIndex + (searchLineEdit_ == NULL ? 0 : 1) + SEARCH_LAYOUT_INDEX; + const int actualIndex = beforeIndex + (searchLineEdit_ == nullptr ? 0 : 1) + SEARCH_LAYOUT_INDEX; layout->insertWidget(actualIndex, widget); // Add the delta of objects changed in case this results in a "move" (i.e. no items added) @@ -998,7 +998,7 @@ void DockWidget::changeTitleColorsFromFocusChange_(QWidget* oldFocus, QWidget* n bool DockWidget::isChildWidget_(const QWidget* widget) const { // Find out whether we're in the parentage for the focused widget - while (widget != NULL) + while (widget != nullptr) { if (widget == this) return true; @@ -1090,7 +1090,7 @@ void DockWidget::loadSettings_() void DockWidget::restoreFloating_(const QByteArray& geometryBytes) { // Restore the widget from the main window - if (mainWindow_ == NULL) + if (mainWindow_ == nullptr) { // Must be floatable, because we can't dock without it assert(features().testFlag(DockWidgetFloatable)); @@ -1105,7 +1105,7 @@ void DockWidget::restoreFloating_(const QByteArray& geometryBytes) // If ignoring settings, bypass main window. Otherwise give main window first opportunity to restore the position if (extraFeatures_.testFlag(DockWidgetIgnoreSettings) || !mainWindow_->restoreDockWidget(this)) { - const bool globalNoDocking = (disableAllDocking_ != NULL && disableAllDocking_->value()); + const bool globalNoDocking = (disableAllDocking_ != nullptr && disableAllDocking_->value()); // Restoration failed; new window. Respect the features() flag to pop up or dock. if (features().testFlag(DockWidgetFloatable) || globalNoDocking) { diff --git a/SDK/simQt/DockWidget.h b/SDK/simQt/DockWidget.h index f598d9704..61ba8b1b3 100644 --- a/SDK/simQt/DockWidget.h +++ b/SDK/simQt/DockWidget.h @@ -110,12 +110,12 @@ class SDKQT_EXPORT DockWidget : public QDockWidget * Create a new Dock Widget. The title will be non-unique, so be sure to update the title * to avoid issues with settings if settings are used. Variant of polymorphic constructor. */ - DockWidget(QWidget* parent=NULL, Qt::WindowFlags flags=Qt::WindowFlags()); + DockWidget(QWidget* parent=nullptr, Qt::WindowFlags flags=Qt::WindowFlags()); /** * Create a new Dock Widget. Variant of polymorphic constructor. */ - DockWidget(const QString& title, QWidget* parent=NULL, Qt::WindowFlags flags=Qt::WindowFlags()); + DockWidget(const QString& title, QWidget* parent=nullptr, Qt::WindowFlags flags=Qt::WindowFlags()); /** * Create a new Dock Widget. Variant of polymorphic constructor. @@ -128,13 +128,13 @@ class SDKQT_EXPORT DockWidget : public QDockWidget * If not set, use setObjectName() to define the registry key for settings. * @param settings Where to save/restore window geometry information. If not specified, then settings will be saved * and loaded from a Private section from QSettings. Note that some features, such as global disable of dockability, - * cannot work properly unless this is specified and non-NULL. + * cannot work properly unless this is specified and non-nullptr. * @param parent The parent widget. Recommend this be set to the QMainWindow. If not set, then * the caller is responsible for calling QMainWindow::addDockWidget() and setFloating() as * needed. Some features like docking button will not work unless this is the QMainWindow. * @param flags Qt window flags */ - DockWidget(const QString& title, simQt::Settings* settings, QWidget* parent=NULL, Qt::WindowFlags flags=Qt::WindowFlags()); + DockWidget(const QString& title, simQt::Settings* settings, QWidget* parent=nullptr, Qt::WindowFlags flags=Qt::WindowFlags()); /** Destructor */ virtual ~DockWidget(); @@ -169,7 +169,7 @@ class SDKQT_EXPORT DockWidget : public QDockWidget */ QAction* isDockableAction() const; - /** Retrieves the search field, may be NULL if searching is disabled. */ + /** Retrieves the search field, may be nullptr if searching is disabled. */ SearchLineEdit* searchLineEdit() const; /** Adds a widget to the title bar, returning 0 on success */ diff --git a/SDK/simQt/EntityCategoryFilter.cpp b/SDK/simQt/EntityCategoryFilter.cpp index d0ef744dd..b399a493e 100644 --- a/SDK/simQt/EntityCategoryFilter.cpp +++ b/SDK/simQt/EntityCategoryFilter.cpp @@ -31,14 +31,14 @@ EntityCategoryFilter::EntityCategoryFilter(simData::DataStore* dataStore, Widget : EntityFilter(), categoryFilter_(new simData::CategoryFilter(dataStore, true)), widgetType_(widgetType), - settings_(NULL) + settings_(nullptr) { } EntityCategoryFilter::~EntityCategoryFilter() { delete categoryFilter_; - categoryFilter_ = NULL; + categoryFilter_ = nullptr; } bool EntityCategoryFilter::acceptEntity(simData::ObjectId id) const @@ -64,7 +64,7 @@ QWidget* EntityCategoryFilter::widget(QWidget* newWidgetParent) const } } - return NULL; + return nullptr; } void EntityCategoryFilter::getFilterSettings(QMap& settings) const diff --git a/SDK/simQt/EntityCategoryFilter.h b/SDK/simQt/EntityCategoryFilter.h index 3abd01d6a..b9dcbae6f 100644 --- a/SDK/simQt/EntityCategoryFilter.h +++ b/SDK/simQt/EntityCategoryFilter.h @@ -47,7 +47,7 @@ class SDKQT_EXPORT EntityCategoryFilter : public EntityFilter /** Enumeration of different ways we can create/display a widget for this filter. */ enum WidgetType { - /** widget() will return NULL, creating nothing when integrated into Qt. */ + /** widget() will return nullptr, creating nothing when integrated into Qt. */ NO_WIDGET, /** widget() will return a CategoryFilterWidget, the new style of category filtering. */ SHOW_WIDGET @@ -72,8 +72,8 @@ class SDKQT_EXPORT EntityCategoryFilter : public EntityFilter virtual bool acceptEntity(simData::ObjectId id) const; /** - * Inherited from EntityFilter, returns a new instance of the widget to be displayed, otherwise returns NULL - * @param newWidgetParent QWidget parent, useful for memory management purposes; may be NULL if desired + * Inherited from EntityFilter, returns a new instance of the widget to be displayed, otherwise returns nullptr + * @param newWidgetParent QWidget parent, useful for memory management purposes; may be nullptr if desired * @return QWidget used for changing filter settings */ virtual QWidget* widget(QWidget* newWidgetParent) const; diff --git a/SDK/simQt/EntityFilter.h b/SDK/simQt/EntityFilter.h index f2b5ce0a5..c8110451c 100644 --- a/SDK/simQt/EntityFilter.h +++ b/SDK/simQt/EntityFilter.h @@ -43,7 +43,7 @@ namespace simQt { * the filter happens in this method. * The implementation must also provide a means for EntityProxyModel to obtain a QWidget for this filter * by implementing the widget() method. The caller is responsible for memory of the newly created widget. - * Implementations should create the widget if they want it to be shown, otherwise, return NULL. + * Implementations should create the widget if they want it to be shown, otherwise, return nullptr. * * Implementations should emit the filterUpdated signal when the filter has changed, in case the user wants * to re-apply the filter to its model @@ -65,8 +65,8 @@ namespace simQt { /** * Returns a new widget for this filter. If the filter has no widget, or does not wish it to be shown, - * this will return NULL. The memory for this new widget is now owned by the caller - * @param newWidgetParent QWidget parent, useful for memory management purposes; may be NULL if desired + * this will return nullptr. The memory for this new widget is now owned by the caller + * @param newWidgetParent QWidget parent, useful for memory management purposes; may be nullptr if desired * @return QWidget used for changing filter settings */ virtual QWidget* widget(QWidget* newWidgetParent) const = 0; diff --git a/SDK/simQt/EntityLineEdit.cpp b/SDK/simQt/EntityLineEdit.cpp index 5f09cc8fc..eb0207f95 100644 --- a/SDK/simQt/EntityLineEdit.cpp +++ b/SDK/simQt/EntityLineEdit.cpp @@ -52,8 +52,8 @@ namespace { EntityDialog::EntityDialog(QWidget* parent, simQt::EntityTreeModel* entityTreeModel, simData::ObjectType type, simCore::Clock* clock, SettingsPtr settings) : QDialog(parent), entityTreeModel_(entityTreeModel), - entityStateFilter_(NULL), - centerBind_(NULL) + entityStateFilter_(nullptr), + centerBind_(nullptr) { setWindowTitle(tr("Select Entity")); setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint); @@ -69,7 +69,7 @@ EntityDialog::EntityDialog(QWidget* parent, simQt::EntityTreeModel* entityTreeMo if (settings) tree_->setSettings(settings); - if (clock != NULL) + if (clock != nullptr) { entityStateFilter_ = new simQt::EntityStateFilter(*entityTreeModel_->dataStore(), *clock, true); tree_->addEntityFilter(entityStateFilter_); @@ -109,7 +109,7 @@ void EntityDialog::setItemSelected(uint64_t id) void EntityDialog::setStateFilter(EntityStateFilter::State state) { - if (entityStateFilter_ != NULL) + if (entityStateFilter_ != nullptr) { entityStateFilter_->setStateFilter(state); } @@ -117,7 +117,7 @@ void EntityDialog::setStateFilter(EntityStateFilter::State state) EntityStateFilter::State EntityDialog::stateFilter() const { - if (entityStateFilter_ != NULL) + if (entityStateFilter_ != nullptr) return entityStateFilter_->stateFilter(); return EntityStateFilter::BOTH; @@ -125,15 +125,15 @@ EntityStateFilter::State EntityDialog::stateFilter() const void EntityDialog::setCenterEntity(CenterEntity* centerEntity) { - if (centerBind_ != NULL) + if (centerBind_ != nullptr) { // Dev error, call only once assert(false); return; } - // OK to pass in a NULL - if (centerEntity == NULL) + // OK to pass in a nullptr + if (centerEntity == nullptr) return; centerBind_ = new BindCenterEntityToEntityTreeComposite(*centerEntity, *tree_, *entityTreeModel_->dataStore(), tree_); @@ -190,19 +190,19 @@ class EntityLineEdit::DataStoreListener : public simData::DataStore::DefaultList EntityLineEdit::EntityLineEdit(QWidget* parent, simQt::EntityTreeModel* entityTreeModel, simData::ObjectType type) : QWidget(parent), - composite_(NULL), - entityTreeModel_(NULL), // set below with the setModel call - entityDialog_(NULL), + composite_(nullptr), + entityTreeModel_(nullptr), // set below with the setModel call + entityDialog_(nullptr), uniqueId_(0), unavailableId_(0), valid_(true), needToVerify_(false), type_(type), - clock_(NULL), - entityStateFilter_(NULL), + clock_(nullptr), + entityStateFilter_(nullptr), state_(EntityStateFilter::BOTH), settings_(SettingsPtr()), - centerEntity_(NULL) + centerEntity_(nullptr) { ResourceInitializer::initialize(); // Needs to be here so that Qt Designer works. @@ -223,7 +223,7 @@ EntityLineEdit::EntityLineEdit(QWidget* parent, simQt::EntityTreeModel* entityTr EntityLineEdit::~EntityLineEdit() { - if ((entityTreeModel_ != NULL) && (dataListenerPtr_ != NULL)) + if ((entityTreeModel_ != nullptr) && (dataListenerPtr_ != nullptr)) entityTreeModel_->dataStore()->removeListener(dataListenerPtr_); closeEntityDialog(); delete composite_; @@ -234,13 +234,13 @@ void EntityLineEdit::setModel(simQt::EntityTreeModel* model, simData::ObjectType type_ = type; clock_ = clock; - if (model != NULL) + if (model != nullptr) { entityTreeModel_ = model; entityTreeModel_->setToListView(); proxy_ = new EntityProxyModel(this); - if (clock != NULL) + if (clock != nullptr) { entityStateFilter_ = new simQt::EntityStateFilter(*entityTreeModel_->dataStore(), *clock_); proxy_->addEntityFilter(entityStateFilter_); // proxy takes ownership of entityStateFilter_ @@ -267,11 +267,11 @@ void EntityLineEdit::setModel(simQt::EntityTreeModel* model, simData::ObjectType dataListenerPtr_ = simData::DataStore::ListenerPtr(new DataStoreListener(this)); entityTreeModel_->dataStore()->addListener(dataListenerPtr_); } - else if (entityTreeModel_ != NULL) + else if (entityTreeModel_ != nullptr) { entityTreeModel_->dataStore()->removeListener(dataListenerPtr_); dataListenerPtr_.reset(); - entityTreeModel_ = NULL; + entityTreeModel_ = nullptr; } } @@ -282,10 +282,10 @@ void EntityLineEdit::setStateFilter(EntityStateFilter::State state) state_ = state; - if (entityStateFilter_ != NULL) + if (entityStateFilter_ != nullptr) entityStateFilter_->setStateFilter(state_); - if (entityDialog_ != NULL) + if (entityDialog_ != nullptr) entityDialog_->setStateFilter(state_); emit stateFilterChanged(state_); @@ -298,7 +298,7 @@ EntityStateFilter::State EntityLineEdit::stateFilter() const void EntityLineEdit::wasActived_(const QModelIndex & index) { - if (entityTreeModel_ == NULL) + if (entityTreeModel_ == nullptr) return; QCompleter* completer = composite_->lineEdit->completer(); @@ -315,7 +315,7 @@ void EntityLineEdit::wasActived_(const QModelIndex & index) needToVerify_ = false; setTextStyle_(true); emit itemSelected(uniqueId_); - if (entityDialog_ != NULL) + if (entityDialog_ != nullptr) entityDialog_->setItemSelected(uniqueId_); } @@ -335,7 +335,7 @@ QString EntityLineEdit::selectedName() const int EntityLineEdit::setSelected(uint64_t id) { - if (entityTreeModel_ == NULL || id == uniqueId_) + if (entityTreeModel_ == nullptr || id == uniqueId_) return 1; bool doEmit = (uniqueId_ != id); @@ -347,7 +347,7 @@ int EntityLineEdit::setSelected(uint64_t id) uniqueId_ = id; needToVerify_ = true; setTextStyle_(false); - if (entityDialog_ != NULL) + if (entityDialog_ != nullptr) entityDialog_->setItemSelected(uniqueId_); if (doEmit) emit itemSelected(uniqueId_); @@ -363,7 +363,7 @@ int EntityLineEdit::setSelected(uint64_t id) uniqueId_ = id; needToVerify_ = false; setTextStyle_(true); - if (entityDialog_ != NULL) + if (entityDialog_ != nullptr) entityDialog_->setItemSelected(uniqueId_); if (doEmit) emit itemSelected(uniqueId_); @@ -382,10 +382,10 @@ void EntityLineEdit::setCenterEntity(CenterEntity* centerEntity) void EntityLineEdit::showEntityDialog_() { - if (entityTreeModel_ == NULL) + if (entityTreeModel_ == nullptr) return; - if (entityDialog_ == NULL) + if (entityDialog_ == nullptr) { entityDialog_ = new EntityDialog(this, entityTreeModel_, type_, clock_, settings_); entityDialog_->setStateFilter(state_); @@ -405,7 +405,7 @@ void EntityLineEdit::closeEntityDialog() { entityDialog_->hide(); entityDialog_->deleteLater(); - entityDialog_ = NULL; + entityDialog_ = nullptr; } } @@ -425,7 +425,7 @@ void EntityLineEdit::checkForReapply_() void EntityLineEdit::editingFinished_() { - if (entityTreeModel_ == NULL) + if (entityTreeModel_ == nullptr) return; // Clearing out the line Edit is a special case @@ -435,7 +435,7 @@ void EntityLineEdit::editingFinished_() uniqueId_ = 0; needToVerify_ = true; setTextStyle_(false); - if (entityDialog_ != NULL) + if (entityDialog_ != nullptr) entityDialog_->setItemSelected(uniqueId_); if (doEmit) emit itemSelected(uniqueId_); @@ -452,7 +452,7 @@ void EntityLineEdit::editingFinished_() else { setTextStyle_(true); - if (entityDialog_ != NULL) + if (entityDialog_ != nullptr) entityDialog_->setItemSelected(uniqueId_); } if (oldId != uniqueId_) diff --git a/SDK/simQt/EntityLineEdit.h b/SDK/simQt/EntityLineEdit.h index 9af2e8fd2..7b8286566 100644 --- a/SDK/simQt/EntityLineEdit.h +++ b/SDK/simQt/EntityLineEdit.h @@ -102,7 +102,7 @@ class SDKQT_EXPORT EntityLineEdit : public QWidget public: /** Constructor */ - EntityLineEdit(QWidget* parent, simQt::EntityTreeModel* entityTreeModel = NULL, simData::ObjectType type = simData::ALL); + EntityLineEdit(QWidget* parent, simQt::EntityTreeModel* entityTreeModel = nullptr, simData::ObjectType type = simData::ALL); virtual ~EntityLineEdit(); /** Returns the Unique ID of the currently selected Entity; returns zero if none */ @@ -110,7 +110,7 @@ class SDKQT_EXPORT EntityLineEdit : public QWidget /** Returns the name of the currently selected Entity; returns "" if none */ QString selectedName() const; /** The model that holds all the entity information filtered by type */ - void setModel(simQt::EntityTreeModel* model, simData::ObjectType type = simData::ALL, simCore::Clock* clock = NULL); + void setModel(simQt::EntityTreeModel* model, simData::ObjectType type = simData::ALL, simCore::Clock* clock = nullptr); // Options for customizing the widget diff --git a/SDK/simQt/EntityNameFilter.cpp b/SDK/simQt/EntityNameFilter.cpp index a56cee5cf..43b9b02ce 100644 --- a/SDK/simQt/EntityNameFilter.cpp +++ b/SDK/simQt/EntityNameFilter.cpp @@ -39,19 +39,19 @@ EntityNameFilter::EntityNameFilter(AbstractEntityTreeModel* model) : EntityFilter(), model_(model), regExp_(new RegExpImpl("")), - widget_(NULL) + widget_(nullptr) { } EntityNameFilter::~EntityNameFilter() { delete regExp_; - regExp_ = NULL; + regExp_ = nullptr; } bool EntityNameFilter::acceptEntity(simData::ObjectId id) const { - if (model_ == NULL) + if (model_ == nullptr) return false; return acceptIndex_(model_->index(id)); @@ -59,7 +59,7 @@ bool EntityNameFilter::acceptEntity(simData::ObjectId id) const QWidget* EntityNameFilter::widget(QWidget* newWidgetParent) const { - return NULL; + return nullptr; } void EntityNameFilter::getFilterSettings(QMap& settings) const @@ -87,7 +87,7 @@ void EntityNameFilter::setFilterSettings(const QMap& settings void EntityNameFilter::bindToWidget(EntityFilterLineEdit* widget) { widget_ = widget; - if (widget_ == NULL) + if (widget_ == nullptr) return; connect(widget_, SIGNAL(changed(QString, Qt::CaseSensitivity, QRegExp::PatternSyntax)), this, SLOT(setRegExpAttributes_(QString, Qt::CaseSensitivity, QRegExp::PatternSyntax))); } @@ -100,7 +100,7 @@ void EntityNameFilter::setModel(AbstractEntityTreeModel* model) void EntityNameFilter::setRegExp(const QRegExp& regExp) { // Update the GUI if it's valid - if (widget_ != NULL) + if (widget_ != nullptr) { ScopedSignalBlocker block(*widget_); widget_->configure(regExp.pattern(), regExp.caseSensitivity(), regExp.patternSyntax()); @@ -144,9 +144,9 @@ bool EntityNameFilter::acceptIndex_(const QModelIndex& index) const { // Should only pass in a valid index const QAbstractItemModel* model = index.model(); - assert(model != NULL); + assert(model != nullptr); // Make sure pointers are valid - if ((model == NULL) || (regExp_ == NULL)) + if ((model == nullptr) || (regExp_ == nullptr)) return false; // Check if this index passes the filter, return true if it does diff --git a/SDK/simQt/EntityNameFilter.h b/SDK/simQt/EntityNameFilter.h index 32a1ecf8f..0bf277f17 100644 --- a/SDK/simQt/EntityNameFilter.h +++ b/SDK/simQt/EntityNameFilter.h @@ -56,8 +56,8 @@ class SDKQT_EXPORT EntityNameFilter : public EntityFilter virtual bool acceptEntity(simData::ObjectId id) const; /** - * Inherited from EntityFilter, always returns NULL, as this class currently doesn't create a widget - * @param newWidgetParent QWidget parent, useful for memory management purposes; may be NULL if desired + * Inherited from EntityFilter, always returns nullptr, as this class currently doesn't create a widget + * @param newWidgetParent QWidget parent, useful for memory management purposes; may be nullptr if desired * @return QWidget used for changing filter settings */ virtual QWidget* widget(QWidget* newWidgetParent) const; diff --git a/SDK/simQt/EntityProxyModel.cpp b/SDK/simQt/EntityProxyModel.cpp index 34621df9b..5ba3ce380 100644 --- a/SDK/simQt/EntityProxyModel.cpp +++ b/SDK/simQt/EntityProxyModel.cpp @@ -30,7 +30,7 @@ namespace simQt { EntityProxyModel::EntityProxyModel(QObject *parent) : QSortFilterProxyModel(parent), alwaysShow_(0), - model_(NULL) + model_(nullptr) { } @@ -43,7 +43,7 @@ namespace simQt { void EntityProxyModel::setSourceModel(QAbstractItemModel *sourceModel) { - if (model_ != NULL) + if (model_ != nullptr) { disconnect(model_, SIGNAL(rowsAboutToBeRemoved(const QModelIndex&, int, int)), this, SLOT(entitiesRemoved_(const QModelIndex&, int, int))); disconnect(model_, SIGNAL(dataChanged(const QModelIndex&, const QModelIndex&)), this, SLOT(entitiesUpdated_())); @@ -54,7 +54,7 @@ namespace simQt { model_ = dynamic_cast(sourceModel); QSortFilterProxyModel::setSourceModel(sourceModel); - if (model_ != NULL) + if (model_ != nullptr) { connect(model_, SIGNAL(rowsAboutToBeRemoved(const QModelIndex&, int, int)), this, SLOT(entitiesRemoved_(const QModelIndex&, int, int))); connect(model_, SIGNAL(dataChanged(const QModelIndex&, const QModelIndex&)), this, SLOT(entitiesUpdated_())); @@ -108,7 +108,7 @@ namespace simQt { for (auto it = entityFilters_.begin(); it != entityFilters_.end(); ++it) { QWidget* filterWidget = (*it)->widget(newWidgetParent); - if (filterWidget != NULL) // only add the widget if not NULL + if (filterWidget != nullptr) // only add the widget if not nullptr rv.push_back(filterWidget); } return rv; @@ -121,7 +121,7 @@ namespace simQt { void EntityProxyModel::setAlwaysShow(simData::ObjectId id) { - if ((alwaysShow_ == id) || (model_ == NULL)) + if ((alwaysShow_ == id) || (model_ == nullptr)) return; // If item passes the filters, no need to set it to always show @@ -138,7 +138,7 @@ namespace simQt { // now get entity id AbstractEntityTreeItem *item = static_cast(index0.internalPointer()); simData::ObjectId id = 0; - if (item != NULL) + if (item != nullptr) id = item->id(); else { diff --git a/SDK/simQt/EntityStateFilter.cpp b/SDK/simQt/EntityStateFilter.cpp index f2e20c26f..6665f55de 100644 --- a/SDK/simQt/EntityStateFilter.cpp +++ b/SDK/simQt/EntityStateFilter.cpp @@ -104,7 +104,7 @@ QWidget* EntityStateFilter::widget(QWidget* newWidgetParent) const connect(this, SIGNAL(entityStateChanged(int)), rv, SLOT(setCurrentIndex(int))); return rv; } - return NULL; + return nullptr; } void EntityStateFilter::getFilterSettings(QMap& settings) const diff --git a/SDK/simQt/EntityStateFilter.h b/SDK/simQt/EntityStateFilter.h index 4a180c3e1..3a63fe410 100644 --- a/SDK/simQt/EntityStateFilter.h +++ b/SDK/simQt/EntityStateFilter.h @@ -61,8 +61,8 @@ namespace simQt { virtual bool acceptEntity(simData::ObjectId id) const; /** - * Inherited from EntityFilter, returns a new instance of the widget to be displayed, otherwise returns NULL - * @param newWidgetParent QWidget parent, useful for memory management purposes; may be NULL if desired + * Inherited from EntityFilter, returns a new instance of the widget to be displayed, otherwise returns nullptr + * @param newWidgetParent QWidget parent, useful for memory management purposes; may be nullptr if desired * @return QWidget used for changing filter settings */ virtual QWidget* widget(QWidget* newWidgetParent) const; diff --git a/SDK/simQt/EntityTreeComposite.cpp b/SDK/simQt/EntityTreeComposite.cpp index bde633662..82dfb0407 100644 --- a/SDK/simQt/EntityTreeComposite.cpp +++ b/SDK/simQt/EntityTreeComposite.cpp @@ -169,7 +169,7 @@ class EntityTreeComposite::Observer : public simQt::Settings::Observer virtual void onSettingChange(const QString& name, const QVariant& value) { - ButtonActions* actions = NULL; + ButtonActions* actions = nullptr; for (size_t index = 0; index < parent_.buttonActions_.size(); ++index) { if (parent_.buttonActions_[index]->settingsKey() == name) @@ -195,11 +195,11 @@ class EntityTreeComposite::Observer : public simQt::Settings::Observer EntityTreeComposite::EntityTreeComposite(QWidget* parent) : QWidget(parent), - composite_(NULL), - entityTreeWidget_(NULL), - model_(NULL), - nameFilter_(NULL), - filterDialog_(NULL), + composite_(nullptr), + entityTreeWidget_(nullptr), + model_(nullptr), + nameFilter_(nullptr), + filterDialog_(nullptr), useCenterAction_(false), treeViewUsable_(true), useEntityIcons_(true), @@ -219,7 +219,7 @@ EntityTreeComposite::EntityTreeComposite(QWidget* parent) connect(entityTreeWidget_, SIGNAL(filterSettingsChanged(QMap)), this, SIGNAL(filterSettingsChanged(QMap))); // Echo out the signal // model is null at startup. Will be updated in the name filter in the call to setModel() - nameFilter_ = new EntityNameFilter(NULL); + nameFilter_ = new EntityNameFilter(nullptr); nameFilter_->bindToWidget(composite_->lineEdit); addEntityFilter(nameFilter_); @@ -293,10 +293,9 @@ void EntityTreeComposite::setMargins(int left, int top, int right, int bottom) composite_->verticalLayout->layout()->setContentsMargins(left, top, right, bottom); } -#ifdef USE_DEPRECATED_SIMDISSDK_API void EntityTreeComposite::addExternalAction(QAction* action) { - if ((action == NULL) || action->isSeparator()) + if ((action == nullptr) || action->isSeparator()) return; externalActions_.push_back(action); @@ -306,7 +305,6 @@ void EntityTreeComposite::removeExternalActions() { externalActions_.clear(); } -#endif void EntityTreeComposite::makeAndDisplayMenu_(const QPoint& pos) { @@ -364,7 +362,7 @@ void EntityTreeComposite::addEntityFilter(EntityFilter* entityFilter) void EntityTreeComposite::setModel(AbstractEntityTreeModel* model) { // Must pass in a valid model - assert(model != NULL); + assert(model != nullptr); // SDK-120: If useEntityIcons_ is set, then apply it to the model model_ = model; @@ -390,19 +388,6 @@ int EntityTreeComposite::setSelected(const QList& list) return entityTreeWidget_->setSelected(list); } -#ifdef USE_DEPRECATED_SIMDISSDK_API -/** Sets/clears the selected ID in the entity list */ -void EntityTreeComposite::setSelected(uint64_t id, bool selected) -{ - entityTreeWidget_->setSelected(id, selected); -} - -void EntityTreeComposite::setSelected(QList list, bool selected) -{ - entityTreeWidget_->setSelected(list, selected); -} -#endif - void EntityTreeComposite::scrollTo(uint64_t id, QAbstractItemView::ScrollHint hint) { entityTreeWidget_->scrollTo(id, hint); @@ -524,14 +509,14 @@ void EntityTreeComposite::setSettings(SettingsPtr settings) } // Can only set the setting once - assert(settings_ == NULL); + assert(settings_ == nullptr); settings_ = settings; - if (settings_ == NULL) + if (settings_ == nullptr) return; - if (observer_ == NULL) + if (observer_ == nullptr) observer_.reset(new Observer(*this)); // Filter configuration buttons use signal mappers to convey index @@ -596,7 +581,7 @@ void EntityTreeComposite::saveFilterConfig_(int index) FilterConfiguration newConfig(desc, variantMap); action->setFilterConfiguration(newConfig); // Save the value also to settings - if (settings_ != NULL) + if (settings_ != nullptr) { QVariant value; value.setValue(action->filterConfiguration()); @@ -609,7 +594,7 @@ void EntityTreeComposite::clearFilterConfig_(int index) ButtonActions* action = buttonActions_[index]; FilterConfiguration emptyConfig; action->setFilterConfiguration(emptyConfig); - if (settings_ != NULL) + if (settings_ != nullptr) { QVariant value; value.setValue(action->filterConfiguration()); @@ -631,7 +616,7 @@ void EntityTreeComposite::rowsInserted_(const QModelIndex & parent, int start, i void EntityTreeComposite::showFilters_() { - if (filterDialog_ != NULL) + if (filterDialog_ != nullptr) { filterDialog_->show(); return; @@ -667,7 +652,7 @@ void EntityTreeComposite::closeFilters_() { filterDialog_->hide(); filterDialog_->deleteLater(); - filterDialog_ = NULL; + filterDialog_ = nullptr; } } @@ -727,7 +712,7 @@ void EntityTreeComposite::copySelection_() { QList ids = entityTreeWidget_->selectedItems(); - if (ids.isEmpty() || (model_ == NULL)) + if (ids.isEmpty() || (model_ == nullptr)) return; QString clipboardText; diff --git a/SDK/simQt/EntityTreeComposite.h b/SDK/simQt/EntityTreeComposite.h index 573ca1f9a..3f0ffc92b 100644 --- a/SDK/simQt/EntityTreeComposite.h +++ b/SDK/simQt/EntityTreeComposite.h @@ -50,7 +50,7 @@ class SDKQT_EXPORT FilterDialog : public QDialog Q_OBJECT; public: /** Constructor */ - explicit FilterDialog(QWidget* parent = NULL); + explicit FilterDialog(QWidget* parent = nullptr); virtual ~FilterDialog(){}; /** Override the QDialog close event to emit the closedGui signal */ @@ -168,18 +168,11 @@ class SDKQT_EXPORT EntityTreeComposite : public QWidget QMap configuration_; ///< Map of all filter configuration settings }; -#ifdef USE_DEPRECATED_SIMDISSDK_API /** DEPRECATED: Add an action to the right mouse click menu, separators are ignored */ SDK_DEPRECATE(void addExternalAction(QAction* action), "Method will be removed in a future SDK release"); /** DEPRECATED: Remove all actions added by the addExternalAction() call */ SDK_DEPRECATE(void removeExternalActions(), "Method will be removed in a future SDK release"); - /** DEPRECATED: Sets/clears the selected ID in the entity list */ - SDK_DEPRECATE(void setSelected(uint64_t id, bool selected), "Method will be removed in a future SDK release"); - /** DEPRECATED: Sets/clears selection for the IDs in 'list' */ - SDK_DEPRECATE(void setSelected(QList list, bool selected), "Method will be removed in a future SDK release"); -#endif - public slots: /** If true expand the tree on double click */ void setExpandsOnDoubleClick(bool value); @@ -216,7 +209,7 @@ public slots: void filterSettingsChanged(const QMap& settings); /** Fired before showing the right mouse click menu to allow external code to add and remove actions. */ - void rightClickMenuRequested(QMenu* menu=NULL); + void rightClickMenuRequested(QMenu* menu=nullptr); /** Fired when entityTreeComposite toggles between tree and list view */ void treeViewChanged(bool useTreeView); @@ -272,9 +265,7 @@ private slots: QAction* collapseAllAction_; QAction* expandAllAction_; -#ifdef USE_DEPRECATED_SIMDISSDK_API std::vector externalActions_; -#endif bool useCenterAction_; bool treeViewUsable_; diff --git a/SDK/simQt/EntityTreeModel.cpp b/SDK/simQt/EntityTreeModel.cpp index 59e84efa0..4fdef8be2 100644 --- a/SDK/simQt/EntityTreeModel.cpp +++ b/SDK/simQt/EntityTreeModel.cpp @@ -75,7 +75,7 @@ class EntityTreeModel::TreeListener : public simData::DataStore::Listener // Fulfill the interface virtual void onPostRemoveEntity(simData::DataStore *source, simData::ObjectId removedId, simData::ObjectType ot) {} virtual void onPrefsChange(simData::DataStore *source, simData::ObjectId id) {} - virtual void onTimeChange(simData::DataStore *source) {} + virtual void onChange(simData::DataStore *source) {} virtual void onFlush(simData::DataStore* source, simData::ObjectId id) {} private: @@ -146,9 +146,9 @@ int EntityTreeItem::row() const EntityTreeModel::EntityTreeModel(QObject *parent, simData::DataStore* dataStore) : AbstractEntityTreeModel(parent), - rootItem_(NULL), + rootItem_(nullptr), treeView_(false), - dataStore_(NULL), + dataStore_(nullptr), platformIcon_(":/simQt/images/platform.png"), beamIcon_(":/simQt/images/beam.png"), customRenderingIcon_(":/simQt/images/CustomRender.png"), @@ -171,7 +171,7 @@ EntityTreeModel::EntityTreeModel(QObject *parent, simData::DataStore* dataStore) EntityTreeModel::~EntityTreeModel() { - setDataStore(NULL); + setDataStore(nullptr); delete rootItem_; } @@ -298,14 +298,14 @@ void EntityTreeModel::forceRefresh() // clean up tree widget delete rootItem_; - rootItem_ = new EntityTreeItem(0, NULL); // has no parent + rootItem_ = new EntityTreeItem(0, nullptr); // has no parent delayedAdds_.clear(); // clear any delayed entities since building from the data store itemsById_.clear(); // Get platform objects from DataStore simData::DataStore::IdList platformList; dataStore_->idList(&platformList, simData::PLATFORM); - buildTree_(simData::PLATFORM, dataStore_, platformList, NULL); + buildTree_(simData::PLATFORM, dataStore_, platformList, nullptr); if (customAsTopLevel_) { // Get custom rendering objects from DataStore @@ -319,7 +319,7 @@ void EntityTreeModel::forceRefresh() if (hostId == 0) topLevelCrList.push_back(*it); } - buildTree_(simData::CUSTOM_RENDERING, dataStore_, topLevelCrList, NULL); + buildTree_(simData::CUSTOM_RENDERING, dataStore_, topLevelCrList, nullptr); } endResetModel(); } @@ -331,12 +331,12 @@ EntityTreeItem* EntityTreeModel::findItem_(uint64_t entityId) const if (it != itemsById_.end()) return it->second; - return NULL; + return nullptr; } void EntityTreeModel::setIncludeScenario(bool showScenario) { - bool currentShow = (findItem_(0) != NULL); + bool currentShow = (findItem_(0) != nullptr); if (currentShow == showScenario) return; // nothing changed @@ -350,8 +350,8 @@ void EntityTreeModel::addTreeItem_(uint64_t id, simData::ObjectType type, uint64 { EntityTreeItem* found = findItem_(id); // adding a duplicate - assert(found == NULL); - if (found != NULL) + assert(found == nullptr); + if (found != nullptr) return; EntityTreeItem* parentItem; @@ -384,7 +384,7 @@ void EntityTreeModel::addTreeItem_(uint64_t id, simData::ObjectType type, uint64 void EntityTreeModel::removeEntity_(uint64_t id) { EntityTreeItem* found = findItem_(id); - if (found == NULL) + if (found == nullptr) { // slight chance it might be delayed std::vector::iterator it = std::find(delayedAdds_.begin(), delayedAdds_.end(), id); @@ -430,13 +430,13 @@ void EntityTreeModel::removeAllEntities_() delayedAdds_.clear(); // no point in reseting an empty model - if ((rootItem_ != NULL) && (rootItem_->childCount() == 0)) + if ((rootItem_ != nullptr) && (rootItem_->childCount() == 0)) return; beginResetModel(); delete rootItem_; - rootItem_ = new EntityTreeItem(0, NULL); + rootItem_ = new EntityTreeItem(0, nullptr); itemsById_.clear(); endResetModel(); @@ -453,7 +453,7 @@ QVariant EntityTreeModel::data(const QModelIndex &index, int role) const return QVariant(); EntityTreeItem *item = static_cast(index.internalPointer()); - if (item == NULL) + if (item == nullptr) return QVariant(); switch (role) @@ -535,7 +535,7 @@ QVariant EntityTreeModel::data(const QModelIndex &index, int role) const #ifdef HAVE_SIMVIS simData::DataStore::Transaction transaction; const simData::PlatformPrefs* prefs = dataStore_->platformPrefs(item->id(), &transaction); - if (prefs == NULL) + if (prefs == nullptr) return toolTip; const std::string model = simVis::Registry::instance()->findModelFile(prefs->icon()); @@ -621,7 +621,7 @@ QModelIndex EntityTreeModel::index(int row, int column, const QModelIndex &paren QModelIndex EntityTreeModel::index(uint64_t id) const { EntityTreeItem* item = findItem_(id); - if (item != NULL) + if (item != nullptr) { return createIndex(item->row(), 0, item); } @@ -632,11 +632,11 @@ QModelIndex EntityTreeModel::index(uint64_t id) const QModelIndex EntityTreeModel::index(uint64_t id) { EntityTreeItem* item = findItem_(id); - if (item == NULL) + if (item == nullptr) { commitDelayedEntities_(); item = findItem_(id); - if (item == NULL) + if (item == nullptr) return QModelIndex(); } @@ -649,7 +649,7 @@ uint64_t EntityTreeModel::uniqueId(const QModelIndex &index) const return 0; EntityTreeItem *childItem = static_cast(index.internalPointer()); - if (childItem == NULL) + if (childItem == nullptr) return 0; return childItem->id(); @@ -661,12 +661,12 @@ QModelIndex EntityTreeModel::parent(const QModelIndex &index) const return QModelIndex(); EntityTreeItem *childItem = static_cast(index.internalPointer()); - if (childItem == NULL) + if (childItem == nullptr) return QModelIndex(); EntityTreeItem *parentItem = childItem->parent(); - if (parentItem == NULL) + if (parentItem == nullptr) return QModelIndex(); if (parentItem == rootItem_) diff --git a/SDK/simQt/EntityTreeModel.h b/SDK/simQt/EntityTreeModel.h index 74e6a33f5..6266ed835 100644 --- a/SDK/simQt/EntityTreeModel.h +++ b/SDK/simQt/EntityTreeModel.h @@ -35,7 +35,7 @@ class SDKQT_EXPORT EntityTreeItem : public simQt::AbstractEntityTreeItem { public: /// constructor - EntityTreeItem(simData::ObjectId id, EntityTreeItem *parent=NULL); + EntityTreeItem(simData::ObjectId id, EntityTreeItem *parent=nullptr); virtual ~EntityTreeItem(); virtual uint64_t id() const; diff --git a/SDK/simQt/EntityTreeWidget.cpp b/SDK/simQt/EntityTreeWidget.cpp index b40af1aaf..a95facb94 100644 --- a/SDK/simQt/EntityTreeWidget.cpp +++ b/SDK/simQt/EntityTreeWidget.cpp @@ -56,8 +56,8 @@ class EntityTreeWidget::EntitySettingsObserver : public Settings::Observer EntityTreeWidget::EntityTreeWidget(QTreeView* view) : QObject(view), view_(view), - model_(NULL), - proxyModel_(NULL), + model_(nullptr), + proxyModel_(nullptr), settings_(SettingsPtr()), treeView_(false), pendingSendNumItems_(false), @@ -104,7 +104,7 @@ QList EntityTreeWidget::filterWidgets(QWidget* newWidgetParent) const void EntityTreeWidget::setModel(AbstractEntityTreeModel* model) { - if (model_ != NULL) + if (model_ != nullptr) { disconnect(model_, SIGNAL(rowsInserted(QModelIndex, int, int)), this, SLOT(delaySend_())); disconnect(model_, SIGNAL(rowsRemoved(QModelIndex, int, int)), this, SLOT(delaySend_())); @@ -139,72 +139,9 @@ void EntityTreeWidget::clearSelection() selectionSet_.clear(); } -#ifdef USE_DEPRECATED_SIMDISSDK_API -void EntityTreeWidget::setSelected(uint64_t id, bool selected, bool signalItemsSelected) -{ - if (model_ == NULL) - return; - - // Pull out the index from the proxy - QModelIndex index = proxyModel_->mapFromSource(model_->index(id)); - // If it's invalid, break out - if (index == QModelIndex()) - { - // Make sure the item is not in the selection list (can happen in swap to tree list if - // a gate was selected and beams were filtered) - if (selectionSet_.remove(id)) - selectionList_.removeOne(id); - return; - } - - // If the item is already selected/deselected, then ignore the request - if (view_->selectionModel()->isSelected(index) == selected) - { - // Validate that our cache is consistent with this request - assert(selectionSet_.contains(id) == selected); - return; - } - - // For internal consistency, update the selection_ cache BEFORE changing selection - if (selected) - { - // It's possible that this check could fail if swapping between tree and list, because - // in some cases signals can be blocked and we don't get the update on selections - if (!selectionSet_.contains(id)) - { - selectionSet_.insert(id); - selectionList_.append(id); - } - } - else - { - // Assertion failure means the model thinks we had a selection, but we didn't cache it - assert(selectionSet_.contains(id)); - // Only remove from list, if remove from set succeeds - if (selectionSet_.remove(id)) - selectionList_.removeOne(id); - } - // Update our flag to match the signalItemsSelected flag. Do this so that selectionModel()->select() - // properly tells the view_ to update graphically, but so that we don't unnecessarily update in selectionChanged_() - emitSelectionChanged_ = signalItemsSelected; - // Update the selection - QItemSelectionModel::SelectionFlags flags = QItemSelectionModel::Rows | (selected ? QItemSelectionModel::Select : QItemSelectionModel::Deselect); - view_->selectionModel()->select(index, flags); - view_->selectionModel()->setCurrentIndex(index, flags); - // Restore the flag to true, so that single selections work as expected - emitSelectionChanged_ = true; -} - -void EntityTreeWidget::setSelected(QList list, bool selected) -{ - for (int ii = 0; ii < list.count(); ii++) - setSelected(list[ii], selected, ii == (list.count()-1)); // cause a GUI update on the last selection -} -#endif - int EntityTreeWidget::setSelected(uint64_t id) { - if (model_ == NULL) + if (model_ == nullptr) return 1; if ((selectionList_.size() == 1) && (selectionList_.front() == id)) @@ -241,7 +178,7 @@ int EntityTreeWidget::setSelected(uint64_t id) int EntityTreeWidget::setSelected(const QList& list) { - if (model_ == NULL) + if (model_ == nullptr) return 1; QSet newSet; ///< Use new set to detected changes with selectionSet_ @@ -451,7 +388,7 @@ void EntityTreeWidget::setToTreeView() if (treeView_) return; treeView_ = true; - if (model_ == NULL) + if (model_ == nullptr) return; QList entities = selectedItems(); @@ -468,7 +405,7 @@ void EntityTreeWidget::setToListView() if (!treeView_) return; treeView_ = false; - if (model_ == NULL) + if (model_ == nullptr) return; QList entities = selectedItems(); @@ -491,7 +428,7 @@ void EntityTreeWidget::toggleTreeView(bool useTree) static const int LIST_INDENT = 4; view_->setIndentation(useTree ? TREE_INDENT : LIST_INDENT); - if (model_ == NULL) + if (model_ == nullptr) return; QList entities = selectedItems(); @@ -507,7 +444,7 @@ void EntityTreeWidget::toggleTreeView(bool useTree) void EntityTreeWidget::forceRefresh() { - if (model_ == NULL) + if (model_ == nullptr) return; model_->forceRefresh(); @@ -545,7 +482,7 @@ void EntityTreeWidget::selectionChanged_(const QItemSelection& selected, const Q // Pull out the item from the index, which contains the ID const QModelIndex index2 = proxyModel_->mapToSource(*it); const AbstractEntityTreeItem *item = static_cast(index2.internalPointer()); - if (item == NULL) + if (item == nullptr) continue; // Add the ID to both lists const uint64_t id = item->id(); @@ -565,7 +502,7 @@ void EntityTreeWidget::doubleClicked_(const QModelIndex& index) { QModelIndex index2 = proxyModel_->mapToSource(index); AbstractEntityTreeItem *item = static_cast(index2.internalPointer()); - if (item != NULL) + if (item != nullptr) emit itemDoubleClicked(item->id()); } @@ -587,7 +524,7 @@ void EntityTreeWidget::emitSend_() void EntityTreeWidget::sendNumFilteredItems_() { - if ((proxyModel_ != NULL) && (model_ != NULL)) + if ((proxyModel_ != nullptr) && (model_ != nullptr)) emit numFilteredItemsChanged(proxyModel_->rowCount(), model_->rowCount()); } diff --git a/SDK/simQt/EntityTreeWidget.h b/SDK/simQt/EntityTreeWidget.h index 0b18e2f5e..a56e39028 100644 --- a/SDK/simQt/EntityTreeWidget.h +++ b/SDK/simQt/EntityTreeWidget.h @@ -98,13 +98,6 @@ class SDKQT_EXPORT EntityTreeWidget : public QObject /** Get the settings for all the filters */ void getFilterSettings(QMap& settings) const; -#ifdef USE_DEPRECATED_SIMDISSDK_API - /** DEPRECATED: Sets/clears the selected ID in the entity list; does NOT generate a itemsSelected signal; instead, use setSelected method above */ - void setSelected(uint64_t id, bool selected, bool signalItemsSelected = false); - /** DEPRECATED: Sets/clears selection for the IDs in 'list'; instead, use setSelected method above */ - void setSelected(QList list, bool selected); -#endif - public slots: /** Swaps the view to the hierarchy tree */ void setToTreeView(); diff --git a/SDK/simQt/EntityTypeFilter.cpp b/SDK/simQt/EntityTypeFilter.cpp index 7003fe341..f48a4fb6d 100644 --- a/SDK/simQt/EntityTypeFilter.cpp +++ b/SDK/simQt/EntityTypeFilter.cpp @@ -56,7 +56,7 @@ namespace simQt { connect(this, SIGNAL(entityTypesChanged(unsigned int)), rv, SLOT(setSelections(unsigned int))); return rv; } - return NULL; + return nullptr; } void EntityTypeFilter::getFilterSettings(QMap& settings) const diff --git a/SDK/simQt/EntityTypeFilter.h b/SDK/simQt/EntityTypeFilter.h index b34f5bf81..2f6405fa9 100644 --- a/SDK/simQt/EntityTypeFilter.h +++ b/SDK/simQt/EntityTypeFilter.h @@ -59,8 +59,8 @@ namespace simQt { virtual bool acceptEntity(simData::ObjectId id) const; /** - * Inherited from EntityFilter, returns a new instance of the widget to be displayed, otherwise returns NULL - * @param newWidgetParent QWidget parent, useful for memory management purposes; may be NULL if desired + * Inherited from EntityFilter, returns a new instance of the widget to be displayed, otherwise returns nullptr + * @param newWidgetParent QWidget parent, useful for memory management purposes; may be nullptr if desired * @return QWidget used for changing filter settings */ virtual QWidget* widget(QWidget* newWidgetParent) const; diff --git a/SDK/simQt/EntityTypeFilterWidget.cpp b/SDK/simQt/EntityTypeFilterWidget.cpp index 3bf15bdd9..9f173d95d 100644 --- a/SDK/simQt/EntityTypeFilterWidget.cpp +++ b/SDK/simQt/EntityTypeFilterWidget.cpp @@ -68,7 +68,7 @@ EntityTypeFilterWidget::EntityTypeFilterWidget(QWidget* parent, unsigned int typ EntityTypeFilterWidget::~EntityTypeFilterWidget() { delete ui_; - ui_ = NULL; + ui_ = nullptr; } unsigned int EntityTypeFilterWidget::getSelections() const diff --git a/SDK/simQt/EntityTypeFilterWidget.h b/SDK/simQt/EntityTypeFilterWidget.h index 87fb6cd29..716d9f016 100644 --- a/SDK/simQt/EntityTypeFilterWidget.h +++ b/SDK/simQt/EntityTypeFilterWidget.h @@ -39,7 +39,7 @@ namespace simQt { Q_OBJECT; public: /** Constructor */ - EntityTypeFilterWidget(QWidget* parent = NULL, unsigned int types = simData::ALL); + EntityTypeFilterWidget(QWidget* parent = nullptr, unsigned int types = simData::ALL); /** Destructor */ virtual ~EntityTypeFilterWidget(); diff --git a/SDK/simQt/FileDescriptorReplacement.cpp b/SDK/simQt/FileDescriptorReplacement.cpp index a6bef8b1a..c81cda8e4 100644 --- a/SDK/simQt/FileDescriptorReplacement.cpp +++ b/SDK/simQt/FileDescriptorReplacement.cpp @@ -58,7 +58,7 @@ FileDescriptorReplacement::ReadInLoop::~ReadInLoop() teeToFd_ = -1; delete[] buffer_; - buffer_ = NULL; + buffer_ = nullptr; SAFETRYEND("destroying file descriptor reading loop"); } @@ -93,7 +93,7 @@ void FileDescriptorReplacement::ReadInLoop::selectLoop_() timeVal.tv_sec = 0; timeVal.tv_usec = 100000; // 100 milliseconds - int rv = select(fd_ + 1, &fdSet, NULL, NULL, &timeVal); + int rv = select(fd_ + 1, &fdSet, nullptr, nullptr, &timeVal); if (rv < 0) { stop(); @@ -151,7 +151,7 @@ int FileDescriptorReplacement::ReadInLoop::readBuffer_() int rv = read(fd_, buffer_, FD_BUFFER_SIZE); #endif - // Don't write single NULL characters, and don't write errors + // Don't write single nullptr characters, and don't write errors if (rv > 0 && (rv > 1 || buffer_[0] != '\0')) { // Send the output to the original destination if required @@ -188,7 +188,7 @@ int FileDescriptorReplacement::ReadInLoop::readBuffer_() FileDescriptorReplacement::FileDescriptorReplacement(int whichFd, bool teeToOriginalDest, QObject* parent) : QObject(parent), - reader_(NULL), + reader_(nullptr), replacedFd_(whichFd), savedDupFd_(-1), pipeReadFd_(-1), @@ -319,9 +319,9 @@ int FileDescriptorReplacement::install_(int toFd, int& copyOfOldFd, int& pipeRea // buffered on write, causing reads to block until the stream decides to flush. This // is for buffered output (e.g. printf, fprintf, cout, etc.) and not FD-based write(). if (toFd == STDOUT_FILENO) - setvbuf(stdout, NULL, _IONBF, 0); + setvbuf(stdout, nullptr, _IONBF, 0); else if (toFd == STDERR_FILENO) - setvbuf(stderr, NULL, _IONBF, 0); + setvbuf(stderr, nullptr, _IONBF, 0); // Also on Windows set the default handle buffer as needed if (setStdHandle_(toFd, pipeWriteEnd) != 0) @@ -356,7 +356,7 @@ int FileDescriptorReplacement::setStdHandle_(int toFd, int writeFd) const void FileDescriptorReplacement::startThread_() { - if (reader_ != NULL) + if (reader_ != nullptr) return; QThread *thread = new QThread; thread->setObjectName(tr("FDReplacement %1 Thread").arg(replacedFd_)); @@ -377,18 +377,18 @@ void FileDescriptorReplacement::startThread_() void FileDescriptorReplacement::setReaderToNull_() { - // The purpose of this slot is to set reader_ to NULL. It's possible + // The purpose of this slot is to set reader_ to nullptr. It's possible // that the reader_ will decide on its own when to stop running, due to // an invalid handle for example (this can happen with the use of the // windows API FreeConsole()). Avoid dereferencing stale pointers when - // this happens by setting reader_ to NULL. - reader_ = NULL; + // this happens by setting reader_ to nullptr. + reader_ = nullptr; } void FileDescriptorReplacement::stopThread_() { SAFETRYBEGIN; - if (reader_ != NULL) + if (reader_ != nullptr) { reader_->stop(); @@ -406,7 +406,7 @@ void FileDescriptorReplacement::stopThread_() SAFETRYEND("while stopping FileDescriptorReplacement thread"); // reader_ gets deleted automatically with deleteLater() signal - reader_ = NULL; + reader_ = nullptr; } } diff --git a/SDK/simQt/FileDescriptorReplacement.h b/SDK/simQt/FileDescriptorReplacement.h index 1827c4107..e632e85fe 100644 --- a/SDK/simQt/FileDescriptorReplacement.h +++ b/SDK/simQt/FileDescriptorReplacement.h @@ -61,7 +61,7 @@ class SDKQT_EXPORT FileDescriptorReplacement : public QObject * receive no text from stdout unless teeToOriginalDest is true. * @param parent QObject parent for automatic deletion */ - FileDescriptorReplacement(int whichFd, bool teeToOriginalDest, QObject* parent=NULL); + FileDescriptorReplacement(int whichFd, bool teeToOriginalDest, QObject* parent=nullptr); /** Replaces the descriptor so regular output will continue */ virtual ~FileDescriptorReplacement(); @@ -71,7 +71,7 @@ class SDKQT_EXPORT FileDescriptorReplacement : public QObject * a signal. The console will receive no text from stdout unless teeToStdOut is true. * @param parent QObject parent for automatic deletion */ - static FileDescriptorReplacement* replaceStdout(bool teeToStdOut, QObject* parent = NULL); + static FileDescriptorReplacement* replaceStdout(bool teeToStdOut, QObject* parent = nullptr); /** * Factory method to replace stderr. Useful because STDERR_FILENO is not universally defined. @@ -79,7 +79,7 @@ class SDKQT_EXPORT FileDescriptorReplacement : public QObject * a signal. The console will receive no text from stderr unless teeToStdErr is true. * @param parent QObject parent for automatic deletion */ - static FileDescriptorReplacement* replaceStderr(bool teeToStdErr, QObject* parent = NULL); + static FileDescriptorReplacement* replaceStderr(bool teeToStdErr, QObject* parent = nullptr); signals: /** Text has been read on the specified file descriptor */ diff --git a/SDK/simQt/FileDialog.cpp b/SDK/simQt/FileDialog.cpp index 4099c01e1..a4dc4f855 100644 --- a/SDK/simQt/FileDialog.cpp +++ b/SDK/simQt/FileDialog.cpp @@ -93,7 +93,7 @@ QString FileDialog::saveFile(QWidget* owner, const QString& caption, const QStri // If the caller did not provide a selected filter, attempt to find a matching filter QString* localPointer = selectedFilter; QString localSelectedFilter; - if (localPointer == NULL) + if (localPointer == nullptr) { QString ext = QString::fromStdString(simCore::getExtension(directory.toStdString())); if (!ext.isEmpty()) diff --git a/SDK/simQt/FileDialog.h b/SDK/simQt/FileDialog.h index 90aa019eb..993f7e5fa 100644 --- a/SDK/simQt/FileDialog.h +++ b/SDK/simQt/FileDialog.h @@ -64,54 +64,54 @@ class SDKQT_EXPORT FileDialog /** * Displays a dialog box suitable for saving a file - * @param owner Widget owner for stacking order; NULL to show with no parent + * @param owner Widget owner for stacking order; nullptr to show with no parent * @param caption Top level window text title * @param registryDir Registry directory to load/save last directory, such as "SETTINGS/LastDir" or "DirectorySettings/ImportantFiles" * @param filter Newline separated list of filters, like "Text Files (*.txt,*.ascii)\nAll Files (*)" - * @param selectedFilter If non-NULL, the input value will select the default filter, the output value will contain the text of - * the filter that was selected by the user when file was opened. If NULL the code will use the extension of the last saved + * @param selectedFilter If non-nullptr, the input value will select the default filter, the output value will contain the text of + * the filter that was selected by the user when file was opened. If nullptr the code will use the extension of the last saved * file to set the default filter. * @param options Qt options for the file dialog, such as QFileDialog::ShowDirsOnly. See QFileDialog documentation for all options * @return Name of file selected by user for saving */ - static QString saveFile(QWidget* owner=NULL, const QString& caption="", const QString& registryDir="", - const QString& filter="All Files (*)", QString* selectedFilter=NULL, QFileDialog::Options options=0); + static QString saveFile(QWidget* owner=nullptr, const QString& caption="", const QString& registryDir="", + const QString& filter="All Files (*)", QString* selectedFilter=nullptr, QFileDialog::Options options=0); /** * Displays a dialog box suitable for loading a single file - * @param owner Widget owner for stacking order; NULL to show with no parent + * @param owner Widget owner for stacking order; nullptr to show with no parent * @param caption Top level window text title * @param registryDir Registry directory to load/save last directory, such as "SETTINGS/LastDir" or "DirectorySettings/ImportantFiles" * @param filter Newline separated list of filters, like "Text Files (*.txt,*.ascii)\nAll Files (*)" - * @param selectedFilter If non-NULL, will contain the text of the filter that was selected by the user when file was opened + * @param selectedFilter If non-nullptr, will contain the text of the filter that was selected by the user when file was opened * @param options Qt options for the file dialog, such as QFileDialog::ShowDirsOnly. See QFileDialog documentation for all options * @return Name of file selected by user for loading */ - static QString loadFile(QWidget* owner=NULL, const QString& caption="", const QString& registryDir="", - const QString& filter="All Files (*)", QString* selectedFilter=NULL, QFileDialog::Options options=0); + static QString loadFile(QWidget* owner=nullptr, const QString& caption="", const QString& registryDir="", + const QString& filter="All Files (*)", QString* selectedFilter=nullptr, QFileDialog::Options options=0); /** * Displays a dialog box suitable for loading a multiple files - * @param owner Widget owner for stacking order; NULL to show with no parent + * @param owner Widget owner for stacking order; nullptr to show with no parent * @param caption Top level window text title * @param registryDir Registry directory to load/save last directory, such as "SETTINGS/LastDir" or "DirectorySettings/ImportantFiles" * @param filter Newline separated list of filters, like "Text Files (*.txt,*.ascii)\nAll Files (*)" - * @param selectedFilter If non-NULL, will contain the text of the filter that was selected by the user when file was opened + * @param selectedFilter If non-nullptr, will contain the text of the filter that was selected by the user when file was opened * @param options Qt options for the file dialog, such as QFileDialog::ShowDirsOnly. See QFileDialog documentation for all options * @return Names of files selected by user for loading */ - static QStringList loadFiles(QWidget* owner=NULL, const QString& caption="", const QString& registryDir="", - const QString& filter="All Files (*)", QString* selectedFilter=NULL, QFileDialog::Options options=0); + static QStringList loadFiles(QWidget* owner=nullptr, const QString& caption="", const QString& registryDir="", + const QString& filter="All Files (*)", QString* selectedFilter=nullptr, QFileDialog::Options options=0); /** * Displays a dialog box suitable for browsing for a directory - * @param owner Widget owner for stacking order; NULL to show with no parent + * @param owner Widget owner for stacking order; nullptr to show with no parent * @param caption Top level window text title * @param registryDir Registry directory to load/save last directory, such as "SETTINGS/LastDir" or "DirectorySettings/ImportantFiles" * @param options Qt options for the file dialog, such as QFileDialog::ShowDirsOnly. See QFileDialog documentation for all options * @return Name of directory selected by user */ - static QString findDirectory(QWidget* owner=NULL, const QString& caption="", const QString& registryDir="", + static QString findDirectory(QWidget* owner=nullptr, const QString& caption="", const QString& registryDir="", QFileDialog::Options options=0); diff --git a/SDK/simQt/FileSelectorWidget.cpp b/SDK/simQt/FileSelectorWidget.cpp index 771d972d6..6728afcde 100644 --- a/SDK/simQt/FileSelectorWidget.cpp +++ b/SDK/simQt/FileSelectorWidget.cpp @@ -34,14 +34,15 @@ namespace simQt { FileSelectorWidget::FileSelectorWidget(QWidget* parent) : QWidget(parent), registryKey_("Private/file"), - labelWidget_(NULL), + labelWidget_(nullptr), includeLabel_(false), label_(tr("File")), browserTitle_(tr("Load Data File")), flags_(FileSelectorWidget::FileLoad), filterOption_(FileSelectorWidget::SIMDIS_ASI_FILE_PATTERNS), customFileFilter_(tr("All Files (*)")), - iconBeforeText_(false) + iconBeforeText_(false), + isValid_(true) { ResourceInitializer::initialize(); // Needs to be here so that Qt Designer works. @@ -78,18 +79,18 @@ void FileSelectorWidget::setIconBeforeText(bool alignLeft) iconBeforeText_ = alignLeft; QPushButton* fileButton = ui_->fileButton; ui_->horizontalLayout->removeWidget(fileButton); - if (labelWidget_ != NULL) + if (labelWidget_ != nullptr) ui_->horizontalLayout->removeWidget(labelWidget_); if (alignLeft) { ui_->horizontalLayout->insertWidget(0, fileButton); - if (labelWidget_ != NULL) + if (labelWidget_ != nullptr) ui_->horizontalLayout->addWidget(labelWidget_); } else { - if (labelWidget_ != NULL) + if (labelWidget_ != nullptr) ui_->horizontalLayout->insertWidget(0, labelWidget_); ui_->horizontalLayout->addWidget(fileButton); } @@ -120,7 +121,7 @@ void FileSelectorWidget::setIncludeLabel(bool value) { if (value == true) { - if (labelWidget_ == NULL) + if (labelWidget_ == nullptr) { labelWidget_ = new QLabel(label_); } @@ -133,7 +134,7 @@ void FileSelectorWidget::setIncludeLabel(bool value) { ui_->horizontalLayout->removeWidget(labelWidget_); delete labelWidget_; - labelWidget_ = NULL; + labelWidget_ = nullptr; } includeLabel_ = value; @@ -215,6 +216,24 @@ void FileSelectorWidget::setFilename(const QString& filename) emit filenameChanged(osFilename); } +bool FileSelectorWidget::isValid() const +{ + return isValid_; +} + +void FileSelectorWidget::setValid(bool valid) +{ + if (isValid_ == valid) + return; + + isValid_ = valid; + + if (isValid_) + ui_->fileText->setStyleSheet(""); + else + ui_->fileText->setStyleSheet("QLineEdit {color: red}"); +} + bool FileSelectorWidget::eventFilter(QObject* obj, QEvent* evt) { if (obj == ui_->fileText) diff --git a/SDK/simQt/FileSelectorWidget.h b/SDK/simQt/FileSelectorWidget.h index 712b68c44..600cc47b7 100644 --- a/SDK/simQt/FileSelectorWidget.h +++ b/SDK/simQt/FileSelectorWidget.h @@ -67,7 +67,7 @@ class SDKQT_EXPORT FileSelectorWidget : public QWidget public: /** Constructor */ - FileSelectorWidget(QWidget* parent=NULL); + FileSelectorWidget(QWidget* parent=nullptr); virtual ~FileSelectorWidget(); /** Declare options for the file selector */ @@ -178,9 +178,14 @@ class SDKQT_EXPORT FileSelectorWidget : public QWidget /** Retrieve currently set filename */ QString filename() const; + /** Returns the valid state */ + bool isValid() const; + public slots: /** Sets the filename this selector represents */ void setFilename(const QString& filename); + /** Sets the valid state; if invalid the background is turned red */ + void setValid(bool valid); signals: /** Emitted when the filename changes */ @@ -215,13 +220,14 @@ private slots: QString customFileFilter_; /** Indicates if icon is placed before the text widgets */ bool iconBeforeText_; + /** The valid state of the control as dictated by a caller */ + bool isValid_; /** Re-implement eventFilter() */ virtual bool eventFilter(QObject* obj, QEvent* evt); /** Converts the filter option enum to a readable text */ QString filterOptions2QString_(FileSelectorWidget::FilterOptions option) const; - }; } diff --git a/SDK/simQt/FileUtilities.cpp b/SDK/simQt/FileUtilities.cpp index 5c2fa3e0c..df6dcd6af 100644 --- a/SDK/simQt/FileUtilities.cpp +++ b/SDK/simQt/FileUtilities.cpp @@ -52,10 +52,10 @@ int FileUtilities::createHomePath(const QString& relativeFilePath, bool roaming, absolutePath = QDir::homePath(); #ifdef WIN32 // Assertion failure means that Windows API has changed and no longer supplies this - assert(getenv("APPDATA") != NULL); + assert(getenv("APPDATA") != nullptr); // Pull out the APPDATA variable const char* appDataCstr = (roaming ? getenv("APPDATA") : getenv("LOCALAPPDATA")); - if (appDataCstr != NULL) + if (appDataCstr != nullptr) absolutePath = appDataCstr; else if (absolutePath.isEmpty()) // would only happen if QDir::homePath() is empty return 2; diff --git a/SDK/simQt/FillItemModelWithNodeVisitor.cpp b/SDK/simQt/FillItemModelWithNodeVisitor.cpp index dceaceb40..1c98687ce 100644 --- a/SDK/simQt/FillItemModelWithNodeVisitor.cpp +++ b/SDK/simQt/FillItemModelWithNodeVisitor.cpp @@ -232,12 +232,12 @@ std::string StateSetVisitor::uniformToString(const osg::Uniform& uniform) FillTreeStateSetVisitor::FillTreeStateSetVisitor(QStandardItem& parent, osg::NodeVisitor::TraversalMode tm) : StateSetVisitor(tm), parent_(parent), - modes_(NULL), - attributes_(NULL), - textureModes_(NULL), - textureAttributes_(NULL), - uniforms_(NULL), - defines_(NULL) + modes_(nullptr), + attributes_(nullptr), + textureModes_(nullptr), + textureAttributes_(nullptr), + uniforms_(nullptr), + defines_(nullptr) { } @@ -325,9 +325,9 @@ void FillTreeStateSetVisitor::applyDefine(osg::StateSet& stateSet, const std::st QList FillTreeStateSetVisitor::appendRow_(QStandardItem& parent, const QString& column1, const QString& column2, const QString& column3) const { QList row; - row.push_back(newStandardItem_(NULL, column1)); - row.push_back(newStandardItem_(NULL, column2)); - row.push_back(newStandardItem_(NULL, column3)); + row.push_back(newStandardItem_(nullptr, column1)); + row.push_back(newStandardItem_(nullptr, column2)); + row.push_back(newStandardItem_(nullptr, column3)); parent.appendRow(row); return row; } diff --git a/SDK/simQt/FillItemModelWithNodeVisitor.h b/SDK/simQt/FillItemModelWithNodeVisitor.h index 59d53fb21..f6a37ab47 100644 --- a/SDK/simQt/FillItemModelWithNodeVisitor.h +++ b/SDK/simQt/FillItemModelWithNodeVisitor.h @@ -112,7 +112,7 @@ class SDKQT_EXPORT FillTreeStateSetVisitor : public StateSetVisitor private: /** Helper method to add a row to the given parent */ QList appendRow_(QStandardItem& parent, const QString& column1, const QString& column2, const QString& column3) const; - /** Factory method for a QStandardItem that is not editable. If parent is non-NULL, add to parent. */ + /** Factory method for a QStandardItem that is not editable. If parent is non-nullptr, add to parent. */ QStandardItem* newStandardItem_(QStandardItem* parent, const QString& title) const; /** Finds or creates an item child with the given name, always adding to parent if not existing. */ QStandardItem* getOrCreateStandardItem_(QStandardItem& parent, const QString& title) const; diff --git a/SDK/simQt/FontWidget.cpp b/SDK/simQt/FontWidget.cpp index 3e0f3409c..3f85d9158 100644 --- a/SDK/simQt/FontWidget.cpp +++ b/SDK/simQt/FontWidget.cpp @@ -42,7 +42,7 @@ namespace simQt { FontWidget::FontWidget(QWidget* parent) : QWidget(parent), fontDir_(new QDir()), - ui_(NULL), + ui_(nullptr), useFriendlyFontName_(true) { @@ -181,7 +181,9 @@ void FontWidget::setFontColor(const QColor& fontColor) void FontWidget::setFontSize(int fontSize) { - ui_->fontSizeSpinBox->setValue(fontSize); + // Check for equality to avoid trampling user edits with programmatic updates + if (ui_->fontSizeSpinBox->value() != fontSize) + ui_->fontSizeSpinBox->setValue(fontSize); } void FontWidget::setShowFontColor(bool showColor) diff --git a/SDK/simQt/FontWidget.h b/SDK/simQt/FontWidget.h index 2aa7770c4..ebcb394ae 100644 --- a/SDK/simQt/FontWidget.h +++ b/SDK/simQt/FontWidget.h @@ -67,7 +67,7 @@ class SDKQT_EXPORT FontWidget : public QWidget // QDESIGNER_WIDGET_EXPORT * Constructor * @param parent parent widget */ - explicit FontWidget(QWidget* parent = NULL); + explicit FontWidget(QWidget* parent = nullptr); /** Destructor */ virtual ~FontWidget(); diff --git a/SDK/simQt/GanttChartView.h b/SDK/simQt/GanttChartView.h index 1280e7cdc..a4441df7b 100644 --- a/SDK/simQt/GanttChartView.h +++ b/SDK/simQt/GanttChartView.h @@ -51,7 +51,7 @@ class SDKQT_EXPORT GanttChartView : public QAbstractItemView public: /** Constructor */ - explicit GanttChartView(QWidget* parent = NULL); + explicit GanttChartView(QWidget* parent = nullptr); /** Destructor */ virtual ~GanttChartView(); diff --git a/SDK/simQt/IncrementalCompileSettings.cpp b/SDK/simQt/IncrementalCompileSettings.cpp index 7deb7b7b4..a371f7ac0 100644 --- a/SDK/simQt/IncrementalCompileSettings.cpp +++ b/SDK/simQt/IncrementalCompileSettings.cpp @@ -20,6 +20,8 @@ * disclose, or release this software. * */ +#ifdef USE_DEPRECATED_SIMDISSDK_API + #include #include #include "osgUtil/IncrementalCompileOperation" @@ -78,17 +80,17 @@ IncrementalCompileSettings::IncrementalCompileSettings(simQt::Settings& settings IncrementalCompileSettings::~IncrementalCompileSettings() { delete conservativeTimeRatio_; - conservativeTimeRatio_ = NULL; + conservativeTimeRatio_ = nullptr; delete flushTimeRatio_; - flushTimeRatio_ = NULL; + flushTimeRatio_ = nullptr; delete maxCompilesPerFrame_; - maxCompilesPerFrame_ = NULL; + maxCompilesPerFrame_ = nullptr; delete minimumTimeForCompileUS_; - minimumTimeForCompileUS_ = NULL; + minimumTimeForCompileUS_ = nullptr; delete targetRate_; - targetRate_ = NULL; + targetRate_ = nullptr; delete icoEnabled_; - icoEnabled_ = NULL; + icoEnabled_ = nullptr; } void IncrementalCompileSettings::initialize_() @@ -105,7 +107,7 @@ void IncrementalCompileSettings::setIncrementalEnabled_(bool enabled) { if (!viewer_.valid()) return; - viewer_->setIncrementalCompileOperation(enabled ? ico_.get() : NULL); + viewer_->setIncrementalCompileOperation(enabled ? ico_.get() : nullptr); // Iterate through all views and grab their database pagers osgViewer::ViewerBase::Views views; @@ -113,13 +115,13 @@ void IncrementalCompileSettings::setIncrementalEnabled_(bool enabled) std::set pagers; for (osgViewer::ViewerBase::Views::const_iterator i = views.begin(); i != views.end(); ++i) { - if (*i != NULL && (*i)->getDatabasePager() != NULL) + if (*i != nullptr && (*i)->getDatabasePager() != nullptr) pagers.insert((*i)->getDatabasePager()); } // Apply the ICO to each database pager we found (likely only one shared amongst views) for (std::set::const_iterator i = pagers.begin(); i != pagers.end(); ++i) { - (*i)->setIncrementalCompileOperation(enabled ? ico_.get() : NULL); + (*i)->setIncrementalCompileOperation(enabled ? ico_.get() : nullptr); } } @@ -149,3 +151,5 @@ void IncrementalCompileSettings::setConservativeTimeRatio_(int percent) } } + +#endif /* USE_DEPRECATED_SIMDISSDK_API */ diff --git a/SDK/simQt/IncrementalCompileSettings.h b/SDK/simQt/IncrementalCompileSettings.h index 5a6bcb550..56bd89bbd 100644 --- a/SDK/simQt/IncrementalCompileSettings.h +++ b/SDK/simQt/IncrementalCompileSettings.h @@ -23,6 +23,8 @@ #ifndef SIMQT_INCREMENTALCOMPILESETTINGS_H #define SIMQT_INCREMENTALCOMPILESETTINGS_H +#ifdef USE_DEPRECATED_SIMDISSDK_API + #include #include "osg/ref_ptr" #include "osg/observer_ptr" @@ -36,12 +38,23 @@ class Settings; class BoundBooleanSetting; class BoundIntegerSetting; -/** Manages settings for incremental compilation in OpenGL using an osgViewer::ViewerBase */ +/** + * @deprecated + * + * Manages settings for incremental compilation in OpenGL using an osgViewer::ViewerBase. + * + * This class is deprecated because incremental compilation in OpenSceneGraph 3.6.5+ causes + * intermittent problems, especially with text displays. Incremental Compilation (ICO) has + * been tracked to cause flickering red squares with incrementally compiled text objects, + * including osgEarth MGRS/UTM/GARS grids. It has also been tracked to an intermittent + * issue where textures are reported as immutable, causing runtime GL errors and possibly + * display anomalies. As a result of the instability of ICO, this class is deprecated. + */ class SDKQT_EXPORT IncrementalCompileSettings : public QObject { Q_OBJECT; public: - IncrementalCompileSettings(simQt::Settings& settings, osgViewer::ViewerBase* viewer, QObject* parent=NULL); + IncrementalCompileSettings(simQt::Settings& settings, osgViewer::ViewerBase* viewer, QObject* parent=nullptr); virtual ~IncrementalCompileSettings(); private slots: @@ -74,4 +87,6 @@ private slots: } +#endif /* USE_DEPRECATED_SIMDISSDK_API */ + #endif /* SIMQT_INCREMENTALCOMPILESETTINGS_H */ diff --git a/SDK/simQt/MapDataModel.cpp b/SDK/simQt/MapDataModel.cpp index c6583d8f0..1ccf572b5 100644 --- a/SDK/simQt/MapDataModel.cpp +++ b/SDK/simQt/MapDataModel.cpp @@ -67,25 +67,25 @@ MapReindexer::~MapReindexer() void MapReindexer::getLayers(osgEarth::Map* map, osgEarth::ImageLayerVector& imageLayers) { - if (map != NULL) + if (map != nullptr) map->getLayers(imageLayers); } void MapReindexer::getLayers(osgEarth::Map* map, osgEarth::ElevationLayerVector& elevationLayers) { - if (map != NULL) + if (map != nullptr) map->getLayers(elevationLayers); } void MapReindexer::getLayers(osgEarth::Map* map, FeatureModelLayerVector& modelLayers) { - if (map != NULL) + if (map != nullptr) map->getLayers(modelLayers); } void MapReindexer::getOtherLayers(osgEarth::Map* map, osgEarth::VisibleLayerVector& otherLayers) { - if (map == NULL) + if (map == nullptr) return; osgEarth::VisibleLayerVector allLayers; map->getLayers(allLayers); @@ -93,11 +93,11 @@ void MapReindexer::getOtherLayers(osgEarth::Map* map, osgEarth::VisibleLayerVect for (auto iter = allLayers.begin(); iter != allLayers.end(); ++iter) { const osgEarth::VisibleLayer* layer = (*iter).get(); - if (dynamic_cast(layer) != NULL) + if (dynamic_cast(layer) != nullptr) continue; - if (dynamic_cast(layer) != NULL) + if (dynamic_cast(layer) != nullptr) continue; - if (dynamic_cast(layer) != NULL) + if (dynamic_cast(layer) != nullptr) continue; otherLayers.push_back(*iter); } @@ -359,7 +359,7 @@ class GroupItem : public MapDataModel::Item children_.removeOne(c); } - /** Searches children for one that has the layer provided, returning a row or NULL on failure */ + /** Searches children for one that has the layer provided, returning a row or nullptr on failure */ MapDataModel::Item* itemByLayer(const osgEarth::Layer* layer) const { for (auto it = children_.begin(); it != children_.end(); ++it) @@ -367,7 +367,7 @@ class GroupItem : public MapDataModel::Item if ((*it)->layerPtr().value() == layer) return (*it); } - return NULL; + return nullptr; } private: @@ -418,7 +418,7 @@ class LayerItem : public MapDataModel::Item /** @copydoc MapDataModel::Item::childAt */ virtual Item* childAt(int row) { - return NULL; + return nullptr; } /** @copydoc MapDataModel::Item::rowOfChild */ @@ -851,9 +851,6 @@ class MapDataModel::FeatureModelLayerListener : public osgEarth::VisibleLayerCal if (modelLayer) { emit dataModel_.featureLayerVisibleChanged(modelLayer); -#ifdef USE_DEPRECATED_SIMDISSDK_API - emit dataModel_.modelLayerVisibleChanged(modelLayer); -#endif } } @@ -864,9 +861,6 @@ class MapDataModel::FeatureModelLayerListener : public osgEarth::VisibleLayerCal if (modelLayer) { emit dataModel_.featureLayerOpacityChanged(modelLayer); -#ifdef USE_DEPRECATED_SIMDISSDK_API - emit dataModel_.modelLayerOpacityChanged(modelLayer); -#endif } } @@ -902,7 +896,7 @@ class MapDataModel::OtherLayerListener : public osgEarth::VisibleLayerCallback //---------------------------------------------------------------------------- MapDataModel::MapDataModel(QObject* parent) : QAbstractItemModel(parent), - rootItem_(new MapItem(NULL)), + rootItem_(new MapItem(nullptr)), imageIcon_(":/simQt/images/Globe.png"), elevationIcon_(":/simQt/images/Image.png"), featureIcon_(":/simQt/images/Building Corporation.png") @@ -1016,7 +1010,7 @@ void MapDataModel::removeAllCallbacks_(osgEarth::Map* map) void MapDataModel::fillModel_(osgEarth::Map *map) { // assume begin/end reset model surrounds this function - if (map == NULL) + if (map == nullptr) return; osgEarth::ImageLayerVector imageLayers; @@ -1135,9 +1129,6 @@ void MapDataModel::addFeatureLayer_(osgEarth::FeatureModelLayer *layer, unsigned featureCallbacks_[layer] = cb.get(); layer->addCallback(cb.get()); emit featureLayerAdded(layer); -#ifdef USE_DEPRECATED_SIMDISSDK_API - emit modelLayerAdded(layer); -#endif } void MapDataModel::addOtherLayer_(osgEarth::VisibleLayer *layer, unsigned int index) @@ -1157,7 +1148,7 @@ void MapDataModel::addOtherLayer_(osgEarth::VisibleLayer *layer, unsigned int in MapDataModel::Item* MapDataModel::itemAt_(const QModelIndex &index) const { if (!index.isValid()) - return NULL; + return nullptr; Item *const ret = static_cast(index.internalPointer()); assert(ret); // internal pointer should always be valid @@ -1194,9 +1185,9 @@ QModelIndex MapDataModel::parent(const QModelIndex &child) const return QModelIndex(); Item *const parentsParent = parentItem->parent(); - if (parentsParent == NULL) + if (parentsParent == nullptr) { - // This means that the parent's item is NULL yet we're not dealing with the Map + // This means that the parent's item is nullptr yet we're not dealing with the Map assert(parentItem == rootItem_); return createIndex(0, 0, rootItem_); } @@ -1297,7 +1288,7 @@ void MapDataModel::refreshText() const Item* imageGroup = imageGroup_(); // Only need to emit data changed for the image group if there are images - if (imageGroup != NULL && imageGroup->rowCount() > 0) + if (imageGroup != nullptr && imageGroup->rowCount() > 0) { const QModelIndex imageItem = index(0, 0, mapItem); // Assertion failure means the tree structure changed and this wasn't updated @@ -1307,7 +1298,7 @@ void MapDataModel::refreshText() const Item* elevationGroup = elevationGroup_(); // Only need to emit data changed for the elevation group if there are elevation layers - if (elevationGroup != NULL && elevationGroup->rowCount() > 0) + if (elevationGroup != nullptr && elevationGroup->rowCount() > 0) { const QModelIndex elevItem = index(1, 0, mapItem); // Assertion failure means the tree structure changed and this wasn't updated @@ -1317,7 +1308,7 @@ void MapDataModel::refreshText() const Item* featureGroup = featureGroup_(); // Only need to emit data changed for the model group if there are model layers - if (featureGroup != NULL && featureGroup->rowCount() > 0) + if (featureGroup != nullptr && featureGroup->rowCount() > 0) { const QModelIndex featureItem = index(2, 0, mapItem); // Assertion failure means the tree structure changed and this wasn't updated @@ -1327,7 +1318,7 @@ void MapDataModel::refreshText() const Item* otherGroup = otherGroup_(); // Only need to emit data changed for the other group if there are other layers - if (otherGroup != NULL && otherGroup->rowCount() > 0) + if (otherGroup != nullptr && otherGroup->rowCount() > 0) { const QModelIndex otherItem = index(3, 0, mapItem); // Assertion failure means the tree structure changed and this wasn't updated @@ -1338,11 +1329,11 @@ void MapDataModel::refreshText() QModelIndex MapDataModel::layerIndex(const osgEarth::Layer* layer) const { - if (layer == NULL) + if (layer == nullptr) return QModelIndex(); // Find the appropriate group item based on the item type - GroupItem* group = NULL; + GroupItem* group = nullptr; QModelIndex parentIndex; if (dynamic_cast(layer)) group = static_cast(imageGroup_()); @@ -1360,14 +1351,14 @@ QModelIndex MapDataModel::layerIndex(const osgEarth::Layer* layer) const // Return by calling createIndex with valid values, if the item exists Item* itemByLayer = group->itemByLayer(layer); - if (itemByLayer == NULL) + if (itemByLayer == nullptr) return QModelIndex(); return createIndex(group->rowOfChild(itemByLayer), 0, itemByLayer); } QVariant MapDataModel::layerMapIndex_(osgEarth::Layer* layer) const { - if (layer == NULL || !map_.valid()) + if (layer == nullptr || !map_.valid()) return QVariant(); osgEarth::LayerVector layers; diff --git a/SDK/simQt/MapDataModel.h b/SDK/simQt/MapDataModel.h index 9c8c013d2..a04fffef2 100644 --- a/SDK/simQt/MapDataModel.h +++ b/SDK/simQt/MapDataModel.h @@ -99,7 +99,7 @@ class SDKQT_EXPORT MapDataModel : public QAbstractItemModel explicit MapDataModel(QObject* parent=0); virtual ~MapDataModel(); - /// Changes the underlying Map pointer (NULL is tolerated) + /// Changes the underlying Map pointer (nullptr is tolerated) void bindTo(osgEarth::Map* map); /// Retrieve the underlying map pointer osgEarth::Map* map() const; @@ -128,15 +128,11 @@ class SDKQT_EXPORT MapDataModel : public QAbstractItemModel CHILD_IMAGE = 0, CHILD_ELEVATION, CHILD_FEATURE, -#ifdef USE_DEPRECATED_SIMDISSDK_API - /// @deprecated Use CHILD_FEATURE instead - CHILD_MODEL = CHILD_FEATURE, -#endif CHILD_OTHER, CHILD_NONE }; - /** data() returns the pointer to the layer, or NULL */ + /** data() returns the pointer to the layer, or nullptr */ static const int LAYER_POINTER_ROLE = Qt::UserRole + 0; /** data() returns the type of node: image, elevation, feature, or none for top level MAP selection */ static const int LAYER_TYPE_ROLE = Qt::UserRole + 1; @@ -167,24 +163,6 @@ public slots: /** Qt signal as described by the signal name */ void featureLayerAdded(osgEarth::FeatureModelLayer* layer); -#ifdef USE_DEPRECATED_SIMDISSDK_API - /** - * Qt signal as described by the signal name - * @deprecated Use featureLayerVisibleChanged() instead - */ - void modelLayerVisibleChanged(osgEarth::FeatureModelLayer* layer); - /** - * Qt signal as described by the signal name - * @deprecated Use featureLayerOpacityChanged() instead - */ - void modelLayerOpacityChanged(osgEarth::FeatureModelLayer* layer); - /** - * Qt signal as described by the signal name - * @deprecated Use featureLayerAdded() instead - */ - void modelLayerAdded(osgEarth::FeatureModelLayer* layer); -#endif - /** Qt signal as described by the signal name */ void otherLayerVisibleChanged(osgEarth::VisibleLayer* layer); /** Qt signal as described by the signal name */ @@ -217,7 +195,7 @@ public slots: /** add a layer other than image, elevation, or feature */ void addOtherLayer_(osgEarth::VisibleLayer* layer, unsigned int index); - /** return the Item for the given index (NULL if it can't be represented) */ + /** return the Item for the given index (nullptr if it can't be represented) */ Item* itemAt_(const QModelIndex &index) const; /** return the Item for the imagery group */ diff --git a/SDK/simQt/MonospaceItemDelegate.cpp b/SDK/simQt/MonospaceItemDelegate.cpp index 4a4e62fc1..21f34c3f0 100644 --- a/SDK/simQt/MonospaceItemDelegate.cpp +++ b/SDK/simQt/MonospaceItemDelegate.cpp @@ -93,7 +93,7 @@ QSize MonospaceItemDelegate::sizeHint(const QStyleOptionViewItem& option, const // Pull out the widget, containing extra info for calculating size const QStyleOptionViewItemV3* v3 = qstyleoption_cast(&option); - const QWidget* widget = v3 ? v3->widget : NULL; + const QWidget* widget = v3 ? v3->widget : nullptr; // Get the appropriate style and ask it to give us a size QStyle* style = widget ? widget->style() : QApplication::style(); return style->sizeFromContents(QStyle::CT_ItemViewItem, &opt, QSize(), widget); diff --git a/SDK/simQt/MonospaceItemDelegate.h b/SDK/simQt/MonospaceItemDelegate.h index 336a4dbd4..96a6e3ee1 100644 --- a/SDK/simQt/MonospaceItemDelegate.h +++ b/SDK/simQt/MonospaceItemDelegate.h @@ -34,7 +34,7 @@ class SDKQT_EXPORT MonospaceItemDelegate : public QStyledItemDelegate { public: /** Allocates a single monospace font to use in drawing */ - MonospaceItemDelegate(QObject* parent = NULL); + MonospaceItemDelegate(QObject* parent = nullptr); /** Deletes the font dynamic memory */ virtual ~MonospaceItemDelegate(); diff --git a/SDK/simQt/MruList.cpp b/SDK/simQt/MruList.cpp index a3ac76541..e273a24af 100644 --- a/SDK/simQt/MruList.cpp +++ b/SDK/simQt/MruList.cpp @@ -133,7 +133,7 @@ void MruList::clear() void MruList::openRecentFile_() { QAction* action = qobject_cast(sender()); - if (action != NULL) + if (action != nullptr) emit(fileSelected(action->data().toString())); } @@ -178,8 +178,8 @@ void MruList::fixActions_() action->setEnabled(false); } - // Get rid of NULLs that might be introduced by deleted menus - separators_.removeAll(NULL); + // Get rid of nullptrs that might be introduced by deleted menus + separators_.removeAll(nullptr); // Hide or show separators based on whether any actions are shown for (auto it = separators_.begin(); it != separators_.end(); ++it) (*it)->setVisible(showSeparators); diff --git a/SDK/simQt/MruList.h b/SDK/simQt/MruList.h index 6386dd043..cf006e253 100644 --- a/SDK/simQt/MruList.h +++ b/SDK/simQt/MruList.h @@ -53,7 +53,7 @@ class SDKQT_EXPORT MruList : public QObject Q_OBJECT; public: /** Constructor */ - explicit MruList(int maxFiles, QObject* parent=NULL); + explicit MruList(int maxFiles, QObject* parent=nullptr); virtual ~MruList(); /** Retrieves the maximum number of entries in this list */ @@ -70,7 +70,7 @@ class SDKQT_EXPORT MruList : public QObject * Inserts the MRU list and optional separators into the menu provided. Separators * added will hide automatically. * @param menu Menu into which to add our MRU - * @param beforeAction Insert MRU before this action; if NULL, MRU is appended to list + * @param beforeAction Insert MRU before this action; if nullptr, MRU is appended to list * @param separatorBefore If true, include a menu separator before the MRU. Note that the * separator is hidden automatically when the MRU is empty. * @param separatorAfter If true, include a menu separator after the MRU. Note that the diff --git a/SDK/simQt/PersistentFileLogger.cpp b/SDK/simQt/PersistentFileLogger.cpp index 0957d37b7..9529a3065 100644 --- a/SDK/simQt/PersistentFileLogger.cpp +++ b/SDK/simQt/PersistentFileLogger.cpp @@ -58,8 +58,8 @@ PersistentFileLogger::PersistentFileLogger(const QString& prefix, QObject* paren : QObject(parent), prefix_(sanitizeFilename_(prefix)), startTime_(QDateTime::currentDateTime().toUTC()), - file_(NULL), - stream_(NULL), + file_(nullptr), + stream_(nullptr), openAttempted_(false) { } @@ -82,7 +82,7 @@ int PersistentFileLogger::addText(const QString& text) bool PersistentFileLogger::isOpen() const { - return stream_ != NULL && file_ != NULL && stream_->status() == QTextStream::Ok; + return stream_ != nullptr && file_ != nullptr && stream_->status() == QTextStream::Ok; } QString PersistentFileLogger::filePath() const @@ -93,10 +93,10 @@ QString PersistentFileLogger::filePath() const int PersistentFileLogger::open() { // make sure stream is not open - if (stream_ != NULL || file_ != NULL || openAttempted_) + if (stream_ != nullptr || file_ != nullptr || openAttempted_) { // Check for an error on the stream before returning - if (stream_ == NULL || stream_->status() != QTextStream::Ok) + if (stream_ == nullptr || stream_->status() != QTextStream::Ok) return 1; // File is open, all is good for writing return 0; // success @@ -119,7 +119,7 @@ int PersistentFileLogger::open() { SIM_DEBUG << "Unable to open: " << filename_.toStdString() << "\n"; delete file_; - file_ = NULL; + file_ = nullptr; return 1; } // Create the stream to write to the file diff --git a/SDK/simQt/PersistentFileLogger.h b/SDK/simQt/PersistentFileLogger.h index ff92adba2..9449c49fb 100644 --- a/SDK/simQt/PersistentFileLogger.h +++ b/SDK/simQt/PersistentFileLogger.h @@ -65,7 +65,7 @@ class SDKQT_EXPORT PersistentFileLogger : public QObject Q_OBJECT; public: /** Constructor */ - PersistentFileLogger(const QString& prefix, QObject* parent=NULL); + PersistentFileLogger(const QString& prefix, QObject* parent=nullptr); virtual ~PersistentFileLogger(); /** Returns true if the file is open */ diff --git a/SDK/simQt/RegExpImpl.cpp b/SDK/simQt/RegExpImpl.cpp index c5402125e..7c4522126 100644 --- a/SDK/simQt/RegExpImpl.cpp +++ b/SDK/simQt/RegExpImpl.cpp @@ -37,8 +37,8 @@ RegExpImpl::RegExpImpl(const std::string& exp, CaseSensitivity caseSense, Patter : exp_(exp), caseSensitivity_(caseSense), patternSyntax_(patternSyntax), - qRegExp_(NULL), - fastRegex_(NULL) + qRegExp_(nullptr), + fastRegex_(nullptr) { initializeQRegExp_(); } @@ -48,8 +48,8 @@ RegExpImpl::RegExpImpl(const RegExpImpl& other) : exp_(other.exp_), caseSensitivity_(other.caseSensitivity_), patternSyntax_(other.patternSyntax_), - qRegExp_(NULL), - fastRegex_(NULL) + qRegExp_(nullptr), + fastRegex_(nullptr) { initializeQRegExp_(); } @@ -140,9 +140,9 @@ void RegExpImpl::setPatternSyntax(RegExpImpl::PatternSyntax patternSyntax) //------------------------------------------------------------ bool RegExpImpl::isValid() const { - if (fastRegex_ != NULL) + if (fastRegex_ != nullptr) return fastRegex_->isValid(); - if (qRegExp_ != NULL) + if (qRegExp_ != nullptr) return qRegExp_->isValid(); return false; } @@ -150,9 +150,9 @@ bool RegExpImpl::isValid() const //------------------------------------------------------------ std::string RegExpImpl::errors() const { - if (fastRegex_ != NULL) + if (fastRegex_ != nullptr) return fastRegex_->errorString().toStdString(); - if (qRegExp_ != NULL) + if (qRegExp_ != nullptr) return qRegExp_->errorString().toStdString(); return ""; } @@ -251,7 +251,7 @@ void RegExpImpl::initializeQRegExp_() if (!fastRegex_->isValid()) { delete fastRegex_; - fastRegex_ = NULL; + fastRegex_ = nullptr; } break; } @@ -314,7 +314,7 @@ simData::RegExpFilterPtr RegExpFilterFactoryImpl::createRegExpFilter(const std:: { SIM_ERROR << "Failed to create regular expression: " << newRegExp->errors() << "\n"; delete newRegExp; - newRegExp = NULL; + newRegExp = nullptr; } return simData::RegExpFilterPtr(newRegExp); } diff --git a/SDK/simQt/SearchLineEdit.cpp b/SDK/simQt/SearchLineEdit.cpp index e91cea487..74b42a5ca 100644 --- a/SDK/simQt/SearchLineEdit.cpp +++ b/SDK/simQt/SearchLineEdit.cpp @@ -52,8 +52,8 @@ class NoDisabledStyle : public QProxyStyle SearchLineEdit::SearchLineEdit(QWidget* parent) : QLineEdit(parent), - searchTimer_(NULL), - iconAction_(NULL), + searchTimer_(nullptr), + iconAction_(nullptr), iconEnabled_(true) { // Configure the timer @@ -89,11 +89,11 @@ SearchLineEdit::SearchLineEdit(QWidget* parent) SearchLineEdit::~SearchLineEdit() { delete searchTimer_; - searchTimer_ = NULL; + searchTimer_ = nullptr; delete iconAction_; - iconAction_ = NULL; + iconAction_ = nullptr; delete proxyStyle_; - proxyStyle_ = NULL; + proxyStyle_ = nullptr; } const QPixmap* SearchLineEdit::searchPixmap() const @@ -101,7 +101,7 @@ const QPixmap* SearchLineEdit::searchPixmap() const QLabel* label = dynamic_cast(iconAction_->defaultWidget()); // The QWidgetAction should only have QLabel assert(label); - return label->pixmap(); + return label ? label->pixmap() : nullptr; } int SearchLineEdit::searchDelayInterval() const @@ -119,7 +119,8 @@ void SearchLineEdit::setSearchPixmap(const QPixmap& pixmap) QLabel* label = dynamic_cast(iconAction_->defaultWidget()); // The QWidgetAction should only have QLabel assert(label); - label->setPixmap(pixmap); + if (label) + label->setPixmap(pixmap); } void SearchLineEdit::setSearchDelayInterval(int msec) diff --git a/SDK/simQt/SearchLineEdit.h b/SDK/simQt/SearchLineEdit.h index 1570b76e5..c8c9e004f 100644 --- a/SDK/simQt/SearchLineEdit.h +++ b/SDK/simQt/SearchLineEdit.h @@ -47,7 +47,7 @@ class SDKQT_EXPORT SearchLineEdit : public QLineEdit { Q_OBJECT; public: - explicit SearchLineEdit(QWidget* parent = NULL); + explicit SearchLineEdit(QWidget* parent = nullptr); virtual ~SearchLineEdit(); /** Image for search. @see QLabel::pixmap() */ diff --git a/SDK/simQt/SegmentedSpinBox.cpp b/SDK/simQt/SegmentedSpinBox.cpp index 9618de3ff..81c043444 100644 --- a/SDK/simQt/SegmentedSpinBox.cpp +++ b/SDK/simQt/SegmentedSpinBox.cpp @@ -85,10 +85,10 @@ class SegmentedEventFilter : public QObject SegmentedSpinBox::SegmentedSpinBox(QWidget* parent) : QSpinBox(parent), - completeLine_(NULL), + completeLine_(nullptr), lastEditedTime_(1970, 0), colorCode_(true), - segmentedEventFilter_(NULL), + segmentedEventFilter_(nullptr), timer_(new QTimer(this)), applyInterval_(500) { @@ -114,7 +114,7 @@ class SegmentedEventFilter : public QObject simCore::TimeStamp SegmentedSpinBox::timeStamp() const { - assert(completeLine_ != NULL); + assert(completeLine_ != nullptr); // If the text string does not change then return the given time to prevent a truncated time if (timeString_ == completeLine_->text()) return timeStamp_; @@ -143,7 +143,7 @@ class SegmentedEventFilter : public QObject void SegmentedSpinBox::setTimeStamp(const simCore::TimeStamp& value) { - assert(completeLine_ != NULL); + assert(completeLine_ != nullptr); completeLine_->setTimeStamp(value); lineEdit()->setText(completeLine_->text()); // The text may truncate the value, so keep a copy so that the exact value can be returned if the text does not change @@ -154,7 +154,7 @@ class SegmentedEventFilter : public QObject void SegmentedSpinBox::setTimeRange(int scenarioReferenceYear, const simCore::TimeStamp& start, const simCore::TimeStamp& end) { - assert(completeLine_ != NULL); + assert(completeLine_ != nullptr); int originalYear; simCore::TimeStamp originalStart; simCore::TimeStamp originalEnd; @@ -201,7 +201,7 @@ class SegmentedEventFilter : public QObject delete completeLine_; completeLine_ = line; - if (completeLine_ == NULL) + if (completeLine_ == nullptr) return; // install a new event filter to capture mouse clicks for selecting the appropriate segment in the spin box @@ -230,7 +230,7 @@ class SegmentedEventFilter : public QObject int location = lineEdit()->cursorPosition(); SegmentedText* part = completeLine_->locatePart(static_cast(location)); SegmentedText* previousTabStop = completeLine_->previousTabStop(part); - if (previousTabStop != NULL) + if (previousTabStop != nullptr) { // Did not walk off the front to process the key event int pos = static_cast(completeLine_->getFirstCharacterLocation(previousTabStop)); @@ -244,7 +244,7 @@ class SegmentedEventFilter : public QObject int location = lineEdit()->cursorPosition(); SegmentedText* part = completeLine_->locatePart(static_cast(location)); SegmentedText* nextPart = completeLine_->nextTabStop(part); - if (nextPart != NULL) + if (nextPart != nullptr) { // Did not work off the end to process the key event int pos = static_cast(completeLine_->getFirstCharacterLocation(nextPart)); @@ -345,7 +345,7 @@ class SegmentedEventFilter : public QObject } // Make the change - if (part != NULL) + if (part != nullptr) { part->stepBy(steps); } @@ -356,7 +356,7 @@ class SegmentedEventFilter : public QObject validate(text, pos); QSpinBox::stepBy(steps); - if (part != NULL) + if (part != nullptr) { // select the new segment text int startLocation = static_cast(completeLine_->getFirstCharacterLocation(part)); diff --git a/SDK/simQt/SegmentedSpinBox.h b/SDK/simQt/SegmentedSpinBox.h index 03d095bca..53c28a19e 100644 --- a/SDK/simQt/SegmentedSpinBox.h +++ b/SDK/simQt/SegmentedSpinBox.h @@ -43,7 +43,7 @@ class SDKQT_EXPORT SegmentedSpinBox : public QSpinBox public: /// constructor - SegmentedSpinBox(QWidget* parent=NULL); + SegmentedSpinBox(QWidget* parent=nullptr); virtual ~SegmentedSpinBox(); /// Get Time value diff --git a/SDK/simQt/SegmentedTexts.cpp b/SDK/simQt/SegmentedTexts.cpp index 6d541bacc..5974b2eff 100644 --- a/SDK/simQt/SegmentedTexts.cpp +++ b/SDK/simQt/SegmentedTexts.cpp @@ -127,12 +127,12 @@ static const unsigned int MAX_PRECISION = 6; } // Walked off the end which is OK - return NULL; + return nullptr; } SegmentedText* SegmentedTexts::previousTabStop(const SegmentedText* inputPart) const { - SegmentedText* lastStop = NULL; + SegmentedText* lastStop = nullptr; for (auto it = segments_.begin(); it != segments_.end(); ++it) { auto part = *it; @@ -145,7 +145,7 @@ static const unsigned int MAX_PRECISION = 6; // Did not find the inputPart, so something is wrong assert(false); - return NULL; + return nullptr; } QString SegmentedTexts::text() const @@ -278,7 +278,6 @@ static const unsigned int MAX_PRECISION = 6; return new NumberText(this, 0, maxValue, precision, true, 1.0/scale, true); } -#ifdef USE_DEPRECATED_SIMDISSDK_API NumberText* SegmentedTexts::updateFactionOfSeconds_(int precision) { if (precision < 1) @@ -292,7 +291,6 @@ static const unsigned int MAX_PRECISION = 6; addPart(fraction); return fraction; } -#endif /* USE_DEPRECATED_SIMDISSDK_API */ int SegmentedTexts::fractionToField_(const simCore::Seconds& secondsRounded) const { @@ -415,7 +413,7 @@ static const unsigned int MAX_PRECISION = 6; void NumberText::stepBy(int amount) { // The timeScaleFactor is 1 for seconds, 60 for minutes, 3600 for hours, 0.1 for tenths, etc. - double modfIntPart; + double modfIntPart = 0.0; const double timeScaleFactorFractionPart = std::modf(timeScaleFactor_, &modfIntPart); const int timeScaleFactorIntPart = static_cast(modfIntPart); const int timeScaleNanoSeconds = timeScaleFactorFractionPart * 1e09; @@ -453,7 +451,7 @@ static const unsigned int MAX_PRECISION = 6; else state = QValidator::Invalid; - return count; + return static_cast(count); } while ((count < text.size()) && (text[count] >= '0') && (text[count] <= '9') && ((static_cast(count)-startLocation) < maxDigits_)) @@ -471,7 +469,7 @@ static const unsigned int MAX_PRECISION = 6; else state = QValidator::Invalid; - return count; + return static_cast(count); } QString NumberText::toString_(int value) const @@ -599,10 +597,10 @@ static const unsigned int MAX_PRECISION = 6; if (precision_ != 0) fraction_ = createFactionOfSeconds_(precision_); else - fraction_ = NULL; + fraction_ = nullptr; addPart(seconds_); - if (fraction_ != NULL) + if (fraction_ != nullptr) { addPart(new SeparatorText(".", true)); addPart(fraction_); @@ -613,7 +611,7 @@ static const unsigned int MAX_PRECISION = 6; { const int seconds = seconds_->value(); // Need to scale based on the number of digits after the decimal point. - const int fraction = (fraction_ == NULL) ? 0 : fractionFromField_(fraction_->value(), fraction_->text().size()); + const int fraction = (fraction_ == nullptr) ? 0 : fractionFromField_(fraction_->value(), fraction_->text().size()); return simCore::TimeStamp(scenarioReferenceYear_, simCore::Seconds(seconds, fraction)); } @@ -628,7 +626,7 @@ static const unsigned int MAX_PRECISION = 6; // SecondsTexts fields are always relative to scenarioReferenceYear_: they do not reset to 0 if year rolls over. const simCore::Seconds& secondsSinceScenarioRefYear = stamp.secondsSinceRefYear(scenarioReferenceYear_); seconds_->setValue(static_cast(secondsSinceScenarioRefYear.getSeconds())); - if (fraction_ != NULL) + if (fraction_ != nullptr) fraction_->setValue(fractionToField_(secondsSinceScenarioRefYear)); } @@ -680,12 +678,12 @@ static const unsigned int MAX_PRECISION = 6; if (precision_ != 0) fraction_ = createFactionOfSeconds_(precision_); else - fraction_ = NULL; + fraction_ = nullptr; addPart(minutes_); addPart(new SeparatorText(":", false)); addPart(seconds_); - if (fraction_ != NULL) + if (fraction_ != nullptr) { addPart(new SeparatorText(".", true)); addPart(fraction_); @@ -696,7 +694,7 @@ static const unsigned int MAX_PRECISION = 6; { const int seconds = (minutes_->value() * 60) + seconds_->value(); // Need to scale based on the number of digits after the decimal point. - const int fraction = (fraction_ == NULL) ? 0 : fractionFromField_(fraction_->value(), fraction_->text().size()); + const int fraction = (fraction_ == nullptr) ? 0 : fractionFromField_(fraction_->value(), fraction_->text().size()); return simCore::TimeStamp(scenarioReferenceYear_, simCore::Seconds(seconds, fraction)); } @@ -714,7 +712,7 @@ static const unsigned int MAX_PRECISION = 6; const int minutes = static_cast(secondsSinceRefYear / simCore::SECPERMIN); minutes_->setValue(minutes); seconds_->setValue(static_cast(secondsSinceRefYear - (minutes*simCore::SECPERMIN))); - if (fraction_ != NULL) + if (fraction_ != nullptr) fraction_->setValue(fractionToField_(secondsSinceScenarioRefYear)); } @@ -768,14 +766,14 @@ static const unsigned int MAX_PRECISION = 6; if (precision_ != 0) fraction_ = createFactionOfSeconds_(precision_); else - fraction_ = NULL; + fraction_ = nullptr; addPart(hours_); addPart(new SeparatorText(":", false)); addPart(minutes_); addPart(new SeparatorText(":", false)); addPart(seconds_); - if (fraction_ != NULL) + if (fraction_ != nullptr) { addPart(new SeparatorText(".", true)); addPart(fraction_); @@ -786,7 +784,7 @@ static const unsigned int MAX_PRECISION = 6; { const int64_t seconds = (((hours_->value() * 60) + minutes_->value()) * 60) + seconds_->value(); // Need to scale based on the number of digits after the decimal point. - const int fraction = (fraction_ == NULL) ? 0 : fractionFromField_(fraction_->value(), fraction_->text().size()); + const int fraction = (fraction_ == nullptr) ? 0 : fractionFromField_(fraction_->value(), fraction_->text().size()); return simCore::TimeStamp(scenarioReferenceYear_, simCore::Seconds(seconds, fraction)); } @@ -809,7 +807,7 @@ static const unsigned int MAX_PRECISION = 6; hours_->setValue(hours); minutes_->setValue(minutes); seconds_->setValue(static_cast(secondsSinceRefYear)); - if (fraction_ != NULL) + if (fraction_ != nullptr) fraction_->setValue(fractionToField_(secondsSinceScenarioRefYear)); } @@ -868,7 +866,7 @@ static const unsigned int MAX_PRECISION = 6; if (precision_ != 0) fraction_ = createFactionOfSeconds_(precision_); else - fraction_ = NULL; + fraction_ = nullptr; addPart(days_); addPart(new SeparatorText(" ", false)); @@ -879,7 +877,7 @@ static const unsigned int MAX_PRECISION = 6; addPart(minutes_); addPart(new SeparatorText(":", false)); addPart(seconds_); - if (fraction_ != NULL) + if (fraction_ != nullptr) { addPart(new SeparatorText(".", true)); addPart(fraction_); @@ -895,7 +893,7 @@ static const unsigned int MAX_PRECISION = 6; seconds *= 60; seconds += seconds_->value(); // Need to scale based on the number of digits after the decimal point. - const int fraction = (fraction_ == NULL) ? 0 : fractionFromField_(fraction_->value(), fraction_->text().size()); + const int fraction = (fraction_ == nullptr) ? 0 : fractionFromField_(fraction_->value(), fraction_->text().size()); simCore::TimeStamp stamp(years_->value(), simCore::Seconds(seconds, fraction)); // Remove the timezone offset that was introduced by setTimestamp() @@ -939,7 +937,7 @@ static const unsigned int MAX_PRECISION = 6; hours_->setValue(static_cast(hour)); minutes_->setValue(static_cast(min)); seconds_->setValue(static_cast(sec)); - if (fraction_ != NULL) + if (fraction_ != nullptr) fraction_->setValue(fractionToField_(stamp.secondsSinceRefYear())); } @@ -1013,7 +1011,7 @@ static const unsigned int MAX_PRECISION = 6; if (precision_ != 0) fraction_ = createFactionOfSeconds_(precision_); else - fraction_ = NULL; + fraction_ = nullptr; addPart(month_); addPart(new SeparatorText(" ", false)); @@ -1026,7 +1024,7 @@ static const unsigned int MAX_PRECISION = 6; addPart(minutes_); addPart(new SeparatorText(":", false)); addPart(seconds_); - if (fraction_ != NULL) + if (fraction_ != nullptr) { addPart(new SeparatorText(".", true)); addPart(fraction_); @@ -1038,7 +1036,7 @@ static const unsigned int MAX_PRECISION = 6; const int yearDay = simCore::getYearDay(month_->intValue(), days_->value(), years_->value()); const int64_t secondsIntoYear = yearDay*simCore::SECPERDAY + hours_->value()*simCore::SECPERHOUR + minutes_->value()*simCore::SECPERMIN + seconds_->value(); - const int fraction = (fraction_ == NULL) ? 0 : fractionFromField_(fraction_->value(), fraction_->text().size()); + const int fraction = (fraction_ == nullptr) ? 0 : fractionFromField_(fraction_->value(), fraction_->text().size()); simCore::TimeStamp stamp(years_->value(), simCore::Seconds(secondsIntoYear, fraction)); if (zone_ == simCore::TIMEZONE_LOCAL) @@ -1089,7 +1087,7 @@ static const unsigned int MAX_PRECISION = 6; days_->setValue(dayInMonth); years_->setValue(stamp.referenceYear()); month_->setIntValue(month); - if (fraction_ != NULL) + if (fraction_ != nullptr) fraction_->setValue(fractionToField_(stamp.secondsSinceRefYear())); } catch (const simCore::TimeException &) diff --git a/SDK/simQt/SegmentedTexts.h b/SDK/simQt/SegmentedTexts.h index 8bb31b63f..264e79382 100644 --- a/SDK/simQt/SegmentedTexts.h +++ b/SDK/simQt/SegmentedTexts.h @@ -229,12 +229,12 @@ class SDKQT_EXPORT SegmentedTexts : public QObject size_t getFirstCharacterLocation(const SegmentedText* inputPart) const; /** Calculates the next tab stop after the given Line Segment * @param[in] inputPart Given line segment - * @return The next tab stop after inputPart, can return NULL if walked off the end + * @return The next tab stop after inputPart, can return nullptr if walked off the end */ SegmentedText* nextTabStop(const SegmentedText* inputPart) const; /** Calculates the previous tab stop after the given Line Segment * @param[in] inputPart Given line segment - * @return The previous tab stop after inputPart, can return NULL if walked off the front + * @return The previous tab stop after inputPart, can return nullptr if walked off the front */ SegmentedText* previousTabStop(const SegmentedText* inputPart) const; @@ -259,10 +259,8 @@ class SDKQT_EXPORT SegmentedTexts : public QObject /// Creates the fraction part accounting for the precision. Cannot be const. NumberText* createFactionOfSeconds_(int precision); -#ifdef USE_DEPRECATED_SIMDISSDK_API /// Replaces the fraction part with a new fraction part of the given precision. SDK_DEPRECATE(NumberText* updateFactionOfSeconds_(int precision), "Method will be removed in future SDK release."); -#endif /* USE_DEPRECATED_SIMDISSDK_API */ /// convert the fractional part of Seconds (# of ns) to a field representation int fractionToField_(const simCore::Seconds& secondsRounded) const; diff --git a/SDK/simQt/SettingsGroup.cpp b/SDK/simQt/SettingsGroup.cpp index 8e2765f65..86e0b7a73 100644 --- a/SDK/simQt/SettingsGroup.cpp +++ b/SDK/simQt/SettingsGroup.cpp @@ -183,7 +183,7 @@ void SettingsGroup::setValue(const QString& name, const QVariant& value, Observe settings_->setValue(name, value, skipThisObserver); else { - if (skipThisObserver == NULL) + if (skipThisObserver == nullptr) settings_->setValue(getFullPath_(name), value); else { @@ -277,7 +277,7 @@ int SettingsGroup::addObserver(const QString& name, ObserverPtr observer) { if (settings_) { - if (observer != NULL) + if (observer != nullptr) { if (!path_.isEmpty()) { @@ -298,7 +298,7 @@ int SettingsGroup::removeObserver(const QString& name, ObserverPtr observer) { if (settings_) { - if (observer != NULL) + if (observer != nullptr) { if (!path_.isEmpty()) { diff --git a/SDK/simQt/SettingsItemDelegate.cpp b/SDK/simQt/SettingsItemDelegate.cpp index 00408fe50..f8e3b9fbd 100644 --- a/SDK/simQt/SettingsItemDelegate.cpp +++ b/SDK/simQt/SettingsItemDelegate.cpp @@ -722,7 +722,7 @@ const QStyledItemDelegate* SettingsItemDelegate::findDelegate_(const QModelIndex break; // All other cases handled through default painting/editing } } - return NULL; + return nullptr; } } diff --git a/SDK/simQt/SettingsItemDelegate.h b/SDK/simQt/SettingsItemDelegate.h index d2f3ff277..5de8e38b1 100644 --- a/SDK/simQt/SettingsItemDelegate.h +++ b/SDK/simQt/SettingsItemDelegate.h @@ -36,7 +36,7 @@ class SDKQT_EXPORT SettingsColorItemDelegate : public QStyledItemDelegate Q_OBJECT; public: /** Constructor */ - SettingsColorItemDelegate(QObject* parent = NULL); + SettingsColorItemDelegate(QObject* parent = nullptr); /** Paints a box with the color against a black and a white background. */ virtual void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const; @@ -70,7 +70,7 @@ class SDKQT_EXPORT SettingsDirectorySelectorDelegate : public QStyledItemDelegat Q_OBJECT; public: /** Constructor */ - SettingsDirectorySelectorDelegate(QObject* parent = NULL); + SettingsDirectorySelectorDelegate(QObject* parent = nullptr); virtual ~SettingsDirectorySelectorDelegate(); /** Creates a color editor window */ @@ -92,7 +92,7 @@ class SDKQT_EXPORT SettingsIntegerSpinBoxDelegate : public QStyledItemDelegate { public: /** Constructor */ - SettingsIntegerSpinBoxDelegate(QObject* parent = NULL); + SettingsIntegerSpinBoxDelegate(QObject* parent = nullptr); /** Creates an integer spin box editor window */ virtual QWidget* createEditor(QWidget* parent, const QStyleOptionViewItem& option, const QModelIndex& index) const; @@ -107,7 +107,7 @@ class SDKQT_EXPORT SettingsDoubleSpinBoxDelegate : public QStyledItemDelegate { public: /** Constructor */ - SettingsDoubleSpinBoxDelegate(QObject* parent = NULL); + SettingsDoubleSpinBoxDelegate(QObject* parent = nullptr); /** Creates a double spin box editor window */ virtual QWidget* createEditor(QWidget* parent, const QStyleOptionViewItem& option, const QModelIndex& index) const; @@ -123,7 +123,7 @@ class SDKQT_EXPORT SettingsFileSelectorDelegate : public QStyledItemDelegate Q_OBJECT; public: /** Constructor */ - SettingsFileSelectorDelegate(QObject* parent = NULL); + SettingsFileSelectorDelegate(QObject* parent = nullptr); virtual ~SettingsFileSelectorDelegate(); /** Creates a file selector editor window */ @@ -146,7 +146,7 @@ class SDKQT_EXPORT SettingsEnumerationDelegate : public QStyledItemDelegate Q_OBJECT; public: /** Constructor */ - SettingsEnumerationDelegate(QObject* parent = NULL); + SettingsEnumerationDelegate(QObject* parent = nullptr); /** Creates a file selector editor window */ virtual QWidget* createEditor(QWidget* parent, const QStyleOptionViewItem& option, const QModelIndex& index) const; @@ -166,7 +166,7 @@ class SDKQT_EXPORT SettingsFontSelectorDelegate : public QStyledItemDelegate Q_OBJECT; public: /** Constructor */ - SettingsFontSelectorDelegate(QObject* parent = NULL); + SettingsFontSelectorDelegate(QObject* parent = nullptr); virtual ~SettingsFontSelectorDelegate(); /** Creates a file selector editor window */ @@ -188,7 +188,7 @@ class SDKQT_EXPORT SettingsHexEditDelegate : public QStyledItemDelegate { public: /** Constructor */ - SettingsHexEditDelegate(QObject* parent = NULL); + SettingsHexEditDelegate(QObject* parent = nullptr); /** Creates an hex formatted line edit editor window */ virtual QWidget* createEditor(QWidget* parent, const QStyleOptionViewItem& option, const QModelIndex& index) const; @@ -207,7 +207,7 @@ class SDKQT_EXPORT SettingsHexEditDelegate : public QStyledItemDelegate class SettingsHexEditValidator : public QValidator { public: - SettingsHexEditValidator(unsigned int min, unsigned int max, QObject* parent=NULL); + SettingsHexEditValidator(unsigned int min, unsigned int max, QObject* parent=nullptr); virtual ~SettingsHexEditValidator(); virtual void fixup(QString& input) const; virtual QValidator::State validate(QString& input, int& pos) const; @@ -221,7 +221,7 @@ class SDKQT_EXPORT SettingsItemDelegate : public QStyledItemDelegate { public: /** Constructor */ - SettingsItemDelegate(QObject* parent = NULL); + SettingsItemDelegate(QObject* parent = nullptr); virtual ~SettingsItemDelegate(); /** Overrides QStyledItemDelegate::paint() to delegate to proper data type delegate. */ @@ -239,7 +239,7 @@ class SDKQT_EXPORT SettingsItemDelegate : public QStyledItemDelegate virtual bool eventFilter(QObject *object, QEvent *event); private: - /** Returns the appropriate delegate, or NULL if none */ + /** Returns the appropriate delegate, or nullptr if none */ const QStyledItemDelegate* findDelegate_(const QModelIndex& index) const; /** Delegate for COLOR values */ diff --git a/SDK/simQt/SettingsModel.cpp b/SDK/simQt/SettingsModel.cpp index 142d9022c..bc8a26a0b 100644 --- a/SDK/simQt/SettingsModel.cpp +++ b/SDK/simQt/SettingsModel.cpp @@ -101,7 +101,7 @@ class SettingsModel::TreeNode static const int COLUMN_VALUE = 1; /// Root item constructor - TreeNode(QIcon& icon, const QList &data, TreeNode *parent=NULL) + TreeNode(QIcon& icon, const QList &data, TreeNode *parent=nullptr) : icon_(icon), itemData_(data), parentItem_(parent), @@ -179,7 +179,7 @@ class SettingsModel::TreeNode if (childAtK->path() == name) return childAtK; } - return NULL; + return nullptr; } /// Number of children for this item @@ -302,14 +302,14 @@ class SettingsModel::TreeNode UserEditCommand* setValue(const QVariant& oldValue, const QVariant& toValue) { if (oldValue == toValue) - return NULL; // noop + return nullptr; // noop return new UserEditCommand(fullPath(), oldValue, toValue); } /// Indicates that this is the root / top level item bool isRootItem() const { - return parentItem_ == NULL; + return parentItem_ == nullptr; } const Settings::MetaData& metaData() const @@ -364,7 +364,7 @@ class SettingsModel::TreeNode for (auto it = observers_.begin(); it != observers_.end(); ++it) { const ObserverPtr& ptr = *it; - if (ptr != skipObserver && ptr != NULL) + if (ptr != skipObserver && ptr != nullptr) { ptr->onSettingChange(name, value); } @@ -373,8 +373,8 @@ class SettingsModel::TreeNode void addObserver(ObserverPtr observer) { - // Don't add NULL pointers - if (observer == NULL) + // Don't add nullptrs + if (observer == nullptr) return; // Check for existence of the observer first @@ -496,7 +496,7 @@ class SettingsModel::MementoImpl : public Settings::Memento /** Recursively save the value and iterate through children */ void saveNode_(TreeNode* node) { - if (node == NULL) + if (node == nullptr) return; ValueAndMetaData value; value.value = node->data(Qt::DisplayRole, TreeNode::COLUMN_VALUE); @@ -526,7 +526,7 @@ class SettingsModel::MementoImpl : public Settings::Memento SettingsModel::SettingsModel(QObject* parent, QSettings& settings) : QAbstractItemModel(parent), - rootNode_(NULL), + rootNode_(nullptr), readOnly_(false) { init_(); @@ -542,12 +542,12 @@ SettingsModel::SettingsModel(QObject* parent, QSettings& settings) SettingsModel::SettingsModel(QObject* parent) : QAbstractItemModel(parent), - rootNode_(NULL), + rootNode_(nullptr), format_(QSettings::InvalidFormat), readOnly_(true) { init_(); - reloadModel_(NULL); + reloadModel_(nullptr); } SettingsModel::~SettingsModel() @@ -555,7 +555,7 @@ SettingsModel::~SettingsModel() save(); delete rootNode_; - rootNode_ = NULL; + rootNode_ = nullptr; qDeleteAll(undoStack_); undoStack_.clear(); qDeleteAll(redoStack_); @@ -568,7 +568,7 @@ void SettingsModel::init_() qRegisterMetaTypeStreamOperators("simQt::Settings::MetaData"); // Note that QFileIconProvider requires QApplication and will crash with QCoreApplication - bool hasGuiApp = (qobject_cast(QCoreApplication::instance()) != NULL); + bool hasGuiApp = (qobject_cast(QCoreApplication::instance()) != nullptr); if (hasGuiApp) { QFileIconProvider provider; @@ -620,7 +620,7 @@ QModelIndex SettingsModel::addKeyToTree_(const QString& key) } TreeNode* fromNode = rootNode_; // Assertion failure means this was called prior to finish of construction - assert(fromNode != NULL); + assert(fromNode != nullptr); QStringList directories = key.split('/'); // Assertion failure means that key.isEmpty(), indicates something deeper wrong @@ -640,7 +640,7 @@ QModelIndex SettingsModel::addKeyToTree_(const QString& key) TreeNode* child = fromNode->findChild(directory); // Create the child if it's not found - if (child == NULL) + if (child == nullptr) { child = new TreeNode(folderIcon_, directory, fromNode, forceToPrivate); @@ -658,7 +658,7 @@ QModelIndex SettingsModel::addKeyToTree_(const QString& key) // Assertion failure means above for loop has logic failure and ended with a fromNode // that isn't really correct - assert(fromNode != NULL); + assert(fromNode != nullptr); int newRow = fromNode->childCount(); TreeNode* child = new TreeNode(noIcon_, endKeyName, QVariant(), fromNode, forceToPrivate); @@ -824,7 +824,7 @@ bool SettingsModel::setData(const QModelIndex& index, const QVariant& value, int editCommand = item->setValue(oldValue, (value == Qt::Checked)); else editCommand = item->setValue(oldValue, value); - if (editCommand == NULL) + if (editCommand == nullptr) return false; // error // Put it into the redo stack, then redo it @@ -836,7 +836,7 @@ bool SettingsModel::setData(const QModelIndex& index, const QVariant& value, int SettingsModel::TreeNode* SettingsModel::treeNode_(const QModelIndex& index) const { if (!index.isValid()) - return NULL; + return nullptr; // TreeNode is stored in the internalPointer() return static_cast(index.internalPointer()); } @@ -922,7 +922,7 @@ QModelIndex SettingsModel::findKey_(const QString& relativeKey, const QModelInde QModelIndex idx = index(row, 0, fromParent); TreeNode* treeNode = treeNode_(idx); // If the path() portion matches our portion, continue recursing - if (treeNode != NULL && treeNode->path() == dir) + if (treeNode != nullptr && treeNode->path() == dir) return findKey_(underDir, idx); } // No match found @@ -1021,7 +1021,7 @@ int SettingsModel::saveSettingsFileAs(const QString& path, bool onlyDeltas) void SettingsModel::storeNodes_(QSettings& settings, TreeNode* node, bool force) const { - if (node == NULL) + if (node == nullptr) return; QVariant value = node->data(Qt::DisplayRole, TreeNode::COLUMN_VALUE); @@ -1042,7 +1042,7 @@ void SettingsModel::storeNodes_(QSettings& settings, TreeNode* node, bool force) void SettingsModel::storeNodesDeltas_(QSettings& settings, TreeNode* node) const { - if (node == NULL) + if (node == nullptr) return; QVariant value = node->data(Qt::DisplayRole, TreeNode::COLUMN_VALUE); @@ -1081,7 +1081,7 @@ void SettingsModel::resetDefaults() void SettingsModel::resetDefaults(const QString& name) { TreeNode* rootNode = getNode_(name); - if (rootNode != NULL) + if (rootNode != nullptr) resetDefaults_(rootNode); else { @@ -1092,7 +1092,7 @@ void SettingsModel::resetDefaults(const QString& name) void SettingsModel::resetDefaults_(TreeNode* node) { - if (node == NULL) + if (node == nullptr) return; int size = node->childCount(); @@ -1119,7 +1119,7 @@ SettingsModel::TreeNode* SettingsModel::getNode_(const QString& name) const { QModelIndex idx = findKey_(name, QModelIndex()); if (!idx.isValid()) - return NULL; + return nullptr; return static_cast(idx.internalPointer()); } @@ -1134,7 +1134,7 @@ void SettingsModel::setValue(const QString& name, const QVariant& value, const M bool fire = true; TreeNode* node = getNode_(name); - if (node == NULL) + if (node == nullptr) { QModelIndex idx = addKeyToTree_(name); node = static_cast(idx.internalPointer()); @@ -1168,7 +1168,7 @@ void SettingsModel::setValue(const QString& name, const QVariant& value, const M void SettingsModel::setValue(const QString& name, const QVariant& value, ObserverPtr skipThisObserver) { TreeNode* node = getNode_(name); - if (node != NULL) + if (node != nullptr) { if (node->data(Qt::DisplayRole, TreeNode::COLUMN_VALUE) != value) { @@ -1185,7 +1185,7 @@ void SettingsModel::setValue(const QString& name, const QVariant& value, Observe QVariant SettingsModel::value(const QString& name) const { TreeNode* node = getNode_(name); - if (node != NULL) + if (node != nullptr) return node->data(Qt::DisplayRole, TreeNode::COLUMN_VALUE); return QVariant(); @@ -1194,11 +1194,21 @@ QVariant SettingsModel::value(const QString& name) const QVariant SettingsModel::value(const QString& name, const MetaData& metaData, ObserverPtr observer) { TreeNode* node = getNode_(name); - if (node != NULL) + if (node != nullptr) { node->addObserver(observer); if (node->setMetaData(metaData) == 0) + { + // Set to the default value in metadata + const auto& defaultValue = metaData.defaultValue(); + if (defaultValue.isValid() && !node->data(Qt::DisplayRole, TreeNode::COLUMN_VALUE).isValid()) + { + node->setDataValue(defaultValue); + fireObservers_(observers_, name, defaultValue, observer); + node->fireSettingChange(); + } refreshKey_(name); + } return node->data(Qt::DisplayRole, TreeNode::COLUMN_VALUE); } @@ -1215,18 +1225,22 @@ QVariant SettingsModel::value(const QString& name, const MetaData& metaData, Obs QVariant SettingsModel::value(const QString& name, ObserverPtr observer) { TreeNode* node = getNode_(name); - if (node != NULL) + if (node != nullptr) { addObserver(name, observer); return node->data(Qt::DisplayRole, TreeNode::COLUMN_VALUE); } - return value(name, MetaData(), observer); + QModelIndex idx = addKeyToTree_(name); + node = static_cast(idx.internalPointer()); + node->addObserver(observer); + refreshKey_(name); + return QVariant(); } bool SettingsModel::contains(const QString& name) const { - return getNode_(name) != NULL; + return getNode_(name) != nullptr; } QStringList SettingsModel::allNames() const @@ -1238,7 +1252,7 @@ QStringList SettingsModel::allNames() const void SettingsModel::allNames_(TreeNode* node, QStringList& all) const { - if (node == NULL) + if (node == nullptr) return; int size = node->childCount(); @@ -1259,7 +1273,7 @@ void SettingsModel::allNames_(TreeNode* node, QStringList& all) const int SettingsModel::setMetaData(const QString& name, const SettingsModel::MetaData& metaData) { TreeNode* node = getNode_(name); - if (node == NULL) + if (node == nullptr) return 1; // Did not find it so error out node->setMetaData(metaData); @@ -1269,7 +1283,7 @@ int SettingsModel::setMetaData(const QString& name, const SettingsModel::MetaDat int SettingsModel::metaData(const QString& name, MetaData& metaData) const { TreeNode* node = getNode_(name); - if (node == NULL) + if (node == nullptr) return 1; // Did not find it so error out // Does it begin with our special _MetaData tag? If so, return PRIVATE metadata @@ -1286,13 +1300,13 @@ int SettingsModel::metaData(const QString& name, MetaData& metaData) const int SettingsModel::addObserver(const QString& name, ObserverPtr observer) { TreeNode* node = getNode_(name); - if (node == NULL) + if (node == nullptr) { // did not find setting, so queue up observer pendingObservers_.insert(std::make_pair(name, observer)); return 0; } - if (observer == NULL) + if (observer == nullptr) return 0; node->addObserver(observer); @@ -1307,7 +1321,7 @@ int SettingsModel::removeObserver(const QString& name, ObserverPtr observer) // first remove any pending observers for this setting const auto range = pendingObservers_.equal_range(name); if (range.first != range.second) - assert(node == NULL); // likely pending observer did not get removed when setting node was created + assert(node == nullptr); // likely pending observer did not get removed when setting node was created bool foundPending = false; for (PendingMap::iterator iter = range.first; iter != range.second; ++iter) { @@ -1320,11 +1334,11 @@ int SettingsModel::removeObserver(const QString& name, ObserverPtr observer) } } - // if node is NULL, return failure if observer was not in pending list - if (node == NULL) + // if node is nullptr, return failure if observer was not in pending list + if (node == nullptr) return foundPending ? 0 : 1; - if (observer == NULL) + if (observer == nullptr) return 0; return node->removeObserver(observer); @@ -1332,8 +1346,8 @@ int SettingsModel::removeObserver(const QString& name, ObserverPtr observer) void SettingsModel::addObserver(ObserverPtr observer) { - // Don't add NULL pointers - if (observer == NULL) + // Don't add nullptrs + if (observer == nullptr) return; // Check for existence of the observer first @@ -1391,7 +1405,7 @@ void SettingsModel::initMetaData_(QSettings& settings) { TreeNode* node = getNode_(key); // set the meta data, but do not override - if (node != NULL) + if (node != nullptr) node->setMetaData(qvMetaData.value(), false); } } @@ -1408,7 +1422,7 @@ void SettingsModel::storeMetaData_(QSettings& settings) void SettingsModel::storeMetaData_(QSettings& settings, TreeNode* node) { - if (node == NULL) + if (node == nullptr) return; int size = node->childCount(); diff --git a/SDK/simQt/SettingsModel.h b/SDK/simQt/SettingsModel.h index 145504c2b..01bfa0ee5 100644 --- a/SDK/simQt/SettingsModel.h +++ b/SDK/simQt/SettingsModel.h @@ -60,7 +60,7 @@ class SDKQT_EXPORT SettingsModel : public QAbstractItemModel, public Settings /// Instantiates a new settings model from the provided parent SettingsModel(QObject* parent, QSettings& settings); /// Instantiates new settings model with no dedicated filename; save() is a noop and fileName() is empty. - explicit SettingsModel(QObject* parent = NULL); + explicit SettingsModel(QObject* parent = nullptr); virtual ~SettingsModel(); // from QAbstractItemModel @@ -176,7 +176,7 @@ public slots: /// Implementation of Settings::Memento class MementoImpl; - /// Returns the node for the given string; returns NULL if name does not exist + /// Returns the node for the given string; returns nullptr if name does not exist TreeNode* getNode_(const QString& name) const; /// Fires off the given observer list for the given name and value void fireObservers_(const QList& observers, const QString& name, const QVariant& value, ObserverPtr skipThisObserver = simQt::Settings::ObserverPtr()); diff --git a/SDK/simQt/SettingsProxyModel.h b/SDK/simQt/SettingsProxyModel.h index 57171f87a..aaf7f05db 100644 --- a/SDK/simQt/SettingsProxyModel.h +++ b/SDK/simQt/SettingsProxyModel.h @@ -37,7 +37,7 @@ class SDKQT_EXPORT SettingsSearchFilter : public QSortFilterProxyModel Q_OBJECT; public: /** Constructor */ - SettingsSearchFilter(QAbstractItemModel* settingsModel, QWidget* parent=NULL); + SettingsSearchFilter(QAbstractItemModel* settingsModel, QWidget* parent=nullptr); /** Implements the QSortFilterProxyModel method to apply filtering to the row */ virtual bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const; @@ -62,7 +62,7 @@ class SDKQT_EXPORT SettingsDataLevelFilter : public QSortFilterProxyModel Q_OBJECT; public: /** Constructor */ - SettingsDataLevelFilter(QAbstractItemModel* settingsModel, QWidget* parent=NULL); + SettingsDataLevelFilter(QAbstractItemModel* settingsModel, QWidget* parent=nullptr); /** Implements the QSortFilterProxyModel method to apply filtering to the row */ virtual bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const; @@ -100,7 +100,7 @@ class SDKQT_EXPORT SettingsNoEmptyFoldersFilter : public QSortFilterProxyModel Q_OBJECT; public: /** Constructor */ - SettingsNoEmptyFoldersFilter(QAbstractItemModel* settingsModel, QWidget* parent=NULL); + SettingsNoEmptyFoldersFilter(QAbstractItemModel* settingsModel, QWidget* parent=nullptr); /** Implements the QSortFilterProxyModel method to apply filtering to the row */ virtual bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const; @@ -122,7 +122,7 @@ class SDKQT_EXPORT SettingsProxyModel : public QSortFilterProxyModel Q_OBJECT; public: /** Constructor */ - SettingsProxyModel(QAbstractItemModel* settingsModel, QWidget* parent=NULL); + SettingsProxyModel(QAbstractItemModel* settingsModel, QWidget* parent=nullptr); /** Destructor */ virtual ~SettingsProxyModel(); diff --git a/SDK/simQt/SliderTimeWidgetBinding.cpp b/SDK/simQt/SliderTimeWidgetBinding.cpp index 3e03a4d2d..d97d3cf2e 100644 --- a/SDK/simQt/SliderTimeWidgetBinding.cpp +++ b/SDK/simQt/SliderTimeWidgetBinding.cpp @@ -38,8 +38,8 @@ SliderTimeWidgetBinding::SliderTimeWidgetBinding(QSlider* slider, TimeWidget* ti timeWidget_(timeWidget) { // Must pass in slider and time widget - assert(slider_ != NULL); - assert(timeWidget_ != NULL); + assert(slider_ != nullptr); + assert(timeWidget_ != nullptr); slider_->setRange(0, MAX_RANGE); connect(slider_, SIGNAL(valueChanged(int)), this, SLOT(setTimeWidgetValue_(int))); diff --git a/SDK/simQt/SliderTimeWidgetBinding.h b/SDK/simQt/SliderTimeWidgetBinding.h index fbd1d2ce8..2bfdf2c12 100644 --- a/SDK/simQt/SliderTimeWidgetBinding.h +++ b/SDK/simQt/SliderTimeWidgetBinding.h @@ -46,7 +46,7 @@ class SDKQT_EXPORT SliderTimeWidgetBinding : public QObject public: /** Constructor */ - SliderTimeWidgetBinding(QSlider* slider, TimeWidget* timeWidget, QWidget *parent = NULL); + SliderTimeWidgetBinding(QSlider* slider, TimeWidget* timeWidget, QWidget *parent = nullptr); private slots: void setTimeWidgetValue_(int value); diff --git a/SDK/simQt/SortFilterProxyModel.h b/SDK/simQt/SortFilterProxyModel.h index 55743d49d..f20c89dcc 100644 --- a/SDK/simQt/SortFilterProxyModel.h +++ b/SDK/simQt/SortFilterProxyModel.h @@ -55,7 +55,7 @@ class SDKQT_EXPORT SortFilterProxyModel : public QSortFilterProxyModel * but not for the tertiary sort column, then the tertiary sort column * effectively becomes a secondary sort column. */ - explicit SortFilterProxyModel(QObject* parent = NULL, + explicit SortFilterProxyModel(QObject* parent = nullptr, int secondarySortColumn = SORT_COLUMN_NOT_USED, int tertiarySortColumn = SORT_COLUMN_NOT_USED); diff --git a/SDK/simQt/SplashScreen.cpp b/SDK/simQt/SplashScreen.cpp index f54e097a3..09fc2abb7 100644 --- a/SDK/simQt/SplashScreen.cpp +++ b/SDK/simQt/SplashScreen.cpp @@ -72,8 +72,8 @@ SplashScreen::~SplashScreen() void SplashScreen::addToWindowsTaskbar_() { // Note that as of Qt 4.8.2, setWindowFlags() MAY work to do this, but fails - // due to parent() being NULL; a call in setWindowFlags() accesses parent() - // directly without checking NULL, causing a crash. So we must use Windows API + // due to parent() being nullptr; a call in setWindowFlags() accesses parent() + // directly without checking nullptr, causing a crash. So we must use Windows API #ifdef WIN32 // Pull out the HWND for the splash window diff --git a/SDK/simQt/StartupLayoutManager.cpp b/SDK/simQt/StartupLayoutManager.cpp index 14e66006e..1fc5e9fd5 100644 --- a/SDK/simQt/StartupLayoutManager.cpp +++ b/SDK/simQt/StartupLayoutManager.cpp @@ -64,7 +64,7 @@ void StartupLayoutManager::executeTasks(simQt::Settings& fromSettings) // Get the corresponding task by name from our registered tasks StartupLayoutTaskPtr task = tasks_.value(*it); // ... and execute it. - if (task != NULL) + if (task != nullptr) task->execute(); } } @@ -78,7 +78,7 @@ void StartupLayoutManager::saveToSettings(simQt::Settings& toSettings) { // Task itself knows whether it ought to be saved StartupLayoutTaskPtr task = tasks_.value(*it); - if (task != NULL && task->shouldExecuteOnNextStartup()) + if (task != nullptr && task->shouldExecuteOnNextStartup()) tasksToSave.push_back(*it); } diff --git a/SDK/simQt/StartupLayoutTask.cpp b/SDK/simQt/StartupLayoutTask.cpp index 5bebc7d97..5a7347535 100644 --- a/SDK/simQt/StartupLayoutTask.cpp +++ b/SDK/simQt/StartupLayoutTask.cpp @@ -28,15 +28,15 @@ namespace simQt StartupLayoutTask::StartupLayoutTask() : QObject(), - widget_(NULL) + widget_(nullptr) { } StartupLayoutTask::StartupLayoutTask(QObject* receiver, const char* method) : QObject(), - widget_(NULL) + widget_(nullptr) { - if (receiver != NULL && method != NULL) + if (receiver != nullptr && method != nullptr) connect(this, SIGNAL(executed()), receiver, method); } @@ -46,7 +46,7 @@ StartupLayoutTask::~StartupLayoutTask() bool StartupLayoutTask::shouldExecuteOnNextStartup() const { - return widget_ != NULL && widget_->isVisible(); + return widget_ != nullptr && widget_->isVisible(); } void StartupLayoutTask::execute() @@ -61,7 +61,7 @@ void StartupLayoutTask::setWidget(QWidget* widget) clearWidget(); widget_ = widget; // Tie into the destroyed() signal so we never get into an invalid state - if (widget_ != NULL) + if (widget_ != nullptr) { connect(widget_, SIGNAL(destroyed()), this, SLOT(clearWidget())); } @@ -69,9 +69,9 @@ void StartupLayoutTask::setWidget(QWidget* widget) void StartupLayoutTask::clearWidget() { - if (widget_ != NULL) + if (widget_ != nullptr) disconnect(widget_, SIGNAL(destroyed()), this, SLOT(clearWidget())); - widget_ = NULL; + widget_ = nullptr; } } diff --git a/SDK/simQt/StartupLayoutTask.h b/SDK/simQt/StartupLayoutTask.h index f4a0166c6..f8becf94f 100644 --- a/SDK/simQt/StartupLayoutTask.h +++ b/SDK/simQt/StartupLayoutTask.h @@ -56,15 +56,15 @@ class SDKQT_EXPORT StartupLayoutTask : public QObject virtual ~StartupLayoutTask(); - /** Returns true if the widget is non-NULL and visible at the time of query */ + /** Returns true if the widget is non-nullptr and visible at the time of query */ virtual bool shouldExecuteOnNextStartup() const; /** Emits the executed() signal */ virtual void execute(); public slots: - /** Sets a widget to monitor for visibility. You may set to NULL when widget goes away. */ + /** Sets a widget to monitor for visibility. You may set to nullptr when widget goes away. */ void setWidget(QWidget* widget); - /** Clears the widget; same behavior as setWidget(NULL) */ + /** Clears the widget; same behavior as setWidget(nullptr) */ void clearWidget(); signals: diff --git a/SDK/simQt/StdStreamConsoleChannel.cpp b/SDK/simQt/StdStreamConsoleChannel.cpp index edc2c127a..606309961 100644 --- a/SDK/simQt/StdStreamConsoleChannel.cpp +++ b/SDK/simQt/StdStreamConsoleChannel.cpp @@ -69,7 +69,7 @@ class StdStreamConsoleChannel::TextBuffer */ void segmentBuffer_() { - if (channel_ == NULL) + if (channel_ == nullptr) return; // Segment out by newline, then add to the console diff --git a/SDK/simQt/StdStreamConsoleChannel.h b/SDK/simQt/StdStreamConsoleChannel.h index 0567d465a..051e26980 100644 --- a/SDK/simQt/StdStreamConsoleChannel.h +++ b/SDK/simQt/StdStreamConsoleChannel.h @@ -39,7 +39,7 @@ class SDKQT_EXPORT StdStreamConsoleChannel : public QObject Q_OBJECT; public: /** Constructor */ - StdStreamConsoleChannel(QObject* parent = NULL); + StdStreamConsoleChannel(QObject* parent = nullptr); virtual ~StdStreamConsoleChannel(); /** Binds the streams to the console data model provided */ diff --git a/SDK/simQt/TimeButtons.cpp b/SDK/simQt/TimeButtons.cpp index dad80c9d1..0dcf9c5fb 100644 --- a/SDK/simQt/TimeButtons.cpp +++ b/SDK/simQt/TimeButtons.cpp @@ -80,7 +80,7 @@ class ButtonActions::TimeModeObserver : public simCore::Clock::ModeChangeObserve ButtonActions::ButtonActions(QWidget *parent) : QObject(parent), - clock_(NULL), + clock_(nullptr), stepDecrease_(new QAction(QIcon(":/simQt/images/Navigation Blue Left.png"), "Decrease Rate", parent)), stepBack_(new QAction(QIcon(":/simQt/images/Navigation Blue First.png"), "Step Back", parent)), playReverse_(new QAction(QIcon(":/simQt/images/Navigation Blue Previous.png"), "Play Backward", parent)), @@ -127,7 +127,7 @@ ButtonActions::ButtonActions(QWidget *parent) ButtonActions::~ButtonActions() { - setClockManager(NULL); + setClockManager(nullptr); qDeleteAll(actions()); } @@ -209,7 +209,7 @@ void ButtonActions::setClockManager(simCore::Clock *clock) void ButtonActions::updateEnabledState_() { - bool enable = (clock_ != NULL && clock_->isUserEditable()); + bool enable = (clock_ != nullptr && clock_->isUserEditable()); // Emit a signal to indicate that the state has changed if (toggleLoop_->isEnabled() != enable) @@ -235,7 +235,7 @@ void ButtonActions::updateCheckedState_() simQt::ScopedSignalBlocker blockRealTime(*realTime_); // play, stop, and reverse are exclusive - const simCore::TimeDirection d = (clock_ != NULL) ? clock_->timeDirection() : simCore::STOP; + const simCore::TimeDirection d = (clock_ != nullptr) ? clock_->timeDirection() : simCore::STOP; playReverse_->setChecked(d == simCore::REVERSE); play_->setChecked(d == simCore::FORWARD); stop_->setChecked(d == simCore::STOP); @@ -243,7 +243,7 @@ void ButtonActions::updateCheckedState_() toggleLoop_->setChecked(clock_->canLoop()); // free wheel mode is real time driven by a plug-in - const simCore::Clock::Mode m = (clock_ != NULL) ? clock_->mode() : simCore::Clock::MODE_STEP; + const simCore::Clock::Mode m = (clock_ != nullptr) ? clock_->mode() : simCore::Clock::MODE_STEP; realTime_->setChecked(m == simCore::Clock::MODE_REALTIME || m == simCore::Clock::MODE_FREEWHEEL); } @@ -323,13 +323,13 @@ TimeButtons::TimeButtons(QWidget *parent) TimeButtons::~TimeButtons() { - bindToActions(NULL); + bindToActions(nullptr); delete ui_; } void TimeButtons::bindToActions(ButtonActions* actions) { - if (actions != NULL) + if (actions != nullptr) { ui_->button_StepDecrease->setDefaultAction(actions->stepDecreaseAction()); ui_->button_StepBack->setDefaultAction(actions->stepBackAction()); @@ -342,14 +342,14 @@ void TimeButtons::bindToActions(ButtonActions* actions) } else { - ui_->button_StepDecrease->setDefaultAction(NULL); - ui_->button_StepBack->setDefaultAction(NULL); - ui_->button_PlayBackwards->setDefaultAction(NULL); - ui_->button_Stop->setDefaultAction(NULL); - ui_->button_Play->setDefaultAction(NULL); - ui_->button_Step->setDefaultAction(NULL); - ui_->button_StepIncrease->setDefaultAction(NULL); - ui_->button_Realtime->setDefaultAction(NULL); + ui_->button_StepDecrease->setDefaultAction(nullptr); + ui_->button_StepBack->setDefaultAction(nullptr); + ui_->button_PlayBackwards->setDefaultAction(nullptr); + ui_->button_Stop->setDefaultAction(nullptr); + ui_->button_Play->setDefaultAction(nullptr); + ui_->button_Step->setDefaultAction(nullptr); + ui_->button_StepIncrease->setDefaultAction(nullptr); + ui_->button_Realtime->setDefaultAction(nullptr); } } diff --git a/SDK/simQt/TimeButtons.h b/SDK/simQt/TimeButtons.h index 3b2340cdf..479b10857 100644 --- a/SDK/simQt/TimeButtons.h +++ b/SDK/simQt/TimeButtons.h @@ -38,7 +38,7 @@ class SDKQT_EXPORT ButtonActions : public QObject Q_OBJECT; public: /** Constructor */ - ButtonActions(QWidget *parent = NULL); + ButtonActions(QWidget *parent = nullptr); virtual ~ButtonActions(); /** Returns step decrease action */ @@ -110,7 +110,7 @@ class SDKQT_EXPORT TimeButtons : public QWidget public: /** Constructor */ - TimeButtons(QWidget *parent = NULL); + TimeButtons(QWidget *parent = nullptr); virtual ~TimeButtons(); /** Binds the button to the action */ diff --git a/SDK/simQt/TimeFormatContainer.cpp b/SDK/simQt/TimeFormatContainer.cpp index b7a58b0e1..f8a872373 100644 --- a/SDK/simQt/TimeFormatContainer.cpp +++ b/SDK/simQt/TimeFormatContainer.cpp @@ -36,7 +36,7 @@ static const QString USAGE_STR = QObject::tr("

To edit, mouse click into a fie TimeFormatContainer::TimeFormatContainer(simCore::TimeFormat timeFormat, const QString& name) : timeFormat_(timeFormat), name_(name), - action_(NULL) + action_(nullptr) { } diff --git a/SDK/simQt/TimeFormatContainer.h b/SDK/simQt/TimeFormatContainer.h index 169413277..ad13fa0d7 100644 --- a/SDK/simQt/TimeFormatContainer.h +++ b/SDK/simQt/TimeFormatContainer.h @@ -115,7 +115,7 @@ class SDKQT_EXPORT SecondsContainer : public TimeFormatContainer { public: /// constructor - SecondsContainer(QWidget* parent=NULL); + SecondsContainer(QWidget* parent=nullptr); virtual ~SecondsContainer(); ///@return the underlying widget @@ -161,7 +161,7 @@ class SDKQT_EXPORT MonthContainer : public TimeFormatContainer { public: /// constructor - MonthContainer(QWidget* parent=NULL); + MonthContainer(QWidget* parent=nullptr); virtual ~MonthContainer(); ///@return the underlying widget @@ -208,7 +208,7 @@ class SDKQT_EXPORT OrdinalContainer : public TimeFormatContainer { public: /// constructor - OrdinalContainer(QWidget* parent=NULL); + OrdinalContainer(QWidget* parent=nullptr); virtual ~OrdinalContainer(); ///@return the underlying widget @@ -254,7 +254,7 @@ class SDKQT_EXPORT MinutesContainer : public TimeFormatContainer { public: /// constructor - MinutesContainer(QWidget* parent=NULL); + MinutesContainer(QWidget* parent=nullptr); virtual ~MinutesContainer(); ///@return the underlying widget @@ -300,7 +300,7 @@ class SDKQT_EXPORT HoursContainer : public TimeFormatContainer { public: /// constructor - HoursContainer(QWidget* parent=NULL); + HoursContainer(QWidget* parent=nullptr); virtual ~HoursContainer(); ///@return the underlying widget diff --git a/SDK/simQt/TimeSliderClockBinding.cpp b/SDK/simQt/TimeSliderClockBinding.cpp index 76397107e..384dbc1b8 100644 --- a/SDK/simQt/TimeSliderClockBinding.cpp +++ b/SDK/simQt/TimeSliderClockBinding.cpp @@ -90,7 +90,7 @@ TimeSliderClockBinding::TimeSliderClockBinding(QSlider* parent, simCore::Clock* disabledMode_(disabledMode), allowVisible_(true) { - assert(parent != NULL); // must pass in slider in constructor + assert(parent != nullptr); // must pass in slider in constructor timeObserver_.reset(new TimeObserver(this)); modeObserver_.reset(new ModeObserver(this)); connect(slider_, SIGNAL(valueChanged(int)), this, SLOT(valueChanged_(int))); @@ -112,7 +112,7 @@ void TimeSliderClockBinding::bindClock(simCore::Clock* clock) clock_->registerModeChangeCallback(modeObserver_); } // Set the initial state - fixEnabledState_(clock_ != NULL && clock_->isUserEditable()); + fixEnabledState_(clock_ != nullptr && clock_->isUserEditable()); updateSliderTime_(); } @@ -123,14 +123,14 @@ void TimeSliderClockBinding::unbindClock() clock_->removeTimeCallback(timeObserver_); clock_->removeModeChangeCallback(modeObserver_); } - clock_ = NULL; + clock_ = nullptr; } void TimeSliderClockBinding::valueChanged_(int sliderPos) { assert(sender() == slider_); // Only valid sender of this signal is our slider - if (clock_ == NULL) + if (clock_ == nullptr) return; const simCore::Seconds& deltaTime = clock_->endTime() - clock_->startTime(); if (deltaTime == 0) @@ -168,8 +168,8 @@ void TimeSliderClockBinding::updateSliderTime_() void TimeSliderClockBinding::updateSliderTime_(const simCore::TimeStamp &t) { - assert(clock_ != NULL); // Should not get this notification unless clock_ is non-NULL - if (clock_ == NULL || clock_->endTime() == simCore::INFINITE_TIME_STAMP) + assert(clock_ != nullptr); // Should not get this notification unless clock_ is non-nullptr + if (clock_ == nullptr || clock_->endTime() == simCore::INFINITE_TIME_STAMP) return; const simCore::Seconds& deltaTime = clock_->endTime() - clock_->startTime(); if (deltaTime <= 0) @@ -196,7 +196,7 @@ void TimeSliderClockBinding::setAllowVisible(bool allowVisible) // Visibility is allowed -- it was previously unallowed. We can only mark the item visible // if the clock is user editable, and if that matters for visibility. Let fixEnabledState_() // take care of it. - fixEnabledState_(clock_ != NULL && clock_->isUserEditable()); + fixEnabledState_(clock_ != nullptr && clock_->isUserEditable()); } } diff --git a/SDK/simQt/TimeSliderClockBinding.h b/SDK/simQt/TimeSliderClockBinding.h index ceef35623..e3b2da565 100644 --- a/SDK/simQt/TimeSliderClockBinding.h +++ b/SDK/simQt/TimeSliderClockBinding.h @@ -58,7 +58,7 @@ class SDKQT_EXPORT TimeSliderClockBinding : public QObject * supply a clock instance to bind the slider. Note that the memory * is managed by the parent/child relationship of this class to QSlider */ - TimeSliderClockBinding(QSlider* parent, simCore::Clock* clock=NULL, DisabledMode disabledMode=HIDE_AND_DISABLE); + TimeSliderClockBinding(QSlider* parent, simCore::Clock* clock=nullptr, DisabledMode disabledMode=HIDE_AND_DISABLE); /** Automatically unbinds the clock as needed */ virtual ~TimeSliderClockBinding(); diff --git a/SDK/simQt/TimeWidget.cpp b/SDK/simQt/TimeWidget.cpp index 53101d2c7..42f9e1106 100644 --- a/SDK/simQt/TimeWidget.cpp +++ b/SDK/simQt/TimeWidget.cpp @@ -40,7 +40,7 @@ namespace simQt { TimeWidget::TimeWidget(QWidget* parent) : QWidget(parent), scenarioReferenceYear_(1970), - disabledLineEdit_(NULL), + disabledLineEdit_(nullptr), timeEnabled_(true), labelToolTipSet_(false) { @@ -68,7 +68,7 @@ TimeWidget::TimeWidget(QWidget* parent) layout->setMargin(0); layout->addWidget(title_); layout->addWidget(currentContainer_->widget()); - setLayout(layout); // do not use parent since parent could be NULL + setLayout(layout); // do not use parent since parent could be nullptr colorCodeAction_ = new QAction(tr("&Color Code Text"), this); connect(colorCodeAction_, SIGNAL(triggered()), this, SLOT(setColorCode_())); @@ -86,7 +86,7 @@ TimeWidget::~TimeWidget() containers_.clear(); delete colorCodeAction_; - colorCodeAction_ = NULL; + colorCodeAction_ = nullptr; } void TimeWidget::addContainer_(TimeFormatContainer* widget, const QString& slotText) @@ -322,7 +322,7 @@ void TimeWidget::setTimeEnabled(bool value) timeEnabled_ = value; if (timeEnabled_) { - if (disabledLineEdit_ != NULL) + if (disabledLineEdit_ != nullptr) { disabledLineEdit_->setVisible(false); layout()->removeWidget(disabledLineEdit_); @@ -335,7 +335,7 @@ void TimeWidget::setTimeEnabled(bool value) currentContainer_->widget()->setVisible(false); layout()->removeWidget(currentContainer_->widget()); - if (disabledLineEdit_ == NULL) + if (disabledLineEdit_ == nullptr) { disabledLineEdit_ = new QLineEdit(tr("--------------------------------------"), this); disabledLineEdit_->setEnabled(false); diff --git a/SDK/simQt/TimeWidgetClockBinding.cpp b/SDK/simQt/TimeWidgetClockBinding.cpp index e26d088c7..0bf649f92 100644 --- a/SDK/simQt/TimeWidgetClockBinding.cpp +++ b/SDK/simQt/TimeWidgetClockBinding.cpp @@ -92,13 +92,13 @@ ReferenceYearCache::ReferenceYearCache(simData::DataStore* dataStore) : QObject(), refYear_(1970) { - if (dataStore != NULL) + if (dataStore != nullptr) refYear_ = dataStore->referenceYear(); } void ReferenceYearCache::onScenarioPropertiesChange(simData::DataStore* source) { - if (source != NULL) + if (source != nullptr) { int newYear = source->referenceYear(); if (refYear_ != newYear) @@ -119,20 +119,20 @@ int ReferenceYearCache::referenceYear() const TimeWidgetClockBinding::TimeWidgetClockBinding(simQt::TimeWidget* parent) : QObject(parent), timeWidget_(parent), - clock_(NULL), - dataStore_(NULL), + clock_(nullptr), + dataStore_(nullptr), respectLiveModeEndTime_(true) { - assert(parent != NULL); // must pass in simQt::TimeWidget in constructor + assert(parent != nullptr); // must pass in simQt::TimeWidget in constructor timeObserver_.reset(new TimeObserver(this)); modeObserver_.reset(new ModeObserver(this)); - ReferenceYearCache* cache = new ReferenceYearCache(NULL); + ReferenceYearCache* cache = new ReferenceYearCache(nullptr); refYearCache_.reset(cache); connect(timeWidget_, SIGNAL(timeEdited(const simCore::TimeStamp&)), this, SLOT(setClockTime_(const simCore::TimeStamp&))); connect(cache, SIGNAL(referenceYearChanged(int)), this, SLOT(passRefYearToChildren_())); - bindClock(NULL); - bindDataStore(NULL); + bindClock(nullptr); + bindDataStore(nullptr); } TimeWidgetClockBinding::~TimeWidgetClockBinding() @@ -163,7 +163,7 @@ void TimeWidgetClockBinding::bindClock(simCore::Clock* clock, bool bindCurrentTi // Set the initial state updateDisabledState_(); updateWidgetBounds_(false); - if (clock_ != NULL) + if (clock_ != nullptr) updateWidgetTime_(clock_->currentTime()); } @@ -174,7 +174,7 @@ void TimeWidgetClockBinding::unbindClock() clock_->removeTimeCallback(timeObserver_); clock_->removeModeChangeCallback(modeObserver_); } - clock_ = NULL; + clock_ = nullptr; } void TimeWidgetClockBinding::bindDataStore(simData::DataStore* dataStore) @@ -196,19 +196,19 @@ void TimeWidgetClockBinding::unbindDataStore() { dataStore_->removeScenarioListener(refYearCache_); } - dataStore_ = NULL; + dataStore_ = nullptr; } void TimeWidgetClockBinding::setClockTime_(const simCore::TimeStamp& clockTime) { - if (bindCurrentTime_ && clock_ != NULL && clock_->currentTime() != clockTime && clock_->isUserEditable()) + if (bindCurrentTime_ && clock_ != nullptr && clock_->currentTime() != clockTime && clock_->isUserEditable()) clock_->setTime(clockTime); } void TimeWidgetClockBinding::updateDisabledState_() { if (bindCurrentTime_) - timeWidget_->setEnabled(clock_ != NULL && clock_->isUserEditable()); + timeWidget_->setEnabled(clock_ != nullptr && clock_->isUserEditable()); } void TimeWidgetClockBinding::updateWidgetTime_(const simCore::TimeStamp &t) @@ -224,8 +224,8 @@ void TimeWidgetClockBinding::updateWidgetBounds_(bool notifyTimeChange) return; ReferenceYearCache* cache = dynamic_cast(refYearCache_.get()); // Programming error or dynamic_cast<> RTTI failure can cause assert - assert(cache != NULL); - if (cache != NULL) + assert(cache != nullptr); + if (cache != nullptr) { // Pull out the cache value, but fall back to a valid value if cache isn't right due to no DataStore int refYear = cache->referenceYear(); diff --git a/SDK/simQt/TimeWidgetClockBinding.h b/SDK/simQt/TimeWidgetClockBinding.h index 3707a236b..aa9bc8436 100644 --- a/SDK/simQt/TimeWidgetClockBinding.h +++ b/SDK/simQt/TimeWidgetClockBinding.h @@ -117,8 +117,8 @@ class ReferenceYearCache : public QObject, public simData::DataStore::ScenarioLi { Q_OBJECT; public: - /** Initializes the cache from a given data store (could be NULL) */ - ReferenceYearCache(simData::DataStore *dataStore=NULL); + /** Initializes the cache from a given data store (could be nullptr) */ + ReferenceYearCache(simData::DataStore *dataStore=nullptr); /** Checks on reference year change and emits signal if needed */ virtual void onScenarioPropertiesChange(simData::DataStore* source); diff --git a/SDK/simQt/TimestampedLayerManager.cpp b/SDK/simQt/TimestampedLayerManager.cpp index d52bb4297..d24870cbc 100644 --- a/SDK/simQt/TimestampedLayerManager.cpp +++ b/SDK/simQt/TimestampedLayerManager.cpp @@ -49,7 +49,7 @@ class TimestampedLayerManager::MapListener : public osgEarth::MapCallback virtual void onLayerAdded(osgEarth::Layer *layer, unsigned int index) { osgEarth::ImageLayer* imageLayer = dynamic_cast(layer); - if (imageLayer == NULL) + if (imageLayer == nullptr) return; parent_.addLayerWithTime_(imageLayer); parent_.setTime_(parent_.currTime_); @@ -58,7 +58,7 @@ class TimestampedLayerManager::MapListener : public osgEarth::MapCallback virtual void onLayerRemoved(osgEarth::Layer *layer, unsigned int index) { osgEarth::ImageLayer* imageLayer = dynamic_cast(layer); - if (imageLayer == NULL) + if (imageLayer == nullptr) return; if (!parent_.layerIsTimed(imageLayer)) return; @@ -74,8 +74,10 @@ class TimestampedLayerManager::MapListener : public osgEarth::MapCallback std::map& groups = parent_.groups_; auto groupIter = groups.find(timeGroup); - // If there's at least one timed layer in this group, the group needs to exist - assert(groupIter != groups.end()); + // If there's at least one timed layer in this group, the group needs to exist. However, + // this condition could happen in cases where a layer group gets multiple entries with the + // same time stamp, then the layers get removed. This condition is rare enough that we + // just handle it by breaking out here. if (groupIter == groups.end()) return; @@ -165,7 +167,7 @@ class TimestampedLayerManager::MapChangeObserver : public osgEarth::MapNodeObser /* Reimplemented from MapNodeObserver */ virtual osgEarth::MapNode* getMapNode() { - return (map_.valid() ? map_.get() : NULL); + return (map_.valid() ? map_.get() : nullptr); } /** Return the proper library name */ @@ -217,9 +219,13 @@ TimestampedLayerManager::~TimestampedLayerManager() attachPoint_->removeChild(mapChangeObserver_); clock_.removeTimeCallback(clockListener_); clockListener_.reset(); - osgEarth::MapNode* mapNode = dynamic_cast(mapChangeObserver_.get())->getMapNode(); - if (mapNode && mapNode->getMap()) - mapNode->getMap()->removeMapCallback(mapListener_.get()); + auto* mco = dynamic_cast(mapChangeObserver_.get()); + if (mco) + { + osgEarth::MapNode* mapNode = mco->getMapNode(); + if (mapNode && mapNode->getMap()) + mapNode->getMap()->removeMapCallback(mapListener_.get()); + } restoreOriginalVisibility_(); for (auto groupIter = groups_.begin(); groupIter != groups_.end(); groupIter++) delete groupIter->second; @@ -232,7 +238,7 @@ void TimestampedLayerManager::setTime_(const simCore::TimeStamp& stamp) if (!timingActive_) return; - osgEarth::ImageLayer* oldLayer = NULL; + osgEarth::ImageLayer* oldLayer = nullptr; // Update the current layer for each group for (auto groupIter = groups_.begin(); groupIter != groups_.end(); groupIter++) @@ -272,8 +278,8 @@ void TimestampedLayerManager::setTime_(const simCore::TimeStamp& stamp) currentLayer->setVisible(false); oldLayer = currentLayer.get(); } - currentLayer = NULL; - emit currentTimedLayerChanged(NULL, oldLayer); + currentLayer = nullptr; + emit currentTimedLayerChanged(nullptr, oldLayer); } } } @@ -289,31 +295,18 @@ const osgEarth::ImageLayer* TimestampedLayerManager::getCurrentTimedLayer(const auto groupIter = groups_.find(timeGroup); if (groupIter != groups_.end()) return groupIter->second->currentLayer.get(); - return NULL; + return nullptr; } void TimestampedLayerManager::addLayerWithTime_(osgEarth::ImageLayer* newLayer) { if (!newLayer) return; - const osgEarth::Config& conf = newLayer->getConfig(); - std::string iso8601 = conf.value("time"); - // Fall back to "times" if possible - if (iso8601.empty()) - iso8601 = conf.value("times"); - /* - * Some image layer file types can have time values (e.g. db files). Config values can't be - * changed at time of file read, so time is set as a user value of the layer in these cases. - * Config values take precedence of user values. - */ - if (iso8601.empty()) - newLayer->getUserValue("time", iso8601); + const simCore::TimeStamp& simTime = getLayerTime(newLayer); // If layer has no time, nothing to do with it - if (iso8601.empty()) + if (simTime == simCore::INFINITE_TIME_STAMP) return; - osgEarth::DateTime osgTime(iso8601); - simCore::TimeStamp simTime = simCore::TimeStamp(1970, osgTime.asTimeStamp()); originalVisibility_[newLayer] = newLayer->getVisible(); std::string groupName = getLayerTimeGroup(newLayer); // If the group doesn't exist yet, create it and put it in the map @@ -357,7 +350,7 @@ void TimestampedLayerManager::setMapNode_(osgEarth::MapNode* mapNode) map->getLayers(vec); for (auto i = vec.begin(); i != vec.end(); i++) { - osgEarth::ImageLayer* newLayer = NULL; + osgEarth::ImageLayer* newLayer = nullptr; if (i->valid()) newLayer = dynamic_cast(i->get()); addLayerWithTime_(newLayer); @@ -402,7 +395,7 @@ void TimestampedLayerManager::restoreOriginalVisibility_() } // Unset the group's current layer. Prevents bad starting state when timed visibility is reactiviated - groupIter->second->currentLayer = NULL; + groupIter->second->currentLayer = nullptr; } } @@ -424,9 +417,9 @@ void TimestampedLayerManager::useTimedVisibility_() setTime_(currTime_); } -std::string TimestampedLayerManager::getLayerTimeGroup(const osgEarth::ImageLayer* layer) +std::string TimestampedLayerManager::getLayerTimeGroup(const osgEarth::ImageLayer* layer) const { - if (!layer || !layerIsTimed(layer)) + if (!layer || getLayerTime(layer) == simCore::INFINITE_TIME_STAMP) return ""; const osgEarth::Config& conf = layer->getConfig(); std::string rv = conf.value(TIME_GROUP_TAG); @@ -435,4 +428,28 @@ std::string TimestampedLayerManager::getLayerTimeGroup(const osgEarth::ImageLaye return rv; } +simCore::TimeStamp TimestampedLayerManager::getLayerTime(const osgEarth::ImageLayer* layer) const +{ + if (!layer) + return simCore::INFINITE_TIME_STAMP; + + const osgEarth::Config& conf = layer->getConfig(); + std::string iso8601 = conf.value("time"); + // Fall back to "times" if possible + if (iso8601.empty()) + iso8601 = conf.value("times"); + + // Some image layer file types can have time values (e.g. db files). Config values can't be + // changed at time of file read, so time is set as a user value of the layer in these cases. + // Config values take precedence over user values. + if (iso8601.empty()) + layer->getUserValue("time", iso8601); + // If layer has no time, nothing to do with it + if (iso8601.empty()) + return simCore::INFINITE_TIME_STAMP; + + const osgEarth::DateTime osgTime(iso8601); + return simCore::TimeStamp(1970, osgTime.asTimeStamp()); +} + } diff --git a/SDK/simQt/TimestampedLayerManager.h b/SDK/simQt/TimestampedLayerManager.h index 5b5660726..66b411ec2 100644 --- a/SDK/simQt/TimestampedLayerManager.h +++ b/SDK/simQt/TimestampedLayerManager.h @@ -57,7 +57,7 @@ class SDKQT_EXPORT TimestampedLayerManager : public QObject * @param attachPoint Attach point for an osgEarth::MapNodeObserver * @param parent Parent object */ - TimestampedLayerManager(simCore::Clock& clock, osg::Group* attachPoint, QObject* parent = NULL); + TimestampedLayerManager(simCore::Clock& clock, osg::Group* attachPoint, QObject* parent = nullptr); /** Destructor */ virtual ~TimestampedLayerManager(); @@ -71,7 +71,9 @@ class SDKQT_EXPORT TimestampedLayerManager : public QObject bool layerIsTimed(const osgEarth::ImageLayer* layer) const; /// Gets the time group string from the given layer. Returns empty string if layer is not timed - std::string getLayerTimeGroup(const osgEarth::ImageLayer* layer); + std::string getLayerTimeGroup(const osgEarth::ImageLayer* layer) const; + /** Returns the time associated with the given layer, if layer is timed. Returns simCore::INFINITE_TIME_STAMP if not timed. */ + simCore::TimeStamp getLayerTime(const osgEarth::ImageLayer* layer) const; /** * Returns the layer that has time value closest after the current time for the given time group. @@ -94,14 +96,14 @@ class SDKQT_EXPORT TimestampedLayerManager : public QObject signals: /** - * Emitted when the current layer changes. New layer or old layer can be NULL. If non-NULL, newLayer + * Emitted when the current layer changes. New layer or old layer can be nullptr. If non-nullptr, newLayer * and oldLayer are guaranteed to be part of the map associated with this object at time of emission. This * signal indicates that visibility of timed layers has changed. Further processing is not needed for simple * timed showing or hiding. * @param newLayer New current layer * @param previousLayer Previous current layer */ - void currentTimedLayerChanged(const osgEarth::ImageLayer* newLayer = NULL, const osgEarth::ImageLayer* previousLayer = NULL); + void currentTimedLayerChanged(const osgEarth::ImageLayer* newLayer = nullptr, const osgEarth::ImageLayer* previousLayer = nullptr); private: diff --git a/SDK/simQt/Toast.cpp b/SDK/simQt/Toast.cpp index 6627a7992..48257483d 100644 --- a/SDK/simQt/Toast.cpp +++ b/SDK/simQt/Toast.cpp @@ -50,16 +50,16 @@ static const int INTERVAL_SHORT = 2000; ToastOnWidget::ToastOnWidget(QWidget* widget) : widget_(widget), - hideTimer_(NULL), - popIn_(NULL), - popOut_(NULL) + hideTimer_(nullptr), + popIn_(nullptr), + popOut_(nullptr) { // Set up the toast button if (widget_) toast_ = new ClickableLabel(widget_); else { - // This shouldn't happen; indicates that we were given a NULL widget. + // This shouldn't happen; indicates that we were given a nullptr widget. assert(0); return; } diff --git a/SDK/simQt/UnitContext.cpp b/SDK/simQt/UnitContext.cpp index a88ee5dc7..a4aeadd74 100644 --- a/SDK/simQt/UnitContext.cpp +++ b/SDK/simQt/UnitContext.cpp @@ -346,8 +346,8 @@ void UnitContextProxy::setSubject(UnitContext* newSubject) if (newSubject == subject_) return; - // The new context (subject) must be non-NULL; refuse - assert(newSubject != NULL); + // The new context (subject) must be non-nullptr; refuse + assert(newSubject != nullptr); // First disconnect all signals from the old subject if (subject_) @@ -376,8 +376,8 @@ void UnitContextProxy::setSubject(UnitContext* newSubject) UnitContext* oldSubject = subject_; subject_ = newSubject; - // Try to safely deal with subject_ being NULL by returning (assert should trigger above in debug mode) - if (subject_ == NULL) + // Try to safely deal with subject_ being nullptr by returning (assert should trigger above in debug mode) + if (subject_ == nullptr) return; // Next, connect to the new subject (context) @@ -403,92 +403,92 @@ void UnitContextProxy::setSubject(UnitContext* newSubject) // Detect changes in any of the fields from the old context to the new context bool foundChange = false; - if (oldSubject == NULL || oldSubject->timeFormat() != subject_->timeFormat()) + if (oldSubject == nullptr || oldSubject->timeFormat() != subject_->timeFormat()) { foundChange = true; emit timeFormatChanged(subject_->timeFormat()); } - if (oldSubject == NULL || oldSubject->timePrecision() != subject_->timePrecision()) + if (oldSubject == nullptr || oldSubject->timePrecision() != subject_->timePrecision()) { foundChange = true; emit timePrecisionChanged(subject_->timePrecision()); } - if (oldSubject == NULL || oldSubject->geodeticFormat() != subject_->geodeticFormat()) + if (oldSubject == nullptr || oldSubject->geodeticFormat() != subject_->geodeticFormat()) { foundChange = true; emit geodeticFormatChanged(subject_->geodeticFormat()); } - if (oldSubject == NULL || oldSubject->geodeticPrecision() != subject_->geodeticPrecision()) + if (oldSubject == nullptr || oldSubject->geodeticPrecision() != subject_->geodeticPrecision()) { foundChange = true; emit geodeticPrecisionChanged(subject_->geodeticPrecision()); } - if (oldSubject == NULL || oldSubject->distanceUnits() != subject_->distanceUnits()) + if (oldSubject == nullptr || oldSubject->distanceUnits() != subject_->distanceUnits()) { foundChange = true; emit distanceUnitsChanged(subject_->distanceUnits()); } - if (oldSubject == NULL || oldSubject->distancePrecision() != subject_->distancePrecision()) + if (oldSubject == nullptr || oldSubject->distancePrecision() != subject_->distancePrecision()) { foundChange = true; emit distancePrecisionChanged(subject_->distancePrecision()); } - if (oldSubject == NULL || oldSubject->altitudeUnits() != subject_->altitudeUnits()) + if (oldSubject == nullptr || oldSubject->altitudeUnits() != subject_->altitudeUnits()) { foundChange = true; emit altitudeUnitsChanged(subject_->altitudeUnits()); } - if (oldSubject == NULL || oldSubject->altitudePrecision() != subject_->altitudePrecision()) + if (oldSubject == nullptr || oldSubject->altitudePrecision() != subject_->altitudePrecision()) { foundChange = true; emit altitudePrecisionChanged(subject_->altitudePrecision()); } - if (oldSubject == NULL || oldSubject->angleUnits() != subject_->angleUnits()) + if (oldSubject == nullptr || oldSubject->angleUnits() != subject_->angleUnits()) { foundChange = true; emit angleUnitsChanged(subject_->angleUnits()); } - if (oldSubject == NULL || oldSubject->anglePrecision() != subject_->anglePrecision()) + if (oldSubject == nullptr || oldSubject->anglePrecision() != subject_->anglePrecision()) { foundChange = true; emit anglePrecisionChanged(subject_->anglePrecision()); } - if (oldSubject == NULL || oldSubject->speedUnits() != subject_->speedUnits()) + if (oldSubject == nullptr || oldSubject->speedUnits() != subject_->speedUnits()) { foundChange = true; emit speedUnitsChanged(subject_->speedUnits()); } - if (oldSubject == NULL || oldSubject->speedPrecision() != subject_->speedPrecision()) + if (oldSubject == nullptr || oldSubject->speedPrecision() != subject_->speedPrecision()) { foundChange = true; emit speedPrecisionChanged(subject_->speedPrecision()); } - if (oldSubject == NULL || oldSubject->genericPrecision() != subject_->genericPrecision()) + if (oldSubject == nullptr || oldSubject->genericPrecision() != subject_->genericPrecision()) { foundChange = true; emit genericPrecisionChanged(subject_->genericPrecision()); } - if (oldSubject == NULL || oldSubject->coordinateSystem() != subject_->coordinateSystem()) + if (oldSubject == nullptr || oldSubject->coordinateSystem() != subject_->coordinateSystem()) { foundChange = true; emit coordinateSystemChanged(subject_->coordinateSystem()); } - if (oldSubject == NULL || oldSubject->magneticVariance() != subject_->magneticVariance()) + if (oldSubject == nullptr || oldSubject->magneticVariance() != subject_->magneticVariance()) { foundChange = true; emit magneticVarianceChanged(subject_->magneticVariance()); } - if (oldSubject == NULL || oldSubject->verticalDatum() != subject_->verticalDatum()) + if (oldSubject == nullptr || oldSubject->verticalDatum() != subject_->verticalDatum()) { foundChange = true; emit verticalDatumChanged(subject_->verticalDatum()); } - if (oldSubject == NULL || oldSubject->referenceYear() != subject_->referenceYear()) + if (oldSubject == nullptr || oldSubject->referenceYear() != subject_->referenceYear()) { foundChange = true; emit referenceYearChanged(subject_->referenceYear()); } - if (oldSubject == NULL || oldSubject->datumConvert() != subject_->datumConvert()) + if (oldSubject == nullptr || oldSubject->datumConvert() != subject_->datumConvert()) { foundChange = true; emit datumConvertPtrChanged(subject_->datumConvert()); diff --git a/SDK/simQt/UnitContext.h b/SDK/simQt/UnitContext.h index c9db03fd1..1b92c60d5 100644 --- a/SDK/simQt/UnitContext.h +++ b/SDK/simQt/UnitContext.h @@ -42,7 +42,7 @@ class UnitContext : public QObject, public simCore::UnitContext signals: /** One of the values in the provided unit context has changed. Emitted after individual changes. */ - void unitsChanged(simQt::UnitContext* context=NULL); + void unitsChanged(simQt::UnitContext* context=nullptr); void timeFormatChanged(simCore::TimeFormat fmt=simCore::TIMEFORMAT_ORDINAL); void timePrecisionChanged(unsigned int prec=3); @@ -64,7 +64,7 @@ class UnitContext : public QObject, public simCore::UnitContext void datumConvertPtrChanged(simCore::DatumConvertPtr datum); protected: - UnitContext(QObject* parent=NULL) : QObject(parent) {} + UnitContext(QObject* parent=nullptr) : QObject(parent) {} }; /** Adapter class to the UnitContext that provides simple gets and sets for each field. */ @@ -72,7 +72,7 @@ class UnitContextAdapter : public simQt::UnitContext { Q_OBJECT; public: - UnitContextAdapter(QObject* parent=NULL); + UnitContextAdapter(QObject* parent=nullptr); virtual ~UnitContextAdapter(); // Getters for various unit types @@ -146,7 +146,7 @@ class UnitContextProxy : public simQt::UnitContext { Q_OBJECT; public: - UnitContextProxy(simQt::UnitContext* subject=NULL); + UnitContextProxy(simQt::UnitContext* subject=nullptr); virtual ~UnitContextProxy(); /** Changes the underlying subject of this proxy. */ diff --git a/SDK/simQt/UnitsComboBox.cpp b/SDK/simQt/UnitsComboBox.cpp index 873a23787..ece0378f4 100644 --- a/SDK/simQt/UnitsComboBox.cpp +++ b/SDK/simQt/UnitsComboBox.cpp @@ -246,30 +246,30 @@ void UnitsComboBox::addUnitsItem_(QComboBox& comboBox, const simCore::Units& uni UnitsSelectorComboBox::UnitsSelectorComboBox(QWidget* parent) : QComboBox(parent), - registry_(NULL), + registry_(nullptr), registryOwned_(true) { - setUnitsRegistry(NULL); + setUnitsRegistry(nullptr); connect(this, SIGNAL(currentIndexChanged(int)), this, SLOT(emitUnitsOnCurrentChange_(int))); } void UnitsSelectorComboBox::setUnitsRegistry(const simCore::UnitsRegistry* registry) { - if (registry != NULL && registry == registry_) + if (registry != nullptr && registry == registry_) return; if (registryOwned_) delete registry_; - registry_ = NULL; + registry_ = nullptr; - if (registry != NULL) + if (registry != nullptr) { registry_ = registry; registryOwned_ = false; return; } - // Always have a non-NULL units registry + // Always have a non-nullptr units registry simCore::UnitsRegistry* nonConst = new simCore::UnitsRegistry; nonConst->registerDefaultUnits(); registry_ = nonConst; diff --git a/SDK/simQt/UnitsComboBox.h b/SDK/simQt/UnitsComboBox.h index 289827231..5222c2120 100644 --- a/SDK/simQt/UnitsComboBox.h +++ b/SDK/simQt/UnitsComboBox.h @@ -137,7 +137,7 @@ class SDKQT_EXPORT UnitsSelectorComboBox : public QComboBox Q_PROPERTY(simCore::Units units READ units WRITE setUnits) public: - explicit UnitsSelectorComboBox(QWidget* parent=NULL); + explicit UnitsSelectorComboBox(QWidget* parent=nullptr); virtual ~UnitsSelectorComboBox(); /** Change the registry. Call this before setting units. Registry should outlive this class. */ diff --git a/SDK/simQt/ValueMerge.cpp b/SDK/simQt/ValueMerge.cpp new file mode 100644 index 000000000..7eae5250a --- /dev/null +++ b/SDK/simQt/ValueMerge.cpp @@ -0,0 +1,185 @@ +/* -*- mode: c++ -*- */ +/**************************************************************************** + ***** ***** + ***** Classification: UNCLASSIFIED ***** + ***** Classified By: ***** + ***** Declassify On: ***** + ***** ***** + **************************************************************************** + * + * + * Developed by: Naval Research Laboratory, Tactical Electronic Warfare Div. + * EW Modeling & Simulation, Code 5773 + * 4555 Overlook Ave. + * Washington, D.C. 20375-5339 + * + * License for source code can be found at: + * https://github.com/USNavalResearchLaboratory/simdissdk/blob/master/LICENSE.txt + * + * The U.S. Government retains all rights to use, duplicate, distribute, + * disclose, or release this software. + * + */ +#include +#include +#include +#include +#include +#include +#include +#include "simQt/ColorWidget.h" +#include "simQt/FileSelectorWidget.h" +#include "simQt/ValueMerge.h" + +namespace simQt { + +/** Helper method that sets a widget's font to indicate value conflict */ +template +void setConflictFont(Widget* widget, bool conflict) +{ + QFont font = widget->font(); + // if already matches, do nothing + if (font.italic() == conflict) + return; + font.setItalic(conflict); + widget->setFont(font); +} + +////////////////////////////////////////////////////////////// + +SpinBoxValueMerge::SpinBoxValueMerge(QSpinBox* spinBox, QLabel* label, int defaultValue) + : ValueMerge(defaultValue), + spinBox_(spinBox), + label_(label) +{ +} + +SpinBoxValueMerge::~SpinBoxValueMerge() +{ + // Apply text/value as needed to widget and label + setConflictFont(label_, conflict_); + + int valueToSet = value_; + if (conflict_ || !valueSet_) + valueToSet = defaultValue_; + + if (spinBox_->value() != valueToSet) + spinBox_->setValue(valueToSet); +} + +////////////////////////////////////////////////////////////// + +SpinBoxUValueMerge::SpinBoxUValueMerge(QSpinBox* spinBox, QLabel* label, unsigned int defaultValue) + : ValueMerge(defaultValue), + spinBox_(spinBox), + label_(label) +{ +} + +SpinBoxUValueMerge::~SpinBoxUValueMerge() +{ + // Apply text/value as needed to widget and label + setConflictFont(label_, conflict_); + + int valueToSet = value_; + if (conflict_ || !valueSet_) + valueToSet = defaultValue_; + + if (spinBox_->value() != valueToSet) + spinBox_->setValue(valueToSet); +} + +////////////////////////////////////////////////////////////// + +CheckBoxValueMerge::CheckBoxValueMerge(QCheckBox* checkBox, QLabel* label, bool defaultValue) + : ValueMerge(defaultValue), + checkBox_(checkBox), + label_(label) +{ + // This class does not support tristate check boxes + assert(!checkBox_->isTristate()); +} + +CheckBoxValueMerge::~CheckBoxValueMerge() +{ + // Apply text/value as needed to widget and label + if (label_) + setConflictFont(label_, conflict_); + else + setConflictFont(checkBox_, conflict_); + + bool valueToSet = value_; + if (conflict_ || !valueSet_) + valueToSet = defaultValue_; + + if (checkBox_->isChecked() != valueToSet) + checkBox_->setChecked(valueToSet); +} + +////////////////////////////////////////////////////////////// + +LineEditValueMerge::LineEditValueMerge(QLineEdit* lineEdit, QLabel* label) + : ValueMerge(QString()), + lineEdit_(lineEdit), + label_(label) +{ +} + +LineEditValueMerge::~LineEditValueMerge() +{ + // Apply text/value as needed to widget and label + setConflictFont(label_, conflict_); + + QString valueToSet = value_; + if (conflict_ || !valueSet_) + valueToSet = defaultValue_; + + if (lineEdit_->text() != valueToSet) + lineEdit_->setText(valueToSet); +} + +////////////////////////////////////////////////////////////// + +FileSelectorValueMerge::FileSelectorValueMerge(simQt::FileSelectorWidget* fileSelector, QLabel* label) + : ValueMerge(QString()), + fileSelector_(fileSelector), + label_(label) +{ +} + +FileSelectorValueMerge::~FileSelectorValueMerge() +{ + // Apply text/value as needed to widget and label + setConflictFont(label_, conflict_); + + QString valueToSet = value_; + if (conflict_ || !valueSet_) + valueToSet = defaultValue_; + + if (fileSelector_->filename() != valueToSet) + fileSelector_->setFilename(valueToSet); +} + +////////////////////////////////////////////////////////////// + +ColorValueMerge::ColorValueMerge(simQt::ColorWidget* colorWidget, QLabel* label, const QColor& defaultValue) + : ValueMerge(defaultValue), + colorWidget_(colorWidget), + label_(label) +{ +} + +ColorValueMerge::~ColorValueMerge() +{ + // Apply text/value as needed to widget and label + setConflictFont(label_, conflict_); + + QColor valueToSet = value_; + if (conflict_ || !valueSet_) + valueToSet = defaultValue_; + + if (colorWidget_->color() != valueToSet) + colorWidget_->setColor(valueToSet); +} + +} diff --git a/SDK/simQt/ValueMerge.h b/SDK/simQt/ValueMerge.h new file mode 100644 index 000000000..144eafc57 --- /dev/null +++ b/SDK/simQt/ValueMerge.h @@ -0,0 +1,258 @@ +/* -*- mode: c++ -*- */ +/**************************************************************************** + ***** ***** + ***** Classification: UNCLASSIFIED ***** + ***** Classified By: ***** + ***** Declassify On: ***** + ***** ***** + **************************************************************************** + * + * + * Developed by: Naval Research Laboratory, Tactical Electronic Warfare Div. + * EW Modeling & Simulation, Code 5773 + * 4555 Overlook Ave. + * Washington, D.C. 20375-5339 + * + * License for source code can be found at: + * https://github.com/USNavalResearchLaboratory/simdissdk/blob/master/LICENSE.txt + * + * The U.S. Government retains all rights to use, duplicate, distribute, + * disclose, or release this software. + * + */ + +#ifndef SIMQT_VALUEMERGE_H +#define SIMQT_VALUEMERGE_H + +#include +#include "simCore/Common/Export.h" + +class QCheckBox; +class QLabel; +class QLineEdit; +class QSpinBox; + +namespace simQt { + +class ColorWidget; +class FileSelectorWidget; + +/** + * ValueMerge and its derived classes provide the ability to merge + * values from multiple sources of the same type into a Qt widget. + * Using merge(), a value from all sources will be merged using a + * call to the provided std::function. See merge() documentation + * for more information. + * + * ValueMerge is a base class and should not be used directly. + * Example usage of a derived class is below. + * + * + * // Simple Example: + * std:vector sample = { ... }; + * { + * // Changes to the spin box will not apply until the ValueMerge + * // instance goes out of scope and the destructor is called. + * simQt::SpinBoxValueMerge sampleMerge(ui_->sampleSpin, ui_->sampleSpinLabel, 0); + * sampleMerge.merge(sample, [](int value) -> int { return value; }); + * } + * + * // Class Example: + * std::vector entries = { ... } + * { + * // Changes to the spin box will not apply until the ValueMerge + * // instance goes out of scope and the destructor is called. + * simQt::SpinBoxValueMerge entryMerge(ui_->entryWidthSpin, ui_->entryWidthLabel, 1); + * entryMerge.merge(entries, [](const Entry& entry) -> int { return entry.width(); }); + * } + * + */ +template +class SDKQT_EXPORT ValueMerge +{ +public: + virtual ~ValueMerge() {} + + /** + * Checks values from all entries in the provided container + * to determine if all values match or if a conflict exists. + * @param entries Container containing entries to scan for values. + * The container should be any type that can be iterated using a + * range-based for loop. + * @param func std::function used to access a value from each entry + * in the entries container. The function should accept a single + * parameter of the type in the entries container, and return a + * value matching the type described by ValueTypeT. For example: + * for a container of instances of a class called Entry where + * ValueTypeT represents an integer, a useful function could be: + * [](const Entry& entry) -> int { + * return entry.getIntValue(); + * } + */ + template + void merge(const ContainerT& entries, const FunctionT& func) + { + for (auto entry : entries) + { + ValueTypeT thisVal = func(entry); + if (!valueSet_) + { + valueSet_ = true; + value_ = thisVal; + continue; + } + + if (thisVal != value_) + { + conflict_ = true; + value_ = defaultValue_; + break; // Break out early on conflict + } + } + } + +protected: + /** Restrict constructor usage to derived classes only */ + explicit ValueMerge(const ValueTypeT& defaultValue) + : defaultValue_(defaultValue), + valueSet_(false), + conflict_(false) + { + } + + ValueTypeT defaultValue_; ///< Default value, used when there are conflicts + ValueTypeT value_; ///< Value found by merge(). Ignored if there are conflicts + bool valueSet_; ///< True if value_ has been set + bool conflict_; ///< True if values differ among provided entries +}; + +////////////////////////////////////////////////////////////// + +/** QSpinBox ValueMerge implementation, integer version. */ +class SDKQT_EXPORT SpinBoxValueMerge : public ValueMerge +{ +public: + /** + * QSpinBox ValueMerge implementation, integer version. + * @param spinBox QSpinBox to update with a merged value + * @param label QLabel associated with the spin box, made italic when there's a conflict + * @param defaultValue Default value used when there's a conflict + */ + SpinBoxValueMerge(QSpinBox* spinBox, QLabel* label, int defaultValue); + /** Destructor. Applies merged value and font changes to the spin box and label as needed. */ + virtual ~SpinBoxValueMerge(); + +private: + QSpinBox* spinBox_; + QLabel* label_; +}; + +////////////////////////////////////////////////////////////// + +/** QSpinBox ValueMerge implementation, unsigned integer version. */ +class SDKQT_EXPORT SpinBoxUValueMerge : public ValueMerge +{ +public: + /** + * Construct a new SpinBoxUValueMerge. + * @param spinBox QSpinBox to update with a merged value + * @param label QLabel associated with the spin box, made italic when there's a conflict + * @param defaultValue Default value used when there's a conflict + */ + SpinBoxUValueMerge(QSpinBox* spinBox, QLabel* label, unsigned int defaultValue); + /** Destructor. Applies merged value and font changes to the spin box and label as needed. */ + virtual ~SpinBoxUValueMerge(); + +private: + QSpinBox* spinBox_; + QLabel* label_; +}; + +////////////////////////////////////////////////////////////// + +/** QCheckBox ValueMerge implementation. Does not handle tristate check boxes.*/ +class SDKQT_EXPORT CheckBoxValueMerge : public ValueMerge +{ +public: + /** + * Construct a new CheckBoxValueMerge. + * @param checkbox QCheckBox to update with a merged value + * @param label QLabel associated with the check box, made italic when there's a conflict. + * If label is nullptr, italics will be applied to the QCheckBox's text instead. + * @param defaultValue Default value used when there's a conflict + */ + CheckBoxValueMerge(QCheckBox* checkBox, QLabel* label, bool defaultValue); + /** Destructor. Applies merged value and font changes to the check box and label as needed. */ + virtual ~CheckBoxValueMerge(); + +private: + QCheckBox* checkBox_; + QLabel* label_; +}; + +////////////////////////////////////////////////////////////// + +/** QLineEdit ValueMerge implementation. */ +class SDKQT_EXPORT LineEditValueMerge : public ValueMerge +{ +public: + /** + * Construct a new LineEditValueMerge. This implementation purposely does not + * accept a default value. When a conflict arises, QLineEdit will be cleared. + * @param lineEdit QLineEdit to update with a merged value + * @param label QLabel associated with the line edit, made italic when there's a conflict + */ + LineEditValueMerge(QLineEdit* lineEdit, QLabel* label); + /** Destructor. Applies merged value and font changes to the line edit and label as needed. */ + virtual ~LineEditValueMerge(); + +private: + QLineEdit* lineEdit_; + QLabel* label_; +}; + +////////////////////////////////////////////////////////////// + +/** simQt::FileSelectorWidget ValueMerge implementation. */ +class SDKQT_EXPORT FileSelectorValueMerge : public ValueMerge +{ +public: + /** + * Construct a new FileSelectorValueMerge. This implementation purposely does not + * accept a default value. When a conflict arises, simQt::FileSelectorWidget will be cleared. + * @param fileSelector simQt::FileSelectorWidget to update with a merged value + * @param label QLabel associated with the spin box, made italic when there's a conflict + */ + FileSelectorValueMerge(simQt::FileSelectorWidget* fileSelector, QLabel* label); + /** Destructor. Applies merged value and font changes to the file selector and label as needed. */ + virtual ~FileSelectorValueMerge(); + +private: + simQt::FileSelectorWidget* fileSelector_; + QLabel* label_; +}; + +////////////////////////////////////////////////////////////// + +/** simQt::ColorWidget ValueMerge implementation, integer version. */ +class SDKQT_EXPORT ColorValueMerge : public ValueMerge +{ +public: + /** + * Construct a new simQt::ColorWidget. + * @param colorWidget simQt::ColorWidget to update with a merged value + * @param label QLabel associated with the color widget, made italic when there's a conflict + * @param defaultValue Default value used when there's a conflict + */ + ColorValueMerge(simQt::ColorWidget* colorWidget, QLabel* label, const QColor& defaultValue); + /** Destructor. Applies merged value and font changes to the color widget and label as needed. */ + virtual ~ColorValueMerge(); + +private: + simQt::ColorWidget* colorWidget_; + QLabel* label_; +}; + +} + +#endif diff --git a/SDK/simQt/ViewManagerDataModel.cpp b/SDK/simQt/ViewManagerDataModel.cpp index 6a82e80f1..edf2b8577 100644 --- a/SDK/simQt/ViewManagerDataModel.cpp +++ b/SDK/simQt/ViewManagerDataModel.cpp @@ -39,8 +39,8 @@ class ViewManagerDataModel::TopLevelViewChange : public simVis::ViewManager::Cal : Callback(), dataModel_(dataModel) { - // NULL Data model is not supported (doesn't make sense here) - assert(dataModel_ != NULL); + // nullptr Data model is not supported (doesn't make sense here) + assert(dataModel_ != nullptr); } virtual void operator()(simVis::View* inset, const EventType& e) { @@ -73,8 +73,8 @@ class ViewManagerDataModel::ViewParameterChange : public simVis::View::Callback : Callback(), dataModel_(dataModel) { - // NULL Data model is not supported (doesn't make sense here) - assert(dataModel_ != NULL); + // nullptr Data model is not supported (doesn't make sense here) + assert(dataModel_ != nullptr); } virtual void operator()(simVis::View* view, const EventType& e) { @@ -116,7 +116,7 @@ ViewManagerDataModel::~ViewManagerDataModel() void ViewManagerDataModel::bindTo(simVis::ViewManager* viewManager) { - if (viewManager == NULL) + if (viewManager == nullptr) { unbind(); return; @@ -156,12 +156,12 @@ void ViewManagerDataModel::unbind() userViews_.clear(); viewManager_->removeCallback(viewManagerCB_.get()); - // If old view manager is non-NULL, remove callback + // If old view manager is non-nullptr, remove callback viewManager_->removeCallback(viewManagerCB_.get()); for (unsigned int k = 0; k < viewManager_->getNumViews(); ++k) viewManager_->getView(k)->removeCallback(viewParamCB_.get()); - viewManager_ = NULL; + viewManager_ = nullptr; endResetModel(); } @@ -189,7 +189,7 @@ QModelIndex ViewManagerDataModel::index(int row, int column, const QModelIndex & // Must be an inset view; pull out the view host from "parent" const simVis::View* hostView = viewFromIndex_(parent); - if (hostView == NULL) + if (hostView == nullptr) { return QModelIndex(); } @@ -202,8 +202,8 @@ QModelIndex ViewManagerDataModel::parent(const QModelIndex &child) const if (!child.isValid() || !viewManager_.valid() || !isHierarchical()) return QModelIndex(); const simVis::View* childView = viewFromIndex_(child); - // If view is NULL then there is no parent - if (childView == NULL) + // If view is nullptr then there is no parent + if (childView == nullptr) return QModelIndex(); // Get the first level parent from the child simVis::View* parentView = childView->getHostView(); @@ -223,7 +223,7 @@ int ViewManagerDataModel::rowCount(const QModelIndex &parent) const if (!parent.isValid()) return topLevelViews_.count(); const simVis::View* view = viewFromIndex_(parent); - return view != NULL ? view->getNumInsets() : 0; + return view != nullptr ? view->getNumInsets() : 0; } int ViewManagerDataModel::columnCount(const QModelIndex &parent) const @@ -240,7 +240,7 @@ QVariant ViewManagerDataModel::data(const QModelIndex &index, int role) const { case Qt::DisplayRole: case Qt::EditRole: - if (view != NULL) + if (view != nullptr) { std::string name = view->getName(); if (name.empty() && role == Qt::DisplayRole) @@ -251,7 +251,7 @@ QVariant ViewManagerDataModel::data(const QModelIndex &index, int role) const case Qt::CheckStateRole: // Only show check state for views that are not top level - if (view != NULL && view->getHostView() != NULL && isUserCheckable()) + if (view != nullptr && view->getHostView() != nullptr && isUserCheckable()) return view->isVisible() ? Qt::Checked : Qt::Unchecked; break; @@ -275,7 +275,7 @@ Qt::ItemFlags ViewManagerDataModel::flags(const QModelIndex& index) const const simVis::View* view = viewFromIndex_(index); Qt::ItemFlags flags = Qt::ItemIsEnabled | Qt::ItemIsSelectable; // Only insets can be turned on and off or have its name edited - if (view != NULL && view->getHostView() != NULL && isUserCheckable()) + if (view != nullptr && view->getHostView() != nullptr && isUserCheckable()) flags |= (Qt::ItemIsEditable | Qt::ItemIsUserCheckable); return flags; } @@ -285,12 +285,12 @@ Qt::ItemFlags ViewManagerDataModel::flags(const QModelIndex& index) const bool ViewManagerDataModel::setData(const QModelIndex& index, const QVariant& value, int role) { simVis::View* view = viewFromIndex_(index); - if (!index.isValid() || view == NULL) + if (!index.isValid() || view == nullptr) return QAbstractItemModel::setData(index, value, role); if (role == Qt::EditRole) { - if (view->getHostView() != NULL) + if (view->getHostView() != nullptr) { // Use the trimmed name const std::string trimmed = value.toString().trimmed().toStdString(); @@ -323,7 +323,7 @@ void ViewManagerDataModel::notifyViewRemoved_(simVis::View* view) } // See if it's in the list of top level views and sync if so - if (view->getHostView() == NULL && isHierarchical()) + if (view->getHostView() == nullptr && isHierarchical()) { int idx = topLevelViews_.indexOf(ViewObserverPtr(view)); // Assertion failure means we are out of sync in the list @@ -353,7 +353,7 @@ void ViewManagerDataModel::notifyViewRemoved_(simVis::View* view) QModelIndex ViewManagerDataModel::createIndex_(simVis::View* view) const { - if (view == NULL) + if (view == nullptr) return QModelIndex(); // In flat mode we query the view manager directly if (!isHierarchical()) @@ -361,9 +361,9 @@ QModelIndex ViewManagerDataModel::createIndex_(simVis::View* view) const simVis::View* parent = view->getHostView(); - // Case 1 is that the parent is NULL (e.g. view is top level) + // Case 1 is that the parent is nullptr (e.g. view is top level) int idx = -1; - if (parent == NULL) + if (parent == nullptr) idx = topLevelViews_.indexOf(ViewObserverPtr(view)); else idx = parent->getIndexOfInset(view); @@ -382,7 +382,7 @@ void ViewManagerDataModel::notifyViewAdded_(simVis::View* view) userViews_.push_back(ViewObserverPtr(view)); // Is it top level? If so, sync our topLevelViews_ - if (view->getHostView() == NULL && isHierarchical()) + if (view->getHostView() == nullptr && isHierarchical()) { beginInsertRows(QModelIndex(), topLevelViews_.count(), topLevelViews_.count()); topLevelViews_.push_back(ViewObserverPtr(view)); @@ -451,9 +451,9 @@ simVis::View* ViewManagerDataModel::viewFromIndex_(const QModelIndex& index) con // Non-hierarchical views cannot do the same, because they use begin/endRemoveRows(). // Because of the way View Manager is structured, we can't know exactly which index // was removed, so we instead just do the lookup by index (row) - if (index.internalPointer() != NULL) + if (index.internalPointer() != nullptr) return userViews_.at(index.row()).get(); - return NULL; + return nullptr; } diff --git a/SDK/simQt/ViewManagerDataModel.h b/SDK/simQt/ViewManagerDataModel.h index fdfaafe86..3516ebf16 100644 --- a/SDK/simQt/ViewManagerDataModel.h +++ b/SDK/simQt/ViewManagerDataModel.h @@ -49,7 +49,7 @@ class SDKQT_EXPORT ViewManagerDataModel : public QAbstractItemModel static const int VIEW_ROLE = Qt::UserRole; /** Constructor */ - explicit ViewManagerDataModel(QObject* parent=NULL); + explicit ViewManagerDataModel(QObject* parent=nullptr); virtual ~ViewManagerDataModel(); /// Binds to a given view manager diff --git a/SDK/simQt/ViewWidget.cpp b/SDK/simQt/ViewWidget.cpp index 3d1d36049..ffdd045f6 100644 --- a/SDK/simQt/ViewWidget.cpp +++ b/SDK/simQt/ViewWidget.cpp @@ -25,6 +25,7 @@ * */ #include +#include #include #include "osg/Camera" #include "osg/DisplaySettings" @@ -48,7 +49,7 @@ class ExposedSwapGraphicsWindowQt : public osgQt::GraphicsWindowQt { public: /** Constructor that takes a Traits instance */ - explicit ExposedSwapGraphicsWindowQt(osg::GraphicsContext::Traits* traits, QWidget* parent = NULL, const QGLWidget* shareWidget = NULL, Qt::WindowFlags f = 0) + explicit ExposedSwapGraphicsWindowQt(osg::GraphicsContext::Traits* traits, QWidget* parent = nullptr, const QGLWidget* shareWidget = nullptr, Qt::WindowFlags f = 0) : GraphicsWindowQt(traits, parent, shareWidget, f) { } @@ -69,6 +70,35 @@ class ExposedSwapGraphicsWindowQt : public osgQt::GraphicsWindowQt //////////////////////////////////////////////////////////////// +AutoRepeatFilter::AutoRepeatFilter(QObject* parent) + : QObject(parent), + enabled_(true) +{ +} + +bool AutoRepeatFilter::eventFilter(QObject* obj, QEvent* evt) +{ + if (enabled_ && evt && evt->type() == QEvent::KeyPress) + { + const QKeyEvent* keyEvt = dynamic_cast(evt); + if (keyEvt && keyEvt->isAutoRepeat()) + return true; + } + return QObject::eventFilter(obj, evt); +} + +void AutoRepeatFilter::setEnabled(bool enabled) +{ + enabled_ = enabled; +} + +bool AutoRepeatFilter::isEnabled() const +{ + return enabled_; +} + +//////////////////////////////////////////////////////////////// + ViewWidget::ViewWidget(osgViewer::View* view) : osgQt::GLWidget(simQt::Gl3FormatGuesser::getFormat()) { @@ -84,6 +114,10 @@ ViewWidget::~ViewWidget() void ViewWidget::init_(osgViewer::View* view) { + // Install an event handler to "eat" auto-repeat key events, avoiding keyboard navigation errors + autoRepeatFilter_ = new AutoRepeatFilter(this); + installEventFilter(autoRepeatFilter_); + if (!view) return; @@ -151,4 +185,14 @@ osg::GraphicsContext* ViewWidget::createGraphicsContext_() return new ExposedSwapGraphicsWindowQt(traits.get()); } +void ViewWidget::setAllowAutoRepeatKeys(bool allowAutoRepeat) +{ + autoRepeatFilter_->setEnabled(!allowAutoRepeat); +} + +bool ViewWidget::allowAutoRepeatKeys() const +{ + return !autoRepeatFilter_->isEnabled(); +} + } diff --git a/SDK/simQt/ViewWidget.h b/SDK/simQt/ViewWidget.h index d16d36547..13be36a86 100644 --- a/SDK/simQt/ViewWidget.h +++ b/SDK/simQt/ViewWidget.h @@ -37,6 +37,41 @@ namespace osgViewer { class View; } namespace simQt { +/** + * Filter class that blocks auto-repeat keypress events from reaching the filtered object. This is + * useful for blocking auto-repeat keys from the GLWidget / ViewWidget. osgEarth::EarthManipulator + * can have poor keyboard interaction if the frame rate ever drops under the key autorepeat rate, + * and this filter helps fix that problem. + * + * The following code can be used to install the filter on a widget: + * + * AutoRepeatFilter* filter = new AutoRepeatFilter(viewWidget); + * viewWidget->installEventFilter(filter); + * + * + * Note that this filter is auto-installed on simQt::ViewWidget instances, but is not automatically + * installed on osgQt::GLWidget. So if your application uses osgQt::GLWidget, consider using the filter. + */ +class SDKQT_EXPORT AutoRepeatFilter : public QObject +{ + Q_OBJECT; + +public: + explicit AutoRepeatFilter(QObject* parent = nullptr); + + /** Enables or disables the filtering. If true (default), auto-repeated keys are filtered out. */ + void setEnabled(bool enabled); + /** True if enabled (i.e., auto-repeated keys are filtered out) */ + bool isEnabled() const; + +protected: + // From QObject: + virtual bool eventFilter(QObject* obj, QEvent* evt) override; + +private: + bool enabled_; +}; + /** * A wrapper class to encapsulate an osgViewer::View (such as the simVis::View Main View) in a Qt widget. * @@ -45,6 +80,9 @@ namespace simQt * set the osg::DisplaySettings::instance() values you want before calling the constructor. * * Adapted with permission from deprecated osgEarth::QtGui::ViewerWidget and osgEarth::QtGui::ViewWidget. + * + * Note that this class automatically installs a simQt::AutoRepeatFilter, so your osgGA event handler + * will never report repeated keys from holding down keys. */ class SDKQT_EXPORT ViewWidget : public osgQt::GLWidget { @@ -62,11 +100,18 @@ class SDKQT_EXPORT ViewWidget : public osgQt::GLWidget /** Destructor */ virtual ~ViewWidget(); + /** Enables or disables auto-repeat keyboard events. Set false to disable auto-repeat keys. See simQt::AutoRepeatFilter. */ + void setAllowAutoRepeatKeys(bool allowAutoRepeat); + /** Returns true if auto-repeat keyboard events are enabled. */ + bool allowAutoRepeatKeys() const; + private: /** When widget is wrapping a view, initializes that view to use appropriate graphics context */ void init_(osgViewer::View* view); /** Create a graphics context to associate with OSG Cameras/Views */ osg::GraphicsContext* createGraphicsContext_(); + + AutoRepeatFilter* autoRepeatFilter_; }; } diff --git a/SDK/simQt/WeightedMenuManager.cpp b/SDK/simQt/WeightedMenuManager.cpp index 3b0f578de..ca0c9b366 100644 --- a/SDK/simQt/WeightedMenuManager.cpp +++ b/SDK/simQt/WeightedMenuManager.cpp @@ -66,9 +66,9 @@ static const char* WEIGHTS_PROPERTY = "weights"; WeightedMenuManager::WeightedMenuManager(bool debugMenuWeights) : debugMenuWeights_(debugMenuWeights), - menuBar_(NULL), - toolBar_(NULL), - statusBar_(NULL) + menuBar_(nullptr), + toolBar_(nullptr), + statusBar_(nullptr) { } @@ -84,7 +84,7 @@ QWidget* WeightedMenuManager::topLevelMenu() QMenu* WeightedMenuManager::getOrCreateMenu(QMenu* underMenu, int weight, const QString& menuName) { - if (underMenu == NULL) + if (underMenu == nullptr) return findOrCreateMenu_(topLevelMenu(), weight, menuName); return findOrCreateMenu_(underMenu, weight, menuName); } @@ -96,7 +96,7 @@ void WeightedMenuManager::insertMenuAction(QMenu* menu, int weight, const simQt: void WeightedMenuManager::insertMenuAction(QMenu* menu, int weight, QAction* action) { - if (menu == NULL) + if (menu == nullptr) insertBefore_(topLevelMenu(), weight, action); else insertBefore_(menu, weight, action); @@ -104,8 +104,8 @@ void WeightedMenuManager::insertMenuAction(QMenu* menu, int weight, QAction* act void WeightedMenuManager::insertMenuSeparator(QMenu* menu, int weight) { - QAction* separator = NULL; - if (menu == NULL) + QAction* separator = nullptr; + if (menu == nullptr) insertBefore_(topLevelMenu(), weight, separator); else insertBefore_(menu, weight, separator); @@ -119,7 +119,7 @@ QMenu* WeightedMenuManager::findMenu_(QWidget* parent, const QString& title) con { // Only accept menus in our search (ignore actions) QMenu* topMenu = qobject_cast(*it); - if (topMenu == NULL) + if (topMenu == nullptr) continue; // Figure out the menu title (might be adjusted based on menu weights value) @@ -134,7 +134,7 @@ QMenu* WeightedMenuManager::findMenu_(QWidget* parent, const QString& title) con if (withoutMnemonic_(menuTitle) == title) return topMenu; } - return NULL; + return nullptr; } /** Finds or creates a single menu item under a parent menu bar/menu */ @@ -167,7 +167,7 @@ void WeightedMenuManager::insertSeparator_(QWidget* menuOrToolBar, QAction* befo { // Attempt to insert into a QMenu QMenu* menu = qobject_cast(menuOrToolBar); - if (menu != NULL) + if (menu != nullptr) { menu->insertSeparator(beforeAction); return; @@ -175,7 +175,7 @@ void WeightedMenuManager::insertSeparator_(QWidget* menuOrToolBar, QAction* befo // Attempt to insert into a QToolBar QToolBar* toolbar = qobject_cast(menuOrToolBar); - if (toolbar != NULL) + if (toolbar != nullptr) { toolbar->insertSeparator(beforeAction); return; @@ -190,14 +190,14 @@ QAction* WeightedMenuManager::actionByIndex_(const QWidget* widget, int index) c { const QList actions = widget->actions(); if (index >= actions.size()) - return NULL; + return nullptr; return actions[index]; } // Used to add actions to menus, tool bar, sub-menus, etc. void WeightedMenuManager::insertBefore_(QWidget* widget, int weight, QAction* action) const { - if (widget == NULL) + if (widget == nullptr) return; // Figure out the insert-before based on the weights @@ -208,13 +208,13 @@ void WeightedMenuManager::insertBefore_(QWidget* widget, int weight, QAction* ac QAction* beforeAct = actionByIndex_(widget, std::distance(weights.begin(), insertBefore)); // Add the action to the menu or tool bar - if (action == NULL) + if (action == nullptr) insertSeparator_(widget, beforeAct); else widget->insertAction(beforeAct, action); // Add the new weight to the previous text - if (debugMenuWeights_ && action != NULL) + if (debugMenuWeights_ && action != nullptr) action->setText(QString("%1 %2").arg(weight).arg(action->text())); // Update the weights @@ -227,7 +227,7 @@ void WeightedMenuManager::insertMenu_(QWidget* menuOrBar, QAction* beforeAction, { // QMenu and QMenuBar are not related (enough) and have different routines for inserting menus QMenu* asMenu = qobject_cast(menuOrBar); - if (asMenu != NULL) + if (asMenu != nullptr) { asMenu->insertMenu(beforeAction, menu); return; @@ -235,19 +235,19 @@ void WeightedMenuManager::insertMenu_(QWidget* menuOrBar, QAction* beforeAction, // Attempt with QMenuBar QMenuBar* asMenuBar = qobject_cast(menuOrBar); - if (asMenuBar != NULL) + if (asMenuBar != nullptr) { asMenuBar->insertMenu(beforeAction, menu); return; } // Assertion failure implies that widget is not QMenu and not QMenuBar -- what is it? - assert(asMenuBar != NULL); + assert(asMenuBar != nullptr); } void WeightedMenuManager::insertBefore_(QWidget* menuOrBar, int weight, QMenu* menu) const { - if (menuOrBar == NULL) + if (menuOrBar == nullptr) return; // Figure out the insert-before based on the weights @@ -325,26 +325,26 @@ void WeightedMenuManager::insertToolBarAction(int weight, const simQt::Action* a void WeightedMenuManager::insertToolBarAction(int weight, QAction* action) { - if (toolBar_ == NULL) + if (toolBar_ == nullptr) return; WeightedMenuManager::insertBefore_(toolBar_, weight, action); } void WeightedMenuManager::insertToolBarSeparator(int weight) { - if (toolBar_ == NULL) + if (toolBar_ == nullptr) return; - QAction* separator = NULL; + QAction* separator = nullptr; WeightedMenuManager::insertBefore_(toolBar_, weight, separator); } void WeightedMenuManager::insertWidgetBefore_(QWidget* parentWidget, int weight, QWidget* newWidget) { - if (parentWidget == NULL || newWidget == NULL) + if (parentWidget == nullptr || newWidget == nullptr) return; // Pull out the layout, because that's really what we're working with QBoxLayout* layout = qobject_cast(parentWidget->layout()); - if (layout == NULL) + if (layout == nullptr) return; // Figure out the insert-before based on the weights @@ -366,14 +366,14 @@ void WeightedMenuManager::insertWidgetBefore_(QWidget* parentWidget, int weight, void WeightedMenuManager::insertStatusBarWidget(int weight, QWidget* widget) { - if (statusBar_ == NULL) + if (statusBar_ == nullptr) return; insertWidgetBefore_(statusBar_, weight, widget); } void WeightedMenuManager::insertStatusBarAction(int weight, const simQt::Action* action) { - if (statusBar_ == NULL) + if (statusBar_ == nullptr) return; // Set up a new QToolButton QToolButton* newButton = new QToolButton(statusBar_); @@ -388,10 +388,10 @@ void WeightedMenuManager::insertStatusBarAction(int weight, const simQt::Action* QList WeightedMenuManager::widgetWeights_(QWidget* widget) const { - if (widget == NULL) + if (widget == nullptr) return QList(); const QBoxLayout* layout = qobject_cast(widget->layout()); - if (layout == NULL) + if (layout == nullptr) return QList(); // We store the weights are stored in a named property in the QWidget diff --git a/SDK/simQt/WeightedMenuManager.h b/SDK/simQt/WeightedMenuManager.h index c746a675d..1eb607aae 100644 --- a/SDK/simQt/WeightedMenuManager.h +++ b/SDK/simQt/WeightedMenuManager.h @@ -50,7 +50,7 @@ class SDKQT_EXPORT WeightedMenuManager WeightedMenuManager(bool debugMenuWeights); virtual ~WeightedMenuManager(); - // Set the menu, tool, and status bars to use; may be NULL + // Set the menu, tool, and status bars to use; may be nullptr void setMenuBar(QWidget* menuBar); void setToolBar(QWidget* toolBar); void setStatusBar(QWidget* statusBar); @@ -78,10 +78,7 @@ class SDKQT_EXPORT WeightedMenuManager /** * Returns the top level menu or menu bar (QMenu or QMenuBar) that * is used as the hierarchical parent of created menu items. This - * is the first level for menus. Derived classes should be returning - * either a QMenuBar or QMenu, that can be a parent to new QMenu instances. - * - * NOTE: DEPRECATED. Please use setMenuBar() instead. + * is the first level for menus. */ virtual QWidget* topLevelMenu(); diff --git a/SDK/simQt/WidgetSettings.cpp b/SDK/simQt/WidgetSettings.cpp index 3fe4bb015..452145495 100644 --- a/SDK/simQt/WidgetSettings.cpp +++ b/SDK/simQt/WidgetSettings.cpp @@ -41,7 +41,7 @@ static const QString& SPLITTER_DATA = "/Splitter Data"; void WidgetSettings::saveWidget(simQt::Settings& settings, QWidget* widget) { - if (widget == NULL) + if (widget == nullptr) return; WidgetSettings::saveWindowGeometry_(settings, WINDOWS_SETTINGS, widget); @@ -49,7 +49,7 @@ void WidgetSettings::saveWidget(simQt::Settings& settings, QWidget* widget) void WidgetSettings::loadWidget(simQt::Settings& settings, QWidget* widget) { - if (widget == NULL) + if (widget == nullptr) return; WidgetSettings::loadWindowGeometry_(settings, WINDOWS_SETTINGS, widget); @@ -57,7 +57,7 @@ void WidgetSettings::loadWidget(simQt::Settings& settings, QWidget* widget) int WidgetSettings::saveQSplitter_(simQt::Settings& settings, const QString& path, const QSplitter* splitter) { - if (splitter == NULL) + if (splitter == nullptr) return 1; if (splitter->objectName().isEmpty()) @@ -75,7 +75,7 @@ int WidgetSettings::saveQSplitter_(simQt::Settings& settings, const QString& pat int WidgetSettings::saveQTreeView_(simQt::Settings& settings, const QString& path, const QTreeView* view) { - if (view == NULL) + if (view == nullptr) return 1; if (view->objectName().isEmpty()) @@ -92,7 +92,7 @@ int WidgetSettings::saveQTreeView_(simQt::Settings& settings, const QString& pat { int columns = model->columnCount(); // Ignore the last column if it stretches across - if (view->header() != NULL && view->header()->stretchLastSection()) + if (view->header() != nullptr && view->header()->stretchLastSection()) --columns; if (columns > 0) { @@ -109,7 +109,7 @@ int WidgetSettings::saveQTreeView_(simQt::Settings& settings, const QString& pat int WidgetSettings::saveQColumnView_(simQt::Settings& settings, const QString& path, const QColumnView* view) { - if (view == NULL) + if (view == nullptr) return 1; if (view->objectName().isEmpty()) @@ -129,7 +129,7 @@ int WidgetSettings::saveQColumnView_(simQt::Settings& settings, const QString& p int WidgetSettings::saveQTableView_(simQt::Settings& settings, const QString& path, const QTableView* view) { - if (view == NULL) + if (view == nullptr) return 1; if (view->objectName().isEmpty()) @@ -148,7 +148,7 @@ int WidgetSettings::saveQTableView_(simQt::Settings& settings, const QString& pa { int columns = model->columnCount(); // Ignore the last column if it stretches across - if (view->horizontalHeader() != NULL && view->horizontalHeader()->stretchLastSection()) + if (view->horizontalHeader() != nullptr && view->horizontalHeader()->stretchLastSection()) --columns; if (columns > 0) { @@ -165,7 +165,7 @@ int WidgetSettings::saveQTableView_(simQt::Settings& settings, const QString& pa int WidgetSettings::saveQDialog_(simQt::Settings& settings, const QString& path, const QDialog* dialog) { - if (dialog == NULL) + if (dialog == nullptr) return 1; if (dialog->objectName().isEmpty()) @@ -213,7 +213,7 @@ void WidgetSettings::saveWindowGeometry_(simQt::Settings& settings, const QStrin if (rv != 0) { const QTabWidget* tab = dynamic_cast(object); - if (tab != NULL) + if (tab != nullptr) { for (int ii = 0; ii < tab->count(); ++ii) WidgetSettings::saveWindowGeometry_(settings, newPath + "/", tab->widget(ii)); @@ -228,7 +228,7 @@ void WidgetSettings::saveWindowGeometry_(simQt::Settings& settings, const QStrin int WidgetSettings::loadQSplitter_(simQt::Settings& settings, const QString& path, QSplitter *splitter) { - if (splitter == NULL) + if (splitter == nullptr) return 1; if (splitter->objectName().isEmpty()) @@ -248,7 +248,7 @@ int WidgetSettings::loadQSplitter_(simQt::Settings& settings, const QString& pat int WidgetSettings::loadQTreeView_(simQt::Settings& settings, const QString& path, QTreeView *view) { - if (view == NULL) + if (view == nullptr) return 1; if (view->objectName().isEmpty()) @@ -277,7 +277,7 @@ int WidgetSettings::loadQTreeView_(simQt::Settings& settings, const QString& pat int WidgetSettings::loadQColumnView_(simQt::Settings& settings, const QString& path, QColumnView *view) { - if (view == NULL) + if (view == nullptr) return 1; if (view->objectName().isEmpty()) @@ -297,7 +297,7 @@ int WidgetSettings::loadQColumnView_(simQt::Settings& settings, const QString& p int WidgetSettings::loadQTableView_(simQt::Settings& settings, const QString& path, QTableView *view) { - if (view == NULL) + if (view == nullptr) return 1; if (view->objectName().isEmpty()) @@ -326,7 +326,7 @@ int WidgetSettings::loadQTableView_(simQt::Settings& settings, const QString& pa int WidgetSettings::loadQDialog_(simQt::Settings& settings, const QString& path, QDialog* dialog) { - if (dialog == NULL) + if (dialog == nullptr) return 1; if (dialog->objectName().isEmpty()) @@ -386,7 +386,7 @@ void WidgetSettings::loadWindowGeometry_(simQt::Settings& settings, const QStrin if (rv != 0) { const QTabWidget* tab = dynamic_cast(object); - if (tab != NULL) + if (tab != nullptr) { for (int ii = 0; ii < tab->count(); ++ii) WidgetSettings::loadWindowGeometry_(settings, newPath + "/", tab->widget(ii)); diff --git a/SDK/simQt/WidgetSettings.h b/SDK/simQt/WidgetSettings.h index d7f01b386..6aa502d97 100644 --- a/SDK/simQt/WidgetSettings.h +++ b/SDK/simQt/WidgetSettings.h @@ -75,28 +75,28 @@ class SDKQT_EXPORT WidgetSettings static void loadWidget(simQt::Settings& settings, QWidget* widget); private: - /// Saves splitter info at the specified path; returns 0 if splitter is non-NULL and 1 if someone else needs to process it + /// Saves splitter info at the specified path; returns 0 if splitter is non-nullptr and 1 if someone else needs to process it static int saveQSplitter_(simQt::Settings& settings, const QString& path, const QSplitter *splitter); - /// Saves tree view info at the specified path; returns 0 if view is non-NULL and 1 if someone else needs to process it + /// Saves tree view info at the specified path; returns 0 if view is non-nullptr and 1 if someone else needs to process it static int saveQTreeView_(simQt::Settings& settings, const QString& path, const QTreeView *view); - /// Saves column view info at the specified path; returns 0 if view is non-NULL and 1 if someone else needs to process it + /// Saves column view info at the specified path; returns 0 if view is non-nullptr and 1 if someone else needs to process it static int saveQColumnView_(simQt::Settings& settings, const QString& path, const QColumnView *view); - /// Saves table view info at the specified path; returns 0 if view is non-NULL and 1 if someone else needs to process it + /// Saves table view info at the specified path; returns 0 if view is non-nullptr and 1 if someone else needs to process it static int saveQTableView_(simQt::Settings& settings, const QString& path, const QTableView *view); - /// Saves dialog info at the specified path; returns 0 if dialog is non-NULL and 1 if someone else needs to process it + /// Saves dialog info at the specified path; returns 0 if dialog is non-nullptr and 1 if someone else needs to process it static int saveQDialog_(simQt::Settings& settings, const QString& path, const QDialog* dialog); /// Recursively searches object for savable widgets and stores the info starting at path static void saveWindowGeometry_(simQt::Settings& settings, const QString& path, const QObject *object); - /// Loads splitter info from the specified path; returns 0 if splitter is non-NULL and 1 if someone else needs to process it + /// Loads splitter info from the specified path; returns 0 if splitter is non-nullptr and 1 if someone else needs to process it static int loadQSplitter_(simQt::Settings& settings, const QString& path, QSplitter *splitter); - /// Loads tree view info from the specified path; returns 0 if view is non-NULL and 1 if someone else needs to process it + /// Loads tree view info from the specified path; returns 0 if view is non-nullptr and 1 if someone else needs to process it static int loadQTreeView_(simQt::Settings& settings, const QString& path, QTreeView *view); - /// Loads column view info from the specified path; returns 0 if view is non-NULL and 1 if someone else needs to process it + /// Loads column view info from the specified path; returns 0 if view is non-nullptr and 1 if someone else needs to process it static int loadQColumnView_(simQt::Settings& settings, const QString& path, QColumnView *view); - /// Loads table view info from the specified path; returns 0 if view is non-NULL and 1 if someone else needs to process it + /// Loads table view info from the specified path; returns 0 if view is non-nullptr and 1 if someone else needs to process it static int loadQTableView_(simQt::Settings& settings, const QString& path, QTableView *view); - /// Loads dialog info from the specified path; returns 0 if dialog is non-NULL and 1 if someone else needs to process it + /// Loads dialog info from the specified path; returns 0 if dialog is non-nullptr and 1 if someone else needs to process it static int loadQDialog_(simQt::Settings& settings, const QString& path, QDialog* dialog); /// Recursively searches object for loadable widgets and gets the info starting at path static void loadWindowGeometry_(simQt::Settings& settings, const QString& path, QObject *object); diff --git a/SDK/simUtil/Capabilities.cpp b/SDK/simUtil/Capabilities.cpp index 12f862383..f5d0c64f7 100644 --- a/SDK/simUtil/Capabilities.cpp +++ b/SDK/simUtil/Capabilities.cpp @@ -162,7 +162,7 @@ void Capabilities::init_() void Capabilities::init_(osg::GraphicsContext& gc) { - osg::GLExtensions* ext = NULL; + osg::GLExtensions* ext = nullptr; if (gc.makeCurrent() && gc.getState()) ext = osg::GLExtensions::Get(gc.getState()->getContextID(), true); diff --git a/SDK/simUtil/DataStoreTestHelper.cpp b/SDK/simUtil/DataStoreTestHelper.cpp index 32c12cbc1..1b810e357 100644 --- a/SDK/simUtil/DataStoreTestHelper.cpp +++ b/SDK/simUtil/DataStoreTestHelper.cpp @@ -165,7 +165,7 @@ void DataStoreTestHelper::updatePlatformPrefs(const simData::PlatformPrefs& pref { simData::DataStore::Transaction t; simData::PlatformPrefs* p = dataStore_->mutable_platformPrefs(id, &t); - SDK_ASSERT(p != NULL); + SDK_ASSERT(p != nullptr); p->MergeFrom(prefs); t.commit(); } @@ -174,7 +174,7 @@ void DataStoreTestHelper::updateBeamPrefs(const simData::BeamPrefs& prefs, uint6 { simData::DataStore::Transaction t; simData::BeamPrefs* p = dataStore_->mutable_beamPrefs(id, &t); - SDK_ASSERT(p != NULL); + SDK_ASSERT(p != nullptr); p->MergeFrom(prefs); t.commit(); } @@ -183,7 +183,7 @@ void DataStoreTestHelper::updateGatePrefs(const simData::GatePrefs& prefs, uint6 { simData::DataStore::Transaction t; simData::GatePrefs* p = dataStore_->mutable_gatePrefs(id, &t); - SDK_ASSERT(p != NULL); + SDK_ASSERT(p != nullptr); p->MergeFrom(prefs); t.commit(); } @@ -192,7 +192,7 @@ void DataStoreTestHelper::updateLaserPrefs(const simData::LaserPrefs& prefs, uin { simData::DataStore::Transaction t; simData::LaserPrefs* p = dataStore_->mutable_laserPrefs(id, &t); - SDK_ASSERT(p != NULL); + SDK_ASSERT(p != nullptr); p->MergeFrom(prefs); t.commit(); } @@ -201,7 +201,7 @@ void DataStoreTestHelper::updateLOBPrefs(const simData::LobGroupPrefs& prefs, ui { simData::DataStore::Transaction t; simData::LobGroupPrefs* p = dataStore_->mutable_lobGroupPrefs(id, &t); - SDK_ASSERT(p != NULL); + SDK_ASSERT(p != nullptr); p->MergeFrom(prefs); t.commit(); } @@ -210,7 +210,7 @@ void DataStoreTestHelper::updateProjectorPrefs(const simData::ProjectorPrefs& pr { simData::DataStore::Transaction t; simData::ProjectorPrefs* p = dataStore_->mutable_projectorPrefs(id, &t); - SDK_ASSERT(p != NULL); + SDK_ASSERT(p != nullptr); p->MergeFrom(prefs); t.commit(); } @@ -219,7 +219,7 @@ void DataStoreTestHelper::addPlatformUpdate(double time, uint64_t id) { simData::DataStore::Transaction t; simData::PlatformUpdate *u = dataStore_->addPlatformUpdate(id, &t); - SDK_ASSERT(u != NULL); + SDK_ASSERT(u != nullptr); u->set_time(time); u->set_x(0.0 + time); u->set_y(1.0 + time); @@ -231,7 +231,7 @@ void DataStoreTestHelper::addBeamUpdate(double time, uint64_t id) { simData::DataStore::Transaction t; simData::BeamUpdate *u = dataStore_->addBeamUpdate(id, &t); - SDK_ASSERT(u != NULL); + SDK_ASSERT(u != nullptr); u->set_time(time); u->set_azimuth(0.0 + time); u->set_elevation(1.0 + time); @@ -243,7 +243,7 @@ void DataStoreTestHelper::addGateUpdate(double time, uint64_t id) { simData::DataStore::Transaction t; simData::GateUpdate *u = dataStore_->addGateUpdate(id, &t); - SDK_ASSERT(u != NULL); + SDK_ASSERT(u != nullptr); u->set_time(time); u->set_azimuth(0.0 + time); u->set_elevation(1.0 + time); @@ -255,7 +255,7 @@ void DataStoreTestHelper::addLaserUpdate(double time, uint64_t id) { simData::DataStore::Transaction t; simData::LaserUpdate *u = dataStore_->addLaserUpdate(id, &t); - SDK_ASSERT(u != NULL); + SDK_ASSERT(u != nullptr); u->set_time(time); u->mutable_orientation()->set_yaw(0.0 + time); u->mutable_orientation()->set_pitch(1.0 + time); @@ -267,7 +267,7 @@ void DataStoreTestHelper::addLOBUpdate(double time, uint64_t id) { simData::DataStore::Transaction t; simData::LobGroupUpdate *u = dataStore_->addLobGroupUpdate(id, &t); - SDK_ASSERT(u != NULL); + SDK_ASSERT(u != nullptr); u->set_time(time); simData::LobGroupUpdatePoint *up = u->mutable_datapoints()->Add(); up->set_time(time); @@ -286,7 +286,7 @@ void DataStoreTestHelper::addProjectorUpdate(double time, uint64_t id) { simData::DataStore::Transaction t; simData::ProjectorUpdate *u = dataStore_->addProjectorUpdate(id, &t); - SDK_ASSERT(u != NULL); + SDK_ASSERT(u != nullptr); u->set_time(time); u->set_fov(1.0 + time); t.commit(); @@ -296,7 +296,7 @@ void DataStoreTestHelper::addPlatformCommand(const simData::PlatformCommand& com { simData::DataStore::Transaction t; simData::PlatformCommand *c = dataStore_->addPlatformCommand(id, &t); - SDK_ASSERT(c != NULL); + SDK_ASSERT(c != nullptr); c->MergeFrom(command); t.commit(); } @@ -305,7 +305,7 @@ void DataStoreTestHelper::addBeamCommand(const simData::BeamCommand& command, ui { simData::DataStore::Transaction t; simData::BeamCommand *c = dataStore_->addBeamCommand(id, &t); - SDK_ASSERT(c != NULL); + SDK_ASSERT(c != nullptr); c->MergeFrom(command); t.commit(); } @@ -314,7 +314,7 @@ void DataStoreTestHelper::addGateCommand(const simData::GateCommand& command, ui { simData::DataStore::Transaction t; simData::GateCommand *c = dataStore_->addGateCommand(id, &t); - SDK_ASSERT(c != NULL); + SDK_ASSERT(c != nullptr); c->MergeFrom(command); t.commit(); } @@ -323,7 +323,7 @@ void DataStoreTestHelper::addLaserCommand(const simData::LaserCommand& command, { simData::DataStore::Transaction t; simData::LaserCommand *c = dataStore_->addLaserCommand(id, &t); - SDK_ASSERT(c != NULL); + SDK_ASSERT(c != nullptr); c->MergeFrom(command); t.commit(); } @@ -332,7 +332,7 @@ void DataStoreTestHelper::addLOBCommand(const simData::LobGroupCommand& command, { simData::DataStore::Transaction t; simData::LobGroupCommand *c = dataStore_->addLobGroupCommand(id, &t); - SDK_ASSERT(c != NULL); + SDK_ASSERT(c != nullptr); c->MergeFrom(command); t.commit(); } @@ -341,7 +341,7 @@ void DataStoreTestHelper::addProjectorCommand(const simData::ProjectorCommand& c { simData::DataStore::Transaction t; simData::ProjectorCommand *c = dataStore_->addProjectorCommand(id, &t); - SDK_ASSERT(c != NULL); + SDK_ASSERT(c != nullptr); c->MergeFrom(command); t.commit(); } @@ -350,8 +350,8 @@ void DataStoreTestHelper::addCategoryData(uint64_t id, const std::string& key, c { simData::DataStore::Transaction transaction; simData::CategoryData* catData = dataStore_->addCategoryData(id, &transaction); - SDK_ASSERT(catData != NULL); - if (catData == NULL) + SDK_ASSERT(catData != nullptr); + if (catData == nullptr) return; catData->set_time(startTime); @@ -367,8 +367,8 @@ void DataStoreTestHelper::addGenericData(uint64_t id, const std::string& key, co { simData::DataStore::Transaction transaction; simData::GenericData* genData = dataStore_->addGenericData(id, &transaction); - SDK_ASSERT(genData != NULL); - if (genData == NULL) + SDK_ASSERT(genData != nullptr); + if (genData == nullptr) return; genData->set_time(static_cast(startTime)); @@ -401,10 +401,10 @@ void DataStoreTestHelper::addDataTable(uint64_t entityId, int numRows, const std void DataStoreTestHelper::addDataTableRows_(simData::DataTable* table, int numRows, uint64_t id) { // now add 4 columns - simData::TableColumn* column1 = NULL; - simData::TableColumn* column2 = NULL; - simData::TableColumn* column3 = NULL; - simData::TableColumn* column4 = NULL; + simData::TableColumn* column1 = nullptr; + simData::TableColumn* column2 = nullptr; + simData::TableColumn* column3 = nullptr; + simData::TableColumn* column4 = nullptr; for (int i = 0; i < 4; i++) { std::ostringstream os; diff --git a/SDK/simUtil/DataStoreTestHelper.h b/SDK/simUtil/DataStoreTestHelper.h index 3e647995b..ca5853052 100644 --- a/SDK/simUtil/DataStoreTestHelper.h +++ b/SDK/simUtil/DataStoreTestHelper.h @@ -41,7 +41,7 @@ class SDKUTIL_EXPORT DataStoreTestHelper { public: /** Will create a data store if none is passed in; passed-in memory still belongs to caller */ - DataStoreTestHelper(simData::DataStore* dataStore = NULL); + DataStoreTestHelper(simData::DataStore* dataStore = nullptr); /** Deletes data store if data store was created inside constructor */ virtual ~DataStoreTestHelper(); diff --git a/SDK/simUtil/DatumConvert.cpp b/SDK/simUtil/DatumConvert.cpp index afeabb1c8..aa0525d37 100644 --- a/SDK/simUtil/DatumConvert.cpp +++ b/SDK/simUtil/DatumConvert.cpp @@ -39,7 +39,7 @@ DatumConvert::DatumConvert() DatumConvert::~DatumConvert() { delete wmm_; - wmm_ = NULL; + wmm_ = nullptr; } double DatumConvert::convertMagneticDatum(const simCore::Vec3& lla, const simCore::TimeStamp& timeStamp, double bearingRad, @@ -124,7 +124,7 @@ double DatumConvert::convertVerticalDatum(const simCore::Vec3& lla, const simCor // Convert the meters value to the MSL value double altitude = osgEarth::Units::METERS.convertTo(msl->getUnits(), wgs84Altitude); // Save the transformed coordinate to wgs84Altitude - if (osgEarth::VerticalDatum::transform(msl.get(), NULL, lla.lat() * simCore::RAD2DEG, lla.lon() * simCore::RAD2DEG, altitude)) + if (osgEarth::VerticalDatum::transform(msl.get(), nullptr, lla.lat() * simCore::RAD2DEG, lla.lon() * simCore::RAD2DEG, altitude)) { wgs84Altitude = altitude; } @@ -137,7 +137,7 @@ double DatumConvert::convertVerticalDatum(const simCore::Vec3& lla, const simCor else if (outputDatum == simCore::VERTDATUM_MSL && msl.valid()) { // Convert the wgs84 altitude (meters) to MSL (MSL units) - if (osgEarth::VerticalDatum::transform(NULL, msl.get(), lla.lat() * simCore::RAD2DEG, lla.lon() * simCore::RAD2DEG, outputAltitude)) + if (osgEarth::VerticalDatum::transform(nullptr, msl.get(), lla.lat() * simCore::RAD2DEG, lla.lon() * simCore::RAD2DEG, outputAltitude)) { // Convert back from MSL units to meters outputAltitude = msl->getUnits().convertTo(osgEarth::Units::METERS, outputAltitude); diff --git a/SDK/simUtil/DbConfigurationFile.cpp b/SDK/simUtil/DbConfigurationFile.cpp index d9e5f3c48..390699394 100644 --- a/SDK/simUtil/DbConfigurationFile.cpp +++ b/SDK/simUtil/DbConfigurationFile.cpp @@ -81,7 +81,7 @@ int DbConfigurationFile::load(osg::ref_ptr& mapNode, const st { SIM_ERROR << "Could not resolve filename " << configFile << "\n"; } - mapNode = NULL; + mapNode = nullptr; return 1; } @@ -89,7 +89,7 @@ int DbConfigurationFile::load(osg::ref_ptr& mapNode, const st // is this a .earth file? if (osgDB::getFileExtensionIncludingDot(configFile) == earthFileSuffix) { - mapNode = NULL; + mapNode = nullptr; SAFETRYBEGIN; // Load the map, wrap Node in a ref_ptr to get rid of the memory when done, after switching to Viewer::setMap method @@ -103,7 +103,7 @@ int DbConfigurationFile::load(osg::ref_ptr& mapNode, const st } else // probably a SIMDIS 9 config file { - mapNode = NULL; + mapNode = nullptr; SAFETRYBEGIN; osg::ref_ptr map = simUtil::DbConfigurationFile::loadLegacyConfigFile(adjustedConfigFile, quiet); if (map.valid()) @@ -126,7 +126,7 @@ int DbConfigurationFile::load(osg::ref_ptr& mapNode, const st } // set the map's name - if (mapNode->getMap() != NULL) + if (mapNode->getMap() != nullptr) mapNode->getMap()->setMapName(osgDB::getSimpleFileName(adjustedConfigFile)); return 0; } @@ -149,7 +149,7 @@ osgEarth::Map* DbConfigurationFile::loadLegacyConfigFile(const std::string& file { SIM_ERROR << "Unable to open file (" << filename << ").\n"; } - return NULL; + return nullptr; } std::string sdTerrainDirStr; @@ -157,8 +157,8 @@ osgEarth::Map* DbConfigurationFile::loadLegacyConfigFile(const std::string& file if (configFilename.find("/") != std::string::npos) sdTerrainDirStr = configFilename.substr(0, configFilename.rfind("/") + 1); - // Configure a NULL map at first - osgEarth::Map* map = NULL; + // Configure a nullptr map at first + osgEarth::Map* map = nullptr; // set up names for the loaded layers int imageLayerCount = 1; @@ -188,8 +188,8 @@ osgEarth::Map* DbConfigurationFile::loadLegacyConfigFile(const std::string& file if (!gotValidFirstLine) { // Programming error if assert fires; indicates memory leak - assert(map == NULL); - return NULL; + assert(map == nullptr); + return nullptr; } continue; } @@ -504,7 +504,7 @@ osg::Node* DbConfigurationFile::readEarthFile(std::istream& istream, const std:: { osg::ref_ptr readWrite = osgDB::Registry::instance()->getReaderWriterForExtension("earth"); if (!readWrite.valid()) - return NULL; + return nullptr; osg::ref_ptr dbOptions = new osgDB::Options(); dbOptions->setDatabasePath(relativeTo); @@ -527,7 +527,7 @@ osg::Node* DbConfigurationFile::readEarthFile(const std::string& filename) { std::fstream istream(filename.c_str(), std::ios::in); if (!istream) - return NULL; + return nullptr; return DbConfigurationFile::readEarthFile(istream, filename); } diff --git a/SDK/simUtil/DbConfigurationFile.h b/SDK/simUtil/DbConfigurationFile.h index 8fa9f0980..8ba07867a 100644 --- a/SDK/simUtil/DbConfigurationFile.h +++ b/SDK/simUtil/DbConfigurationFile.h @@ -67,7 +67,7 @@ class SDKUTIL_EXPORT DbConfigurationFile * of load() that is only able to load legacy SIMDIS 9 files. * @param filename Full path to the configuration file to load (e.g. configDefault.txt) * @param quiet If false, errors and warnings are not reported using SIM_NOTIFY. - * @return NULL on inability to load. Else returns a newly allocated osgEarth::Map. + * @return nullptr on inability to load. Else returns a newly allocated osgEarth::Map. * Remember to wrap the return value in an osg::ref_ptr. */ static osgEarth::Map* loadLegacyConfigFile(const std::string& filename, bool quiet=false); @@ -86,7 +86,7 @@ class SDKUTIL_EXPORT DbConfigurationFile * @param filename Name of the file resource to load (should end in .earth). Expected * to be fully adjusted, e.g. using DbConfigurationFile::resolveFilePath(). Will * be passed as-is to osgDB::readNodeFile(). - * @return NULL on error, else newly allocated node from osgDB::readNodeFile() with default earth options + * @return nullptr on error, else newly allocated node from osgDB::readNodeFile() with default earth options */ static osg::Node* readEarthFile(const std::string& filename); @@ -96,7 +96,7 @@ class SDKUTIL_EXPORT DbConfigurationFile * @param istream Input stream holding the .earth file contents * @param relativeTo Absolute path to a location used to help resolve relative paths. Sometimes called "referrer", * or the Database Path in OSG parlance. - * @return NULL on error, else newly allocated node from osgDB::ReaderWriter for earth files + * @return nullptr on error, else newly allocated node from osgDB::ReaderWriter for earth files */ static osg::Node* readEarthFile(std::istream& istream, const std::string& relativeTo); diff --git a/SDK/simUtil/DynamicSelectionPicker.cpp b/SDK/simUtil/DynamicSelectionPicker.cpp index 952013ebb..5a34da13c 100644 --- a/SDK/simUtil/DynamicSelectionPicker.cpp +++ b/SDK/simUtil/DynamicSelectionPicker.cpp @@ -139,7 +139,7 @@ void DynamicSelectionPicker::pickThisFrame_() const double maximumValidRangeSquared = osg::square(maximumValidRange_); double closestRangePx = maximumValidRangeSquared; const double platformAdvantageSquared = osg::square(maximumValidRange_ * platformAdvantagePct_); - simVis::EntityNode* closest = NULL; + simVis::EntityNode* closest = nullptr; // Loop through all entities for (auto i = allEntities.begin(); i != allEntities.end(); ++i) @@ -153,7 +153,7 @@ void DynamicSelectionPicker::pickThisFrame_() continue; // Platforms get a small advantage in picking, so that it's easier to pick platforms than other entities - const bool isPlatform = (dynamic_cast(i->get()) != NULL); + const bool isPlatform = (dynamic_cast(i->get()) != nullptr); // Do not apply the advantage if platform is not already inside the picking area if (isPlatform && rangeSquared < maximumValidRangeSquared) rangeSquared -= platformAdvantageSquared; @@ -175,8 +175,8 @@ void DynamicSelectionPicker::pickThisFrame_() bool DynamicSelectionPicker::isPickable_(const simVis::EntityNode* entityNode) const { - // Avoid NULL and things that don't match the mask - if (entityNode == NULL || (entityNode->getNodeMask() & pickMask_) == 0) + // Avoid nullptr and things that don't match the mask + if (entityNode == nullptr || (entityNode->getNodeMask() & pickMask_) == 0) return false; // Only pick entities with object index tags if (entityNode->objectIndexTag() == 0) diff --git a/SDK/simUtil/ExampleControls.cpp b/SDK/simUtil/ExampleControls.cpp index dd9f47d52..335b718ab 100644 --- a/SDK/simUtil/ExampleControls.cpp +++ b/SDK/simUtil/ExampleControls.cpp @@ -40,14 +40,14 @@ namespace { struct PlatformListData { - PlatformListData() : selected_(NULL) { } + PlatformListData() : selected_(nullptr) { } Control* selected_; std::map labelsById_; }; struct BeamListData { - BeamListData() : selected_(NULL) { } + BeamListData() : selected_(nullptr) { } Control* selected_; }; @@ -81,8 +81,8 @@ namespace if (data_->selected_) data_->selected_->clearBackColor(); - view_->tetherCamera(NULL); - data_->selected_ = NULL; + view_->tetherCamera(nullptr); + data_->selected_ = nullptr; } simVis::View* view_; PlatformListData* data_; diff --git a/SDK/simUtil/ExampleResources.cpp b/SDK/simUtil/ExampleResources.cpp index 31dc83e47..f6e4dce29 100644 --- a/SDK/simUtil/ExampleResources.cpp +++ b/SDK/simUtil/ExampleResources.cpp @@ -139,7 +139,7 @@ Map* simExamples::createHawaiiTMSMap() if (node.valid() && dynamic_cast(node.get())) map = dynamic_cast(node.get())->getMap(); - node = NULL; + node = nullptr; return map.release(); } @@ -430,7 +430,7 @@ void simExamples::SkyNodeTimeUpdater::setSceneManager(simVis::SceneManager* mgr) void simExamples::SkyNodeTimeUpdater::onSetTime(const simCore::TimeStamp &t, bool isJump) { lastTime_ = t; - if (sceneManager_.valid() && sceneManager_->getSkyNode() != NULL) + if (sceneManager_.valid() && sceneManager_->getSkyNode() != nullptr) { sceneManager_->getSkyNode()->setDateTime(osgEarth::DateTime(t.secondsSinceRefYear(1970) + simCore::Seconds(hoursOffset_ * simCore::SECPERHOUR))); } diff --git a/SDK/simUtil/ExampleResources.h b/SDK/simUtil/ExampleResources.h index 6f3f060a6..13cd2b4ec 100644 --- a/SDK/simUtil/ExampleResources.h +++ b/SDK/simUtil/ExampleResources.h @@ -143,7 +143,7 @@ namespace simExamples { public: /** Constructor */ - SkyNodeTimeUpdater(simVis::SceneManager* mgr=NULL); + SkyNodeTimeUpdater(simVis::SceneManager* mgr=nullptr); /** Changes the scene manager */ void setSceneManager(simVis::SceneManager* mgr); /** Update the scene manager's sky node with current clock time */ diff --git a/SDK/simUtil/GridTransform.cpp b/SDK/simUtil/GridTransform.cpp index c3e9767fd..c916e0c3a 100644 --- a/SDK/simUtil/GridTransform.cpp +++ b/SDK/simUtil/GridTransform.cpp @@ -385,17 +385,17 @@ const GridCell* GridTransform::childAt(int row, int column) const if (fixedByColumns_) { if (column < 0 || column >= userNum_) - return NULL; + return nullptr; const int idx = column + userNum_ * row; if (idx >= static_cast(getNumChildren())) - return NULL; + return nullptr; return dynamic_cast(getChild(idx)); } if (row < 0 || row >= userNum_) - return NULL; + return nullptr; const int idx = row + userNum_ * column; if (idx >= static_cast(getNumChildren())) - return NULL; + return nullptr; return dynamic_cast(getChild(idx)); } @@ -404,17 +404,17 @@ GridCell* GridTransform::childAt(int row, int column) if (fixedByColumns_) { if (column < 0 || column >= userNum_) - return NULL; + return nullptr; const int idx = column + userNum_ * row; if (idx >= static_cast(getNumChildren())) - return NULL; + return nullptr; return dynamic_cast(getChild(idx)); } if (row < 0 || row >= userNum_) - return NULL; + return nullptr; const int idx = row + userNum_ * column; if (idx >= static_cast(getNumChildren())) - return NULL; + return nullptr; return dynamic_cast(getChild(idx)); } @@ -472,7 +472,7 @@ int GridTransform::getDefaultWidth() const { // Skip child if it's not visible const GridCell* node = dynamic_cast(getChild(idx)); - if (node == NULL || node->getNodeMask() == 0) + if (node == nullptr || node->getNodeMask() == 0) continue; // Get the current cell width @@ -520,7 +520,7 @@ int GridTransform::getDefaultHeight() const { // Skip child if it's not visible const GridCell* node = dynamic_cast(getChild(idx)); - if (node == NULL || node->getNodeMask() == 0) + if (node == nullptr || node->getNodeMask() == 0) continue; // Get the current cell height @@ -587,7 +587,7 @@ float GridTransform::maxChildWidth_() const { // Skip child if it's not visible const GridCell* node = dynamic_cast(getChild(idx)); - if (node == NULL || node->getNodeMask() == 0) + if (node == nullptr || node->getNodeMask() == 0) continue; if (node->fixedWidth()) width = simCore::sdkMax(node->width(), width); @@ -605,7 +605,7 @@ float GridTransform::maxChildHeight_() const { // Skip child if it's not visible const GridCell* node = dynamic_cast(getChild(idx)); - if (node == NULL || node->getNodeMask() == 0) + if (node == nullptr || node->getNodeMask() == 0) continue; if (node->fixedHeight()) height = simCore::sdkMax(node->height(), height); @@ -685,7 +685,7 @@ void GridTransform::doLayout_() { // Skip child if it's not visible GridCell* node = dynamic_cast(getChild(idx)); - if (node == NULL || node->getNodeMask() == 0) + if (node == nullptr || node->getNodeMask() == 0) continue; // Figure out what our row/column is @@ -851,7 +851,7 @@ void GridTransform::doLayout_() { // Skip child if it's not visible GridCell* node = dynamic_cast(getChild(idx)); - if (node == NULL || node->getNodeMask() == 0) + if (node == nullptr || node->getNodeMask() == 0) continue; // Figure out what our row/column is diff --git a/SDK/simUtil/GridTransform.h b/SDK/simUtil/GridTransform.h index dfcab9357..8ff91e1a6 100644 --- a/SDK/simUtil/GridTransform.h +++ b/SDK/simUtil/GridTransform.h @@ -245,9 +245,9 @@ class SDKUTIL_EXPORT GridTransform : public osg::MatrixTransform int rowOfChild(const GridCell* item) const; /** Returns -1 if child not found */ int columnOfChild(const GridCell* item) const; - /** Returns child at index, or NULL if none */ + /** Returns child at index, or nullptr if none */ const GridCell* childAt(int row, int column) const; - /** Returns child at index, or NULL if none */ + /** Returns child at index, or nullptr if none */ GridCell* childAt(int row, int column); /** Override to update layout */ diff --git a/SDK/simUtil/HudManager.cpp b/SDK/simUtil/HudManager.cpp index d0fb71694..744687e84 100644 --- a/SDK/simUtil/HudManager.cpp +++ b/SDK/simUtil/HudManager.cpp @@ -484,15 +484,15 @@ class HudManager::ResizeHandler : public osgGA::GUIEventHandler /** Checks for resize events */ bool virtual handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa, osg::Object*, osg::NodeVisitor*) { - if (manager_ == NULL) + if (manager_ == nullptr) return false; // this handler does not (always?) receive RESIZE events, so check it manually. if (ea.getEventType() == osgGA::GUIEventAdapter::FRAME) { const osg::View* view = aa.asView(); - const osg::Camera* camera = (view) ? view->getCamera() : NULL; - const osg::Viewport* viewport = (camera) ? camera->getViewport() : NULL; + const osg::Camera* camera = (view) ? view->getCamera() : nullptr; + const osg::Viewport* viewport = (camera) ? camera->getViewport() : nullptr; if (viewport) { int width = static_cast(viewport->width()); @@ -777,13 +777,13 @@ void HudRowText::positionText_(int index, osgText::Text* text) float width = 0.f; osgText::Font* font = const_cast(text->getFont()); // Assertion failure means we don't have a font yet - assert(font != NULL); + assert(font != nullptr); if (!font) return; for (osgText::String::const_iterator i = text->getText().begin(); i != text->getText().end(); ++i) { osgText::Glyph* glyph = font->getGlyph(osgText::FontResolution(text->getFontWidth(), text->getFontHeight()), *i); - if (glyph != NULL) + if (glyph != nullptr) width += glyph->getHorizontalAdvance(); } diff --git a/SDK/simUtil/HudPositionEditor.cpp b/SDK/simUtil/HudPositionEditor.cpp index c81eb9084..ea7391290 100644 --- a/SDK/simUtil/HudPositionEditor.cpp +++ b/SDK/simUtil/HudPositionEditor.cpp @@ -318,7 +318,7 @@ void HudEditorGui::updatePosition(const std::string& windowName) // Get or create the window pointer auto i = windows_.find(windowName); - WindowNodePx* window = NULL; + WindowNodePx* window = nullptr; if (i == windows_.end()) { // Pull out size parameters; they're required on creation @@ -338,7 +338,7 @@ void HudEditorGui::updatePosition(const std::string& windowName) else window = i->second.get(); - // Should not be possible to be NULL here + // Should not be possible to be nullptr here assert(window); if (!window) return; @@ -376,10 +376,10 @@ void HudEditorGui::traverse(osg::NodeVisitor& nv) { // Pull out the View and deal with resize events osgGA::EventVisitor* ev = nv.asEventVisitor(); - osgGA::GUIActionAdapter* aa = (ev ? ev->getActionAdapter() : NULL); - const osg::View* view = (aa ? aa->asView() : NULL); - const osg::Camera* camera = (view ? view->getCamera() : NULL); - const osg::Viewport* viewport = (camera ? camera->getViewport() : NULL); + osgGA::GUIActionAdapter* aa = (ev ? ev->getActionAdapter() : nullptr); + const osg::View* view = (aa ? aa->asView() : nullptr); + const osg::Camera* camera = (view ? view->getCamera() : nullptr); + const osg::Viewport* viewport = (camera ? camera->getViewport() : nullptr); // Determine if resize happened (we can't rely on resize events, they don't always include right size) if (viewport) diff --git a/SDK/simUtil/HudPositionManager.cpp b/SDK/simUtil/HudPositionManager.cpp index b6c4743c4..6235510af 100644 --- a/SDK/simUtil/HudPositionManager.cpp +++ b/SDK/simUtil/HudPositionManager.cpp @@ -117,7 +117,7 @@ HudPositionManager::~HudPositionManager() void HudPositionManager::addWindow(const std::string& name, const osg::Vec2d& defaultPositionPct, RepositionCallback* reposCallback) { // Assertion failure means other asserts in the code will fail due to unexpected precondition - assert(reposCallback != NULL); + assert(reposCallback != nullptr); auto i = allWindows_.find(name); @@ -137,7 +137,7 @@ void HudPositionManager::addWindow(const std::string& name, const osg::Vec2d& de // cases where we will eventually expect that the WindowData* exists, but has // no callback, due to being removed or due to being loaded with a position // "externally" such as through a settings file. - assert(i->second->repositionCallback() == NULL); + assert(i->second->repositionCallback() == nullptr); // It is not necessarily an error to add a window that exists already. Just update // the reposition callback, but don't bother setting the position, because we already @@ -160,8 +160,8 @@ int HudPositionManager::removeWindow(const std::string& name) if (i == allWindows_.end()) return 1; // Assertion failure means removal of a window that was already removed - assert(i->second->repositionCallback() != NULL); - i->second->setRepositionCallback(NULL); + assert(i->second->repositionCallback() != nullptr); + i->second->setRepositionCallback(nullptr); return 0; } @@ -210,7 +210,7 @@ int HudPositionManager::getAllWindows(std::vector& names, bool acti for (auto i = allWindows_.begin(); i != allWindows_.end(); ++i) { // Active callbacks have a reposition callback - if (!activeOnly || i->second->repositionCallback() != NULL) + if (!activeOnly || i->second->repositionCallback() != nullptr) names.push_back(i->first); } return 0; diff --git a/SDK/simUtil/HudPositionManager.h b/SDK/simUtil/HudPositionManager.h index ba79ce3aa..e8d662d64 100644 --- a/SDK/simUtil/HudPositionManager.h +++ b/SDK/simUtil/HudPositionManager.h @@ -147,7 +147,7 @@ class SDKUTIL_EXPORT HudPositionManager : public osg::Referenced /** Retrieves the (immutable) name */ std::string name() const; - /** Sets the reposition callback for the window. May be NULL. */ + /** Sets the reposition callback for the window. May be nullptr. */ void setRepositionCallback(HudPositionManager::RepositionCallback* callback); /** Retrieves the current reposition callback */ HudPositionManager::RepositionCallback* repositionCallback() const; diff --git a/SDK/simUtil/LayerFactory.cpp b/SDK/simUtil/LayerFactory.cpp index 0f2197624..41c0ec3bd 100644 --- a/SDK/simUtil/LayerFactory.cpp +++ b/SDK/simUtil/LayerFactory.cpp @@ -48,7 +48,7 @@ simVis::DBImageLayer* LayerFactory::newDbImageLayer(const std::string& fullPath) #ifndef SIM_HAVE_DB_SUPPORT // Likely developer error unintended assert(0); - return NULL; + return nullptr; #else osgEarth::Config config; config.setReferrer(fullPath); @@ -110,7 +110,7 @@ simVis::DBElevationLayer* LayerFactory::newDbElevationLayer(const std::string& f #ifndef SIM_HAVE_DB_SUPPORT // Likely developer error unintended assert(0); - return NULL; + return nullptr; #else osgEarth::Config config; config.setReferrer(fullPath); @@ -190,7 +190,7 @@ osgEarth::FeatureModelLayer* LayerFactory::newFeatureLayer(const osgEarth::Featu // Error encountered SAFETRYEND("during LayerFactory::newFeatureLayer()"); - return NULL; + return nullptr; } ///////////////////////////////////////////////////////////////// @@ -221,12 +221,12 @@ osgEarth::FeatureModelLayer* ShapeFileLayerFactory::load(const std::string& url) // check the feature source's status for errors, since the layer's status will be ResourceUnavailable until it is opened if (!layer->getFeatureSource()) - return NULL; + return nullptr; osgEarth::Status status = layer->getFeatureSource()->getStatus(); if (status.isError()) { SIM_WARN << "ShapeFileLayerFactory::load(" << url << ") failed : " << status.message() << "\n"; - layer = NULL; + layer = nullptr; } return layer.release(); } diff --git a/SDK/simUtil/LayerFactory.h b/SDK/simUtil/LayerFactory.h index b9afa4c23..d8a6e9aa3 100644 --- a/SDK/simUtil/LayerFactory.h +++ b/SDK/simUtil/LayerFactory.h @@ -59,14 +59,14 @@ namespace simUtil { class SDKUTIL_EXPORT LayerFactory { public: - /** Returns an image layer properly configured for DB layer. May return NULL if not configured with DB support. */ + /** Returns an image layer properly configured for DB layer. May return nullptr if not configured with DB support. */ simVis::DBImageLayer* newDbImageLayer(const std::string& fullPath) const; /** Returns an image layer properly configured for MBTiles layer. */ osgEarth::MBTilesImageLayer* newMbTilesImageLayer(const std::string& fullPath) const; /** Returns an image layer properly configured for GDAL layer. */ osgEarth::GDALImageLayer* newGdalImageLayer(const std::string& fullPath) const; - /** Returns an elevation layer properly configured for DB layer. May return NULL if not configured with DB support. */ + /** Returns an elevation layer properly configured for DB layer. May return nullptr if not configured with DB support. */ simVis::DBElevationLayer* newDbElevationLayer(const std::string& fullPath) const; /** Returns an elevation layer properly configured for MBTiles layer. */ osgEarth::MBTilesElevationLayer* newMbTilesElevationLayer(const std::string& fullPath) const; @@ -79,7 +79,7 @@ class SDKUTIL_EXPORT LayerFactory /** * Factory method for creating a new feature model layer. * @param options Configuration options for the layer. - * @return Feature model layer on success; NULL on failure. Caller responsible for memory. + * @return Feature model layer on success; nullptr on failure. Caller responsible for memory. * (put in ref_ptr) */ static osgEarth::FeatureModelLayer* newFeatureLayer(const osgEarth::FeatureModelLayer::Options& options); diff --git a/SDK/simUtil/LineGraphic.cpp b/SDK/simUtil/LineGraphic.cpp index 6bc27bf74..9c70f1c8f 100644 --- a/SDK/simUtil/LineGraphic.cpp +++ b/SDK/simUtil/LineGraphic.cpp @@ -100,7 +100,7 @@ LineGraphic::~LineGraphic() void LineGraphic::set(const simUtil::Position* origin, const simUtil::Position* destination, const std::string& labelString) { // Update the positions - if (origin != NULL && destination != NULL && origin->isValid() && destination->isValid()) + if (origin != nullptr && destination != nullptr && origin->isValid() && destination->isValid()) { set(origin->lla(), destination->lla(), labelString); } @@ -275,71 +275,6 @@ bool StaticPosition::operator!=(const Position& other) const /////////////////////////////////////////////////////////////////////// -#ifdef USE_DEPRECATED_SIMDISSDK_API - -/** Position based off a platform's location */ -PlatformPosition::PlatformPosition(const simData::DataStore& dataStore, simData::ObjectId platformId) - : dataStore_(dataStore), - platformId_(platformId) -{ -} - -PlatformPosition::~PlatformPosition() -{ -} - -bool PlatformPosition::isValid() const -{ - const simData::PlatformUpdateSlice* slice = dataStore_.platformUpdateSlice(platformId_); - if (slice == NULL) - return false; - return slice->current() != NULL; -} - -const simCore::Vec3& PlatformPosition::lla() const -{ - pullFromDataStore_(lla_); - return lla_; -} - -simData::ObjectId PlatformPosition::platformId() const -{ - return platformId_; -} - -int PlatformPosition::pullFromDataStore_(simCore::Vec3& outLla) const -{ - // Get the current item out of the slice - const simData::PlatformUpdateSlice* slice = dataStore_.platformUpdateSlice(platformId_); - if (slice == NULL) - return 1; - const simData::PlatformUpdate* current = slice->current(); - if (current == NULL) - return 1; - // Pull out and convert position - simCore::Vec3 ecefV3; - current->position(ecefV3); - simCore::CoordinateConverter::convertEcefToGeodeticPos(ecefV3, outLla); - return 0; -} - -bool PlatformPosition::operator==(const Position& other) const -{ - const PlatformPosition* pp = dynamic_cast(&other); - return pp != NULL && - (pp->platformId_ == this->platformId_) && - (&pp->dataStore_ == &this->dataStore_); -} - -bool PlatformPosition::operator!=(const Position& other) const -{ - return !operator==(other); -} - -#endif /* USE_DEPRECATED_SIMDISSDK_API */ - -/////////////////////////////////////////////////////////////////////// - /** Position based off a node's locator LLA coordinate location */ EntityNodePosition::EntityNodePosition(simVis::EntityNode* node) : node_(node) @@ -352,7 +287,7 @@ EntityNodePosition::~EntityNodePosition() bool EntityNodePosition::isValid() const { - if (node_ == NULL) + if (node_ == nullptr) return false; return node_->getNodeMask() != 0; @@ -360,7 +295,7 @@ bool EntityNodePosition::isValid() const const simCore::Vec3& EntityNodePosition::lla() const { - if (node_ != NULL) + if (node_ != nullptr) node_->getPosition(&lla_, simCore::COORD_SYS_LLA); return lla_; @@ -368,7 +303,7 @@ const simCore::Vec3& EntityNodePosition::lla() const simData::ObjectId EntityNodePosition::id() const { - if (node_ == NULL) + if (node_ == nullptr) return 0; return node_->getId(); @@ -376,7 +311,7 @@ simData::ObjectId EntityNodePosition::id() const std::string EntityNodePosition::entityName() const { - if (node_ == NULL) + if (node_ == nullptr) return ""; return node_->getEntityName(simVis::EntityNode::DISPLAY_NAME); @@ -385,7 +320,7 @@ std::string EntityNodePosition::entityName() const bool EntityNodePosition::operator==(const Position& other) const { const EntityNodePosition* pp = dynamic_cast(&other); - return (pp != NULL && (pp->id() == this->id())); + return (pp != nullptr && (pp->id() == this->id())); } bool EntityNodePosition::operator!=(const Position& other) const diff --git a/SDK/simUtil/LineGraphic.h b/SDK/simUtil/LineGraphic.h index 2f2b36cfc..9d0e96ffb 100644 --- a/SDK/simUtil/LineGraphic.h +++ b/SDK/simUtil/LineGraphic.h @@ -211,44 +211,6 @@ class SDKUTIL_EXPORT StaticPosition : public Position simCore::Vec3 lla_; }; -#ifdef USE_DEPRECATED_SIMDISSDK_API -/** - * @deprecated class, may be removed in a future release. Use simUtil::EntityNodePosition instead. - * Position based off a platform's LLA coordinate location. - */ -class SDKUTIL_EXPORT PlatformPosition : public Position -{ -public: - /** Initialize from a data store. */ - PlatformPosition(const simData::DataStore& dataStore, simData::ObjectId platformId); - - virtual bool isValid() const; - virtual const simCore::Vec3& lla() const; - virtual bool operator==(const Position& other) const; - virtual bool operator!=(const Position& other) const; - - /** - * Returns the Unique ID of the platform - * @return The Unique ID of the platform - */ - simData::ObjectId platformId() const; - -protected: - /** Reference-derived */ - virtual ~PlatformPosition(); - -private: - /** Returns 0 on success, pulling LLA out of the data store. */ - int pullFromDataStore_(simCore::Vec3& outLla) const; - - const simData::DataStore& dataStore_; - simData::ObjectId platformId_; - /** Cache of the LLA from the data store. */ - mutable simCore::Vec3 lla_; -}; - -#endif - /** Position based off a node's locator LLA coordinate location. */ class SDKUTIL_EXPORT EntityNodePosition : public Position { diff --git a/SDK/simUtil/MapScale.cpp b/SDK/simUtil/MapScale.cpp index a6735cbd2..db3038dff 100644 --- a/SDK/simUtil/MapScale.cpp +++ b/SDK/simUtil/MapScale.cpp @@ -213,7 +213,7 @@ void MapScale::bindToFocusManager(simVis::FocusManager* focusManager) void MapScale::setUnitsProvider(UnitsProvider* unitsProvider) { - // Fall back to a reasonable implementation rather than setting to NULL + // Fall back to a reasonable implementation rather than setting to nullptr if (unitsProvider) unitsProvider_ = unitsProvider; else diff --git a/SDK/simUtil/MouseDispatcher.cpp b/SDK/simUtil/MouseDispatcher.cpp index d5bb606cf..091b335b0 100644 --- a/SDK/simUtil/MouseDispatcher.cpp +++ b/SDK/simUtil/MouseDispatcher.cpp @@ -117,9 +117,9 @@ MouseDispatcher::MouseDispatcher() MouseDispatcher::~MouseDispatcher() { - setViewManager(NULL); - viewObserver_ = NULL; - eventHandler_ = NULL; + setViewManager(nullptr); + viewObserver_ = nullptr; + eventHandler_ = nullptr; } void MouseDispatcher::setViewManager(simVis::ViewManager* viewManager) @@ -133,7 +133,7 @@ void MouseDispatcher::setViewManager(simVis::ViewManager* viewManager) viewObserver_ = new simVis::AddEventHandlerToViews(eventHandler_.get()); // Remove all observers and GUI handlers - if (viewManager_ != NULL) + if (viewManager_ != nullptr) { viewManager_->removeCallback(viewObserver_.get()); viewObserver_->removeFromViews(*viewManager_); @@ -141,7 +141,7 @@ void MouseDispatcher::setViewManager(simVis::ViewManager* viewManager) viewManager_ = viewManager; // Add back in the observers and GUI handlers to the new view manager - if (viewManager_ != NULL) + if (viewManager_ != nullptr) { viewManager_->addCallback(viewObserver_.get()); viewObserver_->addToViews(*viewManager_); @@ -155,16 +155,16 @@ osgGA::GUIEventHandler* MouseDispatcher::eventHandler() const void MouseDispatcher::addManipulator(int weight, MouseManipulatorPtr manipulator) { - // Don't add NULLs - if (manipulator == NULL) + // Don't add nullptrs + if (manipulator == nullptr) return; priorityMap_.insert(std::make_pair(weight, manipulator)); } void MouseDispatcher::addExclusiveManipulator(MouseManipulatorPtr manipulator) { - // Don't add NULL and don't repeat - if (manipulator == NULL || allExclusive_.find(manipulator) != allExclusive_.end()) + // Don't add nullptr and don't repeat + if (manipulator == nullptr || allExclusive_.find(manipulator) != allExclusive_.end()) return; allExclusive_.insert(manipulator); } @@ -195,14 +195,14 @@ int MouseDispatcher::activateExclusive(MouseManipulatorPtr manipulator) return 0; // not an error; it's still active // Return an error if this manipulator is not in our list of exclusive ones. - if (manipulator != NULL && allExclusive_.find(manipulator) == allExclusive_.end()) + if (manipulator != nullptr && allExclusive_.find(manipulator) == allExclusive_.end()) { SIM_WARN << "MouseDispatcher::activateExclusive(): Please register exclusive mouse mode before calling this method.\n"; return 1; } // Deactivate the old one - if (oldSubject != NULL) + if (oldSubject != nullptr) oldSubject->deactivate(); exclusiveProxy_->setSubject(manipulator); if (manipulator) @@ -213,8 +213,8 @@ int MouseDispatcher::activateExclusive(MouseManipulatorPtr manipulator) int MouseDispatcher::deactivateExclusive(MouseManipulatorPtr manipulator) { - // Avoid deactivate on NULL (meaningless and dev error) - if (manipulator == NULL) + // Avoid deactivate on nullptr (meaningless and dev error) + if (manipulator == nullptr) return 1; // Return early if the manipulator is not active. Perhaps someone diff --git a/SDK/simUtil/MouseDispatcher.h b/SDK/simUtil/MouseDispatcher.h index 8d8532bc8..c6d5793aa 100644 --- a/SDK/simUtil/MouseDispatcher.h +++ b/SDK/simUtil/MouseDispatcher.h @@ -67,9 +67,9 @@ class SDKUTIL_EXPORT MouseDispatcher /** Activates a single exclusive manipulator, deactivating all other mutually exclusive manipulators. */ int activateExclusive(MouseManipulatorPtr manipulator); - /** Deactivates an exclusive manipulator. If it was active, then the active exclusive manipulator is set to NULL. */ + /** Deactivates an exclusive manipulator. If it was active, then the active exclusive manipulator is set to nullptr. */ int deactivateExclusive(MouseManipulatorPtr manipulator); - /** Retrieves the currently active exclusive manipulator; might be NULL */ + /** Retrieves the currently active exclusive manipulator; might be nullptr */ MouseManipulatorPtr activeExclusiveManipulator() const; /** Observable events on the Mouse Dispatcher */ @@ -77,7 +77,7 @@ class SDKUTIL_EXPORT MouseDispatcher { public: virtual ~Observer() {} - /** Manipulator has changed. May be NULL. */ + /** Manipulator has changed. May be nullptr. */ virtual void activeExclusiveManipulatorChanged(MouseManipulatorPtr active, MouseManipulatorPtr oldActive) = 0; }; diff --git a/SDK/simUtil/MouseManipulator.cpp b/SDK/simUtil/MouseManipulator.cpp index 05bca6878..27744b88c 100644 --- a/SDK/simUtil/MouseManipulator.cpp +++ b/SDK/simUtil/MouseManipulator.cpp @@ -36,49 +36,49 @@ MouseManipulatorAdapter::~MouseManipulatorAdapter() int MouseManipulatorAdapter::push(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa) { - if (handler_ == NULL) + if (handler_ == nullptr) return 0; return handler_->handle(ea, aa); } int MouseManipulatorAdapter::release(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa) { - if (handler_ == NULL) + if (handler_ == nullptr) return 0; return handler_->handle(ea, aa); } int MouseManipulatorAdapter::move(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa) { - if (handler_ == NULL) + if (handler_ == nullptr) return 0; return handler_->handle(ea, aa); } int MouseManipulatorAdapter::drag(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa) { - if (handler_ == NULL) + if (handler_ == nullptr) return 0; return handler_->handle(ea, aa); } int MouseManipulatorAdapter::doubleClick(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa) { - if (handler_ == NULL) + if (handler_ == nullptr) return 0; return handler_->handle(ea, aa); } int MouseManipulatorAdapter::scroll(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa) { - if (handler_ == NULL) + if (handler_ == nullptr) return 0; return handler_->handle(ea, aa); } int MouseManipulatorAdapter::frame(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa) { - if (handler_ == NULL) + if (handler_ == nullptr) return 0; return handler_->handle(ea, aa); } @@ -116,49 +116,49 @@ MouseManipulatorProxy::MouseManipulatorProxy(const MouseManipulatorPtr& realMani int MouseManipulatorProxy::push(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa) { - if (manipulator_ == NULL) + if (manipulator_ == nullptr) return 0; return manipulator_->push(ea, aa); } int MouseManipulatorProxy::release(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa) { - if (manipulator_ == NULL) + if (manipulator_ == nullptr) return 0; return manipulator_->release(ea, aa); } int MouseManipulatorProxy::move(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa) { - if (manipulator_ == NULL) + if (manipulator_ == nullptr) return 0; return manipulator_->move(ea, aa); } int MouseManipulatorProxy::drag(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa) { - if (manipulator_ == NULL) + if (manipulator_ == nullptr) return 0; return manipulator_->drag(ea, aa); } int MouseManipulatorProxy::doubleClick(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa) { - if (manipulator_ == NULL) + if (manipulator_ == nullptr) return 0; return manipulator_->doubleClick(ea, aa); } int MouseManipulatorProxy::scroll(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa) { - if (manipulator_ == NULL) + if (manipulator_ == nullptr) return 0; return manipulator_->scroll(ea, aa); } int MouseManipulatorProxy::frame(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa) { - if (manipulator_ == NULL) + if (manipulator_ == nullptr) return 0; return manipulator_->frame(ea, aa); } diff --git a/SDK/simUtil/MouseManipulator.h b/SDK/simUtil/MouseManipulator.h index 491c4847d..253b8e997 100644 --- a/SDK/simUtil/MouseManipulator.h +++ b/SDK/simUtil/MouseManipulator.h @@ -90,8 +90,8 @@ typedef std::shared_ptr MouseManipulatorPtr; class SDKUTIL_EXPORT MouseManipulatorAdapter : public MouseManipulator { public: - /** Instantiate this adapter around the provided GUIEventHandler. This may be NULL. */ - explicit MouseManipulatorAdapter(osgGA::GUIEventHandler* handler=NULL); + /** Instantiate this adapter around the provided GUIEventHandler. This may be nullptr. */ + explicit MouseManipulatorAdapter(osgGA::GUIEventHandler* handler=nullptr); virtual ~MouseManipulatorAdapter(); /** Mouse button pushed, returns non-zero on handled */ @@ -113,7 +113,7 @@ class SDKUTIL_EXPORT MouseManipulatorAdapter : public MouseManipulator virtual void activate(); virtual void deactivate(); - /** Retrieves the underlying GUI Event Handler that, if non-NULL, defines the default behavior for adapter. */ + /** Retrieves the underlying GUI Event Handler that, if non-nullptr, defines the default behavior for adapter. */ osgGA::GUIEventHandler* handler() const; /** Changes the underlying GUI Event Handler used for default behavior in the adapter. */ void setHandler(osgGA::GUIEventHandler* handler); diff --git a/SDK/simUtil/MousePositionManipulator.cpp b/SDK/simUtil/MousePositionManipulator.cpp index 50ba43dd1..d5d15f636 100644 --- a/SDK/simUtil/MousePositionManipulator.cpp +++ b/SDK/simUtil/MousePositionManipulator.cpp @@ -84,7 +84,7 @@ MousePositionManipulator::MousePositionManipulator(osgEarth::MapNode* mapNode, o terrainResolution_(0.00001), scene_(scene) { - assert(mapNode != NULL); + assert(mapNode != nullptr); terrainEngineNode_ = mapNode_->getTerrainEngine(); mapNodePath_.push_back(terrainEngineNode_.get()); elevationQuery_ = new simVis::ElevationQueryProxy(mapNode_->getMap(), scene); @@ -112,9 +112,9 @@ void MousePositionManipulator::setMapNode(osgEarth::MapNode* mapNode) mapNodePath_.clear(); // If we don't have a valid map node, then try to gracefully deal with it - if (mapNode == NULL) + if (mapNode == nullptr) { - terrainEngineNode_ = NULL; + terrainEngineNode_ = nullptr; return; } @@ -202,7 +202,7 @@ int MousePositionManipulator::frame(const osgGA::GUIEventAdapter& ea, osgGA::GUI // NOTE: always return 0, since we don't need to capture the frame event // need to fire off mouseOverLatLon on listeners if elevation query still has a pending elevation query that is finished - if (llaListeners_.empty() || elevationQuery_ == NULL) + if (llaListeners_.empty() || elevationQuery_ == nullptr) return 0; double outElevation = 0.0; // this call does not block, will return false if no pending elevation query available @@ -252,12 +252,12 @@ int MousePositionManipulator::getElevation(const osgEarth::GeoPoint& lonLatAlt, int MousePositionManipulator::getElevation_(const osgEarth::GeoPoint& lonLatAlt, double& elevationMeters, bool blocking) const { - // It's possible that elevation query is NULL for NULL maps - if (elevationQuery_ == NULL) + // It's possible that elevation query is nullptr for nullptr maps + if (elevationQuery_ == nullptr) return 1; // The 3rd argument control how far down the angular resolution to get an answer - return elevationQuery_->getElevation(lonLatAlt, elevationMeters, terrainResolution_, NULL, blocking) ? 0 : 1; + return elevationQuery_->getElevation(lonLatAlt, elevationMeters, terrainResolution_, nullptr, blocking) ? 0 : 1; } void MousePositionManipulator::setTerrainResolution(double resolutionRadians) { diff --git a/SDK/simUtil/PlatformSimulator.cpp b/SDK/simUtil/PlatformSimulator.cpp index 451111920..7cdbd3888 100644 --- a/SDK/simUtil/PlatformSimulator.cpp +++ b/SDK/simUtil/PlatformSimulator.cpp @@ -286,7 +286,7 @@ void PlatformSimulatorManager::simulate_(double now) // create a position update transaction simData::DataStore::Transaction platformTransaction; - simData::PlatformUpdate* platformUpdate = NULL; + simData::PlatformUpdate* platformUpdate = nullptr; // add the update for the platform if (sim->getPlatformId() != ~(static_cast(0))) @@ -348,8 +348,8 @@ CircumnavigationPlatformSimulation::~CircumnavigationPlatformSimulation() void CircumnavigationPlatformSimulation::init_(simVis::View* mainView) { - // Don't crash on NULL accesses - if (!sceneManager_.valid() || mainView == NULL) + // Don't crash on nullptr accesses + if (!sceneManager_.valid() || mainView == nullptr) return; // Bind the scene manager to the data store diff --git a/SDK/simUtil/RecenterEyeOnArea.cpp b/SDK/simUtil/RecenterEyeOnArea.cpp index dbc8890b1..c52e3997c 100644 --- a/SDK/simUtil/RecenterEyeOnArea.cpp +++ b/SDK/simUtil/RecenterEyeOnArea.cpp @@ -82,7 +82,7 @@ int RecenterEyeOnArea::centerOn(double lowerLat, double upperLat, double leftLon // update the eye position's focal point simVis::Viewpoint eyePos = view->getViewpoint(); - eyePos.setNode(NULL); + eyePos.setNode(nullptr); eyePos.focalPoint() = osgEarth::GeoPoint( osgEarth::SpatialReference::create("wgs84"), osg::Vec3d(centerLla.lon() * simCore::RAD2DEG, centerLla.lat() * simCore::RAD2DEG, 0.0)); @@ -92,7 +92,8 @@ int RecenterEyeOnArea::centerOn(double lowerLat, double upperLat, double leftLon eyePos.pitch()->set(-90.0, osgEarth::Units::DEGREES); // Clamp the distance between the close and far eye distances, so that we don't // hit our eyeball on the surface, or zoom out to a pinpoint of an earth - eyePos.setRange(simCore::sdkMin(maxEyeDistance_, simCore::sdkMax(minEyeDistance_, distance))); + osgEarth::Distance range(simCore::sdkMin(maxEyeDistance_, simCore::sdkMax(minEyeDistance_, distance)), osgEarth::Units::METERS); + eyePos.setRange(range); view->setViewpoint(eyePos, transitionSec); return 0; } diff --git a/SDK/simUtil/RecenterEyeOnArea.h b/SDK/simUtil/RecenterEyeOnArea.h index 1ece32c75..f1f26d679 100644 --- a/SDK/simUtil/RecenterEyeOnArea.h +++ b/SDK/simUtil/RecenterEyeOnArea.h @@ -44,9 +44,9 @@ class SDKUTIL_EXPORT RecenterEyeOnArea public: /** * Initialize, optionally with a view to use when recentering. - * @param view Inset view to use when updating viewpoints. If NULL, then setView() must be called before recentering. + * @param view Inset view to use when updating viewpoints. If nullptr, then setView() must be called before recentering. */ - RecenterEyeOnArea(simVis::View* view=NULL); + RecenterEyeOnArea(simVis::View* view=nullptr); /** * Initialize using the current focus of a FocusManager for recentering. * @param focusManager Focus manager whose currently focused inset view will be used for updating viewpoints. diff --git a/SDK/simUtil/Replaceables.cpp b/SDK/simUtil/Replaceables.cpp index f7bee26a0..aa3098d16 100644 --- a/SDK/simUtil/Replaceables.cpp +++ b/SDK/simUtil/Replaceables.cpp @@ -39,7 +39,7 @@ namespace { const simVis::View* getView(simVis::View* view) { if (!view) - return NULL; + return nullptr; const simVis::FocusManager* focusManager =view->getFocusManager(); if (focusManager && focusManager->getFocusedView()) return focusManager->getFocusedView(); @@ -100,9 +100,9 @@ std::string AzimuthVariable::getText() const const osgEarth::Util::EarthManipulator* manip = view->getEarthManipulator(); double azimuth = 0.0; // Prefer the azimuth from getCompositeEulerAngles on the manipulator - if (manip != NULL) + if (manip != nullptr) { - manip->getCompositeEulerAngles(&azimuth, NULL); + manip->getCompositeEulerAngles(&azimuth, nullptr); azimuth *= simCore::RAD2DEG; // format_() expects degrees } else // Fall back to the viewpoint @@ -139,9 +139,9 @@ std::string ElevationVariable::getText() const const osgEarth::Util::EarthManipulator* manip = view->getEarthManipulator(); double elevation = 0.0; // Prefer the azimuth from getCompositeEulerAngles on the manipulator - if (manip != NULL) + if (manip != nullptr) { - manip->getCompositeEulerAngles(NULL, &elevation); + manip->getCompositeEulerAngles(nullptr, &elevation); elevation = -elevation * simCore::RAD2DEG; // format_() expects degrees } else // Fall back to the viewpoint @@ -269,10 +269,10 @@ std::string CenteredVariable::getText() const // Pull out the centered node; note that in a Watched view, the Watcher is considered centered // even though the tether is set (the tether in this case is the watched) - const simVis::EntityNode* entityNode = NULL; + const simVis::EntityNode* entityNode = nullptr; if (focusedView->isWatchEnabled()) entityNode = focusedView->getWatcherNode(); - else if (focusedView->getCameraTether() != NULL) + else if ((focusedView->getCameraTether() != nullptr) && !focusedView->getCameraTether()->getParents().empty()) entityNode = dynamic_cast(focusedView->getCameraTether()->getParent(0)); // Return the name @@ -283,7 +283,7 @@ std::string CenteredVariable::getText() const rv = " "; return rv; } - else if (focusedView->getCameraTether() != NULL) + else if (focusedView->getCameraTether() != nullptr) { // See if the camera is tethered to a centroid const simVis::AveragePositionNode* centroid = dynamic_cast(focusedView->getCameraTether()); diff --git a/SDK/simUtil/ResizeViewManipulator.cpp b/SDK/simUtil/ResizeViewManipulator.cpp index ab81a554f..ff0278096 100644 --- a/SDK/simUtil/ResizeViewManipulator.cpp +++ b/SDK/simUtil/ResizeViewManipulator.cpp @@ -63,11 +63,11 @@ class ResizeViewManipulator::RubberBand parent->removeChild(xform_); } - /** Places a box around the passed in view; if NULL hides the box*/ + /** Places a box around the passed in view; if nullptr hides the box*/ void attach(simVis::View* view) { - // Hide if NULL - if (view == NULL) + // Hide if nullptr + if (view == nullptr) { xform_->setNodeMask(0); return; @@ -75,7 +75,7 @@ class ResizeViewManipulator::RubberBand // Calculate the absolute position of the viewport simVis::View::Extents extents = view->getExtents(); - manip_.toAbsoluteExtents_(*view, extents, NULL); + manip_.toAbsoluteExtents_(*view, extents, nullptr); // Move the matrix to over-top, and turn on node mask xform_->setMatrix(osg::Matrix::scale(extents.width_, extents.height_, 1) * osg::Matrix::translate(extents.x_, extents.y_, 0)); @@ -165,8 +165,8 @@ void ResizeViewManipulator::setEnabled(bool enabled) if (enabled == enabled_) return; enabled_ = enabled; - activeView_ = NULL; - rubberBand_->attach(NULL); + activeView_ = nullptr; + rubberBand_->attach(nullptr); setDragPoint_(NONE); } @@ -182,10 +182,10 @@ int ResizeViewManipulator::push(const osgGA::GUIEventAdapter& ea, osgGA::GUIActi return 0; // Always clear out active view on mouse push - activeView_ = NULL; + activeView_ = nullptr; osg::ref_ptr view = static_cast(aa.asView()); - // Ignore events from NULL views and the main view - if (view == NULL || view == mainView_.get()) + // Ignore events from nullptr views and the main view + if (view == nullptr || view == mainView_.get()) return 0; const osg::Vec2d mousePosition = osg::Vec2d(ea.getX(), ea.getY()); @@ -216,9 +216,9 @@ int ResizeViewManipulator::release(const osgGA::GUIEventAdapter& ea, osgGA::GUIA return 0; // Capture the click and clear out the active view - activeView_ = NULL; + activeView_ = nullptr; rubberBand_->setBold(false); - rubberBand_->attach(NULL); + rubberBand_->attach(nullptr); rubberBand_->highlightCorner(NONE); // After release, make sure the highlighting is correct. We can just call move() here to do that @@ -239,10 +239,10 @@ int ResizeViewManipulator::move(const osgGA::GUIEventAdapter& ea, osgGA::GUIActi // Figure out what view is under the cursor and highlight it osg::ref_ptr underMouse = static_cast(aa.asView()); - // Ignore events from NULL views and the main view - if (underMouse == NULL || underMouse == mainView_.get()) + // Ignore events from nullptr views and the main view + if (underMouse == nullptr || underMouse == mainView_.get()) { - rubberBand_->attach(NULL); + rubberBand_->attach(nullptr); setDragPoint_(NONE); return 0; } @@ -360,7 +360,7 @@ ResizeViewManipulator::DragPoint ResizeViewManipulator::calculateDragPoint_(cons { // Calculate the absolute extents simVis::View::Extents extents = view.getExtents(); - toAbsoluteExtents_(view, extents, NULL); + toAbsoluteExtents_(view, extents, nullptr); // Test the top side if (mouseXY.y() > extents.y_ + extents.height_ - EDGE_SIZE) @@ -403,10 +403,10 @@ void ResizeViewManipulator::toAbsoluteExtents_(const simVis::View& view, simVis: // Pull out the host's size const osg::View* host = view.getHostView(); - if (host == NULL) + if (host == nullptr) return; const osg::Viewport* rvp = host->getCamera()->getViewport(); - if (rvp == NULL) + if (rvp == nullptr) return; // Calculate the absolute pixels @@ -425,10 +425,10 @@ void ResizeViewManipulator::toRatioExtents_(const simVis::View& view, simVis::Vi // Pull out the host's size const osg::View* host = view.getHostView(); - if (host == NULL) + if (host == nullptr) return; const osg::Viewport* rvp = host->getCamera()->getViewport(); - if (rvp == NULL) + if (rvp == nullptr) return; extents.height_ /= rvp->height(); diff --git a/SDK/simUtil/SilverLiningSettings.cpp b/SDK/simUtil/SilverLiningSettings.cpp index 7681b6ad5..653a9fa3b 100644 --- a/SDK/simUtil/SilverLiningSettings.cpp +++ b/SDK/simUtil/SilverLiningSettings.cpp @@ -224,8 +224,8 @@ unsigned long SLAlwaysRealTime::getMilliseconds() const unsigned long SLRegistryClockTime::getMilliseconds() const { const simCore::Clock* clock = simVis::Registry::instance()->getClock(); - // Fall back to default dispaly if clock is NULL - if (clock == NULL) + // Fall back to default dispaly if clock is nullptr + if (clock == nullptr) return 0; // Avoid negative values const simCore::Seconds& elapsed = clock->currentTime() - clock->startTime(); diff --git a/SDK/simUtil/StatsHandler.cpp b/SDK/simUtil/StatsHandler.cpp index 4f10ee8f6..c74b1ba6a 100644 --- a/SDK/simUtil/StatsHandler.cpp +++ b/SDK/simUtil/StatsHandler.cpp @@ -44,7 +44,7 @@ StatsHandler::StatsHandler() void StatsHandler::setStatsType(StatsHandler::StatsType statsType, osgViewer::View* onWhichView) { - if (onWhichView == NULL) + if (onWhichView == nullptr) return; // Due to the way osgViewer::StatsHandler is written, we must iterate through each diff --git a/SDK/simUtil/StatsSizeFixer.h b/SDK/simUtil/StatsSizeFixer.h index ae405f908..3800f8350 100644 --- a/SDK/simUtil/StatsSizeFixer.h +++ b/SDK/simUtil/StatsSizeFixer.h @@ -101,7 +101,7 @@ class StatsSizeFixer : public osgGA::GUIEventHandler static const double STATS_HEIGHT = 1024; osg::Camera* camera = stats_->getCamera(); - if (camera->getGraphicsContext() == NULL) + if (camera->getGraphicsContext() == nullptr) return; camera->setProjectionMatrixAsOrtho2D(0, windowWidth / sizeMultiplier_, STATS_HEIGHT - windowHeight * SCREEN_RATIO / sizeMultiplier_, STATS_HEIGHT); diff --git a/SDK/simUtil/StatusText.cpp b/SDK/simUtil/StatusText.cpp index 6ad0b66db..dc64a700c 100644 --- a/SDK/simUtil/StatusText.cpp +++ b/SDK/simUtil/StatusText.cpp @@ -105,8 +105,8 @@ class StatusText::FrameEventHandler : public osgGA::GUIEventHandler { // Tell the text to resize if the screen size has changed const osg::View* view = aa.asView(); - const osg::Camera* camera = (view) ? view->getCamera() : NULL; - const osg::Viewport* viewport = (camera) ? camera->getViewport() : NULL; + const osg::Camera* camera = (view) ? view->getCamera() : nullptr; + const osg::Viewport* viewport = (camera) ? camera->getViewport() : nullptr; if (viewport) { const int widthPx = static_cast(viewport->width()); @@ -141,7 +141,7 @@ class StatusText::FrameEventHandler : public osgGA::GUIEventHandler StatusText::StatusText(simVis::View* view, simCore::TextReplacerPtr textReplacer, Position pos) : StatusTextNode(textReplacer), view_(view), - frameEventHandler_(NULL), + frameEventHandler_(nullptr), position_(pos) { const osg::Viewport* vp = view->getCamera()->getViewport(); @@ -162,7 +162,7 @@ void StatusText::removeFromView() view_->removeEventHandler(frameEventHandler_); view_->getOrCreateHUD()->removeChild(this); removeChild(statusHudText_.get()); - statusHudText_ = NULL; + statusHudText_ = nullptr; } } diff --git a/SDK/simUtil/ViewpointMonitor.cpp b/SDK/simUtil/ViewpointMonitor.cpp index d64dcb3aa..47f4335bd 100644 --- a/SDK/simUtil/ViewpointMonitor.cpp +++ b/SDK/simUtil/ViewpointMonitor.cpp @@ -111,10 +111,10 @@ void EyePositionState::fillFromView_(simVis::View* view) { view_ = view; - if (view_ == NULL) + if (view_ == nullptr) { - tetherNode_ = NULL; - watchedNode_ = NULL; + tetherNode_ = nullptr; + watchedNode_ = nullptr; isTethered_ = false; isWatching_ = false; isOverheadMode_ = false; @@ -136,7 +136,7 @@ void EyePositionState::fillFromView_(simVis::View* view) isWatching_ = watchedNode_.valid(); // If watching, then the tether node returned from view may be wrong (it may be - // NULL due to how Watch is implemented). Return instead the watcher node. + // nullptr due to how Watch is implemented). Return instead the watcher node. if (isWatching_) { isTethered_ = true; @@ -145,13 +145,13 @@ void EyePositionState::fillFromView_(simVis::View* view) // Tether mode comes from the Earth Manipulator const osgEarth::Util::EarthManipulator* manip = dynamic_cast(view_->getCameraManipulator()); - if (manip == NULL || manip->getSettings() == NULL) + if (manip == nullptr || manip->getSettings() == nullptr) tetherMode_ = osgEarth::Util::EarthManipulator::TETHER_CENTER; else tetherMode_ = manip->getSettings()->getTetherMode(); // Lock settings come from the simVis::EarthManipulator const simVis::EarthManipulator* svManip = dynamic_cast(manip); - if (svManip == NULL) + if (svManip == nullptr) headingLocked_ = pitchLocked_ = false; else { @@ -166,7 +166,7 @@ void EyePositionState::fillFromView_(simVis::View* view) // Pull out az/el from the manipulator directly double azToEye = 0.0; double elToEye = 0.0; - if (manip != NULL) + if (manip != nullptr) manip->getCompositeEulerAngles(&azToEye, &elToEye); else { @@ -279,7 +279,7 @@ ViewpointMonitor::ViewpointMonitor(simVis::View* mainView) // Initialize all the view eye position states simVis::ViewManager* viewManager = mainView_->getViewManager(); - if (viewManager != NULL) + if (viewManager != nullptr) { // Add an observer so we know when views are added or removed viewManager->addCallback(viewManagerObserver_.get()); @@ -321,7 +321,7 @@ const EyePositionState* ViewpointMonitor::eyePositionState(simVis::View* view) c { std::map::const_iterator i = eyeStates_.find(view); if (i == eyeStates_.end()) - return NULL; + return nullptr; return i->second; } diff --git a/SDK/simUtil/ViewpointMonitor.h b/SDK/simUtil/ViewpointMonitor.h index 148b7392c..ded5cd7b4 100644 --- a/SDK/simUtil/ViewpointMonitor.h +++ b/SDK/simUtil/ViewpointMonitor.h @@ -56,9 +56,9 @@ class SDKUTIL_EXPORT EyePositionState /** View used to initialize this state */ simVis::View* view() const; - /** Node on which the view is tethered. May be NULL if !isTethered(). In watch mode, this is the watcher node. */ + /** Node on which the view is tethered. May be nullptr if !isTethered(). In watch mode, this is the watcher node. */ osg::Node* tetherNode() const; - /** In watch mode, returns the node that is being watched. May be NULL if !isWatching(). */ + /** In watch mode, returns the node that is being watched. May be nullptr if !isWatching(). */ simVis::EntityNode* watchedNode() const; /** Returns true if tethered to a node. Must be true if isWatching() is true. */ @@ -117,7 +117,7 @@ class SDKUTIL_EXPORT EyePositionState class SDKUTIL_EXPORT ViewpointMonitor { public: - /** Initialize the monitor with a non-NULL top level view */ + /** Initialize the monitor with a non-nullptr top level view */ ViewpointMonitor(simVis::View* mainView); virtual ~ViewpointMonitor(); @@ -145,7 +145,7 @@ class SDKUTIL_EXPORT ViewpointMonitor * The entity on which is being tethered has changed for the provided view. The node is not * necessarily a simVis::EntityNode, but is likely either an EntityNode or a PlatformModelNode. * Note that the parent of a PlatformModelNode is an EntityNode. This method is called with - * a NULL newTether when untethering. In watch mode, the tether node is the watcher. + * a nullptr newTether when untethering. In watch mode, the tether node is the watcher. * @param view View in which the tether node has changed. * @param newTether Node being tethered to. Likely either a simVis::EntityNode or a * simVis::PlatformNode, but not guaranteed (EarthManipulator allows for any type of node). @@ -166,7 +166,7 @@ class SDKUTIL_EXPORT ViewpointMonitor * being unset), this method is called. * @param view View in which the watched node has changed. * @param watchedNode Node being watched from the viewpoint of a tethered watcher node. May - * be NULL when the watch mode is being disabled. + * be nullptr when the watch mode is being disabled. */ virtual void watchedChanged(simVis::View* view, simVis::EntityNode* watchedNode) = 0; diff --git a/SDK/simUtil/ViewpointPositions.cpp b/SDK/simUtil/ViewpointPositions.cpp index f45f9ca73..fdb0a147a 100644 --- a/SDK/simUtil/ViewpointPositions.cpp +++ b/SDK/simUtil/ViewpointPositions.cpp @@ -30,8 +30,8 @@ namespace simUtil { -/// Initialize the SRS to NULL (lazy initialization later) -const osgEarth::SpatialReference* ViewpointPositions::wgs84Srs_ = NULL; +/// Initialize the SRS to nullptr (lazy initialization later) +const osgEarth::SpatialReference* ViewpointPositions::wgs84Srs_ = nullptr; /// Extracts the Center LLA position out of a viewpoint. Returns Vec3 of Latitude (rad), Longitude (rad), Altitude (meters) simCore::Vec3 ViewpointPositions::centerLla(const osgEarth::Viewpoint& vp) @@ -67,7 +67,7 @@ simCore::Vec3 ViewpointPositions::eyeLla(const simVis::View& view) // Grab the viewpoint directly from the manipulator, instead of the View. This prevents watch // mode offsets from tainting the azimuth/elevation calculations const osgEarth::Util::EarthManipulator* manip = dynamic_cast(view.getCameraManipulator()); - if (manip == NULL) + if (manip == nullptr) { // Failure means we don't have an Earth Manipulator. This might happen if there is // a simVis::View that is used as an inset that displays something besides the scene. @@ -109,7 +109,7 @@ simCore::Vec3 ViewpointPositions::eyeLla(const simVis::View& view) /// Lazy initialization on static WGS-84 SRS */ const osgEarth::SpatialReference* ViewpointPositions::wgs84_() { - if (ViewpointPositions::wgs84Srs_ == NULL) + if (ViewpointPositions::wgs84Srs_ == nullptr) ViewpointPositions::wgs84Srs_ = osgEarth::SpatialReference::create("wgs84"); return ViewpointPositions::wgs84Srs_; } diff --git a/SDK/simVis.h b/SDK/simVis.h index c7346d213..df965271a 100644 --- a/SDK/simVis.h +++ b/SDK/simVis.h @@ -136,6 +136,7 @@ #include "simVis/RFProp/OneWayPowerDataProvider.h" #include "simVis/RFProp/PODProfileDataProvider.h" #include "simVis/RFProp/Profile.h" +#include "simVis/RFProp/ProfileContext.h" #include "simVis/RFProp/ProfileDataProvider.h" #include "simVis/RFProp/ProfileManager.h" #include "simVis/RFProp/RadarParameters.h" diff --git a/SDK/simVis/AlphaTest.cpp b/SDK/simVis/AlphaTest.cpp index 49fc911f4..0595e6c43 100644 --- a/SDK/simVis/AlphaTest.cpp +++ b/SDK/simVis/AlphaTest.cpp @@ -59,7 +59,7 @@ void AlphaTest::installShaderProgram(osg::StateSet* intoStateSet) void AlphaTest::setValues(osg::StateSet* stateset, float threshold, int value) { - if (stateset == NULL) + if (stateset == nullptr) return; // Need GLSL 3.3 to use alpha test shader, else fall back to FFP and hope for compatibility mode diff --git a/SDK/simVis/AnimatedLine.cpp b/SDK/simVis/AnimatedLine.cpp index 7ed50265a..d5af4b5ca 100644 --- a/SDK/simVis/AnimatedLine.cpp +++ b/SDK/simVis/AnimatedLine.cpp @@ -87,6 +87,35 @@ namespace namespace simVis { +AnimatedLineNode::HalfALine::HalfALine() +{ +} + +AnimatedLineNode::HalfALine::~HalfALine() +{ +} + +void AnimatedLineNode::HalfALine::fillSlantLine(unsigned int numSegments, const osg::Vec3d& lastPoint, bool forward) +{ + line1->reserve(numSegments + 1); + line2->reserve(numSegments + 1); + + // Add points to the vertex list, from back to front, for consistent stippling. Order + // matters because it affects the line direction during stippling. + for (unsigned int k = 0; k <= numSegments; ++k) + { + // Add in the subdivided line point + const double percentOfFull = forward ? (static_cast(numSegments - k) / numSegments) : (static_cast(k) / numSegments); + osg::Vec3f point = lastPoint * percentOfFull; + line1->pushVertex(point); + line2->pushVertex(point); + } + + // Finish up + line1->dirty(); + line2->dirty(); +} + AnimatedLineNode::AnimatedLineNode(float lineWidth, bool depthBufferTest) : stipple1_(0xFF00), stipple2_(0x00FF), @@ -118,8 +147,8 @@ void AnimatedLineNode::setEndPoints(const simCore::Coordinate& first, const simC { firstCoord_ = simCore::MultiFrameCoordinate(first); secondCoord_ = second; - firstLocator_ = NULL; - secondLocator_ = NULL; + firstLocator_ = nullptr; + secondLocator_ = nullptr; // Assertion failure means bad input from developer for setting initial endpoint assert(firstCoord_->isValid()); } @@ -128,7 +157,7 @@ void AnimatedLineNode::setEndPoints(const Locator* first, const simCore::Coordin { secondCoord_ = second; firstLocator_ = first; - secondLocator_ = NULL; + secondLocator_ = nullptr; } void AnimatedLineNode::setEndPoints(const Locator* first, const Locator* second) @@ -139,7 +168,7 @@ void AnimatedLineNode::setEndPoints(const Locator* first, const Locator* second) int AnimatedLineNode::getEndPoints(simCore::MultiFrameCoordinate& coord1, simCore::MultiFrameCoordinate& coord2) const { - if (!line1_.valid()) + if (!firstHalf_.line1.valid()) return 1; coord1 = firstCoord_; coord2 = secondCoordMF_; @@ -206,31 +235,55 @@ void AnimatedLineNode::initializeGeometry_() // Geode to hold the geometry. geode_ = new osgEarth::LineGroup(); + firstHalf_.matrix = new osg::MatrixTransform; + secondHalf_.matrix = new osg::MatrixTransform; + geode_->addChild(firstHalf_.matrix); + geode_->addChild(secondHalf_.matrix); // First geometry: { - line1_ = new osgEarth::LineDrawable(GL_LINE_STRIP); - line1_->setName("simVis::AnimatedLine"); - line1_->setDataVariance(osg::Object::DYNAMIC); - line1_->allocate(2); - line1_->setColor(color1_); - line1_->setLineWidth(lineWidth_); - line1_->setStipplePattern(stipple1_); - line1_->dirty(); - geode_->addChild(line1_.get()); + firstHalf_.line1 = new osgEarth::LineDrawable(GL_LINE_STRIP); + firstHalf_.line1->setName("simVis::AnimatedLine"); + firstHalf_.line1->setDataVariance(osg::Object::DYNAMIC); + firstHalf_.line1->allocate(2); + firstHalf_.line1->setColor(color1_); + firstHalf_.line1->setLineWidth(lineWidth_); + firstHalf_.line1->setStipplePattern(stipple1_); + firstHalf_.line1->dirty(); + firstHalf_.matrix->addChild(firstHalf_.line1.get()); + + firstHalf_.line2 = new osgEarth::LineDrawable(GL_LINE_STRIP); + firstHalf_.line2->setName("simVis::AnimatedLine"); + firstHalf_.line2->setDataVariance(osg::Object::DYNAMIC); + firstHalf_.line2->allocate(2); + firstHalf_.line2->setColor(color2_); + firstHalf_.line2->setLineWidth(lineWidth_); + firstHalf_.line2->setStipplePattern(stipple2_); + firstHalf_.line2->dirty(); + firstHalf_.matrix->addChild(firstHalf_.line2.get()); } // Second geometry: { - line2_ = new osgEarth::LineDrawable(GL_LINE_STRIP); - line2_->setName("simVis::AnimatedLine"); - line2_->setDataVariance(osg::Object::DYNAMIC); - line2_->allocate(2); - line2_->setColor(color2_); - line2_->setLineWidth(lineWidth_); - line2_->setStipplePattern(stipple2_); - line2_->dirty(); - geode_->addChild(line2_.get()); + secondHalf_.line1 = new osgEarth::LineDrawable(GL_LINE_STRIP); + secondHalf_.line1->setName("simVis::AnimatedLine"); + secondHalf_.line1->setDataVariance(osg::Object::DYNAMIC); + secondHalf_.line1->allocate(2); + secondHalf_.line1->setColor(color1_); + secondHalf_.line1->setLineWidth(lineWidth_); + secondHalf_.line1->setStipplePattern(stipple1_); + secondHalf_.line1->dirty(); + secondHalf_.matrix->addChild(secondHalf_.line1.get()); + + secondHalf_.line2 = new osgEarth::LineDrawable(GL_LINE_STRIP); + secondHalf_.line2->setName("simVis::AnimatedLine"); + secondHalf_.line2->setDataVariance(osg::Object::DYNAMIC); + secondHalf_.line2->allocate(2); + secondHalf_.line2->setColor(color2_); + secondHalf_.line2->setLineWidth(lineWidth_); + secondHalf_.line2->setStipplePattern(stipple2_); + secondHalf_.line2->dirty(); + secondHalf_.matrix->addChild(secondHalf_.line2.get()); } // top-level state set sets up lighting, etc. @@ -296,10 +349,11 @@ void AnimatedLineNode::update_(double t) simCore::Vec3 ecef1; firstLocator_->getLocatorPosition(&ecef1); firstLocator_->sync(firstLocatorRevision_); - this->setMatrix(osg::Matrix::translate(ecef1.x(), ecef1.y(), ecef1.z())); + firstHalf_.matrix->setMatrix(osg::Matrix::translate(ecef1.x(), ecef1.y(), ecef1.z())); simCore::Vec3 ecef2; secondLocator_->getLocatorPosition(&ecef2); secondLocator_->sync(secondLocatorRevision_); + secondHalf_.matrix->setMatrix(osg::Matrix::translate(ecef2.x(), ecef2.y(), ecef2.z())); // Perform the bendy drawLine_(simCore::MultiFrameCoordinate(simCore::Coordinate(simCore::COORD_SYS_ECEF, ecef1)), simCore::MultiFrameCoordinate(simCore::Coordinate(simCore::COORD_SYS_ECEF, ecef2))); @@ -318,8 +372,7 @@ void AnimatedLineNode::update_(double t) const simCore::MultiFrameCoordinate coord1(simCore::Coordinate(simCore::COORD_SYS_ECEF, ecef1)); if (locatorMoved) { - // Need to update the local matrix - this->setMatrix(osg::Matrix::translate(ecef1.x(), ecef1.y(), ecef1.z())); + firstHalf_.matrix->setMatrix(osg::Matrix::translate(ecef1.x(), ecef1.y(), ecef1.z())); // Update the coordinate reference origin. Note that we could optimize this by // only setting the reference origin when the second coordinate is non-Geo (ECEF/LLA), @@ -335,6 +388,8 @@ void AnimatedLineNode::update_(double t) // Resolve the second coordinate (may or may not be relative, so we need a CoordinateConverter) simCore::MultiFrameCoordinate secondCoordMF; secondCoordMF.setCoordinate(secondCoord_, *coordinateConverter_); + const simCore::Coordinate& ecef2 = secondCoordMF.ecefCoordinate(); + secondHalf_.matrix->setMatrix(osg::Matrix::translate(ecef2.x(), ecef2.y(), ecef2.z())); drawLine_(coord1, secondCoordMF); } @@ -349,7 +404,7 @@ void AnimatedLineNode::update_(double t) { // Reset the matrix const simCore::Coordinate& ecef = firstCoord_->ecefCoordinate(); - this->setMatrix(osg::Matrix::translate(ecef.x(), ecef.y(), ecef.z())); + firstHalf_.matrix->setMatrix(osg::Matrix::translate(ecef.x(), ecef.y(), ecef.z())); // Need to also update the Coordinate Converter with new reference origin. Suffers // the same issue as case 2 for performance here, but is less likely to be a problem @@ -364,6 +419,8 @@ void AnimatedLineNode::update_(double t) // Resolve the second coordinate (may or may not be relative, so we need CoordinateConverter) simCore::MultiFrameCoordinate secondCoordMF; secondCoordMF.setCoordinate(secondCoord_, *coordinateConverter_); + const simCore::Coordinate& ecef = secondCoordMF.ecefCoordinate(); + secondHalf_.matrix->setMatrix(osg::Matrix::translate(ecef.x(), ecef.y(), ecef.z())); drawLine_(firstCoord_, secondCoordMF); } } @@ -373,29 +430,37 @@ void AnimatedLineNode::update_(double t) { if (useOverrideColor_) { - line1_->setColor(colorOverride_); - line2_->setColor(colorOverride_); + firstHalf_.line1->setColor(colorOverride_); + firstHalf_.line2->setColor(colorOverride_); + secondHalf_.line1->setColor(colorOverride_); + secondHalf_.line2->setColor(colorOverride_); } else { - line1_->setColor(color1_); - line2_->setColor(color2_); + firstHalf_.line1->setColor(color1_); + firstHalf_.line2->setColor(color2_); + secondHalf_.line1->setColor(color1_); + secondHalf_.line2->setColor(color2_); } } if (color1_.changed() && !useOverrideColor_) { - line1_->setColor(color1_); + firstHalf_.line1->setColor(color1_); + secondHalf_.line1->setColor(color1_); } if (color2_.changed() && !useOverrideColor_) { - line2_->setColor(color2_); + firstHalf_.line2->setColor(color2_); + secondHalf_.line2->setColor(color2_); } // LineDrawable is efficient in cases of no change - line1_->setLineWidth(lineWidth_); - line2_->setLineWidth(lineWidth_); + firstHalf_.line1->setLineWidth(lineWidth_); + firstHalf_.line2->setLineWidth(lineWidth_); + secondHalf_.line1->setLineWidth(lineWidth_); + secondHalf_.line2->setLineWidth(lineWidth_); // animate the line: const double dt = t - timeLastShift_; @@ -418,16 +483,19 @@ void AnimatedLineNode::update_(double t) ror(stipple2_, bits); } - line1_->setStipplePattern(stipple1_); - line2_->setStipplePattern(stipple2_); - + firstHalf_.line1->setStipplePattern(stipple1_); + firstHalf_.line2->setStipplePattern(stipple2_); + secondHalf_.line1->setStipplePattern(stipple1_); + secondHalf_.line2->setStipplePattern(stipple2_); timeLastShift_ = t; } else { // process changes to stipple even if line is not animating - line1_->setStipplePattern(stipple1_); - line2_->setStipplePattern(stipple2_); + firstHalf_.line1->setStipplePattern(stipple1_); + firstHalf_.line2->setStipplePattern(stipple2_); + secondHalf_.line1->setStipplePattern(stipple1_); + secondHalf_.line2->setStipplePattern(stipple2_); } } @@ -496,48 +564,26 @@ void AnimatedLineNode::drawSlantLine_(const simCore::MultiFrameCoordinate& start } // Reserve 2 points for the output - line1_->clear(); - line2_->clear(); - - // Calculate the reference point in ECEF - const osg::Vec3d zeroPoint = this->getMatrix().getTrans(); - - // Convert back to ECEF and add the vertex relative to the 0 point - simCore::CoordinateConverter cc; - const simCore::Coordinate& outEcef = endPoint.ecefCoordinate(); + firstHalf_.line1->clear(); + firstHalf_.line2->clear(); + secondHalf_.line1->clear(); + secondHalf_.line2->clear(); // Calculate the length of the vector - const osg::Vec3d lastPoint = osg::Vec3d(outEcef.x(), outEcef.y(), outEcef.z()) - zeroPoint; - const double distance = lastPoint.length(); - const double segmentLength = simCore::sdkMin(distance, MAX_SEGMENT_LENGTH); - - // make sure there's enough room. Don't bother shrinking. - const unsigned int numSegs = simCore::sdkMax(MIN_NUM_SEGMENTS, simCore::sdkMin(MAX_NUM_SEGMENTS, static_cast(distance / segmentLength))); - line1_->reserve(numSegs + 1); - line2_->reserve(numSegs + 1); - - // Add points to the vertex list, from back to front, for consistent stippling. Order - // matters because it affects the line direction during stippling. - for (unsigned int k = 0; k <= numSegs; ++k) - { - // Add in the subdivided line point - const double percentOfFull = static_cast((numSegs-k)) / numSegs; // From 1 to 0 - osg::Vec3f point = lastPoint * percentOfFull; - line1_->pushVertex(point); - line2_->pushVertex(point); - } - - // Finish up - line1_->dirty(); - line2_->dirty(); -} - -void AnimatedLineNode::dirtyGeometryBounds_() -{ - for (unsigned int i = 0; i < geode_->getNumDrawables(); ++i) - { - geode_->getDrawable(i)->dirtyBound(); - } + simCore::Vec3 delta; + simCore::v3Subtract(endPoint.ecefCoordinate().position(), startPoint.ecefCoordinate().position(), delta); + const double length = simCore::v3Length(delta); + + // Calculate the number of segments + const double segmentLength = simCore::sdkMin(length, MAX_SEGMENT_LENGTH); + unsigned int numSegs = simCore::sdkMax(MIN_NUM_SEGMENTS, simCore::sdkMin(MAX_NUM_SEGMENTS, static_cast(length / segmentLength))); + // Easier to divide an even number of segments into two lines + if ((numSegs % 2) == 1) + ++numSegs; + + osg::Vec3d midPoint(delta.x() / 2.0, delta.y() / 2.0, delta.z() / 2.0); + firstHalf_.fillSlantLine(numSegs / 2, midPoint, true); + secondHalf_.fillSlantLine(numSegs / 2, -midPoint, false); } void AnimatedLineNode::drawBendingLine_(const simCore::MultiFrameCoordinate& coord1, const simCore::MultiFrameCoordinate& coord2) @@ -554,28 +600,13 @@ void AnimatedLineNode::drawBendingLine_(const simCore::MultiFrameCoordinate& coo const simCore::Coordinate& lla2 = coord2.llaCoordinate(); // Use Sodano method to calculate azimuth and distance - double azimuth = 0.0; - const double distance = simCore::sodanoInverse(lla1.lat(), lla1.lon(), lla1.alt(), lla2.lat(), lla2.lon(), &azimuth); + double azfwd = 0.0; + const double distance = simCore::sodanoInverse(lla1.lat(), lla1.lon(), lla1.alt(), lla2.lat(), lla2.lon(), &azfwd); - // Calculate the reference point in ECEF - const osg::Vec3d zeroPoint = this->getMatrix().getTrans(); - - // purely vertical line will be drawn as a single segment + // purely vertical line will be drawn as a slant line if (distance <= 0.0) { - // Convert back to ECEF and add the vertex - const simCore::Coordinate& outEcef = coord2.ecefCoordinate(); - const osg::Vec3f p2 = osg::Vec3f(outEcef.x(), outEcef.y(), outEcef.z()) - zeroPoint; - - for (unsigned int i = 0; i < 2; ++i) - { - osgEarth::LineDrawable* line = geode_->getLineDrawable(i); - line->clear(); - line->pushVertex(p2); - line->pushVertex(osg::Vec3f()); - line->dirty(); - } - + drawSlantLine_(coord1, coord2); return; } @@ -588,34 +619,76 @@ void AnimatedLineNode::drawBendingLine_(const simCore::MultiFrameCoordinate& coo segmentLength = simCore::sdkMin(distance, MAX_SEGMENT_LENGTH_GROUNDED); } - // make sure there's enough room. Don't bother shrinking. - const unsigned int numSegs = simCore::sdkMax(MIN_NUM_SEGMENTS, simCore::sdkMin(MAX_NUM_SEGMENTS, static_cast(distance / segmentLength))); - osg::ref_ptr verts = new osg::Vec3Array(); - verts->reserve(numSegs + 1); + unsigned int numSegs = simCore::sdkMax(MIN_NUM_SEGMENTS, simCore::sdkMin(MAX_NUM_SEGMENTS, static_cast(distance / segmentLength))); + // Easier to divide an even number of segments into two lines + if ((numSegs % 2) == 1) + ++numSegs; - // Add points to the vertex list, from back to front, for consistent stippling. Order - // matters because it affects the line direction during stippling. - for (unsigned int k = 0; k < numSegs; ++k) + // Point 1 to midpoint { - const float percentOfFull = (float)(numSegs-k) / (float)numSegs; // From 1 to 0 (almost 0) - - // Calculate the LLA value of the point, and replace the altitude - double lat = 0.0; - double lon = 0.0; - simCore::sodanoDirect(lla1.lat(), lla1.lon(), lla1.alt(), distance * percentOfFull, azimuth, &lat, &lon); - const double alt = lla1.alt() + percentOfFull * (lla2.alt() - lla1.alt()); - - // Convert back to ECEF and add the vertex - simCore::Vec3 ecefPos; - simCore::CoordinateConverter::convertGeodeticPosToEcef(simCore::Vec3(lat, lon, alt), ecefPos); - verts->push_back(osg::Vec3f(ecefPos.x(), ecefPos.y(), ecefPos.z()) - zeroPoint); + const osg::Vec3d zeroPoint = firstHalf_.matrix->getMatrix().getTrans(); + + osg::ref_ptr verts = new osg::Vec3Array(); + verts->reserve(numSegs/2 + 1); + + // start at zero + verts->push_back(osg::Vec3f()); + + // Add points to the vertex list, from back to front, for consistent stippling. Order + // matters because it affects the line direction during stippling. + for (unsigned int k = 1; k <= numSegs/2; ++k) + { + const float percentOfFull = (float)k / (float)numSegs; // almost .0 to 0.5 + + // Calculate the LLA value of the point, and replace the altitude + double lat = 0.0; + double lon = 0.0; + simCore::sodanoDirect(lla1.lat(), lla1.lon(), lla1.alt(), distance * percentOfFull, azfwd, &lat, &lon); + const double alt = lla1.alt() + percentOfFull * (lla2.alt() - lla1.alt()); + + // Convert back to ECEF and add the vertex + simCore::Vec3 ecefPos; + simCore::CoordinateConverter::convertGeodeticPosToEcef(simCore::Vec3(lat, lon, alt), ecefPos); + verts->push_back(osg::Vec3f(ecefPos.x(), ecefPos.y(), ecefPos.z()) - zeroPoint); + } + + + + firstHalf_.line1->importVertexArray(verts.get()); + firstHalf_.line2->importVertexArray(verts.get()); } - // Finish up - verts->push_back(osg::Vec3f()); + // Point 2 to midpoint + { + const osg::Vec3d zeroPoint = secondHalf_.matrix->getMatrix().getTrans(); + + osg::ref_ptr verts = new osg::Vec3Array(); + verts->reserve(numSegs / 2 + 1); - geode_->getLineDrawable(0)->importVertexArray(verts.get()); - geode_->getLineDrawable(1)->importVertexArray(verts.get()); + // Add points to the vertex list, from back to front, for consistent stippling. Order + // matters because it affects the line direction during stippling. + for (unsigned int k = numSegs / 2; k < numSegs ; ++k) + { + const float percentOfFull = (float)(k) / (float)numSegs; // From .5 to almost 1.0 + + // Calculate the LLA value of the point, and replace the altitude + double lat = 0.0; + double lon = 0.0; + simCore::sodanoDirect(lla1.lat(), lla1.lon(), lla1.alt(), distance * percentOfFull, azfwd, &lat, &lon); + const double alt = lla1.alt() + percentOfFull * (lla2.alt() - lla1.alt()); + + // Convert back to ECEF and add the vertex + simCore::Vec3 ecefPos; + simCore::CoordinateConverter::convertGeodeticPosToEcef(simCore::Vec3(lat, lon, alt), ecefPos); + verts->push_back(osg::Vec3f(ecefPos.x(), ecefPos.y(), ecefPos.z()) - zeroPoint); + } + + // Finish up + verts->push_back(osg::Vec3f()); + + secondHalf_.line1->importVertexArray(verts.get()); + secondHalf_.line2->importVertexArray(verts.get()); + } } } diff --git a/SDK/simVis/AnimatedLine.h b/SDK/simVis/AnimatedLine.h index 95524841c..0f6b0c594 100644 --- a/SDK/simVis/AnimatedLine.h +++ b/SDK/simVis/AnimatedLine.h @@ -176,7 +176,6 @@ namespace simVis /** Return the class name */ virtual const char* className() const { return "AnimatedLineNode"; } - public: // osg::Node /** On the UPDATE_VISITOR traversal, calls update_() to animate the line */ virtual void traverse(osg::NodeVisitor& nv); @@ -214,8 +213,39 @@ namespace simVis // access to the geode so we can properly dirty the geometries' bounds osg::ref_ptr geode_; - osg::ref_ptr line1_; - osg::ref_ptr line2_; + + /** + * Lines longer than 100 kilometers can show significant jitter at the second point. + * This is due to using the first point as a reference (location (0,0,0)) and the second point + * is drawn relative to the first point with floating point resolution (32 bits). A + * user zooms in on the second point and sees the line "dance" around the second point. + * The solution is to divide the line into two halves. The first half goes from the + * first point to the mid point. The second half goes from the second point to the mid + * point. The two points are the references to their own line and consequently there + * is no "dancing" of the line around either point. The mid points may not line up and + * may "dance" independently. + */ + struct HalfALine + { + osg::ref_ptr matrix; + osg::ref_ptr line1; ///< Point 1 to midpoint + osg::ref_ptr line2; ///< Point 2 to midpoint + + HalfALine(); + virtual ~HalfALine(); + + /** + * Calculates the vertices from lastPoint (ECEF) to (0, 0, 0) with given number of segments. + * @param numSegments Number of segments between last point and (0, 0, 0) + * @param lastPoint The last point in ECEF + * @param forward If true add the vertices from (0, 0, 0) to last point, if false reverse the order + */ + void fillSlantLine(unsigned int numSegments, const osg::Vec3d& lastPoint, bool forward); + }; + + // Need continuous start to end for stipple to work correctly + HalfALine firstHalf_; ///< Start to Midpoint + HalfALine secondHalf_; ///< Midpoint to End // track time deltas for smooth animation double timeLastShift_; @@ -228,9 +258,6 @@ namespace simVis void initializeGeometry_(); void update_(double t); - /** Dirty the bounding box of all geometries */ - void dirtyGeometryBounds_(); - /** Returns true if a slant between two coordinates intersects earth surface */ bool doesLineIntersectEarth_(const simCore::MultiFrameCoordinate& coord1, const simCore::MultiFrameCoordinate& coord2) const; diff --git a/SDK/simVis/Antenna.cpp b/SDK/simVis/Antenna.cpp index 230f861c1..5cd29937e 100644 --- a/SDK/simVis/Antenna.cpp +++ b/SDK/simVis/Antenna.cpp @@ -87,7 +87,7 @@ namespace simVis // Geometry - contains the antenna primitives AntennaNode::AntennaNode(const osg::Quat& rot) - : antennaPattern_(NULL), + : antennaPattern_(nullptr), loadedOK_(false), beamRange_(1.0f), beamScale_(1.0f), @@ -172,7 +172,7 @@ bool AntennaNode::setPrefs(const simData::BeamPrefs& prefs) // Frequency must be > 0, if <= 0 use default value const double freq = prefs.frequency() > 0 ? prefs.frequency() : simCore::DEFAULT_FREQUENCY; antennaPattern_ = simCore::loadPatternFile(patternFile_, freq); - loadedOK_ = (antennaPattern_ != NULL); + loadedOK_ = (antennaPattern_ != nullptr); } polarity_ = static_cast(prefs.polarity()); @@ -335,14 +335,14 @@ void AntennaNode::render_() antGeom->setDataVariance(osg::Object::DYNAMIC); antGeom->setUseVertexBufferObjects(true); - osg::Vec3Array* verts = new osg::Vec3Array(); - antGeom->setVertexArray(verts); + osg::ref_ptr verts = new osg::Vec3Array(); + antGeom->setVertexArray(verts.get()); - osg::Vec3Array* norms = new osg::Vec3Array(osg::Array::BIND_PER_VERTEX); - antGeom->setNormalArray(norms); + osg::ref_ptr norms = new osg::Vec3Array(osg::Array::BIND_PER_VERTEX); + antGeom->setNormalArray(norms.get()); - osg::Vec4Array* colors = new osg::Vec4Array(osg::Array::BIND_PER_VERTEX); - antGeom->setColorArray(colors); + osg::ref_ptr colors = new osg::Vec4Array(osg::Array::BIND_PER_VERTEX); + antGeom->setColorArray(colors.get()); // expected range for vRange is (0, M_PI] const double vRange = osg::clampBetween(lastPrefs_->fieldofview(), std::numeric_limits::min(), M_PI); diff --git a/SDK/simVis/AreaHighlight.cpp b/SDK/simVis/AreaHighlight.cpp index 596fa176e..e1b767695 100644 --- a/SDK/simVis/AreaHighlight.cpp +++ b/SDK/simVis/AreaHighlight.cpp @@ -421,7 +421,7 @@ void CompositeHighlightNode::setShape(simData::CircleHilightShape shape) // Clear out child_, but hold onto it for the scope of this function osg::ref_ptr oldNode = child_; - child_ = NULL; + child_ = nullptr; // Most types are line geometry; try to cast up to avoid deleting LineDrawableHighlightNode* asLineDrawable = dynamic_cast(oldNode.get()); diff --git a/SDK/simVis/Beam.cpp b/SDK/simVis/Beam.cpp index 79bb2cd44..60856affe 100644 --- a/SDK/simVis/Beam.cpp +++ b/SDK/simVis/Beam.cpp @@ -49,7 +49,7 @@ namespace /// check for changes that require us to rebuild the entire beam. bool changeRequiresRebuild(const simData::BeamPrefs* a, const simData::BeamPrefs* b) { - if (a == NULL || b == NULL) + if (a == nullptr || b == nullptr) { return false; } @@ -85,7 +85,7 @@ namespace #ifdef BEAM_IN_PLACE_UPDATES return false; #else - if (a == NULL || b == NULL) + if (a == nullptr || b == nullptr) return false; return PB_FIELD_CHANGED(a, b, range); #endif @@ -105,7 +105,7 @@ BeamVolume::BeamVolume(const simData::BeamPrefs& prefs, const simData::BeamUpdat // if blended, use BIN_BEAM & TPA, otherwise use BIN_OPAQUE_BEAM & BIN_GLOBAL_SIMSDK osg::Geometry* solidGeometry = simVis::SVFactory::solidGeometry(beamSV_.get()); - if (solidGeometry != NULL) + if (solidGeometry != nullptr) { solidGeometry->getOrCreateStateSet()->setRenderBinDetails( (prefs.blended() ? BIN_BEAM : BIN_OPAQUE_BEAM), @@ -114,7 +114,7 @@ BeamVolume::BeamVolume(const simData::BeamPrefs& prefs, const simData::BeamUpdat // if there is a 2nd wireframe geode, it should be renderbin'd to BIN_OPAQUE_BEAM osg::Geode* wireframeGeode = simVis::SVFactory::opaqueGeode(beamSV_.get()); - if (wireframeGeode != NULL) + if (wireframeGeode != nullptr) { // SphericalVolume code only adds the opaque geode when it is adding a geometry or lineGroup assert(wireframeGeode->getNumDrawables() > 0); @@ -182,7 +182,7 @@ void BeamVolume::setBeamScale_(double beamScale) /// update prefs that can be updated without rebuilding the whole beam. void BeamVolume::performInPlacePrefChanges(const simData::BeamPrefs* a, const simData::BeamPrefs* b) { - if (a == NULL || b == NULL) + if (a == nullptr || b == nullptr) return; if (b->commonprefs().has_useoverridecolor() && b->commonprefs().useoverridecolor()) @@ -207,7 +207,7 @@ void BeamVolume::performInPlacePrefChanges(const simData::BeamPrefs* a, const si { // if blended, use BIN_BEAM & TPA, otherwise use BIN_OPAQUE_BEAM & BIN_GLOBAL_SIMSDK osg::Geometry* solidGeometry = simVis::SVFactory::solidGeometry(beamSV_.get()); - if (solidGeometry != NULL) + if (solidGeometry != nullptr) { solidGeometry->getOrCreateStateSet()->setRenderBinDetails( (b->blended() ? BIN_BEAM : BIN_OPAQUE_BEAM), @@ -227,7 +227,7 @@ void BeamVolume::performInPlacePrefChanges(const simData::BeamPrefs* a, const si void BeamVolume::performInPlaceUpdates(const simData::BeamUpdate* a, const simData::BeamUpdate* b) { - if (a == NULL || b == NULL) + if (a == nullptr || b == nullptr) return; #ifdef BEAM_IN_PLACE_UPDATES @@ -274,20 +274,21 @@ BeamNode::BeamNode(const ScenarioManager* scenario, const simData::BeamPropertie setLocator(beamOrientationLocator_.get()); setName("BeamNode"); - localGrid_ = new LocalGridNode(getLocator(), host, referenceYear); - addChild(localGrid_); - - // create the locator node that will parent our geometry and label + // create the locator node that will parent the geometry and label beamLocatorNode_ = new LocatorNode(getLocator()); beamLocatorNode_->setName("Beam Locator"); - beamLocatorNode_->setNodeMask(DISPLAY_MASK_NONE); - addChild(beamLocatorNode_); + beamLocatorNode_->setEntityToMonitor(this); + addChild(beamLocatorNode_.get()); + + // create localGrid_ after beamLocatorNode_ so beamLocatorNode_ is found in findAttachment() for tethering + localGrid_ = new LocalGridNode(getLocator(), host, referenceYear); + addChild(localGrid_.get()); // will be parented to the beamLocatorNode_ when shown antenna_ = new simVis::AntennaNode(osg::Quat(M_PI_2, osg::Vec3d(0., 0., 1.))); label_ = new EntityLabelNode(); - beamLocatorNode_->addChild(label_); + beamLocatorNode_->addChild(label_.get()); // horizon culling: entity culling based on bounding sphere addCullCallback( new osgEarth::HorizonCullCallback() ); @@ -301,6 +302,8 @@ BeamNode::BeamNode(const ScenarioManager* scenario, const simData::BeamPropertie // flatten in overhead mode. simVis::OverheadMode::enableGeometryFlattening(true, this); + // SIM-10724: Labels need to not be flattened to be displayed in overhead mode + simVis::OverheadMode::enableGeometryFlattening(false, label_.get()); } BeamNode::~BeamNode() {} @@ -372,7 +375,7 @@ void BeamNode::setPrefs(const simData::BeamPrefs& prefs) if (lastProps_.type() == simData::BeamProperties_BeamType_TARGET && (!hasLastPrefs_ || PB_FIELD_CHANGED(&lastPrefsApplied_, &prefs, targetid))) { - target_ = NULL; + target_ = nullptr; } applyPrefs_(prefs); @@ -384,7 +387,7 @@ void BeamNode::applyPrefs_(const simData::BeamPrefs& prefs, bool force) { if (prefsOverrides_.size() == 0) { - apply_(NULL, &prefs, force); + apply_(nullptr, &prefs, force); lastPrefsApplied_ = prefs; hasLastPrefs_ = true; } @@ -396,7 +399,7 @@ void BeamNode::applyPrefs_(const simData::BeamPrefs& prefs, bool force) { accumulated.MergeFrom(i->second); } - apply_(NULL, &accumulated, force); + apply_(nullptr, &accumulated, force); lastPrefsApplied_ = accumulated; hasLastPrefs_ = true; } @@ -404,7 +407,7 @@ void BeamNode::applyPrefs_(const simData::BeamPrefs& prefs, bool force) // manage beam pulse animation, creating it when necessary if (prefs.animate()) { - if (beamPulse_ == NULL) + if (beamPulse_ == nullptr) beamPulse_ = new simVis::BeamPulse(getOrCreateStateSet()); beamPulse_->setEnabled(true); @@ -412,7 +415,7 @@ void BeamNode::applyPrefs_(const simData::BeamPrefs& prefs, bool force) beamPulse_->setRate(static_cast(prefs.pulserate())); beamPulse_->setStipplePattern(prefs.pulsestipple()); } - else if (beamPulse_ != NULL) + else if (beamPulse_ != nullptr) beamPulse_->setEnabled(false); } @@ -422,26 +425,7 @@ void BeamNode::setHostMissileOffset(double hostMissileOffset) { hostMissileOffset_ = hostMissileOffset; // force a complete refresh - apply_(NULL, NULL, true); - } -} - -void BeamNode::setActive_(bool active) -{ - // beam can be active (datadraw) without being drawn - if (active) - { - // activate the locator node - beamLocatorNode_->setNodeMask(DISPLAY_MASK_BEAM); - } - else - { - setNodeMask(DISPLAY_MASK_NONE); - // deactivate the locator node - beamLocatorNode_->setNodeMask(DISPLAY_MASK_NONE); - beamLocatorNode_->removeChild(antenna_); - beamLocatorNode_->removeChild(beamVolume_); - beamVolume_ = NULL; + apply_(nullptr, nullptr, true); } } @@ -530,7 +514,10 @@ bool BeamNode::updateFromDataStore(const simData::DataSliceBase* updateSliceBase void BeamNode::flush() { hasLastUpdate_ = false; - setActive_(false); + setNodeMask(DISPLAY_MASK_NONE); + beamLocatorNode_->removeChild(antenna_); + beamLocatorNode_->removeChild(beamVolume_); + beamVolume_ = nullptr; } double BeamNode::range() const @@ -586,7 +573,7 @@ void BeamNode::applyUpdateOverrides_(bool force) { if (updateOverrides_.size() == 0) { - apply_(&lastUpdateFromDS_, NULL, force); + apply_(&lastUpdateFromDS_, nullptr, force); lastUpdateApplied_ = lastUpdateFromDS_; } else @@ -596,12 +583,14 @@ void BeamNode::applyUpdateOverrides_(bool force) { accumulated.MergeFrom(i->second); } - apply_(&accumulated, NULL, force); + apply_(&accumulated, nullptr, force); lastUpdateApplied_ = accumulated; } // we have applied a valid update, and both lastUpdateApplied_ and lastUpdateFromDS_ are valid hasLastUpdate_ = true; + // ensure that the locator node is in sync with its locator; a no-op id they are already in sync. + beamLocatorNode_->syncWithLocator(); } int BeamNode::calculateTargetBeam_(simData::BeamUpdate& targetBeamUpdate) @@ -609,16 +598,16 @@ int BeamNode::calculateTargetBeam_(simData::BeamUpdate& targetBeamUpdate) // this should only be called for target beams; if assert fails, check caller assert(lastProps_.type() == simData::BeamProperties_BeamType_TARGET); - // we should only receive non-NULL updates for target beams which have valid target ids; if assert fails check MemoryDataStore processing + // we should only receive non-nullptr updates for target beams which have valid target ids; if assert fails check MemoryDataStore processing assert(lastPrefsApplied_.targetid() > 0); // update our target reference, for new target, or after a prefs change in target ids occur - if (target_ == NULL || !target_.valid()) + if (target_ == nullptr || !target_.valid()) { if (scenario_.valid()) { target_ = scenario_->find(lastPrefsApplied_.targetid()); - // we should only receive an non-NULL update when target is valid; if assert fails check MemoryDataStore processing + // we should only receive an non-nullptr update when target is valid; if assert fails check MemoryDataStore processing assert(target_.valid()); } if (!target_.valid()) @@ -643,8 +632,8 @@ int BeamNode::calculateTargetBeam_(simData::BeamUpdate& targetBeamUpdate) double azimuth; double elevation; // let the simCore::Calculations implementation do coordinate conversions; it guarantees that only one initialization occurs for both these calculations. - simCore::calculateAbsAzEl(sourceLla, targetLla, &azimuth, &elevation, NULL, simCore::TANGENT_PLANE_WGS_84, NULL); - const double range = simCore::calculateSlant(sourceLla, targetLla, simCore::TANGENT_PLANE_WGS_84, NULL); + simCore::calculateAbsAzEl(sourceLla, targetLla, &azimuth, &elevation, nullptr, simCore::TANGENT_PLANE_WGS_84, nullptr); + const double range = simCore::calculateSlant(sourceLla, targetLla, simCore::TANGENT_PLANE_WGS_84, nullptr); targetBeamUpdate.set_azimuth(azimuth); targetBeamUpdate.set_elevation(elevation); targetBeamUpdate.set_range(range); @@ -682,10 +671,6 @@ void BeamNode::apply_(const simData::BeamUpdate* newUpdate, const simData::BeamP force = force || !hasLastUpdate_ || !hasLastPrefs_ || (newPrefs && PB_SUBFIELD_CHANGED(&lastPrefsApplied_, newPrefs, commonprefs, datadraw)); - // activate the locatorNode - if (force) - setActive_(true); - if (activePrefs->drawtype() == simData::BeamPrefs_DrawType_ANTENNA_PATTERN) { force = force || (newPrefs && PB_FIELD_CHANGED(&lastPrefsApplied_, newPrefs, drawtype)); @@ -708,7 +693,7 @@ void BeamNode::apply_(const simData::BeamUpdate* newUpdate, const simData::BeamP if (beamVolume_) { beamLocatorNode_->removeChild(beamVolume_); - beamVolume_ = NULL; + beamVolume_ = nullptr; } beamLocatorNode_->addChild(antenna_); dirtyBound(); @@ -729,13 +714,13 @@ void BeamNode::apply_(const simData::BeamUpdate* newUpdate, const simData::BeamP // if new geometry is required, build it: if (!beamVolume_ || refreshRequiresNewNode) { - // do not NULL antenna, it needs to persist to provide gain calcs + // do not nullptr antenna, it needs to persist to provide gain calcs beamLocatorNode_->removeChild(antenna_); if (beamVolume_) { beamLocatorNode_->removeChild(beamVolume_); - beamVolume_ = NULL; + beamVolume_ = nullptr; } beamVolume_ = new BeamVolume(*activePrefs, *activeUpdate); @@ -772,7 +757,7 @@ void BeamNode::apply_(const simData::BeamUpdate* newUpdate, const simData::BeamP if (visible && (force || newPrefs)) { // localgrid created in constructor. if assert fails, check for changes. - assert(localGrid_ != NULL); + assert(localGrid_ != nullptr); localGrid_->setPrefs(activePrefs->commonprefs().localgrid(), force); } } @@ -844,7 +829,7 @@ void BeamNode::updateLocator_(const simData::BeamUpdate* newUpdate, const simDat const simData::BeamUpdate* BeamNode::getLastUpdateFromDS() const { - return hasLastUpdate_ ? &lastUpdateFromDS_ : NULL; + return hasLastUpdate_ ? &lastUpdateFromDS_ : nullptr; } void BeamNode::setPrefsOverride(const std::string& id, const simData::BeamPrefs& prefs) @@ -897,7 +882,7 @@ double BeamNode::getClosestPoint(const simCore::Vec3& toLla, simCore::Vec3& clos simCore::calculateGeodeticEndPoint(startPosition, ori.yaw(), ori.pitch(), lastUpdateFromDS_.range(), endPosition); double distanceToBeam = simCore::getClosestPoint(startPosition, endPosition, toLla, closestLla); - const double distanceAlongBeam = simCore::sodanoInverse(startPosition.lat(), startPosition.lon(), startPosition.alt(), closestLla.lat(), closestLla.lon(), NULL, NULL); + const double distanceAlongBeam = simCore::sodanoInverse(startPosition.lat(), startPosition.lon(), startPosition.alt(), closestLla.lat(), closestLla.lon(), nullptr, nullptr); // Subtract the beam width from the distanceToBeam const double x = distanceAlongBeam * sin(0.5 * lastPrefsFromDS_.horizontalwidth()) * cos(ori.pitch()); diff --git a/SDK/simVis/Beam.h b/SDK/simVis/Beam.h index 67422ab12..d7c7999db 100644 --- a/SDK/simVis/Beam.h +++ b/SDK/simVis/Beam.h @@ -87,8 +87,8 @@ namespace simVis * @param host This beam's host entity * @param referenceYear The calculation for the Speed Rings Fixed Time preference needs the scenario reference year */ - BeamNode(const ScenarioManager* scenario, const simData::BeamProperties& props, Locator* locator = NULL, - const simVis::EntityNode* host = NULL, int referenceYear = 1970); + BeamNode(const ScenarioManager* scenario, const simData::BeamProperties& props, Locator* locator = nullptr, + const simVis::EntityNode* host = nullptr, int referenceYear = 1970); /** * Access the properties object currently representing this beam. @@ -147,7 +147,7 @@ namespace simVis void removeUpdateOverride(const std::string& id); /** - * Gets a pointer to the last data store update, or NULL if + * Gets a pointer to the last data store update, or nullptr if * none have been applied. */ const simData::BeamUpdate* getLastUpdateFromDS() const; @@ -221,7 +221,7 @@ namespace simVis /** * Updates the entity based on the bound data store. - * @param updateSlice Data store update slice (could be NULL) + * @param updateSlice Data store update slice (could be nullptr) * @param force true to force the update to be applied; false allows entity to use its own internal logic to decide whether the update should be applied * @return true if update applied, false if not */ @@ -243,7 +243,7 @@ namespace simVis /** * Gets the world position for this beam's origin. This is a convenience * function that extracts the Position information (not rotation) from the underlying locatorNode matrix. - * @param[out] out_position If not NULL, resulting position stored here, in coordinate system as specified by coordsys + * @param[out] out_position If not nullptr, resulting position stored here, in coordinate system as specified by coordsys * @param[in ] coordsys Requested coord sys of the output position (only LLA, ECEF, or ECI supported) * @return 0 if the output parameter is populated successfully, nonzero on failure */ @@ -252,8 +252,8 @@ namespace simVis /** * Gets the world position & orientation for this beam's origin. This is a convenience * function that extracts the Position information and rotation from the underlying locatorNode matrix. - * @param[out] out_position If not NULL, resulting position stored here, in coordinate system as specified by coordsys - * @param[out] out_orientation If not NULL, resulting orientation stored here, in coordinate system as specified by coordsys + * @param[out] out_position If not nullptr, resulting position stored here, in coordinate system as specified by coordsys + * @param[out] out_orientation If not nullptr, resulting orientation stored here, in coordinate system as specified by coordsys * @param[in ] coordsys Requested coord sys of the output position (only LLA, ECEF, or ECI supported) * @return 0 if the output parameter is populated successfully, nonzero on failure */ @@ -282,13 +282,6 @@ namespace simVis /** Copy constructor, not implemented or available. */ BeamNode(const BeamNode&); - /** - * Activate/Deactivate this beam, to be applied when a transition in state of isActive() occurs. - * note that a beam can be active (datadraw) without being drawn - * @param active if true, beam will be activated; if false beam will be deactivated - */ - void setActive_(bool active); - /// update the geometry based on changes in update or preferences. void apply_( const simData::BeamUpdate* update, diff --git a/SDK/simVis/BoxZoomMouseHandler.cpp b/SDK/simVis/BoxZoomMouseHandler.cpp index 0aacb5564..031243090 100644 --- a/SDK/simVis/BoxZoomMouseHandler.cpp +++ b/SDK/simVis/BoxZoomMouseHandler.cpp @@ -34,7 +34,9 @@ namespace simVis { BoxMouseHandler::BoxMouseHandler() - : buttonMask_(osgGA::GUIEventAdapter::LEFT_MOUSE_BUTTON), + : originX_(0.0), + originY_(0.0), + buttonMask_(osgGA::GUIEventAdapter::LEFT_MOUSE_BUTTON), modKeys_(new ModKeyHandler()), cancelDragKey_(osgGA::GUIEventAdapter::KEY_Escape) { @@ -94,7 +96,7 @@ bool BoxMouseHandler::handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionA // Only proceed is there is a current focused view simVis::View* view = dynamic_cast(aa.asView()); - if (view == NULL) + if (view == nullptr) return false; // Validate the view's suitability for use if (!validateView_(*view)) @@ -103,8 +105,8 @@ bool BoxMouseHandler::handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionA view_ = view; // view is unable to maintain watch or cockpit modes when box zooming - view_->enableWatchMode(NULL, NULL); - view_->enableCockpitMode(NULL); + view_->enableWatchMode(nullptr, nullptr); + view_->enableCockpitMode(nullptr); originX_ = ea.getX(); originY_ = ea.getY(); @@ -136,7 +138,7 @@ bool BoxMouseHandler::handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionA if (ext.isRatio_) { simVis::View* hostView = view_->getHostView(); - if (hostView == NULL) + if (hostView == nullptr) { // There's a view that defines its extents as ratio of host, but has no host. // This can happen while creating a view, but should not happen by the time box zooming occurs. @@ -178,9 +180,9 @@ bool BoxMouseHandler::handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionA return false; if (!box_.valid() || !view_.valid()) { - // Need to reset values here to satisfy post-conditions of both being NULL when not dragging - box_ = NULL; - view_ = NULL; + // Need to reset values here to satisfy post-conditions of both being nullptr when not dragging + box_ = nullptr; + view_ = nullptr; return false; } @@ -216,8 +218,8 @@ void BoxMouseHandler::stopDrag_() // Remove the box if (view_.valid() && box_.valid()) view_->getOrCreateHUD()->removeChild(box_); - box_ = NULL; - view_ = NULL; + box_ = nullptr; + view_ = nullptr; } //////////////////////////////////////////////////////////// @@ -267,7 +269,7 @@ void BoxZoomMouseHandler::calculateGeoPointFromScreenXY_(double x, double y, sim bool BoxZoomMouseHandler::validateView_(const simVis::View& view) const { - return (mapNodeForView_(view) != NULL); + return (mapNodeForView_(view) != nullptr); } void BoxZoomMouseHandler::processGeometry_(double originX, double originY, double widthPixels, double heightPixels) @@ -297,7 +299,7 @@ void BoxZoomMouseHandler::processGeometry_(double originX, double originY, doubl vp.range()->set(newRange, osgEarth::Units::METERS); } // Break tether - vp.setNode(NULL); + vp.setNode(nullptr); view_->setViewpoint(vp, durationSec_); return; } @@ -335,7 +337,7 @@ osgEarth::MapNode* BoxZoomMouseHandler::mapNodeForView_(const simVis::View& view simVis::SceneManager* sceneManager = view.getSceneManager(); if (sceneManager) return sceneManager->getMapNode(); - return NULL; + return nullptr; } } diff --git a/SDK/simVis/CMakeLists.txt b/SDK/simVis/CMakeLists.txt index 7dfadf5e5..02b197f4d 100644 --- a/SDK/simVis/CMakeLists.txt +++ b/SDK/simVis/CMakeLists.txt @@ -164,6 +164,7 @@ set(VIS_HEADERS_RFPROP ${VIS_INC}RFProp/OneWayPowerDataProvider.h ${VIS_INC}RFProp/PODProfileDataProvider.h ${VIS_INC}RFProp/Profile.h + ${VIS_INC}RFProp/ProfileContext.h ${VIS_INC}RFProp/ProfileDataProvider.h ${VIS_INC}RFProp/ProfileManager.h ${VIS_INC}RFProp/RadarParameters.h @@ -193,6 +194,7 @@ set(VIS_HEADERS_GOG ${VIS_INC}GOG/LatLonAltBox.h ${VIS_INC}GOG/Line.h ${VIS_INC}GOG/LineSegs.h + ${VIS_INC}GOG/Orbit.h ${VIS_INC}GOG/ParsedShape.h ${VIS_INC}GOG/Parser.h ${VIS_INC}GOG/Points.h @@ -312,6 +314,7 @@ set(VIS_SOURCES_RFPROP ${VIS_SRC}RFProp/OneWayPowerDataProvider.cpp ${VIS_SRC}RFProp/PODProfileDataProvider.cpp ${VIS_SRC}RFProp/Profile.cpp + ${VIS_SRC}RFProp/ProfileContext.cpp ${VIS_SRC}RFProp/ProfileManager.cpp ${VIS_SRC}RFProp/RFPropagationFacade.cpp ${VIS_SRC}RFProp/SNRDataProvider.cpp @@ -336,6 +339,7 @@ set(VIS_SOURCES_GOG ${VIS_SRC}GOG/LatLonAltBox.cpp ${VIS_SRC}GOG/Line.cpp ${VIS_SRC}GOG/LineSegs.cpp + ${VIS_SRC}GOG/Orbit.cpp ${VIS_SRC}GOG/ParsedShape.cpp ${VIS_SRC}GOG/Parser.cpp ${VIS_SRC}GOG/Points.cpp @@ -355,6 +359,14 @@ if(OSGEARTH_SILVERLINING_SUPPORT STREQUAL NODEKIT) set(HAVE_SILVERLINING_NODEKIT 1) endif() +# Detect the rename of osgEarth/ThreadingUtils to osgEarth/Threading +if(EXISTS "${OSGEARTH_LIBRARY_INCLUDE_PATH}/osgEarth/Threading") + set(HAVE_OSGEARTH_THREADING 1) +endif() +# Detect change in ElevationPool::WorkingSet's LRU class, added in changeset (eed04b8a69) +include(CheckOSGEarthMethodExists) +check_osgearth_method_exists(HAVE_WORKINGSET_STRONGLRU "osgEarth/ElevationPool" "StrongLRU") + # TODO Once OSGEarth master hits 3.0, test properly. For now, hardcode set(SDK_OSGEARTH_DEVEL 1) # We require osgEarth 3.0 and osgEarth from 1.11 and prior are not usable @@ -448,6 +460,9 @@ if(SIM_HAVE_DB_SUPPORT) target_compile_definitions(simVis PRIVATE SIM_LITTLE_ENDIAN) endif() endif() +if(HAVE_WORKINGSET_STRONGLRU) + target_compile_definitions(simVis PRIVATE HAVE_WORKINGSET_STRONGLRU) +endif() if(INSTALL_SIMDIS_SDK_LIBRARIES) vsi_install_export(simVis ${SIMDIS_SDK_VERSION_STRING} AnyNewerVersion) diff --git a/SDK/simVis/CentroidManager.cpp b/SDK/simVis/CentroidManager.cpp index df7ac1e99..efad574ee 100644 --- a/SDK/simVis/CentroidManager.cpp +++ b/SDK/simVis/CentroidManager.cpp @@ -71,15 +71,15 @@ CentroidManager::~CentroidManager() AveragePositionNode* CentroidManager::createCentroid(const std::vector& inNodes, View* view) { - // Nothing to do with an empty node vector or a NULL view + // Nothing to do with an empty node vector or a nullptr view if (!view || inNodes.empty()) - return NULL; + return nullptr; - // Remove NULL nodes + // Remove nullptr nodes std::vector nodes(inNodes); - nodes.erase(std::remove(nodes.begin(), nodes.end(), static_cast(NULL)), nodes.end()); + nodes.erase(std::remove(nodes.begin(), nodes.end(), static_cast(nullptr)), nodes.end()); if (nodes.empty()) - return NULL; + return nullptr; CentroidInfo info; auto viewIter = centroids_.find(view); @@ -91,7 +91,7 @@ AveragePositionNode* CentroidManager::createCentroid(const std::vector& nodes, View* view) { - // Nothing to do with an empty node vector or a NULL view + // Nothing to do with an empty node vector or a nullptr view if (!view || nodes.empty()) return; diff --git a/SDK/simVis/CentroidManager.h b/SDK/simVis/CentroidManager.h index 9f02ae616..c1e6aa599 100644 --- a/SDK/simVis/CentroidManager.h +++ b/SDK/simVis/CentroidManager.h @@ -48,7 +48,7 @@ class SDKVIS_EXPORT CentroidManager : public osg::Group /** * Create a centroid using the given nodes. Returns a pointer to the - * created centroid. Will return NULL if the given view is invalid or + * created centroid. Will return nullptr if the given view is invalid or * if nodes is empty or filled with invalid pointers. * @param inNodes Vector of EntityNodes about which to center the view * @param view View to tether to the centroid diff --git a/SDK/simVis/ClassificationBanner.cpp b/SDK/simVis/ClassificationBanner.cpp index 6cdcb5968..1e9886eec 100644 --- a/SDK/simVis/ClassificationBanner.cpp +++ b/SDK/simVis/ClassificationBanner.cpp @@ -58,7 +58,7 @@ void SetToClassificationTextCallback::onScenarioPropertiesChange(simData::DataSt static const float OUTLINE_THICKNESS = 0.03f; ClassificationLabelNode::ClassificationLabelNode() - : dataStore_(NULL) + : dataStore_(nullptr) { listener_.reset(new simVis::SetToClassificationTextCallback(this)); @@ -75,7 +75,7 @@ ClassificationLabelNode::ClassificationLabelNode() ClassificationLabelNode::ClassificationLabelNode(const ClassificationLabelNode& node, const osg::CopyOp& copyop) : Text(node, copyop), - dataStore_(NULL) + dataStore_(nullptr) { listener_.reset(new simVis::SetToClassificationTextCallback(this)); bindTo(node.dataStore_); @@ -189,8 +189,8 @@ ClassificationBanner::ClassificationBanner(simData::DataStore* dataStore, unsign ClassificationBanner::~ClassificationBanner() { - classLabelUpper_->bindTo(NULL); - classLabelLower_->bindTo(NULL); + classLabelUpper_->bindTo(nullptr); + classLabelLower_->bindTo(nullptr); } void ClassificationBanner::addToView(simVis::View* managedView) diff --git a/SDK/simVis/ClassificationBanner.h b/SDK/simVis/ClassificationBanner.h index e5627c3fd..1e9950ea0 100644 --- a/SDK/simVis/ClassificationBanner.h +++ b/SDK/simVis/ClassificationBanner.h @@ -61,17 +61,17 @@ class SDKVIS_EXPORT ClassificationLabelNode : public osgText::Text /** * Binds the label to the data store, so that the label's content and color represents - * the values in the data store's scenario properties. Pass in NULL to unbind. The + * the values in the data store's scenario properties. Pass in nullptr to unbind. The * label can only be bound to a single data store. * @param ds Data store that supplies the classification text and color through scenario - * properties. Use NULL to unbind from the data store. + * properties. Use nullptr to unbind from the data store. */ void bindTo(simData::DataStore* ds); // Override osgText::Text methods virtual osg::Object* cloneType() const { return new ClassificationLabelNode(); } virtual osg::Object* clone(const osg::CopyOp& copyop) const { return new ClassificationLabelNode(*this, copyop); } - virtual bool isSameKindAs(const osg::Object* obj) const { return dynamic_cast(obj) != NULL; } + virtual bool isSameKindAs(const osg::Object* obj) const { return dynamic_cast(obj) != nullptr; } virtual const char* className() const { return "ClassificationLabelNode"; } virtual const char* libraryName() const { return "simVis"; } diff --git a/SDK/simVis/Compass.cpp b/SDK/simVis/Compass.cpp index 8f601ccc6..bc724bfd7 100644 --- a/SDK/simVis/Compass.cpp +++ b/SDK/simVis/Compass.cpp @@ -99,7 +99,7 @@ class CompassFocusManagerAdapter::FocusCallback : public simVis::FocusManager::C CompassFocusManagerAdapter::CompassFocusManagerAdapter(simVis::FocusManager* focusManager, simVis::CompassNode* compass) : focusManager_(focusManager), compass_(compass), - callback_(NULL) + callback_(nullptr) { callback_ = new FocusCallback(this); focusManager_->addCallback(callback_.get()); @@ -180,18 +180,18 @@ void CompassNode::initCompass_(const std::string& compassFilename) compassImageXform_->setMatrix(osg::Matrix::translate(osg::Vec3f(0.f, 0.f, -0.01f))); // Add a red line (tristrip) to indicate the pointing angle - osg::Geometry* pointer = new osg::Geometry; - osg::Vec3Array* points = new osg::Vec3Array; + osg::ref_ptr pointer = new osg::Geometry; + osg::ref_ptr points = new osg::Vec3Array; points->push_back(osg::Vec3(-0.5f, POS_POINTING_MIN_Y, 0.f)); points->push_back(osg::Vec3(0.5f, POS_POINTING_MIN_Y, 0.f)); points->push_back(osg::Vec3(-0.5f, POS_POINTING_MAX_Y, 0.f)); points->push_back(osg::Vec3(0.5f, POS_POINTING_MAX_Y, 0.f)); - osg::Vec4Array* colors = new osg::Vec4Array; + osg::ref_ptr colors = new osg::Vec4Array; colors->push_back(POINTING_LINE_COLOR); - pointer->setVertexArray(points); - pointer->setColorArray(colors, osg::Array::BIND_OVERALL); + pointer->setVertexArray(points.get()); + pointer->setColorArray(colors.get(), osg::Array::BIND_OVERALL); pointer->addPrimitiveSet(new osg::DrawArrays(GL_TRIANGLE_STRIP, 0, 4)); - addChild(pointer); + addChild(pointer.get()); } void CompassNode::initWindVane_() @@ -287,7 +287,7 @@ void CompassNode::updateCompass_() { // Figure out the camera heading; use EarthManipulator to account for tether mode rotations const osgEarth::Util::EarthManipulator* manip = dynamic_cast(view->getCameraManipulator()); - if (manip != NULL) + if (manip != nullptr) { manip->getCompositeEulerAngles(&headingDeg); // Convert to degrees @@ -397,8 +397,8 @@ class Compass::RepositionEventHandler : public osgGA::GUIEventHandler if (ea.getEventType() == osgGA::GUIEventAdapter::FRAME) { const osg::View* view = aa.asView(); - const osg::Camera* camera = (view ? view->getCamera() : NULL); - const osg::Viewport* viewport = (camera ? camera->getViewport() : NULL); + const osg::Camera* camera = (view ? view->getCamera() : nullptr); + const osg::Viewport* viewport = (camera ? camera->getViewport() : nullptr); if (viewport) { osg::Vec2d newWh(viewport->width(), viewport->height()); @@ -434,7 +434,7 @@ Compass::~Compass() void Compass::setDrawView(simVis::View* drawView) { - if (drawView == NULL) + if (drawView == nullptr) { removeFromView(); return; @@ -472,7 +472,7 @@ void Compass::removeFromView() // stop callbacks for frame updates drawView_->removeEventHandler(repositionEventHandler_.get()); drawView_->getOrCreateHUD()->removeChild(this); - drawView_ = NULL; + drawView_ = nullptr; } } diff --git a/SDK/simVis/Compass.h b/SDK/simVis/Compass.h index 6c72762c1..67e949c40 100644 --- a/SDK/simVis/Compass.h +++ b/SDK/simVis/Compass.h @@ -49,7 +49,7 @@ class SDKVIS_EXPORT CompassFocusManagerAdapter virtual ~CompassFocusManagerAdapter(); /** - * Tell our compass to focus this view, which may be NULL + * Tell our compass to focus this view, which may be nullptr * @param focusedView Swap the compass to report values from this view (make it active) */ void focusView(simVis::View* focusedView); @@ -197,7 +197,7 @@ class SDKVIS_EXPORT Compass : public CompassNode * Display the Compass node as an overlay in the specified view * @param drawView View on which the compass is drawn (in lower right corner). May * be different than the active view, which feeds the heading values for compass. - * Passing in NULL is equivalent to calling removeFromView(). + * Passing in nullptr is equivalent to calling removeFromView(). */ void setDrawView(simVis::View* drawView); @@ -207,7 +207,7 @@ class SDKVIS_EXPORT Compass : public CompassNode */ void removeFromView(); - /** Retrieves the current draw view (may be NULL) */ + /** Retrieves the current draw view (may be nullptr) */ simVis::View* drawView() const; /// Override traverse() to adjust the active view in some cases diff --git a/SDK/simVis/CustomRendering.cpp b/SDK/simVis/CustomRendering.cpp index 7c9e374dd..1d5c3067f 100644 --- a/SDK/simVis/CustomRendering.cpp +++ b/SDK/simVis/CustomRendering.cpp @@ -68,8 +68,7 @@ CustomRenderingNode::CustomRenderingNode(const ScenarioManager* scenario, const // create the locator node that will parent our geometry customLocatorNode_ = new LocatorNode(getLocator()); - // Locator node starts turned off until an update is received to turn it on - customLocatorNode_->setNodeMask(0); + customLocatorNode_->setEntityToMonitor(this); addChild(customLocatorNode_); // Apply the override color shader to the container @@ -163,7 +162,7 @@ void CustomRenderingNode::setPrefs(const simData::CustomRenderingPrefs& prefs) { const bool prefsDraw = prefs.commonprefs().datadraw() && prefs.commonprefs().draw(); // Visibility is determined by both customActive_ and draw state preferences - setNodeMask_((customActive_ && prefsDraw) ? simVis::DISPLAY_MASK_CUSTOM_RENDERING : simVis::DISPLAY_MASK_NONE); + setNodeMask((customActive_ && prefsDraw) ? simVis::DISPLAY_MASK_CUSTOM_RENDERING : simVis::DISPLAY_MASK_NONE); if (prefsDraw) updateLabel_(prefs); @@ -242,7 +241,7 @@ const std::string CustomRenderingNode::getEntityName(EntityNode::NameType nameTy bool CustomRenderingNode::updateFromDataStore(const simData::DataSliceBase* updateSliceBase, bool force) { - if (updateCallback_ == NULL) + if (updateCallback_ == nullptr) return false; if (updateCallback_->update(updateSliceBase, force)) @@ -262,7 +261,7 @@ bool CustomRenderingNode::updateFromDataStore(const simData::DataSliceBase* upda void CustomRenderingNode::flush() { - setNodeMask_(DISPLAY_MASK_NONE); + setNodeMask(DISPLAY_MASK_NONE); } int CustomRenderingNode::getPosition(simCore::Vec3* out_position, simCore::CoordinateSystem coordsys) const @@ -297,7 +296,7 @@ void CustomRenderingNode::setCustomActive(bool value) if (hasLastPrefs_) prefsDraw = lastPrefs_.commonprefs().datadraw() && lastPrefs_.commonprefs().draw(); // Visibility is determined by both customActive_ and draw state preferences - setNodeMask_((customActive_ && prefsDraw) ? DISPLAY_MASK_CUSTOM_RENDERING : DISPLAY_MASK_NONE); + setNodeMask((customActive_ && prefsDraw) ? DISPLAY_MASK_CUSTOM_RENDERING : DISPLAY_MASK_NONE); } LocatorNode* CustomRenderingNode::locatorNode() const @@ -336,10 +335,4 @@ void CustomRenderingNode::getPickingPoints(std::vector& ecefVec) con ecefVec.push_back(osg::Vec3d(locatorNodeEcef.x(), locatorNodeEcef.y(), locatorNodeEcef.z())); } -void CustomRenderingNode::setNodeMask_(unsigned int mask) -{ - setNodeMask(mask); - customLocatorNode_->setNodeMask(mask == 0 ? 0 : ~0); -} - } diff --git a/SDK/simVis/CustomRendering.h b/SDK/simVis/CustomRendering.h index dadf50d99..410cc23e2 100644 --- a/SDK/simVis/CustomRendering.h +++ b/SDK/simVis/CustomRendering.h @@ -52,7 +52,7 @@ class SDKVIS_EXPORT CustomRenderingNode : public EntityNode * @param referenceYear The calculation for the Speed Rings Fixed Time preference needs the scenario reference year */ CustomRenderingNode(const ScenarioManager* scenario, const simData::CustomRenderingProperties& props, - const simVis::EntityNode* host = NULL, int referenceYear = 1970); + const simVis::EntityNode* host = nullptr, int referenceYear = 1970); /** * Access the properties object currently representing this custom. @@ -165,7 +165,7 @@ class SDKVIS_EXPORT CustomRenderingNode : public EntityNode /** * Updates the entity based on the bound data store. - * @param updateSlice Data store update slice (could be NULL) + * @param updateSlice Data store update slice (could be nullptr) * @param force true to force the update to be applied; false allows entity to use its own internal logic to decide whether the update should be applied * @return true if update applied, false if not */ @@ -183,7 +183,7 @@ class SDKVIS_EXPORT CustomRenderingNode : public EntityNode /** * Gets the world position for this custom's origin. This is a convenience * function that extracts the Position information (not rotation) from the underlying locatorNode matrix. - * @param[out] out_position If not NULL, resulting position stored here, in coordinate system as specified by coordsys + * @param[out] out_position If not nullptr, resulting position stored here, in coordinate system as specified by coordsys * @param[in ] coordsys Requested coord sys of the output position (only LLA, ECEF, or ECI supported) * @return 0 if the output parameter is populated successfully, nonzero on failure */ @@ -192,8 +192,8 @@ class SDKVIS_EXPORT CustomRenderingNode : public EntityNode /** * Gets the world position & orientation for this custom's origin. This is a convenience * function that extracts the Position information and rotation from the underlying locatorNode matrix. - * @param[out] out_position If not NULL, resulting position stored here, in coordinate system as specified by coordsys - * @param[out] out_orientation If not NULL, resulting orientation stored here, in coordinate system as specified by coordsys + * @param[out] out_position If not nullptr, resulting position stored here, in coordinate system as specified by coordsys + * @param[out] out_orientation If not nullptr, resulting orientation stored here, in coordinate system as specified by coordsys * @param[in ] coordsys Requested coord sys of the output position (only LLA, ECEF, or ECI supported) * @return 0 if the output parameter is populated successfully, nonzero on failure */ @@ -215,7 +215,7 @@ class SDKVIS_EXPORT CustomRenderingNode : public EntityNode // Expose the locator node so an outside source can add graphics. LocatorNode* locatorNode() const; - /// Returns the host. May be NULL if hosted under the scenario with no parent + /// Returns the host. May be nullptr if hosted under the scenario with no parent const EntityNode* host() const; /* @@ -256,12 +256,6 @@ class SDKVIS_EXPORT CustomRenderingNode : public EntityNode */ void updateOverrideColor_(const simData::CustomRenderingPrefs& prefs); - /** - * Set the node mask for this object and its locator - * @param mask Node mask to set on this object and its locator - */ - void setNodeMask_(unsigned int mask); - osg::observer_ptr scenario_; osg::observer_ptr host_; osg::ref_ptr contentCallback_; @@ -283,4 +277,3 @@ class SDKVIS_EXPORT CustomRenderingNode : public EntityNode } //namespace simVis #endif //SIMVIS_CUSTOM_H - diff --git a/SDK/simVis/CylinderGeode.cpp b/SDK/simVis/CylinderGeode.cpp index 1850b0536..11b997d91 100644 --- a/SDK/simVis/CylinderGeode.cpp +++ b/SDK/simVis/CylinderGeode.cpp @@ -44,14 +44,14 @@ CylinderGeode::CylinderGeode(PlatformNode &hostPlatform) stateSet->setRenderBinDetails(BIN_CYLINDER, BIN_TWO_PASS_ALPHA); // Add to the platform - if (hostPlatform.getModel() != NULL) + if (hostPlatform.getModel() != nullptr) hostPlatform.getModel()->addScaledChild(transform_.get()); } CylinderGeode::~CylinderGeode() { removeFromScene_(); - transform_ = NULL; + transform_ = nullptr; } void CylinderGeode::rebuild_() diff --git a/SDK/simVis/CylinderStorage.cpp b/SDK/simVis/CylinderStorage.cpp index a46ae2a16..75388631e 100644 --- a/SDK/simVis/CylinderStorage.cpp +++ b/SDK/simVis/CylinderStorage.cpp @@ -139,7 +139,7 @@ void CylinderStorage::addCylinderData(simData::ObjectId platId, uint64_t cylinde return; } - if (dataStoreListener_ == NULL) + if (dataStoreListener_ == nullptr) { // Listens for changes to the dataStore dataStoreListener_.reset(new DataStoreListener(*this)); diff --git a/SDK/simVis/DB/QSNodeID96.cpp b/SDK/simVis/DB/QSNodeID96.cpp index 59c810081..fda3c4086 100644 --- a/SDK/simVis/DB/QSNodeID96.cpp +++ b/SDK/simVis/DB/QSNodeID96.cpp @@ -226,7 +226,7 @@ QSNodeID96 QSNodeID96::operator&(const QSNodeID96& value) const //--------------------------------------------------------------------------- void QSNodeID96::pack(uint8_t* buffer) const { - if (buffer == NULL) + if (buffer == nullptr) return; beWrite(buffer, &three_); beWrite(buffer + sizeof(three_), &two_); @@ -236,7 +236,7 @@ void QSNodeID96::pack(uint8_t* buffer) const //--------------------------------------------------------------------------- void QSNodeID96::unpack(const uint8_t* buffer) { - if (buffer == NULL) + if (buffer == nullptr) return; beRead(buffer, &three_); beRead(buffer + sizeof(three_), &two_); diff --git a/SDK/simVis/DB/QSPosXYExtents.cpp b/SDK/simVis/DB/QSPosXYExtents.cpp index ab4f31c20..ef0d450df 100644 --- a/SDK/simVis/DB/QSPosXYExtents.cpp +++ b/SDK/simVis/DB/QSPosXYExtents.cpp @@ -68,7 +68,7 @@ void PosXPosYExtents::setAll(const QsPosType& minXIn, const QsPosType& maxXIn, c void PosXPosYExtents::pack(uint8_t* buffer) const { - if (buffer == NULL) + if (buffer == nullptr) return; beWrite(buffer, &minX); beWrite(buffer + sizeof(minX), &maxX); @@ -78,7 +78,7 @@ void PosXPosYExtents::pack(uint8_t* buffer) const void PosXPosYExtents::unpack(const uint8_t* buffer) { - if (buffer == NULL) + if (buffer == nullptr) return; beRead(buffer, &minX); beRead(buffer + sizeof(minX), &maxX); diff --git a/SDK/simVis/DB/SQLiteDataBaseReadUtil.cpp b/SDK/simVis/DB/SQLiteDataBaseReadUtil.cpp index 66704a249..45008832c 100644 --- a/SDK/simVis/DB/SQLiteDataBaseReadUtil.cpp +++ b/SDK/simVis/DB/SQLiteDataBaseReadUtil.cpp @@ -35,7 +35,7 @@ namespace template void unpackArray(SomeClass* givenArray, const uint8_t* givenBuffer, const uint32_t& numElements) { - if ((givenArray == NULL) || (givenBuffer == NULL)) + if ((givenArray == nullptr) || (givenBuffer == nullptr)) return; size_t i; @@ -137,11 +137,11 @@ QsErrorType SQLiteDataBaseReadUtil::openDatabaseFile(const std::string& dbFileNa sqlite3** sqlite3Db, const int& flags) const { - if (dbFileName.empty() || (sqlite3Db == NULL)) + if (dbFileName.empty() || (sqlite3Db == nullptr)) return QS_IS_UNABLE_TO_OPEN_DB; // Attempts to open the database file - int errorCode = sqlite3_open_v2(dbFileName.c_str(), sqlite3Db, flags, NULL); + int errorCode = sqlite3_open_v2(dbFileName.c_str(), sqlite3Db, flags, nullptr); if ((*sqlite3Db == 0) || (errorCode != SQLITE_OK)) { if ((errorCode == SQLITE_BUSY) || @@ -150,7 +150,7 @@ QsErrorType SQLiteDataBaseReadUtil::openDatabaseFile(const std::string& dbFileNa std::cerr << "openDatabaseFile sqlite3_open_v2 Error: " << dbFileName << "\n" << printExtendedErrorMessage(*sqlite3Db); return QS_IS_UNABLE_TO_OPEN_DB; } - if (sqlite3_exec(*sqlite3Db, "PRAGMA CACHE_SIZE=100;", NULL, NULL, NULL) != SQLITE_OK) + if (sqlite3_exec(*sqlite3Db, "PRAGMA CACHE_SIZE=100;", nullptr, nullptr, nullptr) != SQLITE_OK) { std::cerr << "Unable to set SQLite cache size " << dbFileName << "\n"; std::cerr << printExtendedErrorMessage(*sqlite3Db); @@ -173,17 +173,23 @@ QsErrorType SQLiteDataBaseReadUtil::readDataBuffer(sqlite3* sqlite3Db, { int returnValue; - if ((buffer == NULL) || (bufferSize == NULL) || (currentRasterSize == NULL)) + if ((buffer == nullptr) || (bufferSize == nullptr) || (currentRasterSize == nullptr)) return QS_IS_UNEXPECTED_NULL; *currentRasterSize = 0; if (dataTableName.empty() || dbFileName.empty()) return QS_IS_EMPTY_TABLE_NAME; + // Reject names with quotes to avoid injections + if (dataTableName.find('"') != std::string::npos) + { + std::cerr << "readDataBuffer invalid table name (" << dataTableName << ")\n"; + return QS_IS_PREPARE_ERROR; + } // opens the database bool localDb = false; - if (sqlite3Db == NULL) + if (sqlite3Db == nullptr) { if (allowLocalDB == false) return QS_IS_DB_NOT_INITIALIZED; @@ -193,6 +199,8 @@ QsErrorType SQLiteDataBaseReadUtil::readDataBuffer(sqlite3* sqlite3Db, return tmpReturnValue; } + // Note that injection is not possible here due to quotes in configuration string, + // and rejection of strings with quotes. SQLite permits nearly any table name. std::string sqlCommand; sqlCommand = textureSetSelectFileCommand1_; sqlCommand.append(dataTableName); @@ -200,14 +208,14 @@ QsErrorType SQLiteDataBaseReadUtil::readDataBuffer(sqlite3* sqlite3Db, // prepares the statement sqlite3_stmt* stmt = 0; - returnValue = sqlite3_prepare_v2(sqlite3Db, sqlCommand.c_str(), static_cast(sqlCommand.length()), &stmt, NULL); + returnValue = sqlite3_prepare_v2(sqlite3Db, sqlCommand.c_str(), static_cast(sqlCommand.length()), &stmt, nullptr); if (returnValue != SQLITE_OK) { if (displayErrorMessage && (returnValue != SQLITE_BUSY && returnValue != SQLITE_LOCKED)) { std::cerr << "readDataBuffer sqlite3_prepare_v2 Error(" << returnValue << "): " << dbFileName << "\n" << printExtendedErrorMessage(sqlite3Db); } - if (stmt != NULL) sqlite3_finalize(stmt); + if (stmt != nullptr) sqlite3_finalize(stmt); if (localDb) sqlite3_close(sqlite3Db); if ((returnValue == SQLITE_BUSY) || (returnValue == SQLITE_LOCKED)) @@ -237,7 +245,7 @@ QsErrorType SQLiteDataBaseReadUtil::readDataBuffer(sqlite3* sqlite3Db, { if (*currentRasterSize > (*bufferSize)) { - if ((*buffer) != NULL) + if ((*buffer) != nullptr) delete[] * buffer; *buffer = new uint8_t[*currentRasterSize]; *bufferSize = (*currentRasterSize); @@ -260,7 +268,7 @@ QsErrorType SQLiteDataBaseReadUtil::readDataBuffer(sqlite3* sqlite3Db, otherReturnValue = QS_IS_UNABLE_TO_READ_DATA_BUFFER; } - if (stmt != NULL) sqlite3_finalize(stmt); + if (stmt != nullptr) sqlite3_finalize(stmt); if (localDb) { returnValue = sqlite3_close(sqlite3Db); @@ -286,7 +294,7 @@ QsErrorType SQLiteDataBaseReadUtil::getSetFromListOfSetsTable(sqlite3* sqlite3Db bool& timeSpecified, simCore::TimeStamp& timeStamp) const { - if (sqlite3Db == NULL) + if (sqlite3Db == nullptr) return QS_IS_DB_NOT_INITIALIZED; if (tableName.empty()) return QS_IS_EMPTY_TABLE_NAME; @@ -296,11 +304,11 @@ QsErrorType SQLiteDataBaseReadUtil::getSetFromListOfSetsTable(sqlite3* sqlite3Db // prepares the statement sqlite3_stmt* stmt = 0; - returnValue = sqlite3_prepare_v2(sqlite3Db, textureSetSelectCommand_.c_str(), static_cast(textureSetSelectCommand_.length()), &stmt, NULL); + returnValue = sqlite3_prepare_v2(sqlite3Db, textureSetSelectCommand_.c_str(), static_cast(textureSetSelectCommand_.length()), &stmt, nullptr); if (returnValue != SQLITE_OK) { std::cerr << "getSetFromListOfSetsTable sqlite3_prepare_v2 Error(" << returnValue << ")\n" << printExtendedErrorMessage(sqlite3Db); - if (stmt != NULL) sqlite3_finalize(stmt); + if (stmt != nullptr) sqlite3_finalize(stmt); return QS_IS_PREPARE_ERROR; } @@ -356,7 +364,7 @@ QsErrorType SQLiteDataBaseReadUtil::getSetFromListOfSetsTable(sqlite3* sqlite3Db otherReturnValue = QS_IS_TS_NOT_FOUND; } - if (stmt != NULL) sqlite3_finalize(stmt); + if (stmt != nullptr) sqlite3_finalize(stmt); return otherReturnValue; } diff --git a/SDK/simVis/DB/SQLiteDataBaseReadUtil.h b/SDK/simVis/DB/SQLiteDataBaseReadUtil.h index 38aa31f00..5614e3275 100644 --- a/SDK/simVis/DB/SQLiteDataBaseReadUtil.h +++ b/SDK/simVis/DB/SQLiteDataBaseReadUtil.h @@ -87,7 +87,7 @@ namespace simVis_db /** * Reads a node's data buffer from a sets table; caller is responsible for deleting buffer * @param[in] sqlite3Db Pointer to a SQLite database object - * @param[in] dbFileName Name of a SQLite database file, used to fetch a database if sqlite3Db == NULL + * @param[in] dbFileName Name of a SQLite database file, used to fetch a database if sqlite3Db == nullptr * @param[in] dataTableName Name of the table to access within the given database * @param[in] faceIndex Mapping to a face index/orientation, used to create a SQLite idBlob * @param[in] nodeID Used to fill the idBlob diff --git a/SDK/simVis/DBFormat.cpp b/SDK/simVis/DBFormat.cpp index 9924fb7e6..4fb342f6e 100644 --- a/SDK/simVis/DBFormat.cpp +++ b/SDK/simVis/DBFormat.cpp @@ -135,7 +135,7 @@ namespace deepLevel_ = 32; timeSpecified_ = false; timeStamp_ = simCore::INFINITE_TIME_STAMP; - db_ = NULL; + db_ = nullptr; } int rasterFormat_; @@ -362,7 +362,7 @@ osgEarth::Status DBImageLayer::openImplementation() if (cx.dbUtil_.openDatabaseFile(cx.pathname_, &cx.db_, SQLITE_OPEN_READONLY | SQLITE_OPEN_FULLMUTEX) != simVis_db::QS_IS_OK) { - cx.db_ = NULL; + cx.db_ = nullptr; return osgEarth::Status( osgEarth::Status::ResourceUnavailable, osgEarth::Stringify() << "Failed to open DB file at " << options().url()->full()); @@ -392,7 +392,7 @@ osgEarth::Status DBImageLayer::openImplementation() if (err != simVis_db::QS_IS_OK) { sqlite3_close(cx.db_); - cx.db_ = NULL; + cx.db_ = nullptr; return osgEarth::Status( osgEarth::Status::ResourceUnavailable, osgEarth::Stringify() << "Failed to read metadata for " << cx.pathname_); @@ -485,7 +485,7 @@ osgEarth::GeoImage DBImageLayer::createImageImplementation(const osgEarth::TileK } // Query the database - TextureDataType* buf = NULL; + TextureDataType* buf = nullptr; uint32_t bufSize = 0; uint32_t currentRasterSize = 0; @@ -557,7 +557,7 @@ osgEarth::GeoImage DBImageLayer::createImageImplementation(const osgEarth::TileK { // Raster size of 0 means no tile in the db //OE_DEBUG << "No image in the database for key " << key->str() << std::endl; - result = NULL; + result = nullptr; } } else @@ -639,7 +639,7 @@ osgEarth::Status DBElevationLayer::openImplementation() if (cx.dbUtil_.openDatabaseFile(cx.pathname_, &cx.db_, SQLITE_OPEN_READONLY | SQLITE_OPEN_FULLMUTEX) != simVis_db::QS_IS_OK) { - cx.db_ = NULL; + cx.db_ = nullptr; return osgEarth::Status( osgEarth::Status::ResourceUnavailable, osgEarth::Stringify() << "Failed to open DB file at " << options().url()->full()); @@ -669,7 +669,7 @@ osgEarth::Status DBElevationLayer::openImplementation() if (err != simVis_db::QS_IS_OK) { sqlite3_close(cx.db_); - cx.db_ = NULL; + cx.db_ = nullptr; return osgEarth::Status( osgEarth::Status::ResourceUnavailable, osgEarth::Stringify() << "Failed to read metadata for " << cx.pathname_); @@ -756,7 +756,7 @@ osgEarth::GeoHeightField DBElevationLayer::createHeightFieldImplementation(const } // Query the database - TextureDataType* buf = NULL; + TextureDataType* buf = nullptr; uint32_t bufSize = 0; uint32_t currentRasterSize = 0; @@ -838,7 +838,7 @@ osgEarth::GeoHeightField DBElevationLayer::createHeightFieldImplementation(const else { // Raster size of 0 means no tile in the db - result = NULL; + result = nullptr; } } else diff --git a/SDK/simVis/DisableDepthOnAlpha.cpp b/SDK/simVis/DisableDepthOnAlpha.cpp index 6b758910b..a1040bb56 100644 --- a/SDK/simVis/DisableDepthOnAlpha.cpp +++ b/SDK/simVis/DisableDepthOnAlpha.cpp @@ -58,7 +58,7 @@ void DisableDepthOnAlpha::installShaderProgram(osg::StateSet* intoStateSet) void DisableDepthOnAlpha::setValues(osg::StateSet* stateset, int value) { - if (stateset == NULL) + if (stateset == nullptr) return; int over = value & osg::StateAttribute::OVERRIDE; @@ -73,7 +73,7 @@ void DisableDepthOnAlpha::setValues(osg::StateSet* stateset, int value) void DisableDepthOnAlpha::setAlphaThreshold(osg::StateSet* stateset, float alphaThreshold, int value) { - if (stateset != NULL) + if (stateset != nullptr) stateset->addUniform(new osg::Uniform(DEPTH_THRESHOLD.c_str(), alphaThreshold), value); } diff --git a/SDK/simVis/DynamicScaleTransform.cpp b/SDK/simVis/DynamicScaleTransform.cpp index 89b25807a..7c6553080 100644 --- a/SDK/simVis/DynamicScaleTransform.cpp +++ b/SDK/simVis/DynamicScaleTransform.cpp @@ -176,7 +176,7 @@ osg::Node* DynamicScaleTransform::getSizingNode_() return sizingNode_.get(); if (getNumChildren() > 0) return getChild(0); - return NULL; + return nullptr; } void DynamicScaleTransform::setSizingNode(osg::Node* node) @@ -280,7 +280,7 @@ void DynamicScaleTransform::clearOverrideScale() double DynamicScaleTransform::getSimulatedOrthoRange_(osgUtil::CullVisitor* cv) const { - // Check for NULL, such as invalid dynamic_cast<> + // Check for nullptr, such as invalid dynamic_cast<> if (!cv) return 0.0; diff --git a/SDK/simVis/ElevationQueryProxy.cpp b/SDK/simVis/ElevationQueryProxy.cpp index b1f25a377..41ce52015 100644 --- a/SDK/simVis/ElevationQueryProxy.cpp +++ b/SDK/simVis/ElevationQueryProxy.cpp @@ -23,23 +23,29 @@ #include "osgEarth/MapNodeObserver" #include "osgEarth/ElevationPool" #include "osgEarth/ElevationQuery" -#include "osgEarth/ThreadingUtils" +#include "simVis/osgEarthVersion.h" #include "simVis/ElevationQueryProxy.h" +#ifdef HAVE_OSGEARTH_THREADING +#include "osgEarth/Threading" +#else +#include "osgEarth/ThreadingUtils" +#endif + namespace { -bool getElevationFromSample(osgEarth::ElevationSample* sample, +bool getElevationFromSample(osgEarth::RefElevationSample* sample, double& out_elevation, double* out_actualResolution) { - if (sample != NULL) + if (sample != nullptr) { - out_elevation = sample->elevation; + out_elevation = sample->elevation().as(osgEarth::Units::METERS); if (out_elevation == NO_DATA_VALUE) out_elevation = 0.0; if (out_actualResolution) - *out_actualResolution = sample->resolution; + *out_actualResolution = sample->resolution().getValue(); return true; } @@ -56,7 +62,7 @@ namespace simVis struct ElevationQueryProxy::PrivateData { /// Future object that monitors the status of the elevation query result - osgEarth::Threading::Future elevationResult_; + osgEarth::Threading::Future elevationResult_; }; /** @@ -108,12 +114,13 @@ class ElevationQueryProxy::MapChangeListener : public osg::Node, public osgEarth ElevationQueryProxy::ElevationQueryProxy(const osgEarth::Map* map, osg::Group* scene) : lastElevation_(NO_DATA_VALUE), lastResolution_(NO_DATA_VALUE), - query_(NULL), + query_(nullptr), map_(map), scene_(scene) { data_ = new PrivateData(); query_ = new osgEarth::Util::ElevationQuery(map); + asyncSampler_ = new osgEarth::AsyncElevationSampler(map); if (scene_.valid()) { @@ -127,9 +134,15 @@ ElevationQueryProxy::~ElevationQueryProxy() if (scene_.valid()) scene_->removeChild(mapChangeListener_); delete query_; - query_ = NULL; + query_ = nullptr; delete data_; - data_ = NULL; + data_ = nullptr; + + if (asyncSampler_) + { + delete asyncSampler_; + asyncSampler_ = nullptr; + } } osgEarth::Util::ElevationQuery* ElevationQueryProxy::q() const @@ -143,12 +156,12 @@ bool ElevationQueryProxy::getPendingElevation(double& out_elevation, double* out if (!data_->elevationResult_.isAvailable()) return false; - osg::ref_ptr sample = data_->elevationResult_.release(); + osg::ref_ptr sample = data_->elevationResult_.release(); getElevationFromSample(sample.get(), out_elevation, out_actualResolution); // cache values lastElevation_ = out_elevation; - lastResolution_ = sample->resolution; + lastResolution_ = sample->resolution().getValue(); return true; } @@ -159,27 +172,32 @@ bool ElevationQueryProxy::getElevationFromPool_(const osgEarth::GeoPoint& point, if (!map_.lock(map)) return false; - unsigned int lod = 23u; // use reasonable default value, same as osgEarth::ElevationQuery - if (desiredResolution > 0.0) - { - int level = map->getProfile()->getLevelOfDetailForHorizResolution(desiredResolution, 257); - if (level > 0) - lod = level; - } + // Assume the caller expressed the desired resolution in map units. + // A resolution or zero means "maximum available". + osgEarth::Distance resolution(desiredResolution, map->getSRS()->getUnits()); - data_->elevationResult_ = map->getElevationPool()->getElevation(point, lod); - // if blocking, get elevation result immediately if (blocking) { - osg::ref_ptr sample = data_->elevationResult_.get(); - bool rv = getElevationFromSample(sample.get(), out_elevation, out_actualResolution); - // cache values - lastElevation_ = out_elevation; - lastResolution_ = sample->resolution; - return rv; + // synchronous query - will not return until an answer is generated + osgEarth::ElevationSample sample = map->getElevationPool()->getSample( + point, + resolution, + &workingSet_); + + if (sample.hasData()) + { + lastElevation_ = sample.elevation().as(osgEarth::Units::METERS); + lastResolution_ = sample.resolution().getValue(); + } + } + else // (!blocking) + { + // Start a new background query. + // Returns immediately but result not available until later. + data_->elevationResult_ = asyncSampler_->getSample(point, resolution); } - // return cached values while waiting for query to return + // if non-blocking, return last recorded values while waiting for result out_elevation = lastElevation_; if (out_actualResolution) *out_actualResolution = lastResolution_; @@ -192,15 +210,6 @@ bool ElevationQueryProxy::getElevation(const osgEarth::GeoPoint& point, double& return getElevationFromPool_(point, out_elevation, desiredResolution, out_actualResolution, blocking); } -#ifdef USE_DEPRECATED_SIMDISSDK_API -void ElevationQueryProxy::setMaxTilesToCache(int value) -{ - // After 10/2016 API, now uses map's elevation tile pool and this method is gone. - // If you really want to change it from default of 128, you can do so by - // calling map->getElevationPool()->setMaxEntries(). -} -#endif - void ElevationQueryProxy::setMap(const osgEarth::Map* map) { // Avoid expensive operations on re-do of same map @@ -209,13 +218,21 @@ void ElevationQueryProxy::setMap(const osgEarth::Map* map) delete query_; query_ = new osgEarth::Util::ElevationQuery(map); + + if (asyncSampler_) + { + delete asyncSampler_; + } + asyncSampler_ = new osgEarth::AsyncElevationSampler(map); + map_ = map; + } void ElevationQueryProxy::setMapNode(const osgEarth::MapNode* mapNode) { - if (mapNode == NULL) - setMap(NULL); + if (mapNode == nullptr) + setMap(nullptr); else setMap(mapNode->getMap()); } diff --git a/SDK/simVis/ElevationQueryProxy.h b/SDK/simVis/ElevationQueryProxy.h index 14894f2e0..402f05efb 100644 --- a/SDK/simVis/ElevationQueryProxy.h +++ b/SDK/simVis/ElevationQueryProxy.h @@ -23,9 +23,10 @@ #ifndef SIMVIS_ELEVATIONQUERYPROXY_H #define SIMVIS_ELEVATIONQUERYPROXY_H -#include "simCore/Common/Common.h" #include "osg/observer_ptr" #include "osg/ref_ptr" +#include "osgEarth/ElevationQuery" +#include "simCore/Common/Common.h" namespace osg { class Group; @@ -35,9 +36,6 @@ namespace osgEarth { class GeoPoint; class Map; class MapNode; - namespace Util { - class ElevationQuery; - } } namespace simVis @@ -105,18 +103,6 @@ class SDKVIS_EXPORT ElevationQueryProxy */ bool getPendingElevation(double& out_elevation, double* out_actualResolution = 0L); -#ifdef USE_DEPRECATED_SIMDISSDK_API - /** - * @deprecated - * Sets the maximum cache size for elevation tiles. Forwards to ElevationQuery::setMaxTilesToCache(). - * Newer versions of osgEarth do not implement this method, as the ElevationQuery will instead use - * the pool from the Map. If you really need to increase the maximum tiles to cache, call the - * Map method map->getElevationPool()->setMaxEntries(). - * @param value Number of tiles to cache - */ - SDK_DEPRECATE(void setMaxTilesToCache(int value), "Method is removed in newer osgEarth."); -#endif - /** Changes the MapNode that is associated with the query. */ void setMap(const osgEarth::Map* map); /** Changes the MapNode that is associated with the query. Calls setMap(osgEarth::Map*) appropriately. */ @@ -137,6 +123,9 @@ class SDKVIS_EXPORT ElevationQueryProxy osg::observer_ptr map_; osg::observer_ptr scene_; + osgEarth::AsyncElevationSampler* asyncSampler_; + osgEarth::ElevationPool::WorkingSet workingSet_; + class MapChangeListener; /// listener to map changes, to update the map reference osg::ref_ptr mapChangeListener_; diff --git a/SDK/simVis/Entity.cpp b/SDK/simVis/Entity.cpp index 9e2a78c27..1e9c2e92f 100644 --- a/SDK/simVis/Entity.cpp +++ b/SDK/simVis/Entity.cpp @@ -75,11 +75,12 @@ void CoordSurfaceClamping::clampCoordToMapSurface(simCore::Coordinate& coord) // Both methods for getting terrain elevation have drawbacks that make them undesirable in certain situations. SIM-10423 // getHeight() can give inaccurate results depending on how much map data is loaded into the scene graph, while ElevationEnvelope can be prohibitively slow if there are many clamped entities - if (useMaxElevPrec_ && envelope_.valid()) + if (useMaxElevPrec_) { - double hae = envelope_->getElevation(llaCoord.lon()*simCore::RAD2DEG, llaCoord.lat()*simCore::RAD2DEG); - if (hae != NO_DATA_VALUE) - elevation = hae; + osgEarth::GeoPoint point(mapNode_->getMapSRS(), llaCoord.lon()*simCore::RAD2DEG, llaCoord.lat()*simCore::RAD2DEG, 0, osgEarth::ALTMODE_ABSOLUTE); + osgEarth::ElevationSample sample = mapNode_->getMap()->getElevationPool()->getSample(point, osgEarth::Distance(1.0, osgEarth::Units::METERS), &workingSet_); + if (sample.hasData()) + elevation = sample.elevation().as(osgEarth::Units::METERS); } else { @@ -99,7 +100,7 @@ void CoordSurfaceClamping::clampCoordToMapSurface(simCore::Coordinate& coord) coord = llaCoord; } -void CoordSurfaceClamping::clampCoordToMapSurface(simCore::Coordinate& coord, osgEarth::ElevationEnvelope::Context& context) +void CoordSurfaceClamping::clampCoordToMapSurface(simCore::Coordinate& coord, osgEarth::ElevationPool::WorkingSet& workingSet) { // nothing to do if we don't have valid ways of accessing elevation if (!mapNode_.valid()) @@ -126,11 +127,12 @@ void CoordSurfaceClamping::clampCoordToMapSurface(simCore::Coordinate& coord, os // Both methods for getting terrain elevation have drawbacks that make them undesirable in certain situations. SIM-10423 // getHeight() can give inaccurate results depending on how much map data is loaded into the scene graph, while ElevationEnvelope can be prohibitively slow if there are many clamped entities - if (useMaxElevPrec_ && envelope_.valid()) + if (useMaxElevPrec_) { - double hae = envelope_->getElevation(llaCoord.lon()*simCore::RAD2DEG, llaCoord.lat()*simCore::RAD2DEG, context); - if (hae != NO_DATA_VALUE) - elevation = hae; + osgEarth::GeoPoint point(mapNode_->getMapSRS(), llaCoord.lon()*simCore::RAD2DEG, llaCoord.lat()*simCore::RAD2DEG, 0, osgEarth::ALTMODE_ABSOLUTE); + osgEarth::ElevationSample sample = mapNode_->getMap()->getElevationPool()->getSample(point, osgEarth::Distance(1.0, osgEarth::Units::METERS), &workingSet_); + if (sample.hasData()) + elevation = sample.elevation().as(osgEarth::Units::METERS); } else { @@ -158,10 +160,11 @@ bool CoordSurfaceClamping::isValid() const void CoordSurfaceClamping::setMapNode(const osgEarth::MapNode* map) { mapNode_ = map; - if (mapNode_.valid() && useMaxElevPrec_) - envelope_ = mapNode_->getMap()->getElevationPool()->createEnvelope(mapNode_->getMapSRS(), MAX_LOD); - else - envelope_ = NULL; +#ifdef HAVE_WORKINGSET_STRONGLRU + workingSet_.clear(); +#else + workingSet_._lru.clear(); +#endif } void CoordSurfaceClamping::setUseMaxElevPrec(bool useMaxElevPrec) @@ -170,14 +173,6 @@ void CoordSurfaceClamping::setUseMaxElevPrec(bool useMaxElevPrec) return; useMaxElevPrec_ = useMaxElevPrec; - if (useMaxElevPrec_ && mapNode_.valid()) - { - // Envelope should not be valid if useMaxElevPrec was just turned on - assert(!envelope_.valid()); - envelope_ = mapNode_->getMap()->getElevationPool()->createEnvelope(mapNode_->getMapSRS(), MAX_LOD); - } - else - envelope_ = NULL; } ///////////////////////////////////////////////////////////////////////////////// @@ -192,7 +187,7 @@ EntityNode::EntityNode(simData::ObjectType type, Locator* locator) EntityNode::~EntityNode() { - setLocator(NULL); + setLocator(nullptr); } bool EntityNode::isVisible() const @@ -276,7 +271,7 @@ std::string EntityNode::getEntityName_(const simData::CommonPrefs& common, Entit void EntityNode::setLabelContentCallback(LabelContentCallback* cb) { - if (cb == NULL) + if (cb == nullptr) contentCallback_ = new NullEntityCallback(); else contentCallback_ = cb; diff --git a/SDK/simVis/Entity.h b/SDK/simVis/Entity.h index a7d5fef98..64fcd44ca 100644 --- a/SDK/simVis/Entity.h +++ b/SDK/simVis/Entity.h @@ -76,7 +76,7 @@ namespace simVis void clampCoordToMapSurface(simCore::Coordinate& coord); /** clampCoordToMapSurface() variation that accepts a context for optimization. */ - void clampCoordToMapSurface(simCore::Coordinate& coord, osgEarth::ElevationEnvelope::Context& context); + void clampCoordToMapSurface(simCore::Coordinate& coord, osgEarth::ElevationPool::WorkingSet& ws); /** Return true if able to apply clamping, false otherwise */ bool isValid() const; @@ -89,7 +89,7 @@ namespace simVis private: osg::observer_ptr mapNode_; - osg::ref_ptr envelope_; + osgEarth::ElevationPool::WorkingSet workingSet_; bool useMaxElevPrec_; }; @@ -104,7 +104,7 @@ namespace simVis * @param type Type of entity node to alleviate the need for dynamic casting * @param locator Locator that will position this node */ - EntityNode(simData::ObjectType type, Locator* locator = NULL); + EntityNode(simData::ObjectType type, Locator* locator = nullptr); public: /** Enumerates different name types for the label */ @@ -144,10 +144,10 @@ namespace simVis /** * Sets a custom callback that will be used to generate the string that goes in the label. - * @param callback Callback that will generate content; if NULL will only display entity name/alias + * @param callback Callback that will generate content; if nullptr will only display entity name/alias */ void setLabelContentCallback(LabelContentCallback* callback); - /// Returns current content callback; guaranteed non-NULL + /// Returns current content callback; guaranteed non-nullptr LabelContentCallback& labelContentCallback() const; /// Returns the pop up text based on the label content callback, update and preference @@ -165,7 +165,7 @@ namespace simVis * function that extracts the Position information (not rotation) from the * Entity's underlying locator or locatorNode. * - * @param[out] out_position If not NULL, resulting position stored here, in coordinate system as specified by coordsys + * @param[out] out_position If not nullptr, resulting position stored here, in coordinate system as specified by coordsys * @param[in ] coordsys Requested coord sys of the output position (only LLA, ECEF, or ECI supported) * @return 0 if the output parameter is populated successfully, nonzero on failure */ @@ -176,8 +176,8 @@ namespace simVis * function that extracts the Position information and rotation from the * locatorNode matrix. * - * @param[out] out_position If not NULL, resulting position stored here, in coordinate system as specified by coordsys - * @param[out] out_orientation If not NULL, resulting orientation stored here, in coordinate system as specified by coordsys + * @param[out] out_position If not nullptr, resulting position stored here, in coordinate system as specified by coordsys + * @param[out] out_orientation If not nullptr, resulting orientation stored here, in coordinate system as specified by coordsys * @param[in ] coordsys Requested coord sys of the output position (only LLA, ECEF, or ECI supported) * @return 0 if the output parameter is populated successfully, nonzero on failure */ @@ -217,7 +217,7 @@ namespace simVis if (dynamic_cast(node)) return static_cast(node); } - return NULL; + return nullptr; } /** @@ -233,7 +233,7 @@ namespace simVis if (dynamic_cast(node)) return static_cast(node); } - return NULL; + return nullptr; } /** @@ -271,7 +271,7 @@ namespace simVis /** * Updates the entity based on the bound data store. The implementation class * must provide this method. - * @param updateSlice Data store update slice (could be NULL) + * @param updateSlice Data store update slice (could be nullptr) * @param force true to force the update to be applied; false allows entity to use its own internal logic to decide whether the update should be applied * @return true if update applied, false if not */ diff --git a/SDK/simVis/EntityLabel.h b/SDK/simVis/EntityLabel.h index a17618a7e..227206d04 100644 --- a/SDK/simVis/EntityLabel.h +++ b/SDK/simVis/EntityLabel.h @@ -42,7 +42,7 @@ class SDKVIS_EXPORT EntityLabelNode : public osg::Group /// constructor for (most) entity that provides a locatorNode to parent/position the label EntityLabelNode(); - /// constructor for (lob & projector) entity that does not provide a locatorNode to parent/position the label + /// constructor for (custom rendering) entity that does not provide a transform-derived parent to position the label explicit EntityLabelNode(simVis::Locator* locator); /// Update the label with the given preferences and text diff --git a/SDK/simVis/EphemerisVector.cpp b/SDK/simVis/EphemerisVector.cpp index 1d3d66940..8c2c3feac 100644 --- a/SDK/simVis/EphemerisVector.cpp +++ b/SDK/simVis/EphemerisVector.cpp @@ -61,12 +61,12 @@ class EphemerisVector::RebuildOnTimer : public osg::Callback virtual bool run(osg::Object* object, osg::Object* data) { EphemerisVector* ephemeris = dynamic_cast(object); - if (ephemeris != NULL) + if (ephemeris != nullptr) { // Clock should always be set when using ephemeris vectors const simCore::Clock* clock = simVis::Registry::instance()->getClock(); - assert(clock != NULL); - if (clock != NULL) + assert(clock != nullptr); + if (clock != nullptr) { const simCore::TimeStamp& now = clock->currentTime(); const simCore::Seconds& delta = now - ephemeris->lastUpdateTime_; @@ -108,7 +108,7 @@ EphemerisVector::EphemerisVector(const simVis::Color& moonColor, const simVis::C EphemerisVector::~EphemerisVector() { delete coordConvert_; - coordConvert_ = NULL; + coordConvert_ = nullptr; } void EphemerisVector::setModelNode(const PlatformModelNode* hostPlatformModel) @@ -140,8 +140,8 @@ void EphemerisVector::rebuild_(const simData::PlatformPrefs& prefs) // Clock should always be set when using ephemeris vectors const simCore::Clock* clock = simVis::Registry::instance()->getClock(); - assert(clock != NULL); - if (clock == NULL) + assert(clock != nullptr); + if (clock == nullptr) { setNodeMask(0); return; diff --git a/SDK/simVis/EyePositionManager.h b/SDK/simVis/EyePositionManager.h index 725b0fb82..13b0118db 100644 --- a/SDK/simVis/EyePositionManager.h +++ b/SDK/simVis/EyePositionManager.h @@ -184,7 +184,7 @@ class NullEyePositionManager : public simVis::EyePositionManager virtual std::string insetString(simVis::View *viewport) { return ""; } virtual void cycleEyeView(simVis::View *viewport, bool forwardCycle) { } // Treated as an opaque pointer by consumers - virtual simVis::EyePosition* eyePositionByName(const std::string &eyePositionName) { return NULL; } + virtual simVis::EyePosition* eyePositionByName(const std::string &eyePositionName) { return nullptr; } virtual void applyEyePositionToPort(simVis::EyePosition *eyePosition, simVis::View *viewport) { } virtual void removeEyePosition(simVis::EyePosition *eyePosition) { } virtual void removeEyePosition(const std::string& name) { } diff --git a/SDK/simVis/GOG/Annotation.cpp b/SDK/simVis/GOG/Annotation.cpp index 7bf8dfa4c..7f8c24064 100644 --- a/SDK/simVis/GOG/Annotation.cpp +++ b/SDK/simVis/GOG/Annotation.cpp @@ -53,10 +53,16 @@ GogNodeInterface* TextAnnotation::deserialize( const std::string text = Utils::decodeAnnotation(parsedShape.stringValue(GOG_TEXT)); p.parseGeometry(parsedShape); - GogNodeInterface* rv = NULL; - osgEarth::GeoPositionNode* label = NULL; + GogNodeInterface* rv = nullptr; + osgEarth::GeoPositionNode* label = nullptr; - if (parsedShape.hasValue(GOG_ICON)) + // Turning on Callouts disables PlaceNodes with icons. To try to help avoid that error, we detect + // the current technique in screen space layout, and if it's callouts, we don't show the icon + const auto& technique = osgEarth::ScreenSpaceLayout::getOptions().technique(); + const bool hasCallouts = technique.isSet() && technique.get() == osgEarth::ScreenSpaceLayoutOptions::TECHNIQUE_CALLOUTS; + + // Only start with the icon, if callouts are disabled + if (parsedShape.hasValue(GOG_ICON) && !hasCallouts) { std::string iconFile = parsedShape.stringValue(GOG_ICON); osg::ref_ptr image = osgDB::readImageFile(simCore::StringUtils::trim(iconFile, "\"")); @@ -83,7 +89,7 @@ GogNodeInterface* TextAnnotation::deserialize( else { osg::PositionAttitudeTransform* trans = label->getPositionAttitudeTransform(); - if (trans != NULL) + if (trans != nullptr) trans->setPosition(p.getLTPOffset()); } label->setDynamic(true); diff --git a/SDK/simVis/GOG/Arc.cpp b/SDK/simVis/GOG/Arc.cpp index d74bf0081..0a624a05b 100644 --- a/SDK/simVis/GOG/Arc.cpp +++ b/SDK/simVis/GOG/Arc.cpp @@ -278,20 +278,20 @@ GogNodeInterface* Arc::deserialize(const ParsedShape& parsedShape, simVis::GOG:: // never cross 0 with the osgEarth drawing algorithm. end = angFix2PI_(end); - // If the end and start are the same value, return NULL to draw nothing. Cannot + // If the end and start are the same value, return nullptr to draw nothing. Cannot // use the angleend command to draw circles (use angledeg instead) if (simCore::areAnglesEqual(start.as(Units::RADIANS), end.as(Units::RADIANS))) { context.errorHandler_->printError(lineNumber, "Arc AngleEnd cannot be same value as AngleStart"); - return NULL; + return nullptr; } } // whether to include the center point in the geometry. bool filled = p.style_.has(); osgEarth::GeometryFactory gf; - Geometry* outlineShape = (Geometry*)new LineString(); - Geometry* filledShape = (Geometry*)new osgEarth::Polygon(); + osg::ref_ptr outlineShape = new LineString(); + osg::ref_ptr filledShape = new osgEarth::Polygon(); if (parsedShape.hasValue(GOG_MAJORAXIS)) { @@ -299,23 +299,23 @@ GogNodeInterface* Arc::deserialize(const ParsedShape& parsedShape, simVis::GOG:: if (parsedShape.hasValue(GOG_MINORAXIS)) { Distance minorRadius = Distance(p.units_.rangeUnits_.convertTo(simCore::Units::METERS, 0.5 * parsedShape.doubleValue(GOG_MINORAXIS, 2000.0)), Units::METERS); - outlineShape = createEllipticalArc(osg::Vec3d(0, 0, 0), radius, minorRadius, rotation, start, end, hasInnerRadius, iRadius, false, outlineShape, gf); - filledShape = createEllipticalArc(osg::Vec3d(0, 0, 0), radius, minorRadius, rotation, start, end, hasInnerRadius, iRadius, true, filledShape, gf); + outlineShape = createEllipticalArc(osg::Vec3d(0, 0, 0), radius, minorRadius, rotation, start, end, hasInnerRadius, iRadius, false, outlineShape.get(), gf); + filledShape = createEllipticalArc(osg::Vec3d(0, 0, 0), radius, minorRadius, rotation, start, end, hasInnerRadius, iRadius, true, filledShape.get(), gf); } else { - outlineShape = createArc(osg::Vec3d(0, 0, 0), radius, start + rotation, end + rotation, hasInnerRadius, iRadius, false, outlineShape, gf); - filledShape = createArc(osg::Vec3d(0, 0, 0), radius, start + rotation, end + rotation, hasInnerRadius, iRadius, true, filledShape, gf); + outlineShape = createArc(osg::Vec3d(0, 0, 0), radius, start + rotation, end + rotation, hasInnerRadius, iRadius, false, outlineShape.get(), gf); + filledShape = createArc(osg::Vec3d(0, 0, 0), radius, start + rotation, end + rotation, hasInnerRadius, iRadius, true, filledShape.get(), gf); } } else { - outlineShape = createArc(osg::Vec3d(0, 0, 0), radius, start + rotation, end + rotation, hasInnerRadius, iRadius, false, outlineShape, gf); - filledShape = createArc(osg::Vec3d(0, 0, 0), radius, start + rotation, end + rotation, hasInnerRadius, iRadius, true, filledShape, gf); + outlineShape = createArc(osg::Vec3d(0, 0, 0), radius, start + rotation, end + rotation, hasInnerRadius, iRadius, false, outlineShape.get(), gf); + filledShape = createArc(osg::Vec3d(0, 0, 0), radius, start + rotation, end + rotation, hasInnerRadius, iRadius, true, filledShape.get(), gf); } - osgEarth::LocalGeometryNode* shapeNode = NULL; - osgEarth::LocalGeometryNode* fillNode = NULL; + osgEarth::LocalGeometryNode* shapeNode = nullptr; + osgEarth::LocalGeometryNode* fillNode = nullptr; osg::Group* g = new osg::Group(); // remove the polygon symbol for the shape, since it should only exist in the fillNode @@ -334,21 +334,21 @@ GogNodeInterface* Arc::deserialize(const ParsedShape& parsedShape, simVis::GOG:: Utils::configureStyleForClipping(fillStyle); } - shapeNode = new osgEarth::LocalGeometryNode(outlineShape, shapeStyle); + shapeNode = new osgEarth::LocalGeometryNode(outlineShape.get(), shapeStyle); shapeNode->setMapNode(mapNode); - fillNode = new osgEarth::LocalGeometryNode(filledShape, fillStyle); + fillNode = new osgEarth::LocalGeometryNode(filledShape.get(), fillStyle); fillNode->setMapNode(mapNode); } else { - shapeNode = new HostedLocalGeometryNode(outlineShape, shapeStyle); - fillNode = new HostedLocalGeometryNode(filledShape, fillStyle); + shapeNode = new HostedLocalGeometryNode(outlineShape.get(), shapeStyle); + fillNode = new HostedLocalGeometryNode(filledShape.get(), fillStyle); } shapeNode->setName("Arc Outline Node"); fillNode->setName("Arc Fill Node"); - GogNodeInterface* rv = NULL; + GogNodeInterface* rv = nullptr; if (shapeNode) { Utils::applyLocalGeometryOffsets(*shapeNode, p, nodeType); diff --git a/SDK/simVis/GOG/Circle.cpp b/SDK/simVis/GOG/Circle.cpp index 9201c5f09..395e24c1f 100644 --- a/SDK/simVis/GOG/Circle.cpp +++ b/SDK/simVis/GOG/Circle.cpp @@ -47,7 +47,7 @@ GogNodeInterface* Circle::deserialize(const ParsedShape& parsedShape, osgEarth::GeometryFactory gf; Geometry* shape = gf.createCircle(osg::Vec3d(0, 0, 0), radius); - osgEarth::LocalGeometryNode* node = NULL; + osgEarth::LocalGeometryNode* node = nullptr; if (nodeType == GOGNODE_GEOGRAPHIC) { @@ -62,7 +62,7 @@ GogNodeInterface* Circle::deserialize(const ParsedShape& parsedShape, node = new HostedLocalGeometryNode(shape, p.style_); node->setName("GOG Circle Position"); - GogNodeInterface* rv = NULL; + GogNodeInterface* rv = nullptr; if (node) { Utils::applyLocalGeometryOffsets(*node, p, nodeType); diff --git a/SDK/simVis/GOG/Cone.cpp b/SDK/simVis/GOG/Cone.cpp index dc6b4238f..1c63b5c28 100644 --- a/SDK/simVis/GOG/Cone.cpp +++ b/SDK/simVis/GOG/Cone.cpp @@ -84,7 +84,7 @@ GogNodeInterface* Cone::deserialize(const ParsedShape& parsedShape, coneGeom->addPrimitiveSet(new osg::DrawArrays(GL_TRIANGLE_STRIP, 0, coneVerts->size())); capGeom->addPrimitiveSet(new osg::DrawArrays(GL_TRIANGLE_STRIP, 0, capVerts->size())); - osgEarth::LocalGeometryNode* node = NULL; + osgEarth::LocalGeometryNode* node = nullptr; if (nodeType == GOGNODE_GEOGRAPHIC) { node = new osgEarth::LocalGeometryNode(); diff --git a/SDK/simVis/GOG/Cylinder.cpp b/SDK/simVis/GOG/Cylinder.cpp index db461358c..fbd2a846e 100644 --- a/SDK/simVis/GOG/Cylinder.cpp +++ b/SDK/simVis/GOG/Cylinder.cpp @@ -102,12 +102,12 @@ GogNodeInterface* Cylinder::deserialize(const ParsedShape& parsedShape, // never cross 0 with the osgEarth drawing algorithm. end = angFix2PI(end); - // If the end and start are the same value, return NULL to draw nothing. Cannot + // If the end and start are the same value, return nullptr to draw nothing. Cannot // use the angleend command to draw circles (use angledeg instead) if (simCore::areAnglesEqual(start.as(Units::RADIANS), end.as(Units::RADIANS))) { context.errorHandler_->printError(lineNumber, "Cylinder AngleEnd cannot be same value as AngleStart"); - return NULL; + return nullptr; } } @@ -133,7 +133,7 @@ GogNodeInterface* Cylinder::deserialize(const ParsedShape& parsedShape, float heightValue = height.as(Units::METERS); // first the extruded side shape: - LocalGeometryNode* sideNode = NULL; + LocalGeometryNode* sideNode = nullptr; { Style style(p.style_); style.getOrCreate()->height() = heightValue; @@ -160,7 +160,7 @@ GogNodeInterface* Cylinder::deserialize(const ParsedShape& parsedShape, } // next the top cap: - LocalGeometryNode* topCapNode = NULL; + LocalGeometryNode* topCapNode = nullptr; { Style style(p.style_); @@ -202,7 +202,7 @@ GogNodeInterface* Cylinder::deserialize(const ParsedShape& parsedShape, } // next the bottom cap: - LocalGeometryNode* bottomCapNode = NULL; + LocalGeometryNode* bottomCapNode = nullptr; { Style style(p.style_); @@ -228,7 +228,7 @@ GogNodeInterface* Cylinder::deserialize(const ParsedShape& parsedShape, g->addChild(bottomCapNode); } - CylinderNodeInterface* rv = NULL; + CylinderNodeInterface* rv = nullptr; if (sideNode && topCapNode && bottomCapNode) { rv = new CylinderNodeInterface(g.get(), sideNode, topCapNode, bottomCapNode, metaData); diff --git a/SDK/simVis/GOG/Ellipse.cpp b/SDK/simVis/GOG/Ellipse.cpp index 5b40d0999..f7af160aa 100644 --- a/SDK/simVis/GOG/Ellipse.cpp +++ b/SDK/simVis/GOG/Ellipse.cpp @@ -61,7 +61,7 @@ GogNodeInterface* Ellipse::deserialize(const ParsedShape& parsedShape, osgEarth::GeometryFactory gf; Geometry* shape = gf.createEllipse(osg::Vec3d(0, 0, 0), minorRadius, majorRadius, rotation); - osgEarth::LocalGeometryNode* node = NULL; + osgEarth::LocalGeometryNode* node = nullptr; if (nodeType == GOGNODE_GEOGRAPHIC) { diff --git a/SDK/simVis/GOG/Ellipsoid.cpp b/SDK/simVis/GOG/Ellipsoid.cpp index 7b6314ae2..31727914b 100644 --- a/SDK/simVis/GOG/Ellipsoid.cpp +++ b/SDK/simVis/GOG/Ellipsoid.cpp @@ -49,7 +49,7 @@ GogNodeInterface* Ellipsoid::deserialize(const ParsedShape& parsedShape, if (parsedShape.hasValue(GOG_RADIUS)) { - x_diam = parsedShape.doubleValue(GOG_RADIUS, 0) * 2; + x_diam.set(parsedShape.doubleValue(GOG_RADIUS, 0) * 2, osgEarth::Units::METERS); y_diam = x_diam; if (z_diam == 0.0) z_diam = x_diam; @@ -65,7 +65,7 @@ GogNodeInterface* Ellipsoid::deserialize(const ParsedShape& parsedShape, y_radius_m, x_radius_m, z_radius_m, color); // y, x, z order to match SIMDIS 9 shape->setName("GOG Ellipsoid"); - osgEarth::LocalGeometryNode* node = NULL; + osgEarth::LocalGeometryNode* node = nullptr; if (nodeType == GOGNODE_GEOGRAPHIC) { @@ -78,7 +78,7 @@ GogNodeInterface* Ellipsoid::deserialize(const ParsedShape& parsedShape, node = new HostedLocalGeometryNode(shape, p.style_); node->setName("GOG Ellipsoid Position"); - GogNodeInterface* rv = NULL; + GogNodeInterface* rv = nullptr; if (node) { Utils::applyLocalGeometryOffsets(*node, p, nodeType); @@ -88,4 +88,4 @@ GogNodeInterface* Ellipsoid::deserialize(const ParsedShape& parsedShape, return rv; } -} } \ No newline at end of file +} } diff --git a/SDK/simVis/GOG/GOGNode.cpp b/SDK/simVis/GOG/GOGNode.cpp index 42679bd36..a776d19a9 100644 --- a/SDK/simVis/GOG/GOGNode.cpp +++ b/SDK/simVis/GOG/GOGNode.cpp @@ -35,6 +35,7 @@ GogMetaData::GogMetaData() : metadata(""), shape(GOG_UNKNOWN), loadFormat(FORMAT_GOG), + altitudeUnits_(simCore::Units::FEET), setFields_(0), allowingSetExplicitly_(true) { diff --git a/SDK/simVis/GOG/GOGNode.h b/SDK/simVis/GOG/GOGNode.h index 6b0fe1db3..cadfd2a6c 100644 --- a/SDK/simVis/GOG/GOGNode.h +++ b/SDK/simVis/GOG/GOGNode.h @@ -31,6 +31,7 @@ #include "osg/Group" #include "simCore/Common/Common.h" #include "simCore/Calc/Vec3.h" +#include "simCore/Calc/Units.h" namespace simCore { class UnitsRegistry; } @@ -89,7 +90,7 @@ namespace simVis { namespace GOG const simCore::UnitsRegistry* unitsRegistry_; GOGContext() - : unitsRegistry_(NULL) + : unitsRegistry_(nullptr) { } }; @@ -128,7 +129,8 @@ namespace simVis { namespace GOG GOG_HEMISPHERE, GOG_LATLONALTBOX, GOG_CONE, - GOG_IMAGEOVERLAY + GOG_IMAGEOVERLAY, + GOG_ORBIT }; /** Describes the original load format of the shape */ @@ -153,6 +155,7 @@ namespace simVis { namespace GOG GogShape shape; ///< identifying the exact shape type of the GOG LoadFormat loadFormat; ///< indicate the original load format of the GOG size_t lineNumber; ///< line number from the source GOG file + simCore::Units altitudeUnits_; ///< altitude units specified in the GOG file public: GogMetaData(); bool isSetExplicitly(GogSerializableField field) const; ///< determines if a field is explicitly set diff --git a/SDK/simVis/GOG/GOGRegistry.cpp b/SDK/simVis/GOG/GOGRegistry.cpp index 828006f8b..422c51e14 100644 --- a/SDK/simVis/GOG/GOGRegistry.cpp +++ b/SDK/simVis/GOG/GOGRegistry.cpp @@ -35,6 +35,7 @@ #include "simVis/GOG/LatLonAltBox.h" #include "simVis/GOG/Line.h" #include "simVis/GOG/LineSegs.h" +#include "simVis/GOG/Orbit.h" #include "simVis/GOG/ParsedShape.h" #include "simVis/GOG/Points.h" #include "simVis/GOG/Polygon.h" @@ -87,6 +88,7 @@ GOGRegistry::GOGRegistry(osgEarth::MapNode* mapNode) add("points", new SF()); add("sphere", new SF()); add("imageoverlay", new SF()); + add("orbit", new SF()); } GOGRegistry::GOGRegistry(const GOGRegistry& rhs) @@ -105,14 +107,14 @@ GogNodeInterface* GOGRegistry::createGOG(const ParsedShape& parsedShape, const G const osgEarth::Style& overrideStyle, const GOGContext& context, const GogMetaData& metaData, GogFollowData& followData) const { - GogNodeInterface* result = NULL; + GogNodeInterface* result = nullptr; std::string key = osgEarth::toLower(parsedShape.shape()); // don't allow attached GOGs with absolute values if (nodeType == GOGNODE_HOSTED && parsedShape.hasValue(GOG_ABSOLUTE)) { SIM_WARN << "Attempting to load attached GOG with absolute points\n"; - return NULL; + return nullptr; } DeserializerTable::const_iterator i = deserializers_.find(key); if (i != deserializers_.end()) diff --git a/SDK/simVis/GOG/GOGRegistry.h b/SDK/simVis/GOG/GOGRegistry.h index 4917b585b..dd3f8d0ec 100644 --- a/SDK/simVis/GOG/GOGRegistry.h +++ b/SDK/simVis/GOG/GOGRegistry.h @@ -77,7 +77,7 @@ class SDKVIS_EXPORT GOGRegistry /** * Fetched the map node associated with the registry - * @return A map node, or NULL if this is a localized object + * @return A map node, or nullptr if this is a localized object */ osgEarth::MapNode* getMapNode() const { return mapNode_.get(); } diff --git a/SDK/simVis/GOG/GogNodeInterface.cpp b/SDK/simVis/GOG/GogNodeInterface.cpp index fff651579..b2377e04b 100644 --- a/SDK/simVis/GOG/GogNodeInterface.cpp +++ b/SDK/simVis/GOG/GogNodeInterface.cpp @@ -38,10 +38,10 @@ #include "osgEarth/LocalGeometryNode" #include "osgEarth/PlaceNode" #include "osgEarth/PolygonSymbol" -#include "osgEarth/Units" +#include "osgEarth/RenderSymbol" #include "osgEarth/Style" #include "osgEarth/TextSymbol" -#include "osgEarth/RenderSymbol" +#include "osgEarth/Units" #include "simNotify/Notify.h" #include "simCore/Calc/Angle.h" #include "simCore/Calc/CoordinateConverter.h" @@ -49,10 +49,11 @@ #include "simCore/String/Format.h" #include "simCore/String/Utils.h" #include "simCore/String/ValidNumber.h" -#include "simVis/Types.h" #include "simVis/Constants.h" -#include "simVis/Registry.h" +#include "simVis/OverrideColor.h" #include "simVis/OverheadMode.h" +#include "simVis/Registry.h" +#include "simVis/Types.h" #include "simVis/Utils.h" #include "simVis/GOG/GOG.h" #include "simVis/GOG/GOGNode.h" @@ -86,7 +87,7 @@ namespace { if (!node || (!referencePosition && !node->getPosition().isValid())) return 1; // use reference point if it's valid, otherwise use the node's position - osgEarth::GeoPoint refPosition = referencePosition != NULL ? *referencePosition : node->getPosition(); + osgEarth::GeoPoint refPosition = referencePosition != nullptr ? *referencePosition : node->getPosition(); osg::Vec3d centerPoint; @@ -104,8 +105,8 @@ namespace { centerPoint = node->getBound().center(); simCore::Coordinate llaCoord; - // apply the offset to the ref position if using the local offset or if the map node is NULL which indicates this is a hosted node (relative to ref position) - if (useLocalOffset || node->getMapNode() == NULL) + // apply the offset to the ref position if using the local offset or if the map node is nullptr which indicates this is a hosted node (relative to ref position) + if (useLocalOffset || node->getMapNode() == nullptr) { // if the offsets are non-zero, apply the offsets to our reference position simCore::CoordinateConverter converter; @@ -145,12 +146,17 @@ GogNodeInterface::GogNodeInterface(osg::Node* osgNode, const simVis::GOG::GogMet defaultFont_("arial.ttf"), defaultTextSize_(15), defaultTextColor_(simVis::Color::Red), - rangeUnits_(simCore::Units::YARDS) + rangeUnits_(simCore::Units::YARDS), + opacity_(1.f) { if (osgNode_.valid()) { osgNode_->setNodeMask(simVis::DISPLAY_MASK_GOG); + // Initialize the override color + simVis::OverrideColor::setCombineMode(osgNode_->getOrCreateStateSet(), simVis::OverrideColor::MULTIPLY_COLOR); + simVis::OverrideColor::setColor(osgNode_->getOrCreateStateSet(), osg::Vec4f(1.f, 1.f, 1.f, 1.f)); + // flatten in overhead mode by default - subclass might change this simVis::OverheadMode::enableGeometryFlattening(true, osgNode_.get()); } @@ -191,8 +197,8 @@ void GogNodeInterface::applyToStyle(const ParsedShape& parent, const UnitsState& // for performance reasons, cache all style updates, apply once when done beginStyleUpdates_(); - metaData_.allowSetExplicitly(false); ///< setFields will incorrectly respond to defaults here, so cache the correct value and restore it at the end - + metaData_.allowSetExplicitly(false); // setFields will incorrectly respond to defaults here, so cache the correct value and restore it at the end + metaData_.altitudeUnits_ = units.altitudeUnits_; // need to cache altitude units here, since some altitude values can be changed const std::string& key = parent.shape(); const simVis::GOG::GogShape gogShape = metaData_.shape; bool is3dShape = (gogShape == GOG_SPHERE || gogShape == GOG_ELLIPSOID || gogShape == GOG_HEMISPHERE || @@ -202,7 +208,7 @@ void GogNodeInterface::applyToStyle(const ParsedShape& parent, const UnitsState& bool isExtruded = simCore::stringIsTrueToken(parent.stringValue(GOG_EXTRUDE)) && !is3dShape; // do we need a PolygonSymbol? - bool isFillable = isExtruded || key == "poly" || key == "polygon" || key == "ellipse" || key == "circle" || key == "arc" || is3dShape; + bool isFillable = isExtruded || key == "poly" || key == "polygon" || key == "ellipse" || key == "circle" || key == "arc" || key == "orbit" || is3dShape; bool isFilled = isFillable && simCore::stringIsTrueToken(parent.stringValue(GOG_FILLED)); // do we need a LineSymbol? @@ -472,8 +478,15 @@ void GogNodeInterface::serializeToStream(std::ostream& gogOutputStream) // altoffset double altOffset = 0.0; if (getAltOffset(altOffset) == 0 && metaData_.isSetExplicitly(GOG_THREE_D_OFFSET_ALT_SET)) + { + // if not serializing geometry, which always uses meters, convert to the stored altitude units + if (!serializeGeometry) + { + simCore::Units curUnits(simCore::Units::METERS); + altOffset = curUnits.convertTo(metaData_.altitudeUnits_, altOffset); + } gogOutputStream << "3d offsetalt " << altOffset << "\n"; - + } // font int fontSize; std::string fontFile; @@ -700,6 +713,12 @@ int GogNodeInterface::getTextOutline(osg::Vec4f& outlineColor, simData::TextOutl return 1; } +int GogNodeInterface::getOpacity(float& opacity) const +{ + opacity = opacity_; + return 0; +} + void GogNodeInterface::setAltitudeMode(AltitudeMode altMode) { metaData_.setExplicitly(GOG_ALTITUDE_MODE_SET); @@ -1026,6 +1045,15 @@ void GogNodeInterface::setTextOutline(const osg::Vec4f& outlineColor, simData::T // NOP only applies to label nodes } +void GogNodeInterface::setOpacity(float opacity) +{ + if (opacity == opacity_) + return; + opacity_ = opacity; + if (osgNode_.valid()) + simVis::OverrideColor::setColor(osgNode_->getOrCreateStateSet(), osg::Vec4f(1.f, 1.f, 1.f, opacity_)); +} + void GogNodeInterface::addGogNodeListener(GogNodeListenerPtr listener) { std::vector::iterator i = std::find(listeners_.begin(), listeners_.end(), listener); @@ -1093,7 +1121,7 @@ void GogNodeInterface::setGeoPositionAltitude_(osgEarth::GeoPositionNode& node, void GogNodeInterface::initializeFromGeoPositionNode_(const osgEarth::GeoPositionNode& node) { - hasMapNode_ = (node.getMapNode() != NULL); + hasMapNode_ = (node.getMapNode() != nullptr); // use node position if there is a map node if (hasMapNode_) altitude_ = node.getPosition().alt(); @@ -1111,7 +1139,7 @@ bool GogNodeInterface::hasValidAltitudeMode() const // check for an AltitudeSymbol const osgEarth::AltitudeSymbol* alt = style_.getSymbol(); - if (alt == NULL) + if (alt == nullptr) return false; // check for altitude mode ALTITUDE_NONE @@ -1199,6 +1227,7 @@ bool GogNodeInterface::isFillable_(simVis::GOG::GogShape shape) const case simVis::GOG::GOG_POINTS: case simVis::GOG::GOG_POLYGON: case simVis::GOG::GOG_CONE: + case simVis::GOG::GOG_ORBIT: return true; default: break; @@ -1219,6 +1248,7 @@ bool GogNodeInterface::isLined_(simVis::GOG::GogShape shape) const case simVis::GOG::GOG_LINESEGS: case simVis::GOG::GOG_POINTS: case simVis::GOG::GOG_POLYGON: + case simVis::GOG::GOG_ORBIT: return true; default: break; @@ -1328,20 +1358,14 @@ FeatureNodeInterface::FeatureNodeInterface(osgEarth::FeatureNode* featureNode, c : GogNodeInterface(featureNode, metaData), featureNode_(featureNode) { - if (featureNode_.valid() && featureNode_->getFeature()) - { - style_ = *(featureNode_->getFeature()->style()); - hasMapNode_ = true; // feature nodes always have a map node - } - initializeFillColor_(); - initializeLineColor_(); + init_(); +} - // initialize our original altitudes - osgEarth::Geometry* geometry = featureNode_->getFeature()->getGeometry(); - for (size_t i = 0; i < geometry->size(); ++i) - { - originalAltitude_.push_back((*geometry)[i].z()); - } +FeatureNodeInterface::FeatureNodeInterface(osg::Group* node, osgEarth::FeatureNode* featureNode, const simVis::GOG::GogMetaData& metaData) + : GogNodeInterface(node, metaData), + featureNode_(featureNode) +{ + init_(); } int FeatureNodeInterface::getPosition(osg::Vec3d& position, osgEarth::GeoPoint* referencePosition) const @@ -1435,8 +1459,9 @@ int FeatureNodeInterface::getTessellation(TessellationStyle& tessellation) const void FeatureNodeInterface::setAltOffset(double altOffsetMeters) { - if (altOffsetMeters == altOffset_) + if (altOffsetMeters == altOffset_ || !featureNode_.valid()) return; + osgEarth::Geometry* geometry = featureNode_->getFeature()->getGeometry(); if (!geometry) return; @@ -1510,10 +1535,10 @@ void FeatureNodeInterface::setTessellation(TessellationStyle style) // adjust tessellation based on feature dimension const osgEarth::Feature* feature = featureNode_->getFeature(); - if (feature != NULL) + if (feature != nullptr) { const osgEarth::SpatialReference* srs = feature->getSRS(); - if (srs != NULL) + if (srs != nullptr) { osg::BoundingSphered boundS; if (feature->getWorldBound(srs->getGeocentricSRS(), boundS)) @@ -1523,7 +1548,7 @@ void FeatureNodeInterface::setTessellation(TessellationStyle style) } } } - ls->tessellationSize() = tessellationSpacingM; // in meters + ls->tessellationSize()->set(tessellationSpacingM, osgEarth::Units::METERS); // in meters } else { @@ -1615,6 +1640,22 @@ void FeatureNodeInterface::setStyle_(const osgEarth::Style& style) } } +void FeatureNodeInterface::init_() +{ + if (featureNode_.valid() && featureNode_->getFeature()) + { + style_ = *(featureNode_->getFeature()->style()); + hasMapNode_ = true; // feature nodes always have a map node + // initialize our original altitudes + const osgEarth::Geometry* geometry = featureNode_->getFeature()->getGeometry(); + for (size_t i = 0; i < geometry->size(); ++i) + { + originalAltitude_.push_back((*geometry)[i].z()); + } + } + initializeFillColor_(); + initializeLineColor_(); +} /////////////////////////////////////////////////////////////////// @@ -1917,9 +1958,9 @@ void CylinderNodeInterface::setStyle_(const osgEarth::Style& style) if (!filled_ && style_.has()) sideStyle.getOrCreate()->fill()->color() = style_.getSymbol()->stroke()->color(); - // If we are filled, then side's backface culling should be unset; if unfilled, then it should be set false + // If we are filled, then side's backface culling should be true; if unfilled, then it should be set false if (filled_) - sideStyle.getOrCreate()->backfaceCulling().unset(); + sideStyle.getOrCreate()->backfaceCulling() = true; else sideStyle.getOrCreate()->backfaceCulling() = false; sideNode_->setStyle(sideStyle); @@ -2069,7 +2110,7 @@ void SphericalNodeInterface::setColor_(const osg::Vec4f& color) // need to dig down into the LocalGeometryNode to get the underlying Geometry object to set its color array // NOTE: this assumes a specific implementation for spherical nodes. May fail if that implementation changes osg::Group* group = localNode_->getPositionAttitudeTransform(); - osg::Node* node = group->getNumChildren() > 0 ? group->getChild(0) : NULL; + osg::Node* node = group->getNumChildren() > 0 ? group->getChild(0) : nullptr; if (!node) return; osg::Geode* geode = node->asGeode(); @@ -2096,7 +2137,7 @@ void SphericalNodeInterface::setStyle_(const osgEarth::Style& style) // Find the internal node osg::Group* group = localNode_->getPositionAttitudeTransform(); - osg::Node* node = group->getNumChildren() > 0 ? group->getChild(0) : NULL; + osg::Node* node = group->getNumChildren() > 0 ? group->getChild(0) : nullptr; if (!node) return; @@ -2166,7 +2207,7 @@ void ConeNodeInterface::setFillColor(const osg::Vec4f& color) // Set the color on the cone body osg::Group* group = localNode_->getPositionAttitudeTransform(); - osg::Node* node = group->getNumChildren() > 0 ? group->getChild(0) : NULL; + osg::Node* node = group->getNumChildren() > 0 ? group->getChild(0) : nullptr; if (!node) return; osg::Geometry* geometry = node->asGeometry(); @@ -2179,7 +2220,7 @@ void ConeNodeInterface::setFillColor(const osg::Vec4f& color) geometry->setColorArray(colorArray); // Set the color on the cone cap - osg::Node* capNode = group->getNumChildren() > 1 ? group->getChild(1) : NULL; + osg::Node* capNode = group->getNumChildren() > 1 ? group->getChild(1) : nullptr; if (!capNode) return; osg::Geometry* capGeometry = capNode->asGeometry(); @@ -2194,6 +2235,8 @@ ImageOverlayInterface::ImageOverlayInterface(osgEarth::ImageOverlay* imageNode, : GogNodeInterface(imageNode, metaData), imageNode_(imageNode) { + // Turn off the color shader, since it doesn't work for image overlay + simVis::OverrideColor::setCombineMode(imageNode_->getOrCreateStateSet(), simVis::OverrideColor::OFF); } int ImageOverlayInterface::getPosition(osg::Vec3d& position, osgEarth::GeoPoint* referencePosition) const @@ -2209,6 +2252,13 @@ int ImageOverlayInterface::getPosition(osg::Vec3d& position, osgEarth::GeoPoint* return 0; } +void ImageOverlayInterface::setOpacity(float opacity) +{ + GogNodeInterface::setOpacity(opacity); + if (imageNode_.valid()) + imageNode_->setAlpha(opacity); +} + void ImageOverlayInterface::adjustAltitude_() { // no-op @@ -2224,4 +2274,85 @@ void ImageOverlayInterface::setStyle_(const osgEarth::Style& style) // no-op, can't update style } +LatLonAltBoxInterface::LatLonAltBoxInterface(osg::Group* node, osgEarth::FeatureNode* topNode, osgEarth::FeatureNode* bottomNode, const simVis::GOG::GogMetaData& metaData) + : FeatureNodeInterface(node, topNode, metaData), + bottomNode_(bottomNode) +{ + if (featureNode_.valid()) + initAltitudes_(*featureNode_.get(), originalAltitude_); + if (bottomNode_.valid()) + initAltitudes_(*bottomNode_.get(), bottomAltitude_); +} + +void LatLonAltBoxInterface::setAltOffset(double altOffsetMeters) +{ + if (altOffsetMeters == altOffset_) + return; + + metaData_.setExplicitly(GOG_THREE_D_OFFSET_ALT_SET); + altOffset_ = altOffsetMeters; + + if (featureNode_.valid()) + applyAltOffsets_(*featureNode_.get(), originalAltitude_); + if (bottomNode_.valid()) + applyAltOffsets_(*bottomNode_.get(), bottomAltitude_); +} + +void LatLonAltBoxInterface::serializeGeometry_(bool relativeShape, std::ostream& gogOutputStream) const +{ + // no-op, LatLonAltBox corners are stored in the meta data +} + +void LatLonAltBoxInterface::serializeKeyword_(std::ostream& gogOutputStream) const +{ + // nothing to do, LLA box includes the keyword in their metadata as part of the corner LLAs +} + +void LatLonAltBoxInterface::setStyle_(const osgEarth::Style& style) +{ + // make sure backface culling is always on + style_.getOrCreateSymbol()->backfaceCulling() = true; + + FeatureNodeInterface::setStyle_(style); + if (&style != &style_) + style_ = style; + if (!deferringStyleUpdates_() && bottomNode_.valid()) + { + bottomNode_->setStyle(style_); + bottomNode_->getFeature()->style() = style_; + bottomNode_->dirty(); + } +} + +void LatLonAltBoxInterface::initAltitudes_(osgEarth::FeatureNode& node, std::vector& altitudes) const +{ + altitudes.clear(); + // use GeometryIterator to get all the points, since it works on MultiGeometries + osgEarth::GeometryIterator iter(node.getFeature()->getGeometry(), false); + while (iter.hasMore()) + { + osgEarth::Geometry* part = iter.next(); + for (size_t i = 0; i < part->size(); ++i) + altitudes.push_back((*part)[i].z()); + } +} + +void LatLonAltBoxInterface::applyAltOffsets_(osgEarth::FeatureNode& node, const std::vector& altitudes) const +{ + osgEarth::Geometry* geometry = node.getFeature()->getGeometry(); + if (!geometry) + return; + + // now apply the altitude offset to all of our position points, use the GeometryIterator which works on MultiGeometries + osgEarth::GeometryIterator iter(geometry, false); + size_t altIndex = 0; + while (iter.hasMore()) + { + osgEarth::Geometry* part = iter.next(); + for (size_t i = 0; i < part->size() && altIndex < altitudes.size(); ++i, ++altIndex) + (*part)[i].z() = altitudes.at(altIndex) + altOffset_; + } + node.dirty(); +} + } } diff --git a/SDK/simVis/GOG/GogNodeInterface.h b/SDK/simVis/GOG/GogNodeInterface.h index 0c4b8c096..0015b4417 100644 --- a/SDK/simVis/GOG/GogNodeInterface.h +++ b/SDK/simVis/GOG/GogNodeInterface.h @@ -217,7 +217,7 @@ class SDKVIS_EXPORT GogNodeInterface * @param referencePosition will use this for ref position if it is valid, when applying local offset * @return 0 if position was found, non-zero otherwise */ - virtual int getPosition(osg::Vec3d& position, osgEarth::GeoPoint* referencePosition = NULL) const = 0; + virtual int getPosition(osg::Vec3d& position, osgEarth::GeoPoint* referencePosition = nullptr) const = 0; /** * Get the reference position of the shape on the map, in osgEarth::GeoPoint position format, lon/lat/alt degrees/degrees/meters. @@ -242,6 +242,13 @@ class SDKVIS_EXPORT GogNodeInterface */ virtual int getTextOutline(osg::Vec4f& outlineColor, simData::TextOutline& outlineThickness) const; + /** + * Retrieves the opacity value assigned to the GOG object. By default, this is 1.0 (opaque). + * @param opacity Opacity for the overlay; 0.0 for transparent, 1.0 for fully opaque. + * @return 0 if this overlay has an opacity value, non-zero otherwise. + */ + int getOpacity(float& opacity) const; + /** * Get the underlying osg::Node that represents the Overlay in the scene graph * @return the Overlay osg::Node @@ -348,6 +355,14 @@ class SDKVIS_EXPORT GogNodeInterface */ virtual void setTextOutline(const osg::Vec4f& outlineColor, simData::TextOutline outlineThickness); + /** + * Sets an overriding opacity value on the GOG object. This opacity is multiplied against any other + * opacities for foreground color, outline, image alpha value, etc. and is efficient for applying + * an overarching transparency level for the GOG. + * @param opacity Alpha value from 0.0 (transparent) to 1.0 (opaque) + */ + virtual void setOpacity(float opacity); + /** * Indicates if the shape has a properly formatted AltitudeSymbol or an ExtrusionSymbol based * on the altitude mode combinations applied in the setAltitudeMode method. Will return true @@ -495,6 +510,9 @@ class SDKVIS_EXPORT GogNodeInterface /** Range units specified by user in file */ simCore::Units rangeUnits_; + /** cache the opacity value, for efficiency */ + float opacity_; + /** listeners for updates */ std::vector listeners_; }; @@ -511,7 +529,7 @@ class SDKVIS_EXPORT AnnotationNodeInterface : public GogNodeInterface public: AnnotationNodeInterface(osgEarth::AnnotationNode* annotationNode, const simVis::GOG::GogMetaData& metaData); virtual ~AnnotationNodeInterface(); - virtual int getPosition(osg::Vec3d& position, osgEarth::GeoPoint* referencePosition = NULL) const; + virtual int getPosition(osg::Vec3d& position, osgEarth::GeoPoint* referencePosition = nullptr) const; protected: virtual void adjustAltitude_(); @@ -530,8 +548,10 @@ class SDKVIS_EXPORT FeatureNodeInterface : public GogNodeInterface public: /** Constructor */ FeatureNodeInterface(osgEarth::FeatureNode* featureNode, const simVis::GOG::GogMetaData& metaData); + /** Constructor with parent group node */ + FeatureNodeInterface(osg::Group* node, osgEarth::FeatureNode* featureNode, const simVis::GOG::GogMetaData& metaData); virtual ~FeatureNodeInterface() {} - virtual int getPosition(osg::Vec3d& position, osgEarth::GeoPoint* referencePosition = NULL) const; + virtual int getPosition(osg::Vec3d& position, osgEarth::GeoPoint* referencePosition = nullptr) const; virtual int getTessellation(TessellationStyle& style) const; virtual void setAltitudeMode(AltitudeMode altMode); virtual void setAltOffset(double altOffsetMeters); @@ -543,10 +563,12 @@ class SDKVIS_EXPORT FeatureNodeInterface : public GogNodeInterface virtual void serializeGeometry_(bool relativeShape, std::ostream& gogOutputStream) const; virtual void setStyle_(const osgEarth::Style& style); -private: osg::observer_ptr featureNode_; /// cache the original altitude values, to apply altitude offset dynamically std::vector originalAltitude_; + +private: + void init_(); }; /** @@ -558,7 +580,7 @@ class SDKVIS_EXPORT LocalGeometryNodeInterface : public GogNodeInterface /** Constructor */ LocalGeometryNodeInterface(osgEarth::LocalGeometryNode* localNode, const simVis::GOG::GogMetaData& metaData); virtual ~LocalGeometryNodeInterface() {} - virtual int getPosition(osg::Vec3d& position, osgEarth::GeoPoint* referencePosition = NULL) const; + virtual int getPosition(osg::Vec3d& position, osgEarth::GeoPoint* referencePosition = nullptr) const; /// override the get reference position virtual int getReferencePosition(osg::Vec3d& referencePosition) const; @@ -582,7 +604,7 @@ class SDKVIS_EXPORT LabelNodeInterface : public GogNodeInterface LabelNodeInterface(osgEarth::GeoPositionNode* labelNode, const simVis::GOG::GogMetaData& metaData); virtual ~LabelNodeInterface() {} virtual int getFont(std::string& fontFile, int& fontSize, osg::Vec4f& fontColor) const; - virtual int getPosition(osg::Vec3d& position, osgEarth::GeoPoint* referencePosition = NULL) const; + virtual int getPosition(osg::Vec3d& position, osgEarth::GeoPoint* referencePosition = nullptr) const; virtual int getTextOutline(osg::Vec4f& outlineColor, simData::TextOutline& outlineThickness) const; virtual int getDeclutterPriority(int& priority) const; virtual void setFont(const std::string& fontName, int fontSize, const osg::Vec4f& color); @@ -615,7 +637,7 @@ class SDKVIS_EXPORT CylinderNodeInterface : public GogNodeInterface /** Constructor */ CylinderNodeInterface(osg::Group* groupNode, osgEarth::LocalGeometryNode* sideNode, osgEarth::LocalGeometryNode* topCapNode, osgEarth::LocalGeometryNode* bottomCapNode, const simVis::GOG::GogMetaData& metaData); virtual ~CylinderNodeInterface(); - virtual int getPosition(osg::Vec3d& position, osgEarth::GeoPoint* referencePosition = NULL) const; + virtual int getPosition(osg::Vec3d& position, osgEarth::GeoPoint* referencePosition = nullptr) const; virtual void setAltitudeMode(AltitudeMode altMode); protected: @@ -643,7 +665,7 @@ class SDKVIS_EXPORT ArcNodeInterface : public GogNodeInterface /** Constructor */ ArcNodeInterface(osg::Group* groupNode, osgEarth::LocalGeometryNode* shapeNode, osgEarth::LocalGeometryNode* fillNode, const simVis::GOG::GogMetaData& metatData); virtual ~ArcNodeInterface() {} - virtual int getPosition(osg::Vec3d& position, osgEarth::GeoPoint* referencePosition = NULL) const; + virtual int getPosition(osg::Vec3d& position, osgEarth::GeoPoint* referencePosition = nullptr) const; virtual void setFilledState(bool state); protected: @@ -695,7 +717,7 @@ class SDKVIS_EXPORT ConeNodeInterface : public LocalGeometryNodeInterface }; /** -* Implementation of GogNodeInterface for an image overlay object, which is eqivalent to a KML ground overlay. +* Implementation of GogNodeInterface for an image overlay object, which is equivalent to a KML ground overlay. * Basic implementation since editing KML objects is limited. */ class SDKVIS_EXPORT ImageOverlayInterface : public GogNodeInterface @@ -703,7 +725,10 @@ class SDKVIS_EXPORT ImageOverlayInterface : public GogNodeInterface public: ImageOverlayInterface(osgEarth::ImageOverlay* imageNode, const simVis::GOG::GogMetaData& metaData); virtual ~ImageOverlayInterface() {} - virtual int getPosition(osg::Vec3d& position, osgEarth::GeoPoint* referencePosition = NULL) const; + virtual int getPosition(osg::Vec3d& position, osgEarth::GeoPoint* referencePosition = nullptr) const; + + /** Override opacity, since the override color approach doesn't work */ + virtual void setOpacity(float opacity) override; protected: virtual void adjustAltitude_(); @@ -714,6 +739,34 @@ class SDKVIS_EXPORT ImageOverlayInterface : public GogNodeInterface osg::observer_ptr imageNode_; }; +/** +* Implementation of GogNodeInterface for a LatLonAltBox, which requires multiple FeatureNodes to display correctly +*/ +class SDKVIS_EXPORT LatLonAltBoxInterface : public FeatureNodeInterface +{ +public: + LatLonAltBoxInterface(osg::Group* node, osgEarth::FeatureNode* topNode, osgEarth::FeatureNode* bottomNode, const simVis::GOG::GogMetaData& metaData); + virtual ~LatLonAltBoxInterface() {} + // handle the special case for MultiGeometry + virtual void setAltOffset(double altOffsetMeters); + +protected: + virtual void serializeGeometry_(bool relativeShape, std::ostream& gogOutputStream) const; + virtual void serializeKeyword_(std::ostream& gogOutputStream) const; + virtual void setStyle_(const osgEarth::Style& style); + +private: + /// store the altitudes of the specified node into the specified altitudes vector, handles iterating through MultiGeometry + void initAltitudes_(osgEarth::FeatureNode& node, std::vector& altitudes) const; + /// apply the altitude offsets, handles iterating through MultiGeometry + void applyAltOffsets_(osgEarth::FeatureNode& node, const std::vector& altitudes) const; + + osg::observer_ptr bottomNode_; + /// original altitudes of the bottom node + std::vector bottomAltitude_; +}; + + }} #endif /* SIMVIS_GOG_GOGNODEINTERFACE_H */ diff --git a/SDK/simVis/GOG/Hemisphere.cpp b/SDK/simVis/GOG/Hemisphere.cpp index 05a091415..30719c3ae 100644 --- a/SDK/simVis/GOG/Hemisphere.cpp +++ b/SDK/simVis/GOG/Hemisphere.cpp @@ -52,13 +52,13 @@ GogNodeInterface* Hemisphere::deserialize(const ParsedShape& parsedShape, if (radius_m <= 0.f) { SIM_WARN << "Cannot create hemisphere with no radius\n"; - return NULL; + return nullptr; } osg::Node* shape = osgEarth::AnnotationUtils::createHemisphere( radius_m, color); shape->setName("GOG Hemisphere"); - osgEarth::LocalGeometryNode* node = NULL; + osgEarth::LocalGeometryNode* node = nullptr; if (nodeType == GOGNODE_GEOGRAPHIC) { @@ -76,7 +76,7 @@ GogNodeInterface* Hemisphere::deserialize(const ParsedShape& parsedShape, node = new HostedLocalGeometryNode(shape, p.style_); node->setName("GOG Hemisphere Position"); - GogNodeInterface* rv = NULL; + GogNodeInterface* rv = nullptr; if (node) { Utils::applyLocalGeometryOffsets(*node, p, nodeType); diff --git a/SDK/simVis/GOG/ImageOverlay.cpp b/SDK/simVis/GOG/ImageOverlay.cpp index 1041711f7..eb25bcc43 100644 --- a/SDK/simVis/GOG/ImageOverlay.cpp +++ b/SDK/simVis/GOG/ImageOverlay.cpp @@ -41,7 +41,7 @@ GogNodeInterface* ImageOverlay::deserialize( const GogMetaData& metaData, osgEarth::MapNode* mapNode) { - GogNodeInterface* rv = NULL; + GogNodeInterface* rv = nullptr; if (!parsedShape.hasValue(GOG_ICON)) return rv; diff --git a/SDK/simVis/GOG/LatLonAltBox.cpp b/SDK/simVis/GOG/LatLonAltBox.cpp index 5cc8fcda7..453bf9557 100644 --- a/SDK/simVis/GOG/LatLonAltBox.cpp +++ b/SDK/simVis/GOG/LatLonAltBox.cpp @@ -20,9 +20,11 @@ * disclose, or release this software. * */ +#include "osg/FrontFace" #include "osgEarth/GeometryFactory" #include "osgEarth/GeometryCompiler" #include "osgEarth/FeatureNode" +#include "simCore/Calc/CoordinateConverter.h" #include "simVis/GOG/LatLonAltBox.h" #include "simVis/GOG/GogNodeInterface.h" #include "simVis/GOG/ParsedShape.h" @@ -127,42 +129,45 @@ GogNodeInterface* LatLonAltBox::deserialize(const ParsedShape& parsedShape, // semi-transparent. If you always want to see lines then remove this line. style.getOrCreateSymbol()->backfaceCulling() = true; - // result geometry: - MultiGeometry* lines = new MultiGeometry(); - Geometry* bottom = lines->add(new NoRewindRing()); + // geometry for bottom/left/back + MultiGeometry* linesBottom = new MultiGeometry(); + Geometry* bottom = linesBottom->add(new NoRewindRing()); bottom->push_back(minPoint.vec3d()); bottom->push_back(minPoint.x(), maxPoint.y(), minPoint.z()); bottom->push_back(maxPoint.x(), maxPoint.y(), minPoint.z()); bottom->push_back(maxPoint.x(), minPoint.y(), minPoint.z()); - Geometry* top = lines->add(new NoRewindRing()); + // geometry for top/right/front + MultiGeometry* linesTop = new MultiGeometry(); + Geometry* top = linesTop->add(new NoRewindRing()); top->push_back(minPoint.x(), minPoint.y(), maxPoint.z()); top->push_back(maxPoint.x(), minPoint.y(), maxPoint.z()); top->push_back(maxPoint.x(), maxPoint.y(), maxPoint.z()); top->push_back(minPoint.x(), maxPoint.y(), maxPoint.z()); + osgEarth::Geometry::Orientation ori2 = top->getOrientation(); // Top and bottom are required for proper display above and below. Sides are not required for 0-height. if (maxPoint.z() > minPoint.z()) { - Geometry* left = lines->add(new NoRewindRing()); + Geometry* left = linesBottom->add(new NoRewindRing()); left->push_back(minPoint.x(), minPoint.y(), minPoint.z()); left->push_back(minPoint.x(), minPoint.y(), maxPoint.z()); left->push_back(minPoint.x(), maxPoint.y(), maxPoint.z()); left->push_back(minPoint.x(), maxPoint.y(), minPoint.z()); - Geometry* right = lines->add(new NoRewindRing()); + Geometry* right = linesTop->add(new NoRewindRing()); right->push_back(maxPoint.x(), minPoint.y(), minPoint.z()); right->push_back(maxPoint.x(), maxPoint.y(), minPoint.z()); right->push_back(maxPoint.x(), maxPoint.y(), maxPoint.z()); right->push_back(maxPoint.x(), minPoint.y(), maxPoint.z()); - Geometry* back = lines->add(new NoRewindRing()); + Geometry* back = linesBottom->add(new NoRewindRing()); back->push_back(minPoint.x(), maxPoint.y(), minPoint.z()); back->push_back(minPoint.x(), maxPoint.y(), maxPoint.z()); back->push_back(maxPoint.x(), maxPoint.y(), maxPoint.z()); back->push_back(maxPoint.x(), maxPoint.y(), minPoint.z()); - Geometry* front = lines->add(new NoRewindRing()); + Geometry* front = linesTop->add(new NoRewindRing()); front->push_back(minPoint.x(), minPoint.y(), minPoint.z()); front->push_back(maxPoint.x(), minPoint.y(), minPoint.z()); front->push_back(maxPoint.x(), minPoint.y(), maxPoint.z()); @@ -173,17 +178,30 @@ GogNodeInterface* LatLonAltBox::deserialize(const ParsedShape& parsedShape, if (!parsedShape.hasValue(GOG_FILLED)) style.remove(); - Feature* feature = new Feature(lines, mapNode->getMapSRS(), style); - feature->setName("GOG LatLonAltBox Feature"); - osgEarth::FeatureNode* node = new osgEarth::FeatureNode(feature); - node->setName("GOG LatLonAltBox"); - node->setMapNode(mapNode); - GogNodeInterface* rv = new FeatureNodeInterface(node, metaData); + Feature* featureBottom = new Feature(linesBottom, p.srs_.get(), style); + featureBottom->setName("GOG LatLonAltBox Feature Bottom"); + osgEarth::FeatureNode* nodeBottom = new osgEarth::FeatureNode(featureBottom); + nodeBottom->setName("GOG LatLonAltBox Bottom"); + nodeBottom->setMapNode(mapNode); + // Set the node facing to clockwise, to solve winding issue with osgEarth + nodeBottom->getOrCreateStateSet()->setAttributeAndModes(new osg::FrontFace(osg::FrontFace::CLOCKWISE), osg::StateAttribute::ON); + + Feature* featureTop = new Feature(linesTop, p.srs_.get(), style); + featureTop->setName("GOG LatLonAltBox Feature Top"); + osgEarth::FeatureNode* nodeTop = new osgEarth::FeatureNode(featureTop); + nodeTop->setName("GOG LatLonAltBox Top"); + nodeTop->setMapNode(mapNode); + + osg::Group* parent = new osg::Group(); + parent->addChild(nodeBottom); + parent->addChild(nodeTop); + + GogNodeInterface* rv = new LatLonAltBoxInterface(parent, nodeTop, nodeBottom, metaData); rv->applyToStyle(parsedShape, p.units_); return rv; } // no "hosted" version of this GOG. - return NULL; + return nullptr; } } } diff --git a/SDK/simVis/GOG/Line.cpp b/SDK/simVis/GOG/Line.cpp index 7fb80a69b..8f655d6d7 100644 --- a/SDK/simVis/GOG/Line.cpp +++ b/SDK/simVis/GOG/Line.cpp @@ -47,7 +47,7 @@ GogNodeInterface* Line::deserialize(const ParsedShape& parsedShape, { p.parseGeometry(parsedShape); - GogNodeInterface* rv = NULL; + GogNodeInterface* rv = nullptr; if (nodeType == GOGNODE_GEOGRAPHIC) { diff --git a/SDK/simVis/GOG/LineSegs.cpp b/SDK/simVis/GOG/LineSegs.cpp index e5cab62fa..a42723da0 100644 --- a/SDK/simVis/GOG/LineSegs.cpp +++ b/SDK/simVis/GOG/LineSegs.cpp @@ -59,7 +59,7 @@ GogNodeInterface* LineSegs::deserialize(const ParsedShape& parsedShape, } p.geom_ = m; - GogNodeInterface* rv = NULL; + GogNodeInterface* rv = nullptr; if (nodeType == GOGNODE_GEOGRAPHIC) { // Try to prevent terrain z-fighting. diff --git a/SDK/simVis/GOG/Orbit.cpp b/SDK/simVis/GOG/Orbit.cpp new file mode 100644 index 000000000..52aea8bd5 --- /dev/null +++ b/SDK/simVis/GOG/Orbit.cpp @@ -0,0 +1,171 @@ +/* -*- mode: c++ -*- */ +/**************************************************************************** + ***** ***** + ***** Classification: UNCLASSIFIED ***** + ***** Classified By: ***** + ***** Declassify On: ***** + ***** ***** + **************************************************************************** + * + * + * Developed by: Naval Research Laboratory, Tactical Electronic Warfare Div. + * EW Modeling & Simulation, Code 5773 + * 4555 Overlook Ave. + * Washington, D.C. 20375-5339 + * + * License for source code can be found at: + * https://github.com/USNavalResearchLaboratory/simdissdk/blob/master/LICENSE.txt + * + * The U.S. Government retains all rights to use, duplicate, distribute, + * disclose, or release this software. + * + */ + +#include "osgEarth/LocalGeometryNode" +#include "simCore/Calc/Angle.h" +#include "simCore/Calc/Calculations.h" +#include "simCore/Calc/Math.h" +#include "simVis/GOG/ErrorHandler.h" +#include "simVis/GOG/GogNodeInterface.h" +#include "simVis/GOG/HostedLocalGeometryNode.h" +#include "simVis/GOG/ParsedShape.h" +#include "simVis/GOG/Utils.h" +#include "simVis/GOG/Orbit.h" + + +namespace { + +// generate an orbit geometry from specified parameters, azimuth in radians, others in meters +osgEarth::Geometry* createOrbit(double azimuthRad, double lengthM, double radiusM, double altitudeM) +{ + osgEarth::Geometry* geom = new osgEarth::LineString(); + if (radiusM <= 0) + return nullptr; + + const double startRad = simCore::angFix2PI(azimuthRad + M_PI_2); + const double endRad = startRad + M_PI; + const double span = M_PI; + const double segLen = radiusM / 8.0; + const double circumference = 2 * M_PI * radiusM; + const double numSegments = ceil(circumference / segLen); + const double step = span / numSegments; + + double ctrX = 0; + double ctrY = 0; + + // generate arc on first end of the orbit + for (int i = numSegments; i >= 0; --i) + { + const double angle = simCore::angFix2PI(startRad + step * static_cast(i)); + const double x = ctrX + sin(angle) * radiusM; + const double y = ctrY + cos(angle) * radiusM; + geom->push_back(osg::Vec3d(x, y, altitudeM)); + } + + // calculate center point on other end of orbit + ctrX = sin(azimuthRad) * lengthM; + ctrY = cos(azimuthRad) * lengthM; + + // generate arc on other end of the orbit + for (int i = numSegments; i >= 0; --i) + { + const double angle = simCore::angFix2PI(endRad + step * static_cast(i)); + const double x = ctrX + sin(angle) * radiusM; + const double y = ctrY + cos(angle) * radiusM; + geom->push_back(osg::Vec3d(x, y, altitudeM)); + } + // add back in first point to close the shape + geom->push_back(geom->front()); + + geom->rewind(osgEarth::Geometry::ORIENTATION_CCW); + return geom; +} + +} + +namespace simVis { namespace GOG { + +GogNodeInterface* Orbit::deserialize( + const ParsedShape& parsedShape, + simVis::GOG::ParserData& p, + const GOGNodeType& nodeType, + const GOGContext& context, + const GogMetaData& metaData, + osgEarth::MapNode* mapNode) +{ + double radius = p.units_.rangeUnits_.convertTo(simCore::Units::METERS, parsedShape.doubleValue(GOG_RADIUS, 1000.)); + const size_t lineNumber = parsedShape.lineNumber(); + + if (radius <= 0) + { + context.errorHandler_->printError(lineNumber, "Orbit must have a valid radius"); + return nullptr; + } + + osgEarth::LocalGeometryNode* node = nullptr; + if (nodeType == GOGNODE_GEOGRAPHIC) + { + if (!parsedShape.hasValue(GOG_CENTERLL) || !parsedShape.hasValue(GOG_CENTERLL2)) + { + context.errorHandler_->printError(lineNumber, "Orbit must have both center points, [centerll,centerlla,centerlatlon] and centerll2"); + return nullptr; + } + + // if center points are not set, the hasValue() checks above were implemented incorrectly + assert(p.centerLLA_.isSet()); + assert(p.centerLLA2_.isSet()); + + const osg::Vec3d& ctr1 = p.centerLLA_.get(); + const osg::Vec3d& ctr2 = p.centerLLA2_.get(); + + // find azimuth and length of orbit + double azimuth = 0.; + double length = simCore::sodanoInverse(ctr1.y() * simCore::DEG2RAD, ctr1.x() * simCore::DEG2RAD, ctr1.z(), + ctr2.y() * simCore::DEG2RAD, ctr2.x() * simCore::DEG2RAD, &azimuth, nullptr); + osgEarth::Geometry* geom = createOrbit(azimuth, length, radius, ctr1.z()); + + osgEarth::Style style(p.style_); + node = new osgEarth::LocalGeometryNode(geom, style); + node->setMapNode(mapNode); + + } + else + { + if (!parsedShape.hasValue(GOG_CENTERXY) || !parsedShape.hasValue(GOG_CENTERXY2)) + { + context.errorHandler_->printError(lineNumber, "Orbit relative must have both center points, [centerxy,centerxyz] and centerxy2"); + return nullptr; + } + // if center points are not set, the hasValue() checks above were implemented incorrectly + assert(p.centerXYZ_.isSet()); + assert(p.centerXYZ2_.isSet()); + + const osg::Vec3d ctr1 = p.centerXYZ_.get(); + const osg::Vec3d ctr2 = p.centerXYZ2_.get(); + + double xLen = ctr1.x() - ctr2.x(); + double yLen = ctr1.y() - ctr2.y(); + double length = sqrt((xLen * xLen) + (yLen * yLen)); + double azimuth = atan(xLen / yLen); + + if (yLen > 0) + azimuth += M_PI; + + osgEarth::Geometry* geom = createOrbit(simCore::angFix2PI(azimuth), length, radius, ctr1.z()); + osgEarth::Style style(p.style_); + node = new HostedLocalGeometryNode(geom, style); + } + + GogNodeInterface* rv = nullptr; + if (node) + { + node->setName("Orbit"); + Utils::applyLocalGeometryOffsets(*node, p, nodeType); + rv = new LocalGeometryNodeInterface(node, metaData); + rv->applyToStyle(parsedShape, p.units_); + } + + return rv; + } + +}} diff --git a/SDK/simVis/GOG/Orbit.h b/SDK/simVis/GOG/Orbit.h new file mode 100644 index 000000000..8a6412083 --- /dev/null +++ b/SDK/simVis/GOG/Orbit.h @@ -0,0 +1,52 @@ +/* -*- mode: c++ -*- */ +/**************************************************************************** + ***** ***** + ***** Classification: UNCLASSIFIED ***** + ***** Classified By: ***** + ***** Declassify On: ***** + ***** ***** + **************************************************************************** + * + * + * Developed by: Naval Research Laboratory, Tactical Electronic Warfare Div. + * EW Modeling & Simulation, Code 5773 + * 4555 Overlook Ave. + * Washington, D.C. 20375-5339 + * + * License for source code can be found at: + * https://github.com/USNavalResearchLaboratory/simdissdk/blob/master/LICENSE.txt + * + * The U.S. Government retains all rights to use, duplicate, distribute, + * disclose, or release this software. + * + */ +#ifndef SIMVIS_GOG_ORBIT_H +#define SIMVIS_GOG_ORBIT_H + +#include "simVis/GOG/GOGNode.h" + +namespace osgEarth { class MapNode; } + +namespace simVis { namespace GOG { + +class GogNodeInterface; +class ParsedShape; +class ParserData; + +/** Display GOG Orbit */ +class SDKVIS_EXPORT Orbit +{ +public: + /** Create the orbit from the parser data and GOG meta data */ + GogNodeInterface* deserialize( + const ParsedShape& parsedShape, + simVis::GOG::ParserData& p, + const GOGNodeType& nodeType, + const GOGContext& context, + const GogMetaData& metaData, + osgEarth::MapNode* mapNode); +}; + +} } // namespace simVis::GOG + +#endif // SIMVIS_GOG_ORBIT_H diff --git a/SDK/simVis/GOG/ParsedShape.h b/SDK/simVis/GOG/ParsedShape.h index 5ce7eaaab..c9fd3777e 100644 --- a/SDK/simVis/GOG/ParsedShape.h +++ b/SDK/simVis/GOG/ParsedShape.h @@ -109,6 +109,8 @@ enum ShapeParameter GOG_REF_LAT, // Reference LLA GOG_REF_LON, // Reference LLA GOG_REF_ALT, // Reference LLA + GOG_CENTERLL2, + GOG_CENTERXY2, // GOG Unit Commands GOG_ALTITUDEUNITS = 50, diff --git a/SDK/simVis/GOG/Parser.cpp b/SDK/simVis/GOG/Parser.cpp index 779d8c45c..1f3920c2e 100644 --- a/SDK/simVis/GOG/Parser.cpp +++ b/SDK/simVis/GOG/Parser.cpp @@ -180,12 +180,12 @@ GogNodeInterface* Parser::createGOG(const std::vector& lines, const std::istringstream input(buf.str()); - GogNodeInterface* result = NULL; + GogNodeInterface* result = nullptr; OverlayNodeVector output; std::vector followDataVec; if (createGOGs(input, nodeType, output, followDataVec)) { - result = output.size() > 0 ? output.front() : NULL; + result = output.size() > 0 ? output.front() : nullptr; } if (!followDataVec.empty()) followData = followDataVec.front(); @@ -412,7 +412,8 @@ bool Parser::parse(std::istream& input, std::vector& output, std::v tokens[0] == "poly" || tokens[0] == "polygon" || tokens[0] == "linesegs" || - tokens[0] == "cone" + tokens[0] == "cone" || + tokens[0] == "orbit" ) { if (currentMetaData.shape != GOG_UNKNOWN) @@ -566,6 +567,22 @@ bool Parser::parse(std::istream& input, std::vector& output, std::v printError_(lineNumber, "centerxy/centerxyz command requires at least 2 arguments"); } } + else if (tokens[0] == "centerxy2") + { + if (tokens.size() >= 3) + { + if (type == SHAPE_UNKNOWN) + type = SHAPE_RELATIVE; + else if (type == SHAPE_ABSOLUTE) + continue; + currentMetaData.metadata += line + "\n"; + current.set(GOG_CENTERXY2, PositionStrings(tokens[1], tokens[2])); + } + else + { + printError_(lineNumber, "centerxy2 command requires at least 2 arguments"); + } + } else if (tokens[0] == "centerll" || tokens[0] == "centerlla" || tokens[0] == "centerlatlon") { if (tokens.size() >= 3) @@ -585,6 +602,21 @@ bool Parser::parse(std::istream& input, std::vector& output, std::v printError_(lineNumber, "centerll/centerlla/centerlatlon command requires at least 2 arguments"); } } + else if (tokens[0] == "centerll2" || tokens[0] == "centerlatlon2") + { + if (tokens.size() >= 3) + { + if (type == SHAPE_UNKNOWN) + type = SHAPE_ABSOLUTE; + else if (type == SHAPE_RELATIVE) + continue; + currentMetaData.metadata += line + "\n"; + // note centerll2 only supports lat and lon, altitude for shape must be derived from first center point + current.set(GOG_CENTERLL2, PositionStrings(tokens[1], tokens[2])); + } + else + printError_(lineNumber, "centerll2 command requires at least 2 arguments"); + } // persistent state modifiers: else if (tokens[0] == "linecolor") { @@ -1154,6 +1186,8 @@ GogShape Parser::getShapeFromKeyword(const std::string& keyword) return GOG_CONE; if (keyword == "imageoverlay") return GOG_IMAGEOVERLAY; + if (keyword == "orbit") + return GOG_ORBIT; return GOG_UNKNOWN; } @@ -1191,6 +1225,8 @@ std::string Parser::getKeywordFromShape(GogShape shape) return "cone"; case GOG_IMAGEOVERLAY: return "imageoverlay"; + case GOG_ORBIT: + return "orbit"; case GOG_UNKNOWN: return ""; } @@ -1205,7 +1241,7 @@ bool Parser::loadGOGs(std::istream& input, const GOGNodeType& nodeType, OverlayN void Parser::printError_(size_t lineNumber, const std::string& errorText) const { // Assertion failure means Null Object pattern failed - assert(context_.errorHandler_ != NULL); + assert(context_.errorHandler_ != nullptr); if (context_.errorHandler_) context_.errorHandler_->printError(lineNumber, errorText); } diff --git a/SDK/simVis/GOG/Parser.h b/SDK/simVis/GOG/Parser.h index 4529b5848..b4a96d227 100644 --- a/SDK/simVis/GOG/Parser.h +++ b/SDK/simVis/GOG/Parser.h @@ -78,7 +78,7 @@ namespace simVis { namespace GOG * that if the map node changes, the Parser will not pick up on the change and could cause problems * in parsed items. So it is recommended that the GOG parser be instantiated on demand. */ - Parser(osgEarth::MapNode* mapNode = NULL); + Parser(osgEarth::MapNode* mapNode = nullptr); /** * Constructs a GOG parser. @@ -149,8 +149,8 @@ namespace simVis { namespace GOG const GOGNodeType& nodeType, OverlayNodeVector& output, std::vector& followData, - std::vector* parsedShapes = NULL, - std::vector* metaData = NULL) const; + std::vector* parsedShapes = nullptr, + std::vector* metaData = nullptr) const; /** * Converts the GOG file shape keyword to a GogShape. Assumes keyword is all lower, does exact match @@ -181,8 +181,8 @@ namespace simVis { namespace GOG const GOGNodeType& nodeType, OverlayNodeVector& output, std::vector& followData, - std::vector* parsedShapes = NULL, - std::vector* metaData = NULL) const; + std::vector* parsedShapes = nullptr, + std::vector* metaData = nullptr) const; /** * Add or overwrite a color key with a new color diff --git a/SDK/simVis/GOG/Points.cpp b/SDK/simVis/GOG/Points.cpp index 75cce964a..9c3b00f53 100644 --- a/SDK/simVis/GOG/Points.cpp +++ b/SDK/simVis/GOG/Points.cpp @@ -94,7 +94,7 @@ GogNodeInterface* Points::deserializeImpl_(const ParsedShape& parsedShape, const GogMetaData& metaData, MapNode* mapNode) { - GogNodeInterface* rv = NULL; + GogNodeInterface* rv = nullptr; if (nodeType == GOGNODE_GEOGRAPHIC) { // Try to prevent terrain z-fighting. diff --git a/SDK/simVis/GOG/Polygon.cpp b/SDK/simVis/GOG/Polygon.cpp index 27bed487c..8e2f9756d 100644 --- a/SDK/simVis/GOG/Polygon.cpp +++ b/SDK/simVis/GOG/Polygon.cpp @@ -45,7 +45,7 @@ GogNodeInterface* simVis::GOG::Polygon::deserialize(const ParsedShape& parsedSha osgEarth::MapNode* mapNode) { p.parseGeometry(parsedShape); - GogNodeInterface* rv = NULL; + GogNodeInterface* rv = nullptr; if (nodeType == GOGNODE_GEOGRAPHIC) { // Try to prevent terrain z-fighting. diff --git a/SDK/simVis/GOG/Sphere.cpp b/SDK/simVis/GOG/Sphere.cpp index 913f842c0..1d7975bae 100644 --- a/SDK/simVis/GOG/Sphere.cpp +++ b/SDK/simVis/GOG/Sphere.cpp @@ -51,13 +51,13 @@ GogNodeInterface* Sphere::deserialize(const ParsedShape& parsedShape, if (radius_m <= 0.f) { SIM_WARN << "Cannot create sphere with no radius\n"; - return NULL; + return nullptr; } osg::Node* shape = osgEarth::AnnotationUtils::createSphere( radius_m, color); shape->setName("GOG Sphere"); - osgEarth::LocalGeometryNode* node = NULL; + osgEarth::LocalGeometryNode* node = nullptr; if (nodeType == GOGNODE_GEOGRAPHIC) { @@ -72,7 +72,7 @@ GogNodeInterface* Sphere::deserialize(const ParsedShape& parsedShape, } node->setName("GOG Sphere Position"); - GogNodeInterface* rv = NULL; + GogNodeInterface* rv = nullptr; if (node) { Utils::applyLocalGeometryOffsets(*node, p, nodeType); diff --git a/SDK/simVis/GOG/Utils.cpp b/SDK/simVis/GOG/Utils.cpp index 0b43044e6..ff0406a99 100644 --- a/SDK/simVis/GOG/Utils.cpp +++ b/SDK/simVis/GOG/Utils.cpp @@ -69,7 +69,7 @@ void Utils::applyLocalGeometryOffsets(LocalGeometryNode& node, ParserData& data, { // if this is a hosted node, it will need to set any offsets in the attitude transform's position, since it's position is ignored osg::PositionAttitudeTransform* trans = node.getPositionAttitudeTransform(); - if (trans != NULL) + if (trans != nullptr) trans->setPosition(data.getLTPOffset()); // hosted nodes don't set orientation offsets directly, they are instead applied through a Locator attached to the host } @@ -97,6 +97,7 @@ bool Utils::canSerializeGeometry_(simVis::GOG::GogShape shape) case simVis::GOG::GOG_LATLONALTBOX: case simVis::GOG::GOG_CONE: case simVis::GOG::GOG_IMAGEOVERLAY: + case simVis::GOG::GOG_ORBIT: break; } return false; @@ -377,6 +378,41 @@ ParserData::ParserData(const ParsedShape& parsedShape, const GOGContext& context // annotations have a single center point but don't use centerxyz keyword for relative shapes, so make sure the refPointLLA_ is set for relative annotations else if (shape == GOG_ANNOTATION && !refPointLLA_.isSet() && parsedShape.pointType() == ParsedShape::XYZ) refPointLLA_->set(context_.refPoint_->vec3d()); + + // handle second center point + if (parsedShape.hasValue(GOG_CENTERLL2)) + { + const PositionStrings& p = parsedShape.positionValue(GOG_CENTERLL2); + // Convert altitude value from string + double altitude = 0.; + + if (centerLLA_.isSet()) + altitude = centerLLA_->z(); + // units as per the SIMDIS user manual: + centerLLA2_->set( + parseAngle(p.y, 0.0), // longitude + parseAngle(p.x, 0.0), // latitude + altitude); + } + if (parsedShape.hasValue(GOG_CENTERXY2)) + { + const PositionStrings& p = parsedShape.positionValue(GOG_CENTERXY2); + // Convert values from string + double xyz[3] = { 0. }; + simCore::isValidNumber(p.x, xyz[0]); + simCore::isValidNumber(p.y, xyz[1]); + + // get Z from centerXYZ_ if it's valid + double z = 0.; + if (centerXYZ_.isSet()) + z = centerXYZ_->z(); + + // units as per the SIMDIS user manual: + centerXYZ2_->set( + units_.rangeUnits_.convertTo(simCore::Units::METERS, xyz[0]), + units_.rangeUnits_.convertTo(simCore::Units::METERS, xyz[1]), + z); + } } if (parsedShape.hasValue(GOG_LINEPROJECTION)) diff --git a/SDK/simVis/GOG/Utils.h b/SDK/simVis/GOG/Utils.h index bf536ad67..6505b67ce 100644 --- a/SDK/simVis/GOG/Utils.h +++ b/SDK/simVis/GOG/Utils.h @@ -332,8 +332,10 @@ namespace simVis { namespace GOG GOGContext context_; ///< Context osgEarth::Style style_; ///< Style osgEarth::optional refPointLLA_; ///< Reference point in LLA - osgEarth::optional centerXYZ_; ///< Center point in XXZ + osgEarth::optional centerXYZ_; ///< Center point in XYZ + osgEarth::optional centerXYZ2_; ///< Second center point in XYZ, only valid for some shapes osgEarth::optional centerLLA_; ///< Center point in LLA + osgEarth::optional centerLLA2_; ///< Second center point in LLA, only valid for some shapes osg::ref_ptr geom_; ///< Geometry bool geomIsLLA_; ///< If true than in LLA; if false in XYZ bool geomIsRelative_; ///< If true than GOG is relative; if false GOG is absolute diff --git a/SDK/simVis/Gate.cpp b/SDK/simVis/Gate.cpp index c8a0c00a3..4959b57e7 100644 --- a/SDK/simVis/Gate.cpp +++ b/SDK/simVis/Gate.cpp @@ -62,7 +62,7 @@ GateVolume::GateVolume(simVis::Locator* locator, const simData::GatePrefs* prefs // if outline is on, it should be written (separately) to BIN_OPAQUE_GATE osg::Geometry* solidGeometry = simVis::SVFactory::solidGeometry(gateSV_.get()); - if (solidGeometry != NULL) + if (solidGeometry != nullptr) { const bool isOpaque = prefs->fillpattern() == simData::GatePrefs_FillPattern_WIRE || prefs->fillpattern() == simData::GatePrefs_FillPattern_SOLID || @@ -74,7 +74,7 @@ GateVolume::GateVolume(simVis::Locator* locator, const simData::GatePrefs* prefs } osg::Geode* outlineGeode = simVis::SVFactory::opaqueGeode(gateSV_.get()); - if (outlineGeode != NULL) + if (outlineGeode != nullptr) { // SphericalVolume code only adds the opaque geode when it is adding a geometry or lineGroup assert(outlineGeode->getNumDrawables() > 0); @@ -89,7 +89,7 @@ GateVolume::~GateVolume() /// prefs that can be applied without rebuilding the whole gate void GateVolume::performInPlacePrefChanges(const simData::GatePrefs* a, const simData::GatePrefs* b) { - if (a == NULL || b == NULL) + if (a == nullptr || b == nullptr) return; if (b->commonprefs().useoverridecolor()) @@ -118,7 +118,7 @@ void GateVolume::performInPlacePrefChanges(const simData::GatePrefs* a, const si /// updates that can be updated without rebuilding the whole gate void GateVolume::performInPlaceUpdates(const simData::GateUpdate* a, const simData::GateUpdate* b) { - if (a == NULL || b == NULL) + if (a == nullptr || b == nullptr) return; #ifdef GATE_IN_PLACE_UPDATES @@ -227,7 +227,6 @@ GateCentroid::GateCentroid(simVis::Locator* locator) : LocatorNode(locator) { setName("Centroid Locator"); - setActive(false); geom_ = new osgEarth::LineDrawable(GL_LINES); geom_->setName("simVis::GateCentroid Geometry"); geom_->setColor(simVis::Color::White); @@ -247,12 +246,6 @@ GateCentroid::~GateCentroid() { } -void GateCentroid::setActive(bool active) -{ - // the centroid's nodemask controls locatorNode activation/deactivation - setNodeMask(active ? DISPLAY_MASK_GATE : DISPLAY_MASK_NONE); -} - void GateCentroid::setVisible(bool visible) { // setting the geometry node mask can turn the draw off without turning off the centroid/locator node @@ -313,7 +306,7 @@ GateNode::GateNode(const simData::GateProperties& props, Locator* hostLocator, c // gates can be hosted by platforms or beams const BeamNode* beam = dynamic_cast(host_.get()); - if (beam != NULL && hostLocator) + if (beam != nullptr && hostLocator) { // body and range gates are positioned relative to beam origin, but never relative to beam orientation. // in some cases, the locator that beam provides via getLocator() (beamOrientationLocator_) strips out platform orientation; @@ -364,6 +357,7 @@ GateNode::GateNode(const simData::GateProperties& props, Locator* hostLocator, c // Create the centroid - gate tethering depends on the centroid, so it must always exist (when gate exists) even if centroid is not drawn centroid_ = new GateCentroid(centroidLocator_.get()); + centroid_->setEntityToMonitor(this); addChild(centroid_); // centroid provides a persistent locatornode to parent our label node @@ -383,6 +377,8 @@ GateNode::GateNode(const simData::GateProperties& props, Locator* hostLocator, c // flatten in overhead mode. simVis::OverheadMode::enableGeometryFlattening(true, this); + // SIM-10724: Labels need to not be flattened to be displayed in overhead mode + simVis::OverheadMode::enableGeometryFlattening(false, label_.get()); } GateNode::~GateNode() @@ -461,7 +457,7 @@ void GateNode::applyPrefs_(const simData::GatePrefs& prefs, bool force) { if (prefsOverrides_.size() == 0) { - apply_(NULL, &prefs, force); + apply_(nullptr, &prefs, force); lastPrefsApplied_ = prefs; hasLastPrefs_ = true; } @@ -473,7 +469,7 @@ void GateNode::applyPrefs_(const simData::GatePrefs& prefs, bool force) { accumulated.MergeFrom(i->second); } - apply_(NULL, &accumulated, force); + apply_(nullptr, &accumulated, force); lastPrefsApplied_ = accumulated; hasLastPrefs_ = true; } @@ -523,7 +519,7 @@ bool GateNode::updateFromDataStore(const simData::DataSliceBase* updateSliceBase if (updateSlice->hasChanged() || force || hostChangedToActive || hostChangedToInactive) { const simData::GateUpdate* current = updateSlice->current(); - const bool gateChangedToInactive = (current == NULL && hasLastUpdate_); + const bool gateChangedToInactive = (current == nullptr && hasLastUpdate_); // do not apply update if host is not active if (current && (force || host_->isActive())) @@ -551,9 +547,8 @@ void GateNode::flush() { hasLastUpdate_ = false; setNodeMask(DISPLAY_MASK_NONE); - centroid_->setActive(false); removeChild(gateVolume_); - gateVolume_ = NULL; + gateVolume_ = nullptr; } double GateNode::range() const @@ -577,7 +572,7 @@ int GateNode::getPositionOrientation(simCore::Vec3* out_position, simCore::Vec3* const simData::GateUpdate* GateNode::getLastUpdateFromDS() const { - return hasLastUpdate_ ? &lastUpdateFromDS_ : NULL; + return hasLastUpdate_ ? &lastUpdateFromDS_ : nullptr; } // This method applies the datastore update to the gate, and @@ -602,7 +597,7 @@ void GateNode::applyDataStoreUpdate_(const simData::GateUpdate& update, bool for if (lastUpdateFromDS_.height() <= 0.0 || lastUpdateFromDS_.width() <= 0.0) { const BeamNode* beam = dynamic_cast(host_.get()); - if (beam != NULL) + if (beam != nullptr) { if (lastUpdateFromDS_.height() <= 0.0) lastUpdateFromDS_.set_height(beam->getPrefs().verticalwidth()); @@ -621,7 +616,7 @@ void GateNode::applyUpdateOverrides_(bool force) if (updateOverrides_.size() == 0) { // apply the new update with no overrides. - apply_(&lastUpdateFromDS_, NULL, force); + apply_(&lastUpdateFromDS_, nullptr, force); lastUpdateApplied_ = lastUpdateFromDS_; } else @@ -632,11 +627,13 @@ void GateNode::applyUpdateOverrides_(bool force) { accumulated.MergeFrom(i->second); } - apply_(&accumulated, NULL, force); + apply_(&accumulated, nullptr, force); lastUpdateApplied_ = accumulated; } // we have applied a valid update, and both lastUpdateApplied_ and lastUpdateFromDS_ are valid hasLastUpdate_ = true; + // ensure that the centroid is in sync with its locator; this will be a no-op if they are already in sync. + centroid_->syncWithLocator(); } int GateNode::calculateTargetGate_(const simData::GateUpdate& update, simData::GateUpdate& targetGateUpdate) @@ -651,16 +648,16 @@ int GateNode::calculateTargetGate_(const simData::GateUpdate& update, simData::G return 1; } const BeamNode* beam = dynamic_cast(host_.get()); - if (beam == NULL) + if (beam == nullptr) { // target gate require a host beam; host is not a beam, so exit. return 1; } assert(beam->getProperties().type() == simData::BeamProperties_BeamType_TARGET); - // the target beam should have the correct RAE; will be NULL if target beam could not calculate + // the target beam should have the correct RAE; will be nullptr if target beam could not calculate const simData::BeamUpdate* beamUpdate = beam->getLastUpdateFromDS(); - if (beamUpdate == NULL) + if (beamUpdate == nullptr) return 1; targetGateUpdate.set_time(update.time()); @@ -691,8 +688,8 @@ void GateNode::apply_(const simData::GateUpdate* newUpdate, const simData::GateP const simData::GateUpdate* activeUpdate = newUpdate ? newUpdate : &lastUpdateApplied_; // if assert fails, check that if ((!newUpdate && !hasLastUpdate_) || (!newPrefs && !hasLastPrefs_)) test at top of this routine has not been changed - assert(activePrefs != NULL); - assert(activeUpdate != NULL); + assert(activePrefs != nullptr); + assert(activeUpdate != nullptr); // if datadraw is off, we do not need to do any processing if (activePrefs->commonprefs().datadraw() == false) @@ -712,7 +709,7 @@ void GateNode::apply_(const simData::GateUpdate* newUpdate, const simData::GateP if (gateVolume_) { removeChild(gateVolume_); - gateVolume_ = NULL; + gateVolume_ = nullptr; } if (activePrefs->fillpattern() != simData::GatePrefs_FillPattern_CENTROID) @@ -748,8 +745,6 @@ void GateNode::apply_(const simData::GateUpdate* newUpdate, const simData::GateP PB_FIELD_CHANGED(&lastUpdateApplied_, newUpdate, width) || PB_FIELD_CHANGED(&lastUpdateApplied_, newUpdate, height)))) { - // make sure to activate the centroid locatorNode in case datadraw just turned on; updateLocator_ below will guarantee that locator node is sync'd to its locator - centroid_->setActive(true); // activeUpdate is always valid, and points to the new update if there is a new update, or the previous update otherwise centroid_->update(*activeUpdate); } @@ -767,7 +762,7 @@ void GateNode::apply_(const simData::GateUpdate* newUpdate, const simData::GateP if (visible && (force || newPrefs)) { // localgrid created in constructor. if assert fails, check for changes. - assert(localGrid_ != NULL); + assert(localGrid_ != nullptr); localGrid_->setPrefs(activePrefs->commonprefs().localgrid(), force); } } @@ -851,7 +846,7 @@ bool GateNode::changeRequiresRebuild_(const simData::GateUpdate* newUpdate, cons // this can only be called when prefs and updates are already set; if assert fails, check callers assert(hasLastUpdate_ && hasLastPrefs_); - if (newPrefs != NULL && + if (newPrefs != nullptr && (PB_FIELD_CHANGED(&lastPrefsApplied_, newPrefs, fillpattern) || PB_FIELD_CHANGED(&lastPrefsApplied_, newPrefs, gatedrawmode) || PB_FIELD_CHANGED(&lastPrefsApplied_, newPrefs, drawoutline))) @@ -859,7 +854,7 @@ bool GateNode::changeRequiresRebuild_(const simData::GateUpdate* newUpdate, cons return true; } - if (newUpdate != NULL) + if (newUpdate != nullptr) { #ifdef GATE_IN_PLACE_UPDATES // changing a gate minrange to/from 0.0 requires a rebuild due to simplified shape diff --git a/SDK/simVis/Gate.h b/SDK/simVis/Gate.h index f27ac2c74..8b019c1ac 100644 --- a/SDK/simVis/Gate.h +++ b/SDK/simVis/Gate.h @@ -80,8 +80,6 @@ namespace simVis void update(const simData::GateUpdate& update); /** Clears the geometry from the centroid; use this instead of setting node mask, to avoid center-on-entity issues. */ void setVisible(bool visible); - /** Deactivate the centroid when the gate is not active, activate whenever the gate is active */ - void setActive(bool active); /** Return the proper library name */ virtual const char* libraryName() const { return "simVis"; } @@ -116,8 +114,8 @@ namespace simVis */ explicit GateNode( const simData::GateProperties& props, - Locator* locator = NULL, - const simVis::EntityNode* host = NULL, + Locator* locator = nullptr, + const simVis::EntityNode* host = nullptr, int referenceYear = 1970); /** @@ -213,7 +211,7 @@ namespace simVis /** * Updates the entity based on the bound data store. - * @param updateSlice Data store update slice (could be NULL) + * @param updateSlice Data store update slice (could be nullptr) * @param force true to force the update to be applied; false allows entity to use its own internal logic to decide whether the update should be applied * @return true if update applied, false if not */ @@ -235,7 +233,7 @@ namespace simVis /** * Gets the world position for this gate's centroid. This is a convenience * function that extracts the Position information (not rotation) from the underlying locatorNode matrix. - * @param[out] out_position If not NULL, resulting position stored here, in coordinate system as specified by coordsys + * @param[out] out_position If not nullptr, resulting position stored here, in coordinate system as specified by coordsys * @param[in ] coordsys Requested coord sys of the output position (only LLA, ECEF, or ECI supported) * @return 0 if the output parameter is populated successfully, nonzero on failure */ @@ -244,8 +242,8 @@ namespace simVis /** * Gets the world position & orientation for this gate's centroid. This is a convenience * function that extracts the Position information and rotation from the underlying locatorNode matrix. - * @param[out] out_position If not NULL, resulting position stored here, in coordinate system as specified by coordsys - * @param[out] out_orientation If not NULL, resulting orientation stored here, in coordinate system as specified by coordsys + * @param[out] out_position If not nullptr, resulting position stored here, in coordinate system as specified by coordsys + * @param[out] out_orientation If not nullptr, resulting orientation stored here, in coordinate system as specified by coordsys * @param[in ] coordsys Requested coord sys of the output position (only LLA, ECEF, or ECI supported) * @return 0 if the output parameter is populated successfully, nonzero on failure */ @@ -259,7 +257,7 @@ namespace simVis static unsigned int getMask() { return simVis::DISPLAY_MASK_GATE; } /** - * Gets a pointer to the last data store update, or NULL if + * Gets a pointer to the last data store update, or nullptr if * none have been applied. */ const simData::GateUpdate* getLastUpdateFromDS() const; diff --git a/SDK/simVis/Gl3Utils.h b/SDK/simVis/Gl3Utils.h index 721f73f05..2b72c4595 100644 --- a/SDK/simVis/Gl3Utils.h +++ b/SDK/simVis/Gl3Utils.h @@ -107,7 +107,7 @@ inline void applyMesaGeometryShaderFix(osg::GraphicsContext* graphicsContext) return; graphicsContext->makeCurrent(); const char* glVersionString = reinterpret_cast(glGetString(GL_VERSION)); - if (glVersionString == NULL) + if (glVersionString == nullptr) return; // Only apply the fix to Mesa. It might apply to non-Mesa drivers too, but we'll just fix Mesa for @@ -146,7 +146,7 @@ inline void applyMesaGlVersionOverride() #ifdef __linux__ // To compound the problem, certain MESA drivers on Linux have an additional requirement of setting // the MESA_GL_VERSION_OVERRIDE environment variable, else we get a bad version. - if (getenv("MESA_GL_VERSION_OVERRIDE") == NULL) + if (getenv("MESA_GL_VERSION_OVERRIDE") == nullptr) setenv("MESA_GL_VERSION_OVERRIDE", instance->getGLContextVersion().c_str(), 1); #endif #endif @@ -163,7 +163,7 @@ inline void applyMesaGlVersionOverride() class Gl3RealizeOperation : public osg::Operation { public: - explicit Gl3RealizeOperation(osg::Operation* nested = NULL) + explicit Gl3RealizeOperation(osg::Operation* nested = nullptr) : nested_(nested) { } diff --git a/SDK/simVis/GlDebugMessage.cpp b/SDK/simVis/GlDebugMessage.cpp index 08ce4a206..7513c1f62 100644 --- a/SDK/simVis/GlDebugMessage.cpp +++ b/SDK/simVis/GlDebugMessage.cpp @@ -31,9 +31,9 @@ namespace simVis { GlDebugMessage::GlDebugMessage(osg::GraphicsContext* gc) : register_(false), - glDebugMessageControl_(NULL), - glDebugMessageInsert_(NULL), - glDebugMessageCallback_(NULL) + glDebugMessageControl_(nullptr), + glDebugMessageInsert_(nullptr), + glDebugMessageCallback_(nullptr) { setGraphicsContext(gc); } @@ -41,7 +41,7 @@ GlDebugMessage::GlDebugMessage(osg::GraphicsContext* gc) GlDebugMessage::~GlDebugMessage() { // Disable callbacks - setGraphicsContext(NULL); + setGraphicsContext(nullptr); } void GlDebugMessage::setGraphicsContext(osg::GraphicsContext* gc) @@ -54,11 +54,11 @@ void GlDebugMessage::setGraphicsContext(osg::GraphicsContext* gc) if (gc_.lock(oldGc) && oldGc->makeCurrent()) { if (glDebugMessageCallback_) - glDebugMessageCallback_(NULL, NULL); + glDebugMessageCallback_(nullptr, nullptr); } - glDebugMessageControl_ = NULL; - glDebugMessageInsert_ = NULL; - glDebugMessageCallback_ = NULL; + glDebugMessageControl_ = nullptr; + glDebugMessageInsert_ = nullptr; + glDebugMessageCallback_ = nullptr; // Pull out the new function pointers gc_ = gc; @@ -88,7 +88,7 @@ void GlDebugMessage::registerCallbacks(bool registerWithGl) if (registerWithGl) glDebugMessageCallback_(&GlDebugMessage::processMessage_, this); else - glDebugMessageCallback_(NULL, NULL); + glDebugMessageCallback_(nullptr, nullptr); } void GlDebugMessage::setDebugOutputMode(osg::StateSet& stateSet, osg::StateAttribute::GLMode mode) const diff --git a/SDK/simVis/GlDebugMessage.h b/SDK/simVis/GlDebugMessage.h index 00fa12d0c..4ad97fb33 100644 --- a/SDK/simVis/GlDebugMessage.h +++ b/SDK/simVis/GlDebugMessage.h @@ -120,11 +120,10 @@ class SDKVIS_EXPORT GlDebugMessage osg::observer_ptr gc_; bool register_; -#ifndef GL_VERSION_4_3 - typedef void (APIENTRYP PFNGLDEBUGMESSAGECONTROLPROC) (GLenum source, GLenum type, GLenum severity, GLsizei count, const GLuint* ids, GLboolean enabled); - typedef void (APIENTRYP PFNGLDEBUGMESSAGEINSERTPROC) (GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar* buf); - typedef void (APIENTRYP PFNGLDEBUGMESSAGECALLBACKPROC) (GLDEBUGPROC callback, const void* userParam); -#endif + typedef void (GL_APIENTRY* GLDEBUGPROC)(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar* message, const void* userParam); + typedef void (GL_APIENTRY* PFNGLDEBUGMESSAGECONTROLPROC) (GLenum source, GLenum type, GLenum severity, GLsizei count, const GLuint* ids, GLboolean enabled); + typedef void (GL_APIENTRY* PFNGLDEBUGMESSAGEINSERTPROC) (GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar* buf); + typedef void (GL_APIENTRY* PFNGLDEBUGMESSAGECALLBACKPROC) (GLDEBUGPROC callback, const void* userParam); PFNGLDEBUGMESSAGECONTROLPROC glDebugMessageControl_; PFNGLDEBUGMESSAGEINSERTPROC glDebugMessageInsert_; diff --git a/SDK/simVis/Headless.cpp b/SDK/simVis/Headless.cpp index 1288daef9..72d15b40a 100644 --- a/SDK/simVis/Headless.cpp +++ b/SDK/simVis/Headless.cpp @@ -37,8 +37,8 @@ bool simVis::isHeadless() bool simVis::isHeadless() { // UNIX systems that cannot XOpenDisplay() are considered headless - Display* d = XOpenDisplay(NULL); - if (d != NULL) + Display* d = XOpenDisplay(nullptr); + if (d != nullptr) { XCloseDisplay(d); return false; diff --git a/SDK/simVis/InsetViewEventHandler.cpp b/SDK/simVis/InsetViewEventHandler.cpp index ee231a92f..25eb11de1 100644 --- a/SDK/simVis/InsetViewEventHandler.cpp +++ b/SDK/simVis/InsetViewEventHandler.cpp @@ -274,7 +274,7 @@ void CreateInsetEventHandler::completeNewInsetAction_(int mx, int my) inset->setViewpoint(host_->getViewpoint(), 0.0); if (host_->isOverheadEnabled()) inset->enableOverheadMode(true); - if (host_->getCameraTether() != NULL) + if (host_->getCameraTether() != nullptr) inset->tetherCamera(host_->getCameraTether()); // Do add after a complete build @@ -297,9 +297,6 @@ void CreateInsetEventHandler::cancelNewInsetAction_() InsetViewEventHandler::InsetViewEventHandler(simVis::View* host) : focusActionsMask_(ACTION_HOVER), host_(host) -#ifdef USE_DEPRECATED_SIMDISSDK_API - , createInset_(new CreateInsetEventHandler(host)) -#endif { // this callback will allow this object to listen to view events. focusDetector_ = new FocusDetector(host_->getFocusManager(), this); @@ -361,15 +358,9 @@ int InsetViewEventHandler::getFocusActions() const bool InsetViewEventHandler::handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa) { -#ifdef USE_DEPRECATED_SIMDISSDK_API - const bool handled = createInset_->handle(ea, aa); -#else - const bool handled = false; -#endif - if (!handled && ea.getEventType() == ea.FRAME) + if (ea.getEventType() == ea.FRAME) ensureViewListenerInstalled_(); - - return handled; + return false; } } diff --git a/SDK/simVis/InsetViewEventHandler.h b/SDK/simVis/InsetViewEventHandler.h index 6e175dfc3..35b3bc734 100644 --- a/SDK/simVis/InsetViewEventHandler.h +++ b/SDK/simVis/InsetViewEventHandler.h @@ -142,10 +142,6 @@ class SDKVIS_EXPORT InsetViewEventHandler : public osgGA::GUIEventHandler osg::ref_ptr focusDetector_; osg::ref_ptr viewListener_; -#ifdef USE_DEPRECATED_SIMDISSDK_API - osg::ref_ptr createInset_; -#endif - /** Adds the listener to any views as required */ void ensureViewListenerInstalled_(); }; diff --git a/SDK/simVis/Laser.cpp b/SDK/simVis/Laser.cpp index a67c9795d..761ce458e 100644 --- a/SDK/simVis/Laser.cpp +++ b/SDK/simVis/Laser.cpp @@ -39,14 +39,14 @@ namespace simVis LaserNode::LaserNode(const simData::LaserProperties& props, Locator* hostLocator, const EntityNode* host, int referenceYear) : EntityNode(simData::LASER), hasLastUpdate_(false), - node_(NULL), + node_(nullptr), host_(host), - localGrid_(NULL), + localGrid_(nullptr), hasLastPrefs_(false), - label_(NULL) + label_(nullptr) { lastProps_ = props; - Locator* locator = NULL; + Locator* locator = nullptr; if (!props.has_azelrelativetohostori() || !props.azelrelativetohostori()) { @@ -62,7 +62,7 @@ LaserNode::LaserNode(const simData::LaserProperties& props, Locator* hostLocator { // in the azelrelativetohostori case, only a single locator is needed, // b/c position and orientation offsets are both relative to platform orientation. - laserXYZOffsetLocator_ = NULL; + laserXYZOffsetLocator_ = nullptr; locator = new ResolvedPositionOrientationLocator(hostLocator, Locator::COMP_ALL); } @@ -70,7 +70,7 @@ LaserNode::LaserNode(const simData::LaserProperties& props, Locator* hostLocator setNodeMask(DISPLAY_MASK_NONE); locatorNode_ = new LocatorNode(locator); locatorNode_->setName("Laser"); - locatorNode_->setNodeMask(DISPLAY_MASK_NONE); + locatorNode_->setEntityToMonitor(this); addChild(locatorNode_); setName("LaserNode"); @@ -92,6 +92,8 @@ LaserNode::LaserNode(const simData::LaserProperties& props, Locator* hostLocator // flatten in overhead mode. simVis::OverheadMode::enableGeometryFlattening(true, this); + // SIM-10724: Labels need to not be flattened to be displayed in overhead mode + simVis::OverheadMode::enableGeometryFlattening(false, label_.get()); } LaserNode::~LaserNode() {} @@ -158,7 +160,7 @@ void LaserNode::setPrefs(const simData::LaserPrefs& prefs) // validate localgrid prefs changes that might provide user notifications localGrid_->validatePrefs(prefs.commonprefs().localgrid()); - refresh_(NULL, &prefs); + refresh_(nullptr, &prefs); updateLabel_(prefs); lastPrefs_ = prefs; hasLastPrefs_ = true; @@ -171,7 +173,7 @@ bool LaserNode::isActive() const bool LaserNode::isVisible() const { - return getNodeMask() != DISPLAY_MASK_NONE && (node_ != NULL) && node_->getNodeMask() != DISPLAY_MASK_NONE; + return getNodeMask() != DISPLAY_MASK_NONE && (node_ != nullptr) && node_->getNodeMask() != DISPLAY_MASK_NONE; } simData::ObjectId LaserNode::getId() const @@ -209,15 +211,17 @@ bool LaserNode::updateFromDataStore(const simData::DataSliceBase* updateSliceBas if (updateSlice->hasChanged() || force || hostChangedToActive || hostChangedToInactive) { const simData::LaserUpdate* current = updateSlice->current(); - const bool laserChangedToInactive = (current == NULL && hasLastUpdate_); + const bool laserChangedToInactive = (current == nullptr && hasLastUpdate_); // do not apply update if host platform is not active if (current && (force || host_->isActive())) { - refresh_(current, NULL); + refresh_(current, nullptr); lastUpdate_ = *current; hasLastUpdate_ = true; updateApplied = true; + // ensure that the locator node is in sync with its locator; this will be a no-op if they are already in sync. + locatorNode_->syncWithLocator(); } else if (laserChangedToInactive || hostChangedToInactive) { @@ -238,7 +242,6 @@ void LaserNode::flush() { hasLastUpdate_ = false; setNodeMask(DISPLAY_MASK_NONE); - locatorNode_->setNodeMask(DISPLAY_MASK_NONE); } double LaserNode::range() const @@ -251,7 +254,7 @@ double LaserNode::range() const const simData::LaserUpdate* LaserNode::getLastUpdateFromDS() const { - return hasLastUpdate_ ? &lastUpdate_ : NULL; + return hasLastUpdate_ ? &lastUpdate_ : nullptr; } int LaserNode::getPosition(simCore::Vec3* out_position, simCore::CoordinateSystem coordsys) const @@ -287,13 +290,11 @@ void LaserNode::refresh_(const simData::LaserUpdate* newUpdate, const simData::L if (activePrefs->commonprefs().datadraw() == false) { setNodeMask(DISPLAY_MASK_NONE); - // deactivate the locatorNode - locatorNode_->setNodeMask(DISPLAY_MASK_NONE); return; } // force indicates that activePrefs and activeUpdate must be applied, the visual must be redrawn, and the locator updated - const bool force = !hasLastUpdate_ || !hasLastPrefs_ || node_ == NULL || + const bool force = !hasLastUpdate_ || !hasLastPrefs_ || node_ == nullptr || (newPrefs && PB_SUBFIELD_CHANGED(&lastPrefs_, newPrefs, commonprefs, datadraw)); // if new geometry is required, build it @@ -311,8 +312,6 @@ void LaserNode::refresh_(const simData::LaserUpdate* newUpdate, const simData::L locatorNode_->replaceChild(oldNode, node_); else locatorNode_->addChild(node_); - // activate the locatorNode - locatorNode_->setNodeMask(DISPLAY_MASK_LASER); dirtyBound(); } else @@ -341,7 +340,7 @@ void LaserNode::refresh_(const simData::LaserUpdate* newUpdate, const simData::L // update the local grid prefs, if laser is being drawn if (visible && (force || newPrefs)) { - assert(localGrid_ != NULL); + assert(localGrid_ != nullptr); localGrid_->setPrefs(activePrefs->commonprefs().localgrid(), force); } } @@ -376,7 +375,7 @@ void LaserNode::updateLocator_(const simData::LaserUpdate* newUpdate, const simD if (!lastProps_.has_azelrelativetohostori() || !lastProps_.azelrelativetohostori()) { // if assert fails, check that constructor creates this locator for non-relative lasers - assert(laserXYZOffsetLocator_ != NULL); + assert(laserXYZOffsetLocator_ != nullptr); // laser xyz offsets are relative to host platform orientation; laserXYZOffsetLocator_->setLocalOffsets(posOffset, simCore::Vec3(), activeUpdate->time(), false); @@ -419,7 +418,7 @@ osg::Geode* LaserNode::createGeometry_(const simData::LaserPrefs &prefs) void LaserNode::updateLaser_(const simData::LaserPrefs &prefs) { - if (node_ == NULL || node_->getNumChildren() == 0) + if (node_ == nullptr || node_->getNumChildren() == 0) return; osgEarth::LineDrawable* geom = dynamic_cast(node_->getChild(0)); if (!geom) diff --git a/SDK/simVis/Laser.h b/SDK/simVis/Laser.h index cc4476a7b..9c4292260 100644 --- a/SDK/simVis/Laser.h +++ b/SDK/simVis/Laser.h @@ -51,8 +51,8 @@ namespace simVis */ LaserNode( const simData::LaserProperties& props, - Locator* locator = NULL, - const simVis::EntityNode* host = NULL, + Locator* locator = nullptr, + const simVis::EntityNode* host = nullptr, int referenceYear = 1970); /** @@ -118,7 +118,7 @@ namespace simVis /** * Updates the entity based on the bound data store. - * @param updateSlice Data store update slice (could be NULL) + * @param updateSlice Data store update slice (could be nullptr) * @param force true to force the update to be applied; false allows entity to use its own internal logic to decide whether the update should be applied * @return true if update applied, false if not */ @@ -138,7 +138,7 @@ namespace simVis virtual unsigned int objectIndexTag() const; /** - * Gets a pointer to the last data store update, or NULL if + * Gets a pointer to the last data store update, or nullptr if * none have been applied. */ const simData::LaserUpdate* getLastUpdateFromDS() const; @@ -146,7 +146,7 @@ namespace simVis /** * Gets the world position for this laser's origin. This is a convenience * function that extracts the Position information (not rotation) from the underlying locatorNode matrix. - * @param[out] out_position If not NULL, resulting position stored here, in coordinate system as specified by coordsys + * @param[out] out_position If not nullptr, resulting position stored here, in coordinate system as specified by coordsys * @param[in ] coordsys Requested coord sys of the output position (only LLA, ECEF, or ECI supported) * @return 0 if the output parameter is populated successfully, nonzero on failure */ @@ -155,8 +155,8 @@ namespace simVis /** * Gets the world position & orientation for this laser. This is a convenience * function that extracts the Position information and rotation from the underlying locatorNode matrix. - * @param[out] out_position If not NULL, resulting position stored here, in coordinate system as specified by coordsys - * @param[out] out_orientation If not NULL, resulting orientation stored here, in coordinate system as specified by coordsys + * @param[out] out_position If not nullptr, resulting position stored here, in coordinate system as specified by coordsys + * @param[out] out_orientation If not nullptr, resulting orientation stored here, in coordinate system as specified by coordsys * @param[in ] coordsys Requested coord sys of the output position (only LLA, ECEF, or ECI supported) * @return 0 if the output parameter is populated successfully, nonzero on failure */ @@ -187,8 +187,8 @@ namespace simVis /** * Updates the locator if required, based on specified arguments - * @param newUpdate new update data (could be NULL) - * @param newPrefs new prefs settings (could be NULL) + * @param newUpdate new update data (could be nullptr) + * @param newPrefs new prefs settings (could be nullptr) * @param force true to force locator update regardless of other params */ void updateLocator_(const simData::LaserUpdate* newUpdate, const simData::LaserPrefs* newPrefs, bool force); diff --git a/SDK/simVis/LayerRefreshCallback.cpp b/SDK/simVis/LayerRefreshCallback.cpp index 32b56d2ab..046be5c44 100644 --- a/SDK/simVis/LayerRefreshCallback.cpp +++ b/SDK/simVis/LayerRefreshCallback.cpp @@ -44,7 +44,7 @@ class LayerRefreshCallback::MapUpdatedCallback : public osgEarth::MapCallback virtual void onLayerAdded(osgEarth::Layer* layer, unsigned index) { const osgEarth::TileLayer* terrainLayer = dynamic_cast(layer); - if (terrainLayer != NULL) + if (terrainLayer != nullptr) parent_.watchLayer_(terrainLayer); } @@ -52,7 +52,7 @@ class LayerRefreshCallback::MapUpdatedCallback : public osgEarth::MapCallback virtual void onLayerRemoved(osgEarth::Layer* layer, unsigned index) { const osgEarth::TileLayer* terrainLayer = dynamic_cast(layer); - if (terrainLayer != NULL) + if (terrainLayer != nullptr) parent_.forgetLayer_(terrainLayer); } @@ -60,7 +60,7 @@ class LayerRefreshCallback::MapUpdatedCallback : public osgEarth::MapCallback virtual void onLayerEnabled(osgEarth::Layer* layer) { const osgEarth::TileLayer* terrainLayer = dynamic_cast(layer); - if (terrainLayer != NULL) + if (terrainLayer != nullptr) parent_.watchLayer_(terrainLayer); } @@ -68,7 +68,7 @@ class LayerRefreshCallback::MapUpdatedCallback : public osgEarth::MapCallback virtual void onLayerDisabled(osgEarth::Layer* layer) { const osgEarth::TileLayer* terrainLayer = dynamic_cast(layer); - if (terrainLayer != NULL) + if (terrainLayer != nullptr) parent_.forgetLayer_(terrainLayer); } @@ -93,7 +93,7 @@ LayerRefreshCallback::LayerRefreshCallback(const LayerRefreshCallback& rhs, cons LayerRefreshCallback::~LayerRefreshCallback() { - setMapNode(NULL); + setMapNode(nullptr); } void LayerRefreshCallback::setMapNode(osgEarth::MapNode* mapNode) @@ -114,7 +114,7 @@ void LayerRefreshCallback::setMapNode(osgEarth::MapNode* mapNode) if (mapNode_.valid() && mapNode_->getMap()) mapNode_->getMap()->addMapCallback(mapUpdatedCallback_.get()); - enabled_ = (mapNode_ != NULL); + enabled_ = (mapNode_ != nullptr); } bool LayerRefreshCallback::run(osg::Object* object, osg::Object* data) @@ -140,7 +140,7 @@ void LayerRefreshCallback::runImpl_() osg::observer_ptr layer = (*it).layer; if (!layer.valid() || !layer->getEnabled()) { - assert(0); // Should not be watching a NULL or disabled layer + assert(0); // Should not be watching a nullptr or disabled layer continue; } @@ -172,7 +172,7 @@ void LayerRefreshCallback::runImpl_() void LayerRefreshCallback::watchLayer_(const osgEarth::TileLayer* layer) { - if (layer == NULL) + if (layer == nullptr) return; LayerInfo info; @@ -183,7 +183,7 @@ void LayerRefreshCallback::watchLayer_(const osgEarth::TileLayer* layer) void LayerRefreshCallback::forgetLayer_(const osgEarth::TileLayer* layer) { - if (layer == NULL) + if (layer == nullptr) return; for (auto it = watchedLayers_.begin(); it != watchedLayers_.end(); ++it) diff --git a/SDK/simVis/LobGroup.cpp b/SDK/simVis/LobGroup.cpp index bd7e3121b..55d3a283e 100644 --- a/SDK/simVis/LobGroup.cpp +++ b/SDK/simVis/LobGroup.cpp @@ -20,6 +20,7 @@ * disclose, or release this software. * */ +#include "osg/MatrixTransform" #include "osgEarth/GeoData" #include "osgEarth/Horizon" #include "osgEarth/ObjectIndex" @@ -52,7 +53,7 @@ static const std::string SIMVIS_FLASHING_ENABLE = "simvis_flashing_enable"; /** Determines whether the new prefs will require new geometry */ bool prefsRequiresRebuild(const simData::LobGroupPrefs* a, const simData::LobGroupPrefs* b) { - if (a == NULL || b == NULL) + if (!a || !b) return false; // simple case if (PB_SUBFIELD_CHANGED(a, b, commonprefs, useoverridecolor)) @@ -185,17 +186,27 @@ LobGroupNode::LobGroupNode(const simData::LobGroupProperties &props, EntityNode* coordConverter_(new simCore::CoordinateConverter()), ds_(ds), hostId_(host->getId()), - lineCache_(new Cache), - label_(NULL), + lineCache_(new Cache()), + label_(nullptr), lastFlashingState_(false), objectIndexTag_(0) { setName("LobGroup"); - localGrid_ = new LocalGridNode(getLocator(), host, ds.referenceYear()); - addChild(localGrid_); - label_ = new EntityLabelNode(getLocator()); - this->addChild(label_); + // locator node supports entity label and tether + xform_ = new osg::MatrixTransform(); + addChild(xform_.get()); + + // lob group is off until prefs and update turn it on + setNodeMask(DISPLAY_MASK_NONE); + + label_ = new EntityLabelNode(); + // xform_ parents and positions the label + xform_->addChild(label_.get()); + + // create localGrid_ after xform_ so xform_ is found first in findAttachment() for tethering + localGrid_ = new LocalGridNode(getLocator(), host, ds.referenceYear()); + addChild(localGrid_.get()); // horizon culling: entity culling based on bounding sphere addCullCallback( new osgEarth::HorizonCullCallback() ); @@ -209,6 +220,8 @@ LobGroupNode::LobGroupNode(const simData::LobGroupProperties &props, EntityNode* // flatten in overhead mode. simVis::OverheadMode::enableGeometryFlattening(true, this); + // SIM-10724: Labels need to not be flattened to be displayed in overhead mode + simVis::OverheadMode::enableGeometryFlattening(false, label_.get()); // Add a tag for picking objectIndexTag_ = osgEarth::Registry::objectIndex()->tagNode(this, this); @@ -219,10 +232,10 @@ LobGroupNode::~LobGroupNode() osgEarth::Registry::objectIndex()->remove(objectIndexTag_); delete coordConverter_; - coordConverter_ = NULL; + coordConverter_ = nullptr; lineCache_->clearCache(this); delete lineCache_; - lineCache_ = NULL; + lineCache_ = nullptr; } void LobGroupNode::installShaderProgram(osg::StateSet* intoStateSet) @@ -333,8 +346,8 @@ void LobGroupNode::setPrefs(const simData::LobGroupPrefs &prefs) void LobGroupNode::setLineDrawStyle_(double time, simVis::AnimatedLineNode& line, const simData::LobGroupPrefs& defaultValues) { - simData::DataTable* table = ds_.dataTableManager().findTable(getId(), simData::INTERNAL_LOB_DRAWSTYLE_TABLE); - if (table == NULL) + const simData::DataTable* table = ds_.dataTableManager().findTable(getId(), simData::INTERNAL_LOB_DRAWSTYLE_TABLE); + if (!table) { setLineValueFromPrefs_(line, defaultValues); return; @@ -378,8 +391,8 @@ void LobGroupNode::setLineValueFromPrefs_(AnimatedLineNode& line, const simData: template int LobGroupNode::getColumnValue_(const std::string& columnName, const simData::DataTable& table, double time, T& value) const { - simData::TableColumn* column = table.column(columnName); - if (column == NULL) + const simData::TableColumn* column = table.column(columnName); + if (!column) return 1; simData::TableColumn::Iterator iter = column->findAtOrBeforeTime(time); @@ -399,7 +412,7 @@ void LobGroupNode::updateCache_(const simData::LobGroupUpdate &update, const sim { const int numLines = update.datapoints_size(); const simData::PlatformUpdateSlice *platformData = ds_.platformUpdateSlice(hostId_); - if ((numLines <= 0) || (platformData == NULL)) + if ((numLines <= 0) || !platformData) { // no lines, clear out cache and remove all draw nodes lineCache_->clearCache(this); @@ -436,7 +449,7 @@ void LobGroupNode::updateCache_(const simData::LobGroupUpdate &update, const sim // interpolation may be required for LOBs on a moving platform simData::PlatformUpdate interpolatedPlatformUpdate; - if (platformUpdate->time() != time && li != NULL && platformIter.hasNext()) + if (platformUpdate->time() != time && li && platformIter.hasNext()) { // defn of upper_bound previous() assert(platformUpdate->time() < time); @@ -522,6 +535,9 @@ void LobGroupNode::updateCache_(const simData::LobGroupUpdate &update, const sim // Use position only, otherwise rendering will be adversely affected; locator notification is true now // note that if lob is clamped, localgrid will also be clamped getLocator()->setCoordinate(platformCoordPosOnly, time); + + const osg::Vec3d& lobPos = convertToOSG(platformCoordPosOnly.position()); + xform_->setMatrix(osg::Matrixd::translate(lobPos)); } } } @@ -558,11 +574,11 @@ bool LobGroupNode::updateFromDataStore(const simData::DataSliceBase *updateSlice const simData::LobGroupUpdateSlice *updateSlice = static_cast(updateSliceBase); assert(updateSlice); const simData::LobGroupUpdate* current = updateSlice->current(); - const bool lobChangedToActive = (current != NULL && !hasLastUpdate_); + const bool lobChangedToActive = (current && !hasLastUpdate_); // Do any necessary flashing - simData::DataTable* table = ds_.dataTableManager().findTable(getId(), simData::INTERNAL_LOB_DRAWSTYLE_TABLE); - if (table != NULL) + const simData::DataTable* table = ds_.dataTableManager().findTable(getId(), simData::INTERNAL_LOB_DRAWSTYLE_TABLE); + if (table) { bool flashing = false; uint8_t state; diff --git a/SDK/simVis/LobGroup.h b/SDK/simVis/LobGroup.h index b2fa8c8ea..b67ebad0e 100644 --- a/SDK/simVis/LobGroup.h +++ b/SDK/simVis/LobGroup.h @@ -24,9 +24,10 @@ #define SIMVIS_LOB_GROUP_H #include "simData/DataTypes.h" -#include "simVis/Entity.h" #include "simVis/Constants.h" +#include "simVis/Entity.h" +namespace osg { class MatrixTransform; } namespace simCore { class CoordinateConverter; } namespace simData { class DataStore; @@ -79,6 +80,18 @@ class SDKVIS_EXPORT LobGroupNode : public EntityNode /** Retrieves the currently visible end points */ void getVisibleEndPoints(std::vector& ecefVec) const; + /** + * Get the traversal mask for this node type + * @return a traversal mask + */ + static unsigned int getMask() { return simVis::DISPLAY_MASK_LOB_GROUP; } + + /** + * Returns the last update for the LOB Group + * @return the last update for the LOB Group + */ + const simData::LobGroupUpdate* update() const { return &lastUpdate_; } + public: // EntityNode interface /** * Whether the entity is active within the scenario at the current time. @@ -86,7 +99,7 @@ class SDKVIS_EXPORT LobGroupNode : public EntityNode * current scenario time, and has not received a command to turn off * @return true if active; false if not */ - virtual bool isActive() const; + virtual bool isActive() const override; /** * Returns the entity name. Can be used to get the actual name always or the @@ -96,62 +109,50 @@ class SDKVIS_EXPORT LobGroupNode : public EntityNode * @param allowBlankAlias If true DISPLAY_NAME will return blank if usealias is true and alias is blank * @return actual/alias entity name string */ - virtual const std::string getEntityName(EntityNode::NameType nameType, bool allowBlankAlias = false) const; + virtual const std::string getEntityName(EntityNode::NameType nameType, bool allowBlankAlias = false) const override; /// Returns the pop up text based on the label content callback, update and preference - virtual std::string popupText() const; + virtual std::string popupText() const override; /// Returns the hook text based on the label content callback, update and preference - virtual std::string hookText() const; + virtual std::string hookText() const override; /// Returns the legend text based on the label content callback, update and preference - virtual std::string legendText() const; + virtual std::string legendText() const override; /** * Gets the unique ID of the database entity underlying this node. * @return The object ID */ - virtual simData::ObjectId getId() const; + virtual simData::ObjectId getId() const override; /** Get the lob's host's ID */ - virtual bool getHostId(simData::ObjectId& out_hostId) const; + virtual bool getHostId(simData::ObjectId& out_hostId) const override; /** * Update this based on the slice from the data store. - * @param updateSlice Data store update slice (could be NULL) + * @param updateSlice Data store update slice (could be nullptr) * @param force true to force the update to be applied; false allows entity to use its own internal logic to decide whether the update should be applied * @return true if update applied, false if not */ - virtual bool updateFromDataStore(const simData::DataSliceBase *updateSlice, bool force=false); + virtual bool updateFromDataStore(const simData::DataSliceBase *updateSlice, bool force=false) override; /** * Flushes all the entity's data point visualization */ - virtual void flush(); + virtual void flush() override; /** * Returns a range value used for visualization. Will return zero for platforms and projectors. */ - virtual double range() const; + virtual double range() const override; /** This entity type is, at this time, unpickable. */ - virtual unsigned int objectIndexTag() const; - - /** - * Get the traversal mask for this node type - * @return a traversal mask - */ - static unsigned int getMask() { return simVis::DISPLAY_MASK_LOB_GROUP; } - - /** - * Returns the last update for the LOB Group - * @return the last update for the LOB Group - */ - const simData::LobGroupUpdate* update() const { return &lastUpdate_; } + virtual unsigned int objectIndexTag() const override; /** Return the proper library name */ - virtual const char* libraryName() const { return "simVis"; } + virtual const char* libraryName() const override { return "simVis"; } /** Return the class name */ - virtual const char* className() const { return "LobGroupNode"; } + virtual const char* className() const override { return "LobGroupNode"; } private: // types class Cache; @@ -206,6 +207,8 @@ class SDKVIS_EXPORT LobGroupNode : public EntityNode /// Cache of lines drawn Cache *lineCache_; + /// the transform for this lobgroup that positions the entity label and supports tether + osg::ref_ptr xform_; /// the localgrid node for this lobgroup osg::ref_ptr localGrid_; @@ -217,8 +220,6 @@ class SDKVIS_EXPORT LobGroupNode : public EntityNode /// Tag used for picking unsigned int objectIndexTag_; }; - } #endif // SIMVIS_LOB_GROUP_H - diff --git a/SDK/simVis/LocalGrid.cpp b/SDK/simVis/LocalGrid.cpp index 634046e20..20641697f 100644 --- a/SDK/simVis/LocalGrid.cpp +++ b/SDK/simVis/LocalGrid.cpp @@ -929,7 +929,7 @@ void LocalGridNode::updateSpeedRings_(const simData::LocalGridPrefs& prefs, doub int LocalGridNode::processSpeedParams_(const simData::LocalGridPrefs& prefs, double& sizeM, double& timeRadiusSeconds) { - const Locator* hostLocator = (host_.valid() ? host_->getLocator() : NULL); + const Locator* hostLocator = (host_.valid() ? host_->getLocator() : nullptr); if (!hostLocator) return -1; const PlatformNode* hostPlatform = dynamic_cast(host_.get()); diff --git a/SDK/simVis/LocalGrid.h b/SDK/simVis/LocalGrid.h index 1f45fc629..a9e0841b1 100644 --- a/SDK/simVis/LocalGrid.h +++ b/SDK/simVis/LocalGrid.h @@ -47,7 +47,7 @@ namespace simVis * @param[in ] host Host entity node * @param[in ] referenceYear The calculations for the Speed Rings Fixed Time preference needs the scenario reference year */ - LocalGridNode(Locator* hostLocator, const EntityNode* host = NULL, int referenceYear = 1970); + LocalGridNode(Locator* hostLocator, const EntityNode* host = nullptr, int referenceYear = 1970); /** * Checks new preferences for this object, messages to console if there are issues diff --git a/SDK/simVis/Locator.cpp b/SDK/simVis/Locator.cpp index 4c60947f1..c69370a18 100644 --- a/SDK/simVis/Locator.cpp +++ b/SDK/simVis/Locator.cpp @@ -82,7 +82,7 @@ void Locator::setParentLocator(Locator* newParent, unsigned int inheritMask, boo return; } - if (newParent == NULL) + if (newParent == nullptr) { // remove me from my old parent's child list: if (parentLoc_.valid()) @@ -106,7 +106,7 @@ void Locator::setComponentsToInherit(unsigned int value, bool notify) if (notify) notifyListeners_(); } -#ifdef USE_DEPRECATED_SIMDISSDK_API + void Locator::setCoordinate(const simCore::Coordinate& coord, bool notify) { if (coord.coordinateSystem() != simCore::COORD_SYS_ECEF) @@ -128,7 +128,6 @@ void Locator::setCoordinate(const simCore::Coordinate& coord, bool notify) if (notify) notifyListeners_(); } -#endif void Locator::setCoordinate(const simCore::Coordinate& coord, double timestamp, double eciRefTime, bool notify) { @@ -239,21 +238,6 @@ bool Locator::getLocalOffsets(simCore::Vec3& pos, simCore::Vec3& ori) const return true; } -#ifdef USE_DEPRECATED_SIMDISSDK_API -void Locator::setRotationOrder(const Locator::RotationOrder& order, bool notify) -{ - rotOrder_ = order; - if (notify) - notifyListeners_(); -} -#endif - -void Locator::resetToLocalTangentPlane(bool notify) -{ - if (notify) - notifyListeners_(); -} - void Locator::endUpdate() { notifyListeners_(); @@ -275,7 +259,7 @@ double Locator::getTime() const { // if no valid timestamps, return 0. double mostRecentTime = -std::numeric_limits::max(); - for (const Locator* loc = this; loc != NULL; loc = loc->getParentLocator()) + for (const Locator* loc = this; loc != nullptr; loc = loc->getParentLocator()) { const double locatorTime = loc->timestamp_; if (locatorTime != std::numeric_limits::max() && locatorTime > mostRecentTime) @@ -287,7 +271,7 @@ double Locator::getTime() const double Locator::getEciRefTime() const { // traverse up through parents to find first set ECI reference time - for (const Locator* loc = this; loc != NULL; loc = loc->getParentLocator()) + for (const Locator* loc = this; loc != nullptr; loc = loc->getParentLocator()) { if (loc->eciRefTime_ != std::numeric_limits::max()) return loc->eciRefTime_; @@ -298,7 +282,7 @@ double Locator::getEciRefTime() const double Locator::getElapsedEciTime() const { // find the first locator that has a set value for eci reference time - for (const Locator* loc = this; loc != NULL; loc = loc->getParentLocator()) + for (const Locator* loc = this; loc != nullptr; loc = loc->getParentLocator()) { if (loc->eciRefTime_ != std::numeric_limits::max()) { @@ -309,12 +293,10 @@ double Locator::getElapsedEciTime() const return getTime(); } -#ifdef USE_DEPRECATED_SIMDISSDK_API bool Locator::inherits_(unsigned int mask) const { return (componentsToInherit_ & mask) != COMP_NONE; } -#endif bool Locator::getLocatorPosition(simCore::Vec3* out_position, const simCore::CoordinateSystem& coordsys) const { @@ -322,7 +304,7 @@ bool Locator::getLocatorPosition(simCore::Vec3* out_position, const simCore::Coo return false; osg::Matrix m; - if (!getLocatorMatrix(m, Locator::COMP_POSITION)) + if (!getLocatorMatrix(m)) return false; const osg::Vec3d& ecefPos = m.getTrans(); @@ -472,7 +454,7 @@ double Locator::getEciRotationTime() const // sum all rotations of this and all parents double rotationSum = 0.; - for (const Locator* loc = this; loc != NULL; loc = loc->getParentLocator()) + for (const Locator* loc = this; loc != nullptr; loc = loc->getParentLocator()) { if (loc->hasRotation_) rotationSum += loc->eciRotationTime_; @@ -709,13 +691,19 @@ bool ResolvedPositionOrientationLocator::getPosition_(osg::Vec3d& pos, unsigned // resolved position is not modified by children's inheritance orientation components if (getParentLocator() && getParentLocator()->getLocatorMatrix(mat, getComponentsToInherit())) { - // strip out orientation and scale + // strip out orientation and scale; does not strip out rotation. pos = mat.getTrans(); return true; } return false; } -// only apply our local offsets +bool ResolvedPositionOrientationLocator::getRotation_(osg::Matrixd& rotationMatrix) const +{ + // rotation already included by getPosition_ + return false; +} + +// only apply local offsets // do not apply parent offsets, since they have already been processed to produce the resolved position void ResolvedPositionOrientationLocator::applyOffsets_(osg::Matrixd& output, unsigned int comps) const { diff --git a/SDK/simVis/Locator.h b/SDK/simVis/Locator.h index db44bce7a..44cd09c11 100644 --- a/SDK/simVis/Locator.h +++ b/SDK/simVis/Locator.h @@ -123,12 +123,6 @@ class SDKVIS_EXPORT Locator : public osg::Referenced, public osgEarth::Util::Rev */ explicit Locator(Locator* parent, unsigned int compsToInherit = COMP_ALL); -#ifdef USE_DEPRECATED_SIMDISSDK_API - /** - * @deprecated No longer has any function. Rotation order is always HPR. - */ - SDK_DEPRECATE(void setRotationOrder(const RotationOrder& order, bool notify = true), "Method will be removed in a future SDK release"); -#endif /** * Notifies any listeners that properties of this Locator have changed. * Normally this happens automatically, but if you call any of the set* @@ -138,7 +132,6 @@ class SDKVIS_EXPORT Locator : public osg::Referenced, public osgEarth::Util::Rev */ void endUpdate(); -#ifdef USE_DEPRECATED_SIMDISSDK_API /** * @deprecated Interface changed to support ECI coordinates. Use other interface for setCoordinate instead. * Sets the world position, orientation, and velocity vector all at once. @@ -146,7 +139,6 @@ class SDKVIS_EXPORT Locator : public osg::Referenced, public osgEarth::Util::Rev * @param[in ] notify Whether to immediately notify listeners */ SDK_DEPRECATE(void setCoordinate(const simCore::Coordinate& coord, bool notify = true), "Method will be removed in a future SDK release."); -#endif /** * Sets the world position, orientation, and velocity vector all at once. To support @@ -180,11 +172,6 @@ class SDKVIS_EXPORT Locator : public osg::Referenced, public osgEarth::Util::Rev void setLocalOffsets(const simCore::Vec3& pos, const simCore::Vec3& ori, double timestamp = std::numeric_limits::max(), bool notify = true); - /** - * @deprecated No longer has any function. - */ - void resetToLocalTangentPlane(bool notify = true); - /** * Gets the world coordinate that was set by a setCoordinate() operation for this locator * or else for the nearest parent that had its coordinate set via setCoordinate() @@ -225,7 +212,7 @@ class SDKVIS_EXPORT Locator : public osg::Referenced, public osgEarth::Util::Rev * function that extracts the Position information (not rotation) from the * locator matrix. * - * @param[out] out_position If not NULL, resulting position stored here + * @param[out] out_position If not nullptr, resulting position stored here * @param[in ] coordsys Requested coord sys of the output position (only LLA, ECEF, or ECI supported) * @return True if the output parameter is populated successfully */ @@ -237,8 +224,8 @@ class SDKVIS_EXPORT Locator : public osg::Referenced, public osgEarth::Util::Rev * function that extracts the Position information and rotation from the * locator matrix. * - * @param[out] out_position If not NULL, resulting position stored here - * @param[out] out_orientation If not NULL, resulting orientation stored here + * @param[out] out_position If not nullptr, resulting position stored here + * @param[out] out_orientation If not nullptr, resulting orientation stored here * @param[in ] coordsys Requested coord sys of the output position (only LLA, ECEF, or ECI supported) * @return True if the output parameter is populated successfully */ @@ -301,13 +288,13 @@ class SDKVIS_EXPORT Locator : public osg::Referenced, public osgEarth::Util::Rev /** * Get the parent locator. - * @return Locator, or NULL if no parent exists + * @return Locator, or nullptr if no parent exists */ Locator* getParentLocator() { return parentLoc_.get(); } /** * Get the parent locator (tail const version) - * @return Locator, or NULL if no parent exists + * @return Locator, or nullptr if no parent exists */ const Locator* getParentLocator() const { return parentLoc_.get(); } @@ -381,6 +368,13 @@ class SDKVIS_EXPORT Locator : public osg::Referenced, public osgEarth::Util::Rev */ virtual bool getOrientation_(osg::Matrixd& ori, unsigned int comps) const; + /** + * Returns the base rotation of this locator + * @param[out] rotation matrix with rotation + * @return true if there is a non-trivial rotation returned + */ + virtual bool getRotation_(osg::Matrixd& rotation) const; + /** * Returns the input locator matrix with all local offsets (including those of parents) applied, as filtered by the specified inheritance components * @param[in,out] output matrix containing the new locator matrix with offsets applied @@ -401,16 +395,7 @@ class SDKVIS_EXPORT Locator : public osg::Referenced, public osgEarth::Util::Rev */ void notifyListeners_(); -#ifdef USE_DEPRECATED_SIMDISSDK_API SDK_DEPRECATE(bool inherits_(unsigned int mask) const, "Method will be removed in future SDK release."); -#endif - - /** - * Returns the base rotation of this locator - * @param[out] rotation matrix with rotation - * @return true if there is a non-trivial rotation returned - */ - bool getRotation_(osg::Matrixd& rotation) const; /** * Returns an ENU local tangent plane at the specified position @@ -454,25 +439,25 @@ class SDKVIS_EXPORT CachingLocator : public Locator * function that extracts the Position information (not rotation) from the * locator matrix. * - * @param[out] out_position If not NULL, resulting position stored here + * @param[out] out_position If not nullptr, resulting position stored here * @param[in ] coordsys Requested coord sys of the output position (only LLA, ECEF, or ECI supported) * @return True if the output parameter is populated successfully */ virtual bool getLocatorPosition(simCore::Vec3* out_position, - const simCore::CoordinateSystem& coordsys = simCore::COORD_SYS_ECEF) const; + const simCore::CoordinateSystem& coordsys = simCore::COORD_SYS_ECEF) const override; /** * Gets the world position reflected by this Locator. This is just a convenience * function that extracts the Position information and rotation from the * locator matrix. * - * @param[out] out_position If not NULL, resulting position stored here - * @param[out] out_orientation If not NULL, resulting orientation stored here + * @param[out] out_position If not nullptr, resulting position stored here + * @param[out] out_orientation If not nullptr, resulting orientation stored here * @param[in ] coordsys Requested coord sys of the output position (only LLA, ECEF, or ECI supported) * @return True if the output parameter is populated successfully */ virtual bool getLocatorPositionOrientation(simCore::Vec3* out_position, simCore::Vec3* out_orientation, - const simCore::CoordinateSystem& coordsys = simCore::COORD_SYS_ECEF) const; + const simCore::CoordinateSystem& coordsys = simCore::COORD_SYS_ECEF) const override; protected: /// osg::Referenced-derived virtual ~CachingLocator() {} @@ -508,9 +493,11 @@ class SDKVIS_EXPORT ResolvedPositionOrientationLocator : public Locator virtual ~ResolvedPositionOrientationLocator() {} private: /** @copydoc Locator::getPosition_() */ - virtual bool getPosition_(osg::Vec3d& pos, unsigned int comps) const; + virtual bool getPosition_(osg::Vec3d& pos, unsigned int comps) const override; + /** @copydoc Locator::getRotation_() */ + virtual bool getRotation_(osg::Matrixd& rotation) const override; /** @copydoc Locator::applyOffsets_() */ - virtual void applyOffsets_(osg::Matrixd& output, unsigned int comps) const; + virtual void applyOffsets_(osg::Matrixd& output, unsigned int comps) const override; }; /** @@ -532,7 +519,7 @@ class SDKVIS_EXPORT ResolvedPositionLocator : public ResolvedPositionOrientation virtual ~ResolvedPositionLocator() {} private: /** @copydoc Locator::getOrientation_() */ - virtual bool getOrientation_(osg::Matrixd& ori, unsigned int comps) const; + virtual bool getOrientation_(osg::Matrixd& ori, unsigned int comps) const override; }; } diff --git a/SDK/simVis/LocatorNode.cpp b/SDK/simVis/LocatorNode.cpp index ee484f905..a9c626a96 100644 --- a/SDK/simVis/LocatorNode.cpp +++ b/SDK/simVis/LocatorNode.cpp @@ -21,6 +21,7 @@ * */ #include "simCore/Calc/Calculations.h" +#include "simVis/Entity.h" #include "simVis/Locator.h" #include "simVis/OverheadMode.h" #include "simVis/LocatorNode.h" @@ -33,14 +34,14 @@ namespace simVis { LocatorNode::LocatorNode() - : locatorCallback_(NULL), + : locatorCallback_(nullptr), overheadModeHint_(false) { // LocatorNode is valid without any locator; it functions as a group. } LocatorNode::LocatorNode(Locator* locator, unsigned int componentsToTrack) - : locatorCallback_(NULL), + : locatorCallback_(nullptr), componentsToTrack_(componentsToTrack), overheadModeHint_(false) { @@ -50,7 +51,7 @@ LocatorNode::LocatorNode(Locator* locator, unsigned int componentsToTrack) LocatorNode::LocatorNode(const LocatorNode& rhs, const osg::CopyOp& op) : osg::MatrixTransform(rhs, op), matrixRevision_(rhs.matrixRevision_), - locatorCallback_(NULL), + locatorCallback_(nullptr), componentsToTrack_(rhs.componentsToTrack_), overheadModeHint_(rhs.overheadModeHint_) { @@ -96,6 +97,11 @@ int LocatorNode::getPosition(simCore::Vec3* out_position, simCore::CoordinateSys // this locatorNode is not active, and does not have a valid position return 2; } + if (entityToMonitor_.valid() && !entityToMonitor_->isActive()) + { + // locatorNode is inactive: the locatorNode is tracking an entity, and that entity is inactive + return 3; + } const osg::Vec3d& locatorNodeEcef = getMatrix().getTrans(); if (coordsys == simCore::COORD_SYS_LLA) @@ -129,6 +135,11 @@ int LocatorNode::getPositionOrientation(simCore::Vec3* out_position, simCore::Ve // this locatorNode is not active, and does not have a valid position return 2; } + if (entityToMonitor_.valid() && !entityToMonitor_->isActive()) + { + // locatorNode is inactive: the locatorNode is tracking an entity, and that entity is inactive + return 3; + } const osg::Matrixd& m = getMatrix(); const osg::Vec3d& locatorNodeEcef = m.getTrans(); @@ -161,7 +172,17 @@ int LocatorNode::getPositionOrientation(simCore::Vec3* out_position, simCore::Ve void LocatorNode::syncWithLocator() { - if (getNodeMask() != 0 && locator_.valid() && locator_->outOfSyncWith(matrixRevision_)) + if (getNodeMask() == 0 || !locator_.valid()) + { + // this locatorNode is not active, and does not have a valid position + return; + } + if (entityToMonitor_.valid() && !entityToMonitor_->isActive()) + { + // locatorNode is inactive: the locatorNode is tracking an entity, and that entity is inactive + return; + } + if (locator_->outOfSyncWith(matrixRevision_)) { osg::Matrix matrix; @@ -175,8 +196,6 @@ void LocatorNode::syncWithLocator() bool LocatorNode::computeLocalToWorldMatrix(osg::Matrix& out, osg::NodeVisitor* nv) const { - if (getNodeMask() == 0) - return false; if (!locator_.valid()) { // locatorNode with no locator has the position of its parent @@ -184,9 +203,9 @@ bool LocatorNode::computeLocalToWorldMatrix(osg::Matrix& out, osg::NodeVisitor* } osg::Matrix matrix = getMatrix(); - // It is possible that nv is NULL if calling computeBound(), which can happen during intersection + // It is possible that nv is nullptr if calling computeBound(), which can happen during intersection // visitor processing. To address this, the overheadModeHint_ can be set. If set and the Node - // visitor is NULL, then we do overhead mode calculations for bounding area. + // visitor is nullptr, then we do overhead mode calculations for bounding area. if (simVis::OverheadMode::isActive(nv) || (overheadModeHint_ && !nv)) { simCore::Vec3 p( matrix(3,0), matrix(3,1), matrix(3,2) ); @@ -211,6 +230,11 @@ bool LocatorNode::overheadModeHint() const return overheadModeHint_; } +void LocatorNode::setEntityToMonitor(EntityNode* entity) +{ + entityToMonitor_ = entity; +} + //--------------------------------------------------------------------------- SetOverheadModeHintVisitor::SetOverheadModeHintVisitor(bool hint, TraversalMode tm) diff --git a/SDK/simVis/LocatorNode.h b/SDK/simVis/LocatorNode.h index 5df29867d..02a4a9781 100644 --- a/SDK/simVis/LocatorNode.h +++ b/SDK/simVis/LocatorNode.h @@ -24,13 +24,15 @@ #define SIMVIS_LOCATORNODE_H #include "osg/MatrixTransform" +#include "osg/observer_ptr" #include "osgEarth/Revisioning" #include "simCore/Calc/CoordinateSystem.h" #include "simVis/Locator.h" namespace simVis { -//---------------------------------------------------------------------------- +class EntityNode; + /// Track the transform of a parent LocatorNode with a Locator class SDKVIS_EXPORT LocatorNode : public osg::MatrixTransform { @@ -55,7 +57,7 @@ class SDKVIS_EXPORT LocatorNode : public osg::MatrixTransform /// set the Locator for this LocatorNode, recalculates the transform matrix void setLocator(Locator *locator, unsigned int componentsToTrack = Locator::COMP_ALL); - /// Turns on or off a flag to hint to use Overhead Mode for bounds computation when NodeVisitor is NULL + /// Turns on or off a flag to hint to use Overhead Mode for bounds computation when NodeVisitor is nullptr void setOverheadModeHint(bool overheadMode); /// Retrieves a previously set overhead mode hint, used for bounds computation in intersection visitors bool overheadModeHint() const; @@ -65,7 +67,7 @@ class SDKVIS_EXPORT LocatorNode : public osg::MatrixTransform * function that extracts the Position information (not rotation) from the * locatorNode matrix. * - * @param[out] out_position If not NULL, resulting position stored here + * @param[out] out_position If not nullptr, resulting position stored here * @param[in ] coordsys Requested coord sys of the output position (only LLA, ECEF, or ECI supported) * @return 0 if the output parameter is populated successfully, nonzero on failure */ @@ -76,14 +78,20 @@ class SDKVIS_EXPORT LocatorNode : public osg::MatrixTransform * function that extracts the Position information and rotation from the * locatorNode matrix. * - * @param[out] out_position If not NULL, resulting position stored here - * @param[out] out_orientation If not NULL, resulting orientation stored here + * @param[out] out_position If not nullptr, resulting position stored here + * @param[out] out_orientation If not nullptr, resulting orientation stored here * @param[in ] coordsys Requested coord sys of the output position (only LLA, ECEF, or ECI supported) * @return 0 if the output parameter is populated successfully, nonzero on failure */ int getPositionOrientation(simCore::Vec3* out_position, simCore::Vec3* out_orientation, simCore::CoordinateSystem coordsys = simCore::COORD_SYS_ECEF) const; + /** + * Links the locatorNode to an entity such that the isActive() state of the entity determines whether this node is active + * @param entity entity to track + */ + void setEntityToMonitor(EntityNode* entity); + public: /// Synchronizes the transform matrix with the locator virtual void syncWithLocator(); @@ -100,7 +108,8 @@ class SDKVIS_EXPORT LocatorNode : public osg::MatrixTransform osg::ref_ptr locator_; osgEarth::Util::Revision matrixRevision_; osg::ref_ptr locatorCallback_; - unsigned int componentsToTrack_; // Locator::Components mask + osg::observer_ptr entityToMonitor_; ///< if set, the entity whose isActive() state determines the active state of this locatorNode + unsigned int componentsToTrack_; ///< Locator::Components mask /// Sometimes bounds are computed without a node visitor and we need to know if in overhead mode; this flag caches that. bool overheadModeHint_; diff --git a/SDK/simVis/Measurement.cpp b/SDK/simVis/Measurement.cpp index 325c36025..cd23522aa 100644 --- a/SDK/simVis/Measurement.cpp +++ b/SDK/simVis/Measurement.cpp @@ -298,7 +298,7 @@ DownRangeMeasurement::DownRangeMeasurement() double DownRangeMeasurement::value(RangeToolState& state) const { double dr; - simCore::calculateDRCRDownValue(state.beginEntity_->lla_, state.beginEntity_->ypr_.x(), state.endEntity_->lla_, state.earthModel_, &state.coordConv_, &dr, NULL, NULL); + simCore::calculateDRCRDownValue(state.beginEntity_->lla_, state.beginEntity_->ypr_.x(), state.endEntity_->lla_, state.earthModel_, &state.coordConv_, &dr, nullptr, nullptr); return dr; } @@ -316,7 +316,7 @@ CrossRangeMeasurement::CrossRangeMeasurement() double CrossRangeMeasurement::value(RangeToolState& state) const { double cr; - simCore::calculateDRCRDownValue(state.beginEntity_->lla_, state.beginEntity_->ypr_.x(), state.endEntity_->lla_, state.earthModel_, &state.coordConv_, NULL, &cr, NULL); + simCore::calculateDRCRDownValue(state.beginEntity_->lla_, state.beginEntity_->ypr_.x(), state.endEntity_->lla_, state.earthModel_, &state.coordConv_, nullptr, &cr, nullptr); return cr; } @@ -334,7 +334,7 @@ DownRangeCrossRangeDownValueMeasurement::DownRangeCrossRangeDownValueMeasurement double DownRangeCrossRangeDownValueMeasurement::value(RangeToolState& state) const { double dv; - simCore::calculateDRCRDownValue(state.beginEntity_->lla_, state.beginEntity_->ypr_.x(), state.endEntity_->lla_, state.earthModel_, &state.coordConv_, NULL, NULL, &dv); + simCore::calculateDRCRDownValue(state.beginEntity_->lla_, state.beginEntity_->ypr_.x(), state.endEntity_->lla_, state.earthModel_, &state.coordConv_, nullptr, nullptr, &dv); return dv; } @@ -352,7 +352,7 @@ GeoDownRangeMeasurement::GeoDownRangeMeasurement() double GeoDownRangeMeasurement::value(RangeToolState& state) const { double dr; - simCore::calculateGeodesicDRCR(state.beginEntity_->lla_, state.beginEntity_->ypr_.x(), state.endEntity_->lla_, &dr, NULL); + simCore::calculateGeodesicDRCR(state.beginEntity_->lla_, state.beginEntity_->ypr_.x(), state.endEntity_->lla_, &dr, nullptr); return dr; } @@ -370,7 +370,7 @@ GeoCrossRangeMeasurement::GeoCrossRangeMeasurement() double GeoCrossRangeMeasurement::value(RangeToolState& state) const { double cr; - simCore::calculateGeodesicDRCR(state.beginEntity_->lla_, state.beginEntity_->ypr_.x(), state.endEntity_->lla_, NULL, &cr); + simCore::calculateGeodesicDRCR(state.beginEntity_->lla_, state.beginEntity_->ypr_.x(), state.endEntity_->lla_, nullptr, &cr); return cr; } @@ -388,7 +388,7 @@ TrueAzimuthMeasurement::TrueAzimuthMeasurement() double TrueAzimuthMeasurement::value(RangeToolState& state) const { double az; - calculateTrueAngles_(state, &az, NULL, NULL); + calculateTrueAngles_(state, &az, nullptr, nullptr); return az; } @@ -406,7 +406,7 @@ TrueElevationMeasurement::TrueElevationMeasurement() double TrueElevationMeasurement::value(RangeToolState& state) const { double el; - calculateTrueAngles_(state, NULL, &el, NULL); + calculateTrueAngles_(state, nullptr, &el, nullptr); return el; } @@ -424,7 +424,7 @@ TrueCompositeAngleMeasurement::TrueCompositeAngleMeasurement() double TrueCompositeAngleMeasurement::value(RangeToolState& state) const { double cmp; - calculateTrueAngles_(state, NULL, NULL, &cmp); + calculateTrueAngles_(state, nullptr, nullptr, &cmp); return cmp; } @@ -444,7 +444,7 @@ MagneticAzimuthMeasurement::MagneticAzimuthMeasurement(std::shared_ptrconvertMagneticDatum(state.beginEntity_->lla_, state.timeStamp_, az, simCore::COORD_SYS_LLA, simCore::MAGVAR_TRUE, simCore::MAGVAR_WMM, 0.0); return az; } @@ -690,7 +690,7 @@ double VelAzimDownRangeMeasurement::value(RangeToolState& state) const double downRng = 0; simCore::Vec3 fpa; simCore::calculateFlightPathAngles(vel, fpa); - simCore::calculateDRCRDownValue(state.beginEntity_->lla_, fpa[0], state.endEntity_->lla_, state.earthModel_, &state.coordConv_, &downRng, NULL, NULL); + simCore::calculateDRCRDownValue(state.beginEntity_->lla_, fpa[0], state.endEntity_->lla_, state.earthModel_, &state.coordConv_, &downRng, nullptr, nullptr); return downRng; } @@ -714,7 +714,7 @@ double VelAzimCrossRangeMeasurement::value(RangeToolState& state) const double crossRng = 0; simCore::Vec3 fpa; simCore::calculateFlightPathAngles(vel, fpa); - simCore::calculateDRCRDownValue(state.beginEntity_->lla_, fpa[0], state.endEntity_->lla_, state.earthModel_, &state.coordConv_, NULL, &crossRng, NULL); + simCore::calculateDRCRDownValue(state.beginEntity_->lla_, fpa[0], state.endEntity_->lla_, state.earthModel_, &state.coordConv_, nullptr, &crossRng, nullptr); return crossRng; } @@ -738,7 +738,7 @@ double VelAzimGeoDownRangeMeasurement::value(RangeToolState& state) const double downRng = 0; simCore::Vec3 fpa; simCore::calculateFlightPathAngles(vel, fpa); - simCore::calculateGeodesicDRCR(state.beginEntity_->lla_, fpa[0], state.endEntity_->lla_, &downRng, NULL); + simCore::calculateGeodesicDRCR(state.beginEntity_->lla_, fpa[0], state.endEntity_->lla_, &downRng, nullptr); return downRng; } @@ -762,7 +762,7 @@ double VelAzimGeoCrossRangeMeasurement::value(RangeToolState& state) const double crossRng = 0; simCore::Vec3 fpa; simCore::calculateFlightPathAngles(vel, fpa); - simCore::calculateGeodesicDRCR(state.beginEntity_->lla_, fpa[0], state.endEntity_->lla_, NULL, &crossRng); + simCore::calculateGeodesicDRCR(state.beginEntity_->lla_, fpa[0], state.endEntity_->lla_, nullptr, &crossRng); return crossRng; } diff --git a/SDK/simVis/ModelCache.cpp b/SDK/simVis/ModelCache.cpp index 943c39656..4b356fd66 100644 --- a/SDK/simVis/ModelCache.cpp +++ b/SDK/simVis/ModelCache.cpp @@ -122,7 +122,7 @@ class PrepareForProgrammablePipeline : public osg::NodeVisitor { #ifndef OSG_GL_FIXED_FUNCTION_AVAILABLE // osgSim::LightPointNode is not supported in GLCORE, turn it off to prevent warning spam from OSG - if (dynamic_cast(&node) != NULL) + if (dynamic_cast(&node) != nullptr) node.setNodeMask(0); osg::StateSet* ss = node.getStateSet(); @@ -130,22 +130,22 @@ class PrepareForProgrammablePipeline : public osg::NodeVisitor { // GLCORE does not support TexEnv. Remove unnecessary ones osg::TexEnv* texEnv = dynamic_cast(ss->getTextureAttribute(0, osg::StateAttribute::TEXENV)); - if (texEnv != NULL && texEnv->getMode() == osg::TexEnv::MODULATE) + if (texEnv != nullptr && texEnv->getMode() == osg::TexEnv::MODULATE) ss->removeTextureAttribute(0, texEnv); - else if (texEnv != NULL) + else if (texEnv != nullptr) { SIM_WARN << "Unexpected TexEnv mode: 0x" << std::hex << texEnv->getMode() << "\n"; } // GLCORE does not support TexEnvCombine; drop it; see SIMDIS-3227 osg::TexEnvCombine* texEnvCombine = dynamic_cast(ss->getTextureAttribute(0, osg::StateAttribute::TEXENV)); - if (texEnvCombine != NULL) + if (texEnvCombine != nullptr) ss->removeTextureAttribute(0, texEnvCombine); // GLCORE does not support ShadeModel. Only smooth shading is supported. Many SIMDIS // models in sites/ use flat shading, but don't seem to need it. Drop the attribute. osg::ShadeModel* shadeModel = dynamic_cast(ss->getAttribute(osg::StateAttribute::SHADEMODEL)); - if (shadeModel != NULL) + if (shadeModel != nullptr) ss->removeAttribute(shadeModel); // GLCORE does not support mode GL_TEXTURE_2D. But we still need the texture attribute, so just remove mode. @@ -153,7 +153,7 @@ class PrepareForProgrammablePipeline : public osg::NodeVisitor // GLCORE does not support LightModel; drop it; see SIMDIS-3089 osg::LightModel* lightModel = dynamic_cast(ss->getAttribute(osg::StateAttribute::LIGHTMODEL)); - if (lightModel != NULL) + if (lightModel != nullptr) ss->removeAttribute(lightModel); // Fix textures that have GL_LUMINANCE or GL_LUMINANCE_ALPHA @@ -177,7 +177,7 @@ class PrepareForProgrammablePipeline : public osg::NodeVisitor // Some older models that use an FFP Material default to using the diffuse // material color as the active color, but this only works under FFP. Without // a color array, state leakage can occur. - if (geom->getColorArray() == NULL) + if (geom->getColorArray() == nullptr) { osg::Vec4Array* colors = new osg::Vec4Array(osg::Array::BIND_OVERALL, 1); (*colors)[0].set(1, 1, 1, 1); @@ -201,7 +201,7 @@ class ModelCacheLoaderOptions : public osgDB::ReaderWriter::Options ModelCacheLoaderOptions() : boxWhenNotFound(false), addLodNode(true), - clock(NULL) + clock(nullptr) { optimizeFlags = osgUtil::Optimizer::DEFAULT_OPTIMIZATIONS | osgUtil::Optimizer::VERTEX_POSTTRANSFORM | @@ -471,7 +471,7 @@ class ModelCache::LoaderNode : public osg::Group /** Initializes the Loader Node */ LoaderNode() - : cache_(NULL) + : cache_(nullptr) { } @@ -553,7 +553,7 @@ class ModelCache::LoaderNode : public osg::Group if (proxy->getNumChildren()) { osg::ref_ptr loaded = proxy->getChild(0); - // Shouldn't be able to have NULLs here. Investigate what to do if this triggers. + // Shouldn't be able to have nullptrs here. Investigate what to do if this triggers. assert(loaded.valid()); std::string uri; if (!proxy->getUserValue("uri", uri)) @@ -634,7 +634,7 @@ class ModelCache::LoaderNode : public osg::Group ModelCache::ModelCache() : shareArticulatedModels_(false), addLodNode_(true), - clock_(NULL), + clock_(nullptr), cache_(false, 30), // No need for thread safety, max of 30 elements asyncLoader_(new LoaderNode) { @@ -659,7 +659,7 @@ ModelCache::~ModelCache() { // Clear the cache in the loader to avoid stale pointers asyncLoader_->clear(); - asyncLoader_->setCache(NULL); + asyncLoader_->setCache(nullptr); } osg::Node* ModelCache::getOrCreateIconModel(const std::string& uri, bool* pIsImage) @@ -691,7 +691,7 @@ osg::Node* ModelCache::getOrCreateIconModel(const std::string& uri, bool* pIsIma // Farm off to the pseudo-loader osg::ref_ptr result = osgDB::readRefNodeFile(uri + "." + MODEL_LOADER_EXT, opts.get()); if (!result) - return NULL; + return nullptr; // Synchronous load needs to run the shader generator here osg::ref_ptr stateCache = new osgEarth::StateSetCache(); @@ -819,7 +819,7 @@ bool ModelCache::isArticulated(osg::Node* node) osgSim::MultiSwitch* ms = osgEarth::findTopMostNodeOfType(node); if (ms) return true; - return osgEarth::findTopMostNodeOfType(node) != NULL; + return osgEarth::findTopMostNodeOfType(node) != nullptr; } osg::Node* ModelCache::asyncLoaderNode() const diff --git a/SDK/simVis/ModelCache.h b/SDK/simVis/ModelCache.h index 9861eb133..f278b332f 100644 --- a/SDK/simVis/ModelCache.h +++ b/SDK/simVis/ModelCache.h @@ -85,9 +85,9 @@ class SDKVIS_EXPORT ModelCache * @param uri Location of the model to load. This class does not explicitly pass the string * through the simVis::Registry::findModelFile() method, so be sure to call that if the * URI is not going to be automatically found by OSG built-in mechanisms. - * @param pIsImage If non-NULL, will be set to true or false based on whether the URI represents + * @param pIsImage If non-nullptr, will be set to true or false based on whether the URI represents * an image file that needs billboarding. - * @return A node, or NULL if no file was found. + * @return A node, or nullptr if no file was found. */ osg::Node* getOrCreateIconModel(const std::string& uri, bool* pIsImage); diff --git a/SDK/simVis/NavigationModes.cpp b/SDK/simVis/NavigationModes.cpp index 6e981cb8d..4d8bd28a5 100644 --- a/SDK/simVis/NavigationModes.cpp +++ b/SDK/simVis/NavigationModes.cpp @@ -519,4 +519,78 @@ void GisNavigationMode::init_(simVis::View* view, bool enableOverhead, bool watc setLockAzimuthWhilePanning(false); } +// ========================================================================== + +BuilderNavigationMode::BuilderNavigationMode(bool enableOverhead, bool watchMode) +{ + init_(enableOverhead, watchMode); +} + +BuilderNavigationMode::~BuilderNavigationMode() +{ +} + +void BuilderNavigationMode::init_(bool enableOverhead, bool watchMode) +{ + const bool canRotate = !watchMode && !enableOverhead; + const bool canZoom = !watchMode; + + // Left mouse + bindMouse(EarthManipulator::ACTION_EARTH_DRAG, osgGA::GUIEventAdapter::LEFT_MOUSE_BUTTON); + // Right mouse + bindMouse(EarthManipulator::ACTION_ROTATE, osgGA::GUIEventAdapter::RIGHT_MOUSE_BUTTON); + + if (canZoom) + { + // Scroll wheel + NavigationMode::FixedZoomOptions wheelDurationScale; + wheelDurationScale.add(EarthManipulator::OPTION_SCALE_Y, 0.4); + wheelDurationScale.add(EarthManipulator::OPTION_DURATION, 0.2); + bindScroll(EarthManipulator::ACTION_ZOOM_OUT, osgGA::GUIEventAdapter::SCROLL_DOWN, 0, wheelDurationScale); + bindScroll(EarthManipulator::ACTION_ZOOM_IN, osgGA::GUIEventAdapter::SCROLL_UP, 0, wheelDurationScale); + + // middle mouse => continuous zoom + ContinuousZoomOptions continuousZoomOpts; + bindMouse(EarthManipulator::ACTION_ZOOM, osgGA::GUIEventAdapter::MIDDLE_MOUSE_BUTTON, 0, continuousZoomOpts); + } + + if (canRotate) + { + // Shift + left mouse == rotate + bindMouse(EarthManipulator::ACTION_ROTATE, osgGA::GUIEventAdapter::LEFT_MOUSE_BUTTON, osgGA::GUIEventAdapter::MODKEY_SHIFT); + // right mouse == rotate + bindMouse(EarthManipulator::ACTION_ROTATE, osgGA::GUIEventAdapter::RIGHT_MOUSE_BUTTON); + } + + // arrow keys => fixed pan + bindKey(EarthManipulator::ACTION_PAN_LEFT, osgGA::GUIEventAdapter::KEY_Left, 0); + bindKey(EarthManipulator::ACTION_PAN_RIGHT, osgGA::GUIEventAdapter::KEY_Right, 0); + bindKey(EarthManipulator::ACTION_PAN_UP, osgGA::GUIEventAdapter::KEY_Up, 0); + bindKey(EarthManipulator::ACTION_PAN_DOWN, osgGA::GUIEventAdapter::KEY_Down, 0); + + if (canZoom) + { + // ctrl + up/down = zoom in/out + bindKey(EarthManipulator::ACTION_ZOOM_IN, osgGA::GUIEventAdapter::KEY_Up, osgGA::GUIEventAdapter::MODKEY_CTRL); + bindKey(EarthManipulator::ACTION_ZOOM_OUT, osgGA::GUIEventAdapter::KEY_Down, osgGA::GUIEventAdapter::MODKEY_CTRL); + } + + // ctrl + shift + arrow = rotate around + if (canRotate) + { + const int modkeyMask = osgGA::GUIEventAdapter::MODKEY_CTRL | osgGA::GUIEventAdapter::MODKEY_SHIFT; + RotateOptions rotateOptions; + bindKey(EarthManipulator::ACTION_ROTATE_LEFT, osgGA::GUIEventAdapter::KEY_Left, modkeyMask, rotateOptions); + bindKey(EarthManipulator::ACTION_ROTATE_RIGHT, osgGA::GUIEventAdapter::KEY_Right, modkeyMask, rotateOptions); + bindKey(EarthManipulator::ACTION_ROTATE_UP, osgGA::GUIEventAdapter::KEY_Up, modkeyMask, rotateOptions); + bindKey(EarthManipulator::ACTION_ROTATE_DOWN, osgGA::GUIEventAdapter::KEY_Down, modkeyMask, rotateOptions); + } + + // Set min/max bounds + if (enableOverhead) + setMinMaxPitch(-90, -90); + else + setMinMaxPitch(MINIMUM_PITCH, MAXIMUM_PITCH); +} + } diff --git a/SDK/simVis/NavigationModes.h b/SDK/simVis/NavigationModes.h index 95220a13d..6c865ac9b 100644 --- a/SDK/simVis/NavigationModes.h +++ b/SDK/simVis/NavigationModes.h @@ -351,6 +351,43 @@ class View; osg::ref_ptr boxZoom_; }; + /** + * BuilderNavigationMode provides a similar navigation mode to Builder. + * Pass an instance of BuilderNavigationMode to + * EarthManipulator::applySettings in order to enable this navigation mode.

+ * The mappings are: + *

    + *
  • Left mouse button: pan
  • + *
  • Left mouse button + shift: rotation
  • + *
  • Middle mouse button: zoom
  • + *
  • Right mouse button: rotation
  • + *
  • Scroll wheel: zoom
  • + *
  • Arrow keys: pan
  • + *
  • Arrow keys + ctrl: zoom
  • + *
  • Arrow keys + ctrl + shift: rotate
  • + *
+ */ + class SDKVIS_EXPORT BuilderNavigationMode : public NavigationMode + { + public: + /** + * Initialize the Builder navigation mode. + * @param enableOverhead true to create the navigation mode with + * overhead enabled, false to create with perspective mode + * @param watchMode if true, no rotate actions will be applied, as + * rotation is disabled in watchMode + */ + BuilderNavigationMode(bool enableOverhead, bool watchMode); + + protected: + /// osg::Referenced-derived + virtual ~BuilderNavigationMode(); + + private: + /** Initializes the bindings given the parameters. */ + void init_(bool enableOverhead, bool watchMode); + }; + } #endif // SIMVIS_UI_NAVIGATION_MODES diff --git a/SDK/simVis/ObjectSelectionHandler.h b/SDK/simVis/ObjectSelectionHandler.h index 8baeef285..baf31cd5b 100644 --- a/SDK/simVis/ObjectSelectionHandler.h +++ b/SDK/simVis/ObjectSelectionHandler.h @@ -74,7 +74,7 @@ class SDKVIS_EXPORT ObjectSelectionHandler : public osgGA::GUIEventHandler */ void setSelectCallback(SelectCallback *callback); - /// Get the installed acceptance callback, or NULL if none is installed. + /// Get the installed acceptance callback, or nullptr if none is installed. SelectCallback* getSelectCallback() const; /** diff --git a/SDK/simVis/Picker.cpp b/SDK/simVis/Picker.cpp index f35d46d45..a3f489e23 100644 --- a/SDK/simVis/Picker.cpp +++ b/SDK/simVis/Picker.cpp @@ -245,12 +245,12 @@ void IntersectPicker::pickThisFrame_() pickedThisFrame_ = true; // Intersect picker should only pick on Platforms and Platform Models unsigned int acceptMask = DEFAULT_PICK_MASK; - simVis::EntityNode* pickedEntity = NULL; + simVis::EntityNode* pickedEntity = nullptr; if (lastMouseView_.valid()) pickedEntity = scenario_->find(lastMouseView_.get(), mx_, my_, acceptMask); - if (pickedEntity == NULL) + if (pickedEntity == nullptr) { - setPicked_(0, NULL); + setPicked_(0, nullptr); return; } @@ -387,7 +387,7 @@ RTTPicker::RTTPicker(simVis::ViewManager* viewManager, simVis::ScenarioManager* RTTPicker::~RTTPicker() { // Reset RTT Picker's callback to avoid possible invalid-memory situation if RTT Picker outlives us - rttPicker_->setDefaultCallback(NULL); + rttPicker_->setDefaultCallback(nullptr); osg::ref_ptr viewManager; if (viewManager_.lock(viewManager)) viewManager->removeCallback(viewManagerCallback_.get()); diff --git a/SDK/simVis/PlanetariumViewTool.cpp b/SDK/simVis/PlanetariumViewTool.cpp index 876065b7d..656af1bb2 100644 --- a/SDK/simVis/PlanetariumViewTool.cpp +++ b/SDK/simVis/PlanetariumViewTool.cpp @@ -114,7 +114,7 @@ void PlanetariumViewTool::setRange(double range) for (EntityVector::const_iterator i = entities.begin(); i != entities.end(); ++i) { PlatformNode* platform = dynamic_cast(i->get()); - if (platform != NULL && platform != host_.get() && platform->isActive()) + if (platform != nullptr && platform != host_.get() && platform->isActive()) targets_->addOrUpdate(platform); } } @@ -198,9 +198,9 @@ void PlanetariumViewTool::onUninstall(const ScenarioManager& scenario) targets_->removeChildren(0, targets_->getNumChildren()); // scenario has already removed us from the scenegraph - root_ = NULL; - targets_ = NULL; - dome_ = NULL; + root_ = nullptr; + targets_ = nullptr; + dome_ = nullptr; } void PlanetariumViewTool::onEntityAdd(const ScenarioManager& scenario, EntityNode* entity) diff --git a/SDK/simVis/Platform.cpp b/SDK/simVis/Platform.cpp index 0434dc157..04b674bad 100644 --- a/SDK/simVis/Platform.cpp +++ b/SDK/simVis/Platform.cpp @@ -84,7 +84,7 @@ class SetAxisLengthCallback : public osg::Callback virtual bool run(osg::Object* object, osg::Object* data) { AxisVector* vector = dynamic_cast(object); - if (vector != NULL && platform_.valid()) + if (vector != nullptr && platform_.valid()) { const float axisScale = platform_->getPrefs().axisscale(); const float lineLength = VectorScaling::lineLength(platform_->getModel(), axisScale); @@ -114,7 +114,7 @@ class SetCircleRadiusCallback : public osg::Callback { CompositeHighlightNode* area = dynamic_cast(object); // Scale down the radius by a small amount -- 80% -- to reduce highlight size - if (area != NULL && platform_.valid()) + if (area != nullptr && platform_.valid()) area->setRadius(VectorScaling::lineLength(platform_->getModel(), 0.8)); return traverse(object, data); } @@ -163,18 +163,18 @@ PlatformNode::PlatformNode(const simData::PlatformProperties& props, firstHistoryTime_(std::numeric_limits::max()), eciLocator_(eciLocator), expireModeGroupAttach_(expireModeGroupAttach), - track_(NULL), - timeTicks_(NULL), - localGrid_(NULL), - bodyAxisVector_(NULL), - inertialAxisVector_(NULL), + track_(nullptr), + timeTicks_(nullptr), + localGrid_(nullptr), + bodyAxisVector_(nullptr), + inertialAxisVector_(nullptr), scaledInertialTransform_(new PlatformInertialTransform), - velocityAxisVector_(NULL), - ephemerisVector_(NULL), - model_(NULL), - losCreator_(NULL), - opticalLosNode_(NULL), - radioLosNode_(NULL), + velocityAxisVector_(nullptr), + ephemerisVector_(nullptr), + model_(nullptr), + losCreator_(nullptr), + opticalLosNode_(nullptr), + radioLosNode_(nullptr), frontOffset_(0.0), valid_(false), lastPrefsValid_(false), @@ -209,14 +209,14 @@ PlatformNode::~PlatformNode() { if (track_.valid()) expireModeGroup_->removeChild(track_); - track_ = NULL; + track_ = nullptr; if (timeTicks_.valid()) expireModeGroup_->removeChild(timeTicks_); - timeTicks_ = NULL; + timeTicks_ = nullptr; if (expireModeGroupAttach_.valid()) expireModeGroupAttach_->removeChild(expireModeGroup_); - expireModeGroup_ = NULL; + expireModeGroup_ = nullptr; } void PlatformNode::setProperties(const simData::PlatformProperties& props) @@ -244,7 +244,7 @@ void PlatformNode::setRcsPrefs_(const simData::PlatformPrefs& prefs) if (!uri.empty()) { rcs_.reset(simCore::RcsFileParser::loadRCSFile(uri)); - if (rcs_ == NULL) + if (rcs_ == nullptr) { SIM_WARN << LC << "Failed to load RCS file \"" << uri << "\"" << std::endl; } @@ -275,28 +275,16 @@ void PlatformNode::setPrefs(const simData::PlatformPrefs& prefs) if (!lastPrefsValid_ || PB_FIELD_CHANGED((&lastPrefs_), (&prefs), ecidatamode)) { - if (prefs.ecidatamode()) - { - // for eci mode, platforms need to parent their EntityNode locator to the scenario ECI locator - if (!getLocator()->getParentLocator()) - getLocator()->setParentLocator(eciLocator_); - } - else if (getLocator()->getParentLocator() == eciLocator_) - { - // eci mode turned off, platform locator should not have a parent - getLocator()->setParentLocator(NULL); - getLocator()->setEciRotationTime(0., lastUpdateTime_, false); - } // on change of eci data mode, track and timeticks need to be completely recreated if (track_.valid()) { expireModeGroup_->removeChild(track_); - track_ = NULL; + track_ = nullptr; } if (timeTicks_.valid()) { expireModeGroup_->removeChild(timeTicks_); - timeTicks_ = NULL; + timeTicks_ = nullptr; } forceUpdateFromDataStore_ = true; } @@ -325,7 +313,7 @@ void PlatformNode::setPrefs(const simData::PlatformPrefs& prefs) else if (timeTicks_.valid()) { expireModeGroup_->removeChild(timeTicks_); - timeTicks_ = NULL; + timeTicks_ = nullptr; } if (!track_.valid()) @@ -362,10 +350,10 @@ void PlatformNode::setPrefs(const simData::PlatformPrefs& prefs) else { expireModeGroup_->removeChild(track_); - track_ = NULL; + track_ = nullptr; // time ticks is always hidden if track history is hidden expireModeGroup_->removeChild(timeTicks_); - timeTicks_ = NULL; + timeTicks_ = nullptr; } // validate localgrid prefs changes that might provide user notifications @@ -453,12 +441,6 @@ TrackHistoryNode* PlatformNode::getTrackHistory() void PlatformNode::updateLocator_(const simData::PlatformUpdate& u) { - if (u.time() != -1.0 && lastPrefs_.ecidatamode()) - { - // all non-static eci platforms get this corrective rotation; updates at current time should have a total rotation of 0 - getLocator()->setEciRotationTime(-u.time(), u.time(), false); - } - // static platforms by convention have elapsedEciTime 0 const simCore::Coordinate coord( simCore::COORD_SYS_ECEF, @@ -501,7 +483,7 @@ bool PlatformNode::updateFromDataStore(const simData::DataSliceBase* updateSlice } // in file mode, a platform is not valid until time reaches its first datapoint time. - // standard interfaces will return NULL or a sentinel value to indicate that the platform does not have a valid position. + // standard interfaces will return nullptr or a sentinel value to indicate that the platform does not have a valid position. // but there are cases where it is useful to know the position the platform will have when it becomes valid. // as an example, you may want to create a viewport to show the moment the platform becomes valid and starts to move. // to best show this, you want to be able to create the viewport's eyeposition based on that position in advance. @@ -591,7 +573,7 @@ bool PlatformNode::updateFromDataStore(const simData::DataSliceBase* updateSlice } else { - // a NULL update means the platform should be disabled + // a nullptr update means the platform should be disabled setInvalid_(); } @@ -617,12 +599,12 @@ bool PlatformNode::updateFromDataStore(const simData::DataSliceBase* updateSlice if (track_.valid()) { expireModeGroup_->removeChild(track_); - track_ = NULL; + track_ = nullptr; } if (timeTicks_.valid()) { expireModeGroup_->removeChild(timeTicks_); - timeTicks_ = NULL; + timeTicks_ = nullptr; } } // avoid applying a null update over and over @@ -686,10 +668,10 @@ bool PlatformNode::createTrackHistoryNode_(const simData::PlatformPrefs& prefs) if (prefs.ecidatamode()) { // trackhistory for an ECI platform gets a locator derived from the scenario ECI locator - // dev error to construct a platform with a NULL locator + // dev error to construct a platform with a nullptr locator assert(eciLocator_); if (eciLocator_) - track_ = new TrackHistoryNode(ds_, eciLocator_, platformTspiFilterManager_, getId()); + track_ = new TrackHistoryNode(ds_, eciLocator_.get(), platformTspiFilterManager_, getId()); } // trackhistory for platform in ecef datamode gets a new empty locator if (!track_.valid()) @@ -717,10 +699,10 @@ bool PlatformNode::createTimeTicks_(const simData::PlatformPrefs& prefs) if (prefs.ecidatamode()) { - // dev error to construct a platform with a NULL locator argument + // dev error to construct a platform with a nullptr locator argument assert(eciLocator_); if (eciLocator_) - timeTicks_ = new TimeTicks(ds_, eciLocator_, platformTspiFilterManager_, getId()); + timeTicks_ = new TimeTicks(ds_, eciLocator_.get(), platformTspiFilterManager_, getId()); } // for non-ECI platform use a new empty locator if (!timeTicks_.valid()) @@ -768,12 +750,12 @@ double PlatformNode::range() const const simData::PlatformUpdate* PlatformNode::update() const { - return isActive() ? &lastUpdate_ : NULL; + return isActive() ? &lastUpdate_ : nullptr; } const simData::PlatformUpdate* PlatformNode::labelUpdate() const { - return isActive() ? labelUpdate_(lastPrefs_) : NULL; + return isActive() ? labelUpdate_(lastPrefs_) : nullptr; } const std::string PlatformNode::getEntityName(EntityNode::NameType nameType, bool allowBlankAlias) const @@ -883,7 +865,7 @@ void PlatformNode::updateOrRemoveBodyAxis_(bool prefsDraw, const simData::Platfo else if (bodyAxisVector_.valid()) // remove if present { model_->removeScaledChild(bodyAxisVector_.get()); - bodyAxisVector_ = NULL; + bodyAxisVector_ = nullptr; } } @@ -905,7 +887,7 @@ void PlatformNode::updateOrRemoveInertialAxis_(bool prefsDraw, const simData::Pl else if (inertialAxisVector_.valid()) // remove if present { scaledInertialTransform_->removeChild(inertialAxisVector_); - inertialAxisVector_ = NULL; + inertialAxisVector_ = nullptr; } } @@ -928,7 +910,7 @@ void PlatformNode::updateOrRemoveVelocityVector_(bool prefsDraw, const simData:: else if (velocityAxisVector_.valid()) // remove if present { removeChild(velocityAxisVector_); - velocityAxisVector_ = NULL; + velocityAxisVector_ = nullptr; } } @@ -952,7 +934,7 @@ void PlatformNode::updateOrRemoveEphemerisVector_(bool prefsDraw, const simData: else if (ephemerisVector_.valid()) // remove if present { scaledInertialTransform_->removeChild(ephemerisVector_); - ephemerisVector_ = NULL; + ephemerisVector_ = nullptr; } } @@ -973,7 +955,7 @@ void PlatformNode::updateOrRemoveCircleHighlight_(bool prefsDraw, const simData: else if (highlight_.valid()) // remove if present { scaledInertialTransform_->removeChild(highlight_); - highlight_ = NULL; + highlight_ = nullptr; } } @@ -985,7 +967,7 @@ void PlatformNode::updateOrRemoveHorizons_(const simData::PlatformPrefs& prefs, void PlatformNode::updateOrRemoveHorizon_(simCore::HorizonCalculations horizonType, const simData::PlatformPrefs& prefs, bool force) { - RadialLOSNode* los = NULL; + RadialLOSNode* los = nullptr; bool drawHorizon = false; switch (horizonType) { @@ -1104,7 +1086,7 @@ void PlatformNode::updateOrRemoveHorizon_(simCore::HorizonCalculations horizonTy simCore::Coordinate losLlaCoord; converter.convert(losCoord, losLlaCoord, simCore::COORD_SYS_LLA); - rangeDist = simCore::calculateGroundDist(losLlaCoord.position(), platLlaCoord.position(), simCore::WGS_84, NULL); + rangeDist = simCore::calculateGroundDist(losLlaCoord.position(), platLlaCoord.position(), simCore::WGS_84, nullptr); altDist = fabs(losLlaCoord.alt() - platLlaCoord.alt()); } else diff --git a/SDK/simVis/Platform.h b/SDK/simVis/Platform.h index 70aafc073..ba7827408 100644 --- a/SDK/simVis/Platform.h +++ b/SDK/simVis/Platform.h @@ -83,7 +83,7 @@ class SDKVIS_EXPORT PlatformNode : public EntityNode const simData::DataStore& dataStore, PlatformTspiFilterManager& manager, osg::Group* expireModeGroupAttach, - Locator* eciLocator = NULL, + Locator* eciLocator = nullptr, int referenceYear = 1970); /** @@ -100,13 +100,13 @@ class SDKVIS_EXPORT PlatformNode : public EntityNode /** * The track history trail node - * @return track history node, or NULL if it doesn't exists yet + * @return track history node, or nullptr if it doesn't exists yet */ TrackHistoryNode* getTrackHistory(); /** - * Returns the Radar Cross Section of the platform. Can be NULL. - * @return the Radar Cross Section of the platform. Can be NULL. + * Returns the Radar Cross Section of the platform. Can be nullptr. + * @return the Radar Cross Section of the platform. Can be nullptr. */ simCore::RadarCrossSectionPtr getRcs() const; @@ -172,7 +172,7 @@ class SDKVIS_EXPORT PlatformNode : public EntityNode /** * Updates the entity based on the bound data store. - * @param updateSlice Data store update slice (could be NULL + * @param updateSlice Data store update slice (could be nullptr * @param force true to force the update to be applied; false only apply if logic dictates * @return true if update applied, false if not */ @@ -233,14 +233,14 @@ class SDKVIS_EXPORT PlatformNode : public EntityNode /** * Returns the last update for the platform; note this update has been filtered e.g. clamping has been applied - * @return the last update for the platform, or NULL if platform has no valid update + * @return the last update for the platform, or nullptr if platform has no valid update */ const simData::PlatformUpdate* update() const; /** * Returns the update valid for displaying current values in labels, which could be the actual values from the last unfiltered update, * or the filtered values, depending on the label prefs useValues field - * @return the current update for the platform, or NULL if platform has no valid update + * @return the current update for the platform, or nullptr if platform has no valid update */ const simData::PlatformUpdate* labelUpdate() const; diff --git a/SDK/simVis/PlatformAzimElevViewTool.cpp b/SDK/simVis/PlatformAzimElevViewTool.cpp index fa92fb7e7..36cd46d70 100644 --- a/SDK/simVis/PlatformAzimElevViewTool.cpp +++ b/SDK/simVis/PlatformAzimElevViewTool.cpp @@ -166,8 +166,8 @@ void PlatformAzimElevViewTool::onUninstall(const ScenarioManager& scenario) targets_->removeChildren(0, targets_->getNumChildren()); // scenario has already removed us from the scenegraph - root_ = NULL; - targets_ = NULL; + root_ = nullptr; + targets_ = nullptr; } bool PlatformAzimElevViewTool::isInstalled_() const diff --git a/SDK/simVis/PlatformModel.cpp b/SDK/simVis/PlatformModel.cpp index 87629e55c..3dcc276ec 100644 --- a/SDK/simVis/PlatformModel.cpp +++ b/SDK/simVis/PlatformModel.cpp @@ -57,7 +57,7 @@ namespace simVis { /** OSG Mask for traversal (like the select type in SIMDIS 9) */ -const int PlatformModelNode::TRAVERSAL_MASK = simVis::DISPLAY_MASK_PLATFORM_MODEL; +const unsigned int PlatformModelNode::TRAVERSAL_MASK = simVis::DISPLAY_MASK_PLATFORM_MODEL; /** Conversion factor to convert a brightness pref value (0-100) to an ambient light value (from S9) */ static const float BRIGHTNESS_TO_AMBIENT = 0.022f; /** Default brightness ambient value; 36 brightness is the default value */ @@ -100,7 +100,7 @@ class PlatformModelNode::SetModelCallback : public simVis::ModelCache::ModelRead * this => dynamicXform_ => imageIconXform_ <=> imageAlignmentXform_ => offsetXform_ => model_ * \= other scaled children * - * model_ is the representative for the 3D model or 2D image, and may be set to NULL at times. + * model_ is the representative for the 3D model or 2D image, and may be set to nullptr at times. * It is set from the call to simVis::Registry::instance()->getOrCreateIconModel(). * * The offsetXform_ handles transforms provided by the end user to orient and translate the model @@ -234,14 +234,14 @@ bool PlatformModelNode::addScaledChild(osg::Node* node) { // Scaled children go into the imageIconXform_, so that the orientation fixes // for the model do not accidentally swap the location/orientation of attachments - if (imageIconXform_ == NULL) + if (imageIconXform_ == nullptr) return false; return imageIconXform_->addChild(node); } bool PlatformModelNode::removeScaledChild(osg::Node* node) { - if (imageIconXform_ == NULL) + if (imageIconXform_ == nullptr) return false; return imageIconXform_->removeChild(node); } @@ -269,7 +269,7 @@ bool PlatformModelNode::updateModel_(const simData::PlatformPrefs& prefs) const simVis::Registry* registry = simVis::Registry::instance(); if (prefs.icon().empty()) - setModel(NULL, false); + setModel(nullptr, false); else if (!registry->isMemoryCheck()) { // Find the fully qualified URI @@ -301,7 +301,7 @@ void PlatformModelNode::setModel(osg::Node* newModel, bool isImage) if (lastSetModelCallback_.valid()) { lastSetModelCallback_->ignoreResult(); - lastSetModelCallback_ = NULL; + lastSetModelCallback_ = nullptr; } isImageModel_ = isImage; @@ -311,13 +311,13 @@ void PlatformModelNode::setModel(osg::Node* newModel, bool isImage) { offsetXform_->removeChild(model_); alphaVolumeGroup_->removeChild(model_); - model_ = NULL; - dynamicXform_->setSizingNode(NULL); + model_ = nullptr; + dynamicXform_->setSizingNode(nullptr); } // if the new properties say "no model", we're done model_ = newModel; - if (newModel != NULL) + if (newModel != nullptr) { // Set render order by setting render bin. We set the OVERRIDE flag in case the model has renderbins set inside of it. // Note that osg::Depth settings are not changed here, but are instead dealt with inside updateImageDepth_() call below. @@ -527,7 +527,7 @@ bool PlatformModelNode::updateScale_(const simData::PlatformPrefs& prefs) bool PlatformModelNode::updateScaleXyz_(const simData::PlatformPrefs& prefs) { - // By default scalexyz is NULL. It is used to override the scale preference which is defaulted to 1. When uninitialized, it should not override the scale pref. + // By default scalexyz is nullptr. It is used to override the scale preference which is defaulted to 1. When uninitialized, it should not override the scale pref. if (!prefs.has_scalexyz() || (lastPrefsValid_ && !PB_FIELD_CHANGED(&lastPrefs_, &prefs, scalexyz))) return false; @@ -650,7 +650,7 @@ void PlatformModelNode::updateRCS_(const simData::PlatformPrefs& prefs) { // remove it imageIconXform_->removeChild(rcs_.get()); - rcs_ = NULL; + rcs_ = nullptr; } if (rcs_.valid()) diff --git a/SDK/simVis/PlatformModel.h b/SDK/simVis/PlatformModel.h index 30a02ec32..e39ac962c 100644 --- a/SDK/simVis/PlatformModel.h +++ b/SDK/simVis/PlatformModel.h @@ -45,7 +45,7 @@ class RCSNode; class SDKVIS_EXPORT PlatformModelNode : public LocatorNode { public: - static const int TRAVERSAL_MASK; + static const unsigned int TRAVERSAL_MASK; /** Interface for activity callbacks. */ class Callback : public osg::Referenced @@ -71,7 +71,7 @@ class SDKVIS_EXPORT PlatformModelNode : public LocatorNode * Constructs a new platform model node. * @param locator Parent locator from which to inherit position/orientation */ - PlatformModelNode(Locator* locator = NULL); + PlatformModelNode(Locator* locator = nullptr); /** * Gets the bounds of the 3D model, possible scaled diff --git a/SDK/simVis/PolygonStipple.cpp b/SDK/simVis/PolygonStipple.cpp index f74c5e4b5..f4ae8df36 100644 --- a/SDK/simVis/PolygonStipple.cpp +++ b/SDK/simVis/PolygonStipple.cpp @@ -286,7 +286,7 @@ void PolygonStipple::setFfpStipplePattern_(osg::StateSet* stateSet, unsigned int void PolygonStipple::setValues(osg::StateSet* stateset, bool enabled, unsigned int patternIndex) { - if (stateset == NULL) + if (stateset == nullptr) return; // Limit the pattern index diff --git a/SDK/simVis/Popup.cpp b/SDK/simVis/Popup.cpp index 0ee8b7232..e414bb5f4 100644 --- a/SDK/simVis/Popup.cpp +++ b/SDK/simVis/Popup.cpp @@ -124,7 +124,7 @@ osgEarth::Util::Controls::LabelControl* EntityPopup::contentLabel() const // -------------------------------------------------------------------------- -/** Finds the first non-NULL instance of type T in the node path provided */ +/** Finds the first non-nullptr instance of type T in the node path provided */ template T* findNodeInPath(const osg::NodePath& path) { @@ -133,13 +133,13 @@ T* findNodeInPath(const osg::NodePath& path) if (dynamic_cast(*i)) return static_cast(*i); } - return NULL; + return nullptr; } // -------------------------------------------------------------------------- PopupHandler::PopupHandler(SceneManager* scene, View* view) - : scenario_(scene ? scene->getScenario() : NULL), + : scenario_(scene ? scene->getScenario() : nullptr), view_(view) { init_(); @@ -185,12 +185,12 @@ void PopupHandler::clear() { if (currentEntity_.valid()) { - currentEntity_ = NULL; + currentEntity_ = nullptr; if (popup_.valid() && (view_.valid())) { view_->removeOverlayControl(popup_.get()); } - popup_ = NULL; + popup_ = nullptr; entityLocatorRev_.reset(); } } @@ -363,7 +363,7 @@ void PopupHandler::updatePopupFromView(simVis::View* currentView) { view_->removeOverlayControl(popup_.get()); } - popup_ = NULL; + popup_ = nullptr; currentEntity_ = entity; entityLocatorRev_.reset(); } @@ -386,7 +386,7 @@ void PopupHandler::updatePopupFromView(simVis::View* currentView) { auto platform = dynamic_cast(currentEntity_.get()); // Prefer the content callback over the entity's method - if (contentCallback_.valid() && platform != NULL) + if (contentCallback_.valid() && platform != nullptr) { popup_->setContent(contentCallback_->createString(platform)); } diff --git a/SDK/simVis/Popup.h b/SDK/simVis/Popup.h index b18913300..b984ff188 100644 --- a/SDK/simVis/Popup.h +++ b/SDK/simVis/Popup.h @@ -129,7 +129,7 @@ namespace simVis * @param scene Scene under which this object operates * @param view View on which to show the popup */ - explicit PopupHandler(SceneManager* scene, View* view = NULL); + explicit PopupHandler(SceneManager* scene, View* view = nullptr); /// set whether pop-ups are enabled (or not) void enable(bool v = true); diff --git a/SDK/simVis/Projector.cpp b/SDK/simVis/Projector.cpp index b353dfd37..b912fdfdb 100644 --- a/SDK/simVis/Projector.cpp +++ b/SDK/simVis/Projector.cpp @@ -26,6 +26,7 @@ #include "osg/Notify" #include "osgDB/ReadFile" #include "osgUtil/CullVisitor" +#include "osgEarth/EllipsoidIntersector" #include "osgEarth/Horizon" #include "simNotify/Notify.h" @@ -36,6 +37,7 @@ #include "simVis/EntityLabel.h" #include "simVis/LabelContentManager.h" #include "simVis/Locator.h" +#include "simVis/LocatorNode.h" #include "simVis/Platform.h" #include "simVis/ProjectorManager.h" #include "simVis/Registry.h" @@ -44,11 +46,11 @@ #include "simVis/Utils.h" #include "simVis/Projector.h" +namespace +{ static const double DEFAULT_PROJECTOR_FOV_IN_DEG = 45.0; static const float DEFAULT_ALPHA_VALUE = 0.1f; -namespace -{ // draws the geometry of the projection frustum. // (NOTE: some of this code is borrowed from OSG's osgthirdpersonview example) void makeFrustum(const osg::Matrixd& proj, const osg::Matrixd& mv, osg::MatrixTransform* mt) @@ -174,29 +176,37 @@ void ProjectorTextureImpl::setTexture(osg::Texture2D *texture) //------------------------------------------------------------------- ProjectorNode::ProjectorNode(const simData::ProjectorProperties& props, simVis::Locator* hostLocator, const simVis::EntityNode* host) - : EntityNode(simData::PROJECTOR, hostLocator), - lastProps_(props), - host_(host), - hasLastUpdate_(false), - hasLastPrefs_(false), - projectorTextureImpl_(new ProjectorTextureImpl()) + : EntityNode(simData::PROJECTOR, new Locator()), + lastProps_(props), + host_(host), + hostLocator_(hostLocator), + hasLastUpdate_(false), + hasLastPrefs_(false), + projectorTextureImpl_(new ProjectorTextureImpl()) { init_(); } ProjectorNode::~ProjectorNode() { - getLocator()->removeCallback(locatorCallback_.get()); + if (hostLocator_.valid()) + hostLocator_.get()->removeCallback(locatorCallback_.get()); } void ProjectorNode::init_() { - // listen for locator changes so we can update the matrices - locatorCallback_ = new simVis::SyncLocatorCallback(this); - getLocator()->addCallback(locatorCallback_.get()); + // create the locator node that will support tethering and host/position the label. + projectorLocatorNode_ = new LocatorNode(getLocator()); + projectorLocatorNode_->setEntityToMonitor(this); + addChild(projectorLocatorNode_); + + // projector is inactive until prefs and updates make it active + setNodeMask(DISPLAY_MASK_NONE); - // Set this node to be active - setNodeMask(DISPLAY_MASK_PROJECTOR); + // listen for host locator changes so we can update the matrices + locatorCallback_ = new simVis::SyncLocatorCallback(this); + if (hostLocator_.valid()) + hostLocator_.get()->addCallback(locatorCallback_.get()); // Create matrix transform node that houses graphics frustum and set the node mask to off graphics_ = new osg::MatrixTransform(); @@ -225,14 +235,13 @@ void ProjectorNode::init_() projectorTextureImpl_->setTexture(texture_.get()); - label_ = new EntityLabelNode(getLocator()); - addChild(label_); - // labels are culled based on entity center point + label_ = new EntityLabelNode(); + projectorLocatorNode_->addChild(label_); + // labels are positioned on ellipsoid, culled based on label center point osgEarth::HorizonCullCallback* callback = new osgEarth::HorizonCullCallback(); callback->setCullByCenterPointOnly(true); // SIM-11395 - set default ellipsoid, when osgEarth supports it //callback->setHorizon(new osgEarth::Horizon(*getLocator()->getSRS()->getEllipsoid())); - callback->setProxyNode(this); label_->addCullCallback(callback); } @@ -255,13 +264,14 @@ void ProjectorNode::updateLabel_(const simData::ProjectorPrefs& prefs) label += text; } - const float zOffset = 0.0f; + // projector label is typically set to intersection of projector with ellipsoid, so an offset is needed + const float zOffset = 1.0f; label_->update(prefs.commonprefs(), label, zOffset); } const simData::ProjectorUpdate* ProjectorNode::getLastUpdateFromDS() const { - return hasLastUpdate_ ? &lastUpdate_ : NULL; + return hasLastUpdate_ ? &lastUpdate_ : nullptr; } void ProjectorNode::addUniforms(osg::StateSet* stateSet) const @@ -392,11 +402,11 @@ void ProjectorNode::updateOverrideColor_(const simData::ProjectorPrefs& prefs) bool ProjectorNode::readVideoFile_(const std::string& filename) { - osg::Node* result = NULL; + osg::Node* result = nullptr; // Make sure we have the clock which is needed for the video node. simCore::Clock* clock = simVis::Registry::instance()->getClock(); - if (clock != NULL) + if (clock) { osg::ref_ptr options = new simVis::ClockOptions(clock); options->setPluginData("ProjectorTextureProvider", projectorTextureImpl_.get()); @@ -460,7 +470,7 @@ void ProjectorNode::loadRequestedFile_(const std::string& newFilename) void ProjectorNode::setImage(osg::Image* image) { // Reset video node if one is set. - imageProvider_ = NULL; + imageProvider_ = nullptr; texture_->setImage(image); simVis::fixTextureForGlCoreProfile(texture_.get()); } @@ -488,11 +498,19 @@ double ProjectorNode::getVFOV() const return DEFAULT_PROJECTOR_FOV_IN_DEG; } -void ProjectorNode::getMatrices_(osg::Matrixd& projection, osg::Matrixd& locatorMat, osg::Matrixd& modelView) +void ProjectorNode::getMatrices_(osg::Matrixd& projection, osg::Matrixd& locatorMat, osg::Matrixd& modelView) const { const double ar = static_cast(texture_->getImage()->s()) / texture_->getImage()->t(); projection.makePerspective(getVFOV(), ar, 1.0, 1e7); - getLocator()->getLocatorMatrix(locatorMat); + if (hostLocator_.valid()) + { + hostLocator_.get()->getLocatorMatrix(locatorMat); + } + else + { + // it is believed that the host locator cannot go missing + assert(0); + } modelView.invert(locatorMat); } @@ -507,16 +525,16 @@ void ProjectorNode::syncWithLocator() // which means the projector will point straight down by default (since the view vector // is -Z in view space). We want the projector to point along the entity vector, so // we create a view matrix that rotates the view to point along the +Y axis. - const osg::Matrix viewMat = osg::Matrix::rotate(-osg::PI_2, osg::Vec3d(1.0, 0.0, 0.0)); + const osg::Matrix& viewMat = osg::Matrix::rotate(-osg::PI_2, osg::Vec3d(1.0, 0.0, 0.0)); // flip the image if it's upside down const double flip = texture_->getImage()->getOrigin() == osg::Image::TOP_LEFT ? -1.0 : 1.0; // construct the model view matrix: - const osg::Matrix modelViewMat = modelMat * viewMat; + const osg::Matrix& modelViewMat = modelMat * viewMat; // the coordinate generator for our projected texture - - // during traversal, multiple the inverse view matrix by this + // during traversal, multiply the inverse view matrix by this // matrix to set a texture projection uniform that transform // verts from view space to texture space texGenMatrix_ = @@ -531,12 +549,44 @@ void ProjectorNode::syncWithLocator() texProjPosUniform_->set(osg::Vec3f(eye)); texProjDirUniform_->set(osg::Vec3f(cen-eye)); + // determine the best available position for the projector + double eciRefTime = 0.; + double time = 0.; + simCore::Vec3 hostPos; + // obtain current time and eci ref time from host + if (hostLocator_.valid()) + { + const Locator* loc = hostLocator_.get(); + eciRefTime = loc->getEciRefTime(); + time = loc->getTime(); + } + // if ellipsoid intersection can be calculated, use that result as the projector position + osg::Vec3d ellipsoidIntersection; + if (calculator_->intersectLine(eye, cen, ellipsoidIntersection)) + { + const simCore::Vec3& intersection = convertToSim(ellipsoidIntersection); + const simCore::Coordinate projPosition(simCore::COORD_SYS_ECEF, intersection); + getLocator()->setCoordinate(projPosition, time, eciRefTime); + } + else + { + // default to "Null Island" if ellipsoid intersection is not calculable; but use host position if it is available + simCore::Vec3 hostPosEcef(simCore::EARTH_RADIUS, 0., 0.); + if (hostLocator_.valid()) + hostLocator_->getLocatorPosition(&hostPosEcef); + const simCore::Coordinate projPosition(simCore::COORD_SYS_ECEF, hostPosEcef); + getLocator()->setCoordinate(projPosition, time, eciRefTime); + } + // update the frustum geometry makeFrustum(projectionMat, modelViewMat, graphics_); } bool ProjectorNode::isActive() const { + // Projector is "active" when it has datadraw, and a valid update, + // and can be active even if draw is off; + // that means: projector maintains valid internal state even if draw is off. return hasLastUpdate_ && hasLastPrefs_ && lastPrefs_.commonprefs().datadraw(); } @@ -581,7 +631,7 @@ bool ProjectorNode::updateFromDataStore(const simData::DataSliceBase* updateSlic if (updateSlice->hasChanged() || force ||hostChangedToActive || hostChangedToInactive) { const simData::ProjectorUpdate* current = updateSlice->current(); - const bool projectorChangedToInactive = (current == NULL && hasLastUpdate_); + const bool projectorChangedToInactive = (!current && hasLastUpdate_); // do not apply update if host is not active if (current && (force || host_->isActive())) @@ -633,6 +683,20 @@ double ProjectorNode::range() const return 0.0; } +int ProjectorNode::getPosition(simCore::Vec3* out_position, simCore::CoordinateSystem coordsys) const +{ + if (!isActive()) + return 1; + return projectorLocatorNode_->getPosition(out_position, coordsys); +} + +int ProjectorNode::getPositionOrientation(simCore::Vec3* out_position, simCore::Vec3* out_orientation, simCore::CoordinateSystem coordsys) const +{ + if (!isActive()) + return 1; + return projectorLocatorNode_->getPositionOrientation(out_position, out_orientation, coordsys); +} + void ProjectorNode::traverse(osg::NodeVisitor& nv) { EntityNode::traverse(nv); @@ -644,6 +708,11 @@ unsigned int ProjectorNode::objectIndexTag() const return 0; } +void ProjectorNode::setCalculator(std::shared_ptr calculator) +{ + calculator_ = calculator; +} + void ProjectorNode::addProjectionToNode(osg::Node* node) { if (!node) return; @@ -678,7 +747,8 @@ void ProjectorNode::addProjectionToNode(osg::Node* node) void ProjectorNode::removeProjectionFromNode(osg::Node* node) { - if (!node) return; + if (!node) + return; osg::StateSet* stateSet = node->getStateSet(); if (stateSet) diff --git a/SDK/simVis/Projector.h b/SDK/simVis/Projector.h index 9bc868161..3c2404d5c 100644 --- a/SDK/simVis/Projector.h +++ b/SDK/simVis/Projector.h @@ -22,17 +22,18 @@ */ #ifndef SIMVIS_PROJECTOR_H #define SIMVIS_PROJECTOR_H - +#include #include "simData/DataTypes.h" #include "simVis/Constants.h" #include "simVis/Entity.h" namespace osg { class Texture2D; } - +namespace osgEarth { namespace Util { class EllipsoidIntersector; } } namespace simVis { - class EntityLabelNode; - struct LocatorCallback; +class EntityLabelNode; +struct LocatorCallback; +class LocatorNode; /** Projector video interface on the MediaPlayer2 side */ class ProjectorTexture : public osg::Referenced @@ -77,10 +78,9 @@ class SDKVIS_EXPORT ProjectorNode : public EntityNode /** * Construct a new node that projects an image or video on to the terrain. */ - ProjectorNode( - const simData::ProjectorProperties& props, - simVis::Locator* hostLocator, - const simVis::EntityNode* host = NULL); + ProjectorNode(const simData::ProjectorProperties& props, + simVis::Locator* hostLocator, + const simVis::EntityNode* host = nullptr); /** * Gets the last known properties of this object @@ -107,7 +107,7 @@ class SDKVIS_EXPORT ProjectorNode : public EntityNode const osg::Matrixd& getTexGenMatrix() const { return texGenMatrix_; } /** - * Gets a pointer to the last data store update, or NULL if + * Gets a pointer to the last data store update, or nullptr if * none have been applied. */ const simData::ProjectorUpdate* getLastUpdateFromDS() const; @@ -117,6 +117,30 @@ class SDKVIS_EXPORT ProjectorNode : public EntityNode /// Remove projector uniforms from the given StateSet void removeUniforms(osg::StateSet* stateSet) const; + /// Set the calculator that can calculate the projector's ellipsoid intersection + void setCalculator(std::shared_ptr calculator); + + /** Configure a node to accept the texture projected by this projector */ + void addProjectionToNode(osg::Node* node); + + /** Remove the setup configured by addProjectionToNode */ + void removeProjectionFromNode(osg::Node* node); + + /** + * Get the traversal mask for this node type + * @return a traversal mask + */ + static unsigned int getMask() { return simVis::DISPLAY_MASK_PROJECTOR; } + + /** + * Updates the projection uniforms. This called automatically when the locator moves; you + * do not need to call it directly. + */ + void syncWithLocator(); + + /** Traverse the node during visitor pattern */ + virtual void traverse(osg::NodeVisitor& nv) override; + public: // EntityNode interface /** * Whether the entity is active within the scenario at the current time. @@ -124,21 +148,12 @@ class SDKVIS_EXPORT ProjectorNode : public EntityNode * current scenario time, and has not received a command to turn off * @return true if active; false if not */ - virtual bool isActive() const; + virtual bool isActive() const override; /** * Whether this entity is visible. */ - virtual bool isVisible() const; - - /** - * Get the object ID of the beam rendered by this node - * @return object ID - */ - virtual simData::ObjectId getId() const; - - /** Get the projector's host's ID */ - virtual bool getHostId(simData::ObjectId& out_hostId) const; + virtual bool isVisible() const override; /** * Returns the entity name. Can be used to get the actual name always or the @@ -148,62 +163,56 @@ class SDKVIS_EXPORT ProjectorNode : public EntityNode * @param allowBlankAlias If true DISPLAY_NAME will return blank if usealias is true and alias is blank * @return actual/alias entity name string */ - virtual const std::string getEntityName(EntityNode::NameType nameType, bool allowBlankAlias = false) const; + virtual const std::string getEntityName(EntityNode::NameType nameType, bool allowBlankAlias = false) const override; /// Returns the pop up text based on the label content callback, update and preference - virtual std::string popupText() const; + virtual std::string popupText() const override; /// Returns the hook text based on the label content callback, update and preference - virtual std::string hookText() const; + virtual std::string hookText() const override; /// Returns the legend text based on the label content callback, update and preference - virtual std::string legendText() const; + virtual std::string legendText() const override; + + /** This entity type is, at this time, unpickable. */ + virtual unsigned int objectIndexTag() const override; + + /** @copydoc EntityNode::getPosition() */ + virtual int getPosition(simCore::Vec3* out_position, simCore::CoordinateSystem coordsys = simCore::COORD_SYS_ECEF) const override; + + /** @copydoc EntityNode::getPositionOrientation() */ + virtual int getPositionOrientation(simCore::Vec3* out_position, simCore::Vec3* out_orientation, + simCore::CoordinateSystem coordsys = simCore::COORD_SYS_ECEF) const override; + + /** + * Get the object ID of the beam rendered by this node + * @return object ID + */ + virtual simData::ObjectId getId() const override; + + /** Get the projector's host's ID */ + virtual bool getHostId(simData::ObjectId& out_hostId) const override; /** * Updates the entity based on the bound data store. - * @param updateSlice Data store update slice (could be NULL) + * @param updateSlice Data store update slice (could be nullptr) * @param force true to force the update to be applied; false allows entity to use its own internal logic to decide whether the update should be applied * @return true if update applied, false if not */ - virtual bool updateFromDataStore(const simData::DataSliceBase* updateSlice, bool force = false); + virtual bool updateFromDataStore(const simData::DataSliceBase* updateSlice, bool force = false) override; /** * Flushes all the entity's data point visualization. */ - virtual void flush(); + virtual void flush() override; /** * Returns a range value (meters) used for visualization. Will return zero for platforms and projectors. */ - virtual double range() const; - - /** This entity type is, at this time, unpickable. */ - virtual unsigned int objectIndexTag() const; - - /** Configure a node to accept the texture projected by this projector */ - void addProjectionToNode(osg::Node* node); - - /** Remove the setup configured by addProjectionToNode */ - void removeProjectionFromNode(osg::Node* node); - - /** - * Get the traversal mask for this node type - * @return a traversal mask - */ - static unsigned int getMask() { return simVis::DISPLAY_MASK_PROJECTOR; } + virtual double range() const override; /** Return the proper library name */ - virtual const char* libraryName() const { return "simVis"; } + virtual const char* libraryName() const override { return "simVis"; } /** Return the class name */ - virtual const char* className() const { return "ProjectorNode"; } - -public: - /** - * Updates the projection uniforms. This called automatically when the locator moves; you - * do not need to call it directly. - */ - void syncWithLocator(); - - /** Traverse the node during visitor pattern */ - virtual void traverse(osg::NodeVisitor& nv); + virtual const char* className() const override { return "ProjectorNode"; } protected: /// osg::Referenced-derived; destructor body needs to be in the .cpp @@ -213,14 +222,36 @@ class SDKVIS_EXPORT ProjectorNode : public EntityNode /** Copy constructor, not implemented or available. */ ProjectorNode(const ProjectorNode&); - simData::ProjectorProperties lastProps_; - simData::ProjectorPrefs lastPrefs_; - simData::ProjectorUpdate lastUpdate_; + void getMatrices_( + osg::Matrixd& out_projection, + osg::Matrixd& out_locator, + osg::Matrixd& out_modelView) const; + + void init_(); + + /// Read video file + bool readVideoFile_(const std::string& filename); + /// Read raster file + bool readRasterFile_(const std::string& filename); + /// Load new file + void loadRequestedFile_(const std::string& newFilename); + + /// Update label + void updateLabel_(const simData::ProjectorPrefs& prefs); + /// Update override color + void updateOverrideColor_(const simData::ProjectorPrefs& prefs); + + + simData::ProjectorProperties lastProps_; + simData::ProjectorPrefs lastPrefs_; + simData::ProjectorUpdate lastUpdate_; osg::observer_ptr host_; - osg::ref_ptr locatorCallback_; + osg::observer_ptr hostLocator_; ///< locator that tracks the projector origin + osg::ref_ptr locatorCallback_; ///< notifies when projector host (& origin) has moved + osg::ref_ptr projectorLocatorNode_; ///< locator node that tracks the projector/ellipsoid intersection osg::ref_ptr label_; - bool hasLastUpdate_; - bool hasLastPrefs_; + bool hasLastUpdate_; + bool hasLastPrefs_; osg::Matrixd texGenMatrix_; osg::ref_ptr texture_; @@ -239,25 +270,7 @@ class SDKVIS_EXPORT ProjectorNode : public EntityNode osg::ref_ptr colorOverrideUniform_; osg::ref_ptr projectOnNodeCallback_; - - void getMatrices_( - osg::Matrixd& out_projection, - osg::Matrixd& out_locator, - osg::Matrixd& out_modelView); - - void init_(); - - /// Read video file - bool readVideoFile_(const std::string& filename); - /// Read raster file - bool readRasterFile_(const std::string& filename); - /// Load new file - void loadRequestedFile_(const std::string& newFilename); - - /// Update label - void updateLabel_(const simData::ProjectorPrefs& prefs); - /// Update override color - void updateOverrideColor_(const simData::ProjectorPrefs& prefs); + std::shared_ptr calculator_; }; } //namespace simVis diff --git a/SDK/simVis/ProjectorManager.cpp b/SDK/simVis/ProjectorManager.cpp index 2e5caaec9..82e665da6 100644 --- a/SDK/simVis/ProjectorManager.cpp +++ b/SDK/simVis/ProjectorManager.cpp @@ -23,6 +23,7 @@ #include "osg/Depth" #include "osg/BlendFunc" #include "osgUtil/CullVisitor" +#include "osgEarth/EllipsoidIntersector" #include "osgEarth/StringUtils" #include "osgEarth/TerrainEngineNode" #include "osgEarth/VirtualProgram" @@ -53,6 +54,7 @@ simData::ObjectId ProjectorManager::ProjectorLayer::id() const return id_; } +//------------------------------------------------------------------------- /** * Cull callback for a projector layer that will update the * texture projection matrix. Since we need the inverse view @@ -70,9 +72,12 @@ class UpdateProjMatrix : public osgEarth::Layer::TraversalCallback void operator()(osg::Node* node, osg::NodeVisitor* nv) const { + osg::ref_ptr proj; + if (!proj_.lock(proj) || !proj.valid()) + return; osgUtil::CullVisitor* cv = dynamic_cast(nv); osg::ref_ptr ss = new osg::StateSet(); - osg::Matrixf projMat = cv->getCurrentCamera()->getInverseViewMatrix() * proj_->getTexGenMatrix(); + const osg::Matrixf& projMat = cv->getCurrentCamera()->getInverseViewMatrix() * proj->getTexGenMatrix(); ss->addUniform(new osg::Uniform("simProjTexGenMat", projMat)); cv->pushStateSet(ss.get()); traverse(node, nv); @@ -80,9 +85,10 @@ class UpdateProjMatrix : public osgEarth::Layer::TraversalCallback } private: - osg::ref_ptr proj_; + osg::observer_ptr proj_; }; +//------------------------------------------------------------------------- /** * A class to listen to the map for new layers being added */ @@ -103,11 +109,18 @@ class ProjectorManager::MapListener : public osgEarth::MapCallback ProjectorManager& manager_; }; +//------------------------------------------------------------------------- + ProjectorManager::ProjectorManager() : needReorderProjectorLayers_(false) { setCullingActive(false); mapListener_ = new MapListener(*this); + + // using osg default WGS-84 ellipsoid + const osg::EllipsoidModel wgs84EllipsoidModel; + // Passing address of a temporary, but it's OK because it's not retained by EllipsoidIntersector + ellipsoidIntersector_ = std::make_shared(&wgs84EllipsoidModel); } ProjectorManager::~ProjectorManager() @@ -195,6 +208,9 @@ void ProjectorManager::registerProjector(ProjectorNode* proj) projStateSet->setTextureAttribute(PROJECTOR_TEXTURE_UNIT, proj->getTexture()); proj->addUniforms(projStateSet); + + // provide the calculator to the projector so that the projector can calc its ellipsoid point + proj->setCalculator(ellipsoidIntersector_); } void ProjectorManager::unregisterProjector(const ProjectorNode* proj) diff --git a/SDK/simVis/ProjectorManager.h b/SDK/simVis/ProjectorManager.h index 7fd683986..eb3237e7f 100644 --- a/SDK/simVis/ProjectorManager.h +++ b/SDK/simVis/ProjectorManager.h @@ -28,10 +28,16 @@ #include "simCore/Common/Common.h" #include "simData/ObjectId.h" +namespace osgEarth +{ + namespace Util { class EllipsoidIntersector; } +} namespace simVis { class ProjectorNode; +//------------------------------------------------------------------------- + /** Responsible for managing projectors in the scene */ class ProjectorManager : public osg::Group, public osgEarth::MapNodeObserver { @@ -118,6 +124,9 @@ class ProjectorManager : public osg::Group, public osgEarth::MapNodeObserver class MapListener; osg::ref_ptr mapListener_; + /// A class that provides calculation services to projectors + std::shared_ptr ellipsoidIntersector_; + /// A flag to mark when projector layers need to be moved to ensure visibility bool needReorderProjectorLayers_; }; diff --git a/SDK/simVis/RCS.cpp b/SDK/simVis/RCS.cpp index 6c3eac2a4..d12094738 100644 --- a/SDK/simVis/RCS.cpp +++ b/SDK/simVis/RCS.cpp @@ -128,7 +128,7 @@ void RCSNode::setRcs(simCore::RadarCrossSectionPtr newRcs) void RCSNode::rebuild() { - loadedOK_ = (rcsData_ != NULL) ? true : false; + loadedOK_ = (rcsData_ != nullptr) ? true : false; this->removeChildren(0, this->getNumChildren()); if (rcsData_ && (lastPrefs_->drawrcs() || lastPrefs_->draw3drcs())) @@ -164,7 +164,7 @@ RCSRenderer::RCSRenderer(double frequency, float detail, const osg::Vec4& color, bool colorOverride) : - rcs_(NULL), + rcs_(nullptr), polarity_(polarity), freq_(frequency), elev_(elevation), @@ -220,8 +220,8 @@ void RCSRenderer::renderRcs_() } else { - rcs3D_ = NULL; - rcs2D_ = NULL; + rcs3D_ = nullptr; + rcs2D_ = nullptr; } } diff --git a/SDK/simVis/RFProp/ArepsLoader.cpp b/SDK/simVis/RFProp/ArepsLoader.cpp index 935626a79..ba3421f5b 100644 --- a/SDK/simVis/RFProp/ArepsLoader.cpp +++ b/SDK/simVis/RFProp/ArepsLoader.cpp @@ -24,6 +24,7 @@ #include "osgDB/FileUtils" #include "simCore/LUT/LUT2.h" #include "simCore/Calc/Angle.h" +#include "simCore/Calc/Math.h" #include "simCore/Common/Version.h" #include "simCore/String/Tokenizer.h" #include "simCore/String/Format.h" @@ -416,7 +417,7 @@ int ArepsLoader::loadFile(const std::string& arepsFile, simRF::Profile& profile, // PODProfileDataProvider depends on the loss provider const simRF::ProfileDataProvider* lossProvider = profile.getDataProvider()->getProvider(ProfileDataProvider::THRESHOLDTYPE_LOSS); - if (beamHandler_ != NULL && lossProvider) + if (beamHandler_ != nullptr && lossProvider) { osg::ref_ptr podProvider = new PODProfileDataProvider(lossProvider, beamHandler_->getPODLossThreshold()); profile.addProvider(podProvider.get()); @@ -429,15 +430,17 @@ int ArepsLoader::loadFile(const std::string& arepsFile, simRF::Profile& profile, // create providers that depend on the PPF provider const simRF::ProfileDataProvider* ppfProvider = profile.getDataProvider()->getProvider(ProfileDataProvider::THRESHOLDTYPE_FACTOR); - if (beamHandler_ != NULL && ppfProvider) + if (beamHandler_ != nullptr && ppfProvider) { - profile.addProvider(new OneWayPowerDataProvider(ppfProvider, beamHandler_->radarParams())); + osg::ref_ptr oneWayPowerDataProvider = new OneWayPowerDataProvider(ppfProvider, beamHandler_->radarParams()); + profile.addProvider(oneWayPowerDataProvider.get()); osg::ref_ptr twoWayPowerDataProvider = new TwoWayPowerDataProvider(ppfProvider, beamHandler_->radarParams()); profile.addProvider(twoWayPowerDataProvider.get()); // SNRDataProvider depends on TwoWayPowerDataProvider - profile.addProvider(new SNRDataProvider(twoWayPowerDataProvider.get(), beamHandler_->radarParams())); + osg::ref_ptr snrDataProvider = new SNRDataProvider(twoWayPowerDataProvider.get(), beamHandler_->radarParams()); + profile.addProvider(snrDataProvider.get()); } else if (!ppfProvider) { @@ -446,7 +449,7 @@ int ArepsLoader::loadFile(const std::string& arepsFile, simRF::Profile& profile, } // determine if CNR data is available - if (profile.getDataProvider()->getProvider(simRF::ProfileDataProvider::THRESHOLDTYPE_CNR) == NULL) + if (profile.getDataProvider()->getProvider(simRF::ProfileDataProvider::THRESHOLDTYPE_CNR) == nullptr) { missingData += missingData.empty() ? "CNR" : ", CNR"; missingCalcs += missingCalcs.empty() ? "CNR" : ", CNR"; diff --git a/SDK/simVis/RFProp/ArepsLoader.h b/SDK/simVis/RFProp/ArepsLoader.h index e19c89eee..389ca86e1 100644 --- a/SDK/simVis/RFProp/ArepsLoader.h +++ b/SDK/simVis/RFProp/ArepsLoader.h @@ -42,7 +42,7 @@ class SDKVIS_EXPORT ArepsLoader * if no RFPropagationFacade instance is provided, only PPF and Loss providers are supported * @param beamHandler ptr to a RFPropagationFacade instance */ - ArepsLoader(RFPropagationFacade* beamHandler = NULL); + ArepsLoader(RFPropagationFacade* beamHandler = nullptr); ~ArepsLoader(); /** diff --git a/SDK/simVis/RFProp/BearingProfileMap.cpp b/SDK/simVis/RFProp/BearingProfileMap.cpp index f6f5c04b8..8ad620d8c 100644 --- a/SDK/simVis/RFProp/BearingProfileMap.cpp +++ b/SDK/simVis/RFProp/BearingProfileMap.cpp @@ -74,7 +74,7 @@ double BearingProfileMap::getSlotBearing(double bearingR) const Profile* BearingProfileMap::getProfileByBearing(double bearingR) const { BearingProfileMap::const_iterator itr = getSlot_(bearingR); - return (itr != profiles_.end()) ? itr->second.get() : NULL; + return (itr != profiles_.end()) ? itr->second.get() : nullptr; } BearingProfileMap::const_iterator BearingProfileMap::getSlot_(double bearingR) const diff --git a/SDK/simVis/RFProp/BearingProfileMap.h b/SDK/simVis/RFProp/BearingProfileMap.h index ee5a966b2..5f9db83ba 100644 --- a/SDK/simVis/RFProp/BearingProfileMap.h +++ b/SDK/simVis/RFProp/BearingProfileMap.h @@ -54,7 +54,7 @@ class SDKVIS_EXPORT BearingProfileMap /** * Retrieve the profile for the specified bearing * @param bearingR bearing in radians - * @return profile at specified bearing, or NULL if none + * @return profile at specified bearing, or nullptr if none */ Profile* getProfileByBearing(double bearingR) const; diff --git a/SDK/simVis/RFProp/CompositeColorProvider.cpp b/SDK/simVis/RFProp/CompositeColorProvider.cpp index 6537fef3b..75e55bc25 100644 --- a/SDK/simVis/RFProp/CompositeColorProvider.cpp +++ b/SDK/simVis/RFProp/CompositeColorProvider.cpp @@ -185,7 +185,7 @@ void CompositeColorProvider::install(osg::StateSet* stateset) void CompositeColorProvider::uninstall(osg::StateSet* stateset) { - lastStateSet_ = NULL; + lastStateSet_ = nullptr; if (colorMode_ == COLORMODE_GRADIENT) gradientProvider_->uninstall(stateset); else diff --git a/SDK/simVis/RFProp/CompositeProfileProvider.cpp b/SDK/simVis/RFProp/CompositeProfileProvider.cpp index d795c418e..35eb5a149 100644 --- a/SDK/simVis/RFProp/CompositeProfileProvider.cpp +++ b/SDK/simVis/RFProp/CompositeProfileProvider.cpp @@ -43,7 +43,7 @@ int CompositeProfileProvider::getActiveProviderIndex() const const ProfileDataProvider* CompositeProfileProvider::getActiveProvider() const { - return (activeIndex_ != -1) ? providers_[activeIndex_].get() : NULL; + return (activeIndex_ != -1) ? providers_[activeIndex_].get() : nullptr; } int CompositeProfileProvider::setActiveProvider(int index) @@ -84,7 +84,7 @@ const ProfileDataProvider* CompositeProfileProvider::getProvider(ProfileDataProv return providers_[i].get(); } } - return NULL; + return nullptr; } unsigned int CompositeProfileProvider::getNumProviders() const @@ -130,7 +130,7 @@ double CompositeProfileProvider::getMaxRange() const // some providers may not have height information, so these methods use heightProviderIndex_ to find a provider that does have that info unsigned int CompositeProfileProvider::getHeightIndex(double heightM) const { - const ProfileDataProvider* provider = (heightProviderIndex_ != -1) ? providers_[heightProviderIndex_].get() : NULL; + const ProfileDataProvider* provider = (heightProviderIndex_ != -1) ? providers_[heightProviderIndex_].get() : nullptr; // No provider? error out if (!provider) return INVALID_HEIGHT_INDEX; diff --git a/SDK/simVis/RFProp/FunctionalProfileDataProvider.cpp b/SDK/simVis/RFProp/FunctionalProfileDataProvider.cpp index 4769e0a87..009d2f46d 100644 --- a/SDK/simVis/RFProp/FunctionalProfileDataProvider.cpp +++ b/SDK/simVis/RFProp/FunctionalProfileDataProvider.cpp @@ -33,7 +33,7 @@ FunctionalProfileDataProvider::FunctionalProfileDataProvider(const ProfileDataPr FunctionalProfileDataProvider::~FunctionalProfileDataProvider() { - templateProvider_ = NULL; + templateProvider_ = nullptr; } unsigned int FunctionalProfileDataProvider::getNumRanges() const diff --git a/SDK/simVis/RFProp/LUT1ProfileDataProvider.cpp b/SDK/simVis/RFProp/LUT1ProfileDataProvider.cpp index 9f7356e85..6263f5da7 100644 --- a/SDK/simVis/RFProp/LUT1ProfileDataProvider.cpp +++ b/SDK/simVis/RFProp/LUT1ProfileDataProvider.cpp @@ -61,7 +61,7 @@ LUT1ProfileDataProvider::LUT1ProfileDataProvider(simCore::LUT::LUT1 *lut, { // LUT1ProfileDataProvider is taking ownership of the lut assert(lut); - if (lut == NULL) + if (lut == nullptr) { SIM_ERROR << "Attempting to assign a NULL LUT to the LUT1ProfileDataProvider" << std::endl; } @@ -73,7 +73,7 @@ LUT1ProfileDataProvider::LUT1ProfileDataProvider(simCore::LUT::LUT1 *lut, { // LUT1ProfileDataProvider is taking ownership of the lut assert(lut); - if (lut == NULL) + if (lut == nullptr) { SIM_ERROR << "Attempting to assign a NULL LUT to the LUT1ProfileDataProvider" << std::endl; } diff --git a/SDK/simVis/RFProp/LUTProfileDataProvider.cpp b/SDK/simVis/RFProp/LUTProfileDataProvider.cpp index 4de858272..1ad462cb0 100644 --- a/SDK/simVis/RFProp/LUTProfileDataProvider.cpp +++ b/SDK/simVis/RFProp/LUTProfileDataProvider.cpp @@ -32,7 +32,7 @@ LUTProfileDataProvider::LUTProfileDataProvider(simCore::LUT::LUT2 *lut, d { // LUTProfileDataProvider is taking ownership of the lut assert(lut); - if (lut == NULL) + if (lut == nullptr) { SIM_ERROR << "Attempting to assign a NULL LUT to the LUTProfileDataProvider" << std::endl; } @@ -44,7 +44,7 @@ LUTProfileDataProvider::LUTProfileDataProvider(simCore::LUT::LUT2 *lut, P { // LUTProfileDataProvider is taking ownership of the lut assert(lut); - if (lut == NULL) + if (lut == nullptr) { SIM_ERROR << "Attempting to assign a NULL LUT to the LUTProfileDataProvider" << std::endl; } diff --git a/SDK/simVis/RFProp/Profile.cpp b/SDK/simVis/RFProp/Profile.cpp index d3c7d3b38..b93b4fc61 100644 --- a/SDK/simVis/RFProp/Profile.cpp +++ b/SDK/simVis/RFProp/Profile.cpp @@ -27,11 +27,11 @@ #include "osgEarth/PointDrawable" #include "osgEarth/NodeUtils" #include "simCore/Calc/Angle.h" -#include "simCore/Calc/Calculations.h" #include "simCore/Calc/Interpolation.h" #include "simVis/Constants.h" #include "simVis/Utils.h" #include "simVis/RFProp/CompositeProfileProvider.h" +#include "simVis/RFProp/ProfileContext.h" #include "simVis/RFProp/Profile.h" namespace simRF { @@ -111,7 +111,7 @@ void Profile::setDataProvider(CompositeProfileProvider* dataProvider) { data_ = dataProvider; // if providers change, null the texture to force it to recreate (if necessary) - texture_ = NULL; + texture_ = nullptr; dirty(); } } @@ -122,7 +122,7 @@ void Profile::setProfileContext(std::shared_ptr profileContext) if (profileContext_) { // ensure that this profile matches the shared context - setThresholdType(profileContext->type_); + setThresholdType(profileContext->type); dirty(); } } @@ -132,7 +132,7 @@ void Profile::setThresholdType(ProfileDataProvider::ThresholdType type) if (data_.valid()) data_->setActiveProvider(type); // null the texture to force it to recreate - texture_ = NULL; + texture_ = nullptr; dirty(); } @@ -165,19 +165,19 @@ void Profile::init_() verts_ = new osg::Vec3Array(osg::Array::BIND_PER_VERTEX); values_ = new osg::FloatArray(osg::Array::BIND_PER_VERTEX); values_->setNormalize(false); - group_ = NULL; + group_ = nullptr; if (!profileContext_) return; - if (profileContext_->mode_ != DRAWMODE_3D_TEXTURE) - texture_ = NULL; + if (profileContext_->mode != DRAWMODE_3D_TEXTURE) + texture_ = nullptr; // ensure that our provider is valid - if (data_.valid() && data_->getActiveProvider() != NULL) + if (data_.valid() && data_->getActiveProvider() != nullptr) { group_ = new osg::Group; - switch (profileContext_->mode_) + switch (profileContext_->mode) { case DRAWMODE_2D_HORIZONTAL: init2DHoriz_(); @@ -223,18 +223,9 @@ float Profile::getTerrainHgt_(float gndRng) const return value; } -void Profile::adjustSpherical_(osg::Vec3& v, const simCore::Vec3& tpSphereXYZ) +double Profile::adjustHeight_(double x, double y, double z) const { - if (!profileContext_) - { - // dev error; can't init a profile without a profileContext_ - assert(0); - return; - } - simCore::Vec3 sphereXYZ; - simCore::tangentPlane2Sphere(profileContext_->refLLA_, simCore::Vec3(v[0], v[1], v[2]), sphereXYZ, &tpSphereXYZ); - const double alt = v3Length(sphereXYZ) - simCore::EARTH_RADIUS; - v.z() = v.z() - (alt - v.z()) + profileContext_->refLLA_.alt(); + return profileContext_ ? profileContext_->adjustHeight(simCore::Vec3(x, y, z)) : z; } void Profile::init2DHoriz_() @@ -249,7 +240,7 @@ void Profile::init2DHoriz_() const double rangeStep = data_->getRangeStep(); const double numRanges = data_->getNumRanges(); const unsigned int startIndex = verts_->size(); - unsigned int heightIndex = data_->getHeightIndex(profileContext_->heightM_); + unsigned int heightIndex = data_->getHeightIndex(profileContext_->heightM); // Error check the height index if (heightIndex == CompositeProfileProvider::INVALID_HEIGHT_INDEX || heightIndex > (data_->getNumHeights() - 1)) { @@ -261,16 +252,13 @@ void Profile::init2DHoriz_() verts_->reserve(2 * numRanges); values_->reserve(2 * numRanges); - simCore::Vec3 tpSphereXYZ; - simCore::geodeticToSpherical(profileContext_->refLLA_.lat(), profileContext_->refLLA_.lon(), profileContext_->refLLA_.alt(), tpSphereXYZ); - // init the flag that indicates whether this profile has seen valid data bool validDataStarted = false; for (unsigned int i = 0; i < numRanges; i++) { const double range = minRange + rangeStep * i; - double height = profileContext_->heightM_; - if (profileContext_->agl_ && !terrainHeights_.empty()) + double height = profileContext_->heightM; + if (profileContext_->agl && !terrainHeights_.empty()) { height += getTerrainHgt_(static_cast(range)); heightIndex = data_->getHeightIndex(height); @@ -296,17 +284,12 @@ void Profile::init2DHoriz_() validDataStarted = true; } + // use one height adjustment for both vertices + height = adjustHeight_(range * cosTheta0_, range * sinTheta0_, height); // Left vert - osg::Vec3 v0(range * cosTheta0_, range * sinTheta0_, height); + const osg::Vec3f v0(range * cosTheta0_, range * sinTheta0_, height); // Right vert - osg::Vec3 v1(range * cosTheta1_, range * sinTheta1_, height); - - if (profileContext_->sphericalEarth_) - { - adjustSpherical_(v0, tpSphereXYZ); - adjustSpherical_(v1, tpSphereXYZ); - } - + const osg::Vec3f v1(range * cosTheta1_, range * sinTheta1_, height); verts_->push_back(v1); verts_->push_back(v0); values_->push_back(value); @@ -386,9 +369,6 @@ void Profile::init2DVert_() // if assert fails, check that init_ ensures that we have a valid provider assert(numHeights > 0); - simCore::Vec3 tpSphereXYZ; - simCore::geodeticToSpherical(profileContext_->refLLA_.lat(), profileContext_->refLLA_.lon(), profileContext_->refLLA_.alt(), tpSphereXYZ); - // 2DVert draw mode can be combined with 2DHorz mode; cache the starting point for vertices relevant to this draw mode const unsigned int startIndex = verts_->size(); const unsigned int numVerts = numHeights * numRanges; @@ -401,16 +381,9 @@ void Profile::init2DVert_() for (unsigned int h = 0; h < numHeights; h++) { - const double height = minHeight + heightStep * h; - osg::Vec3 v(0., range, height); - - if (profileContext_->sphericalEarth_) - { - adjustSpherical_(v, tpSphereXYZ); - } - + const double height = adjustHeight_(0., range, minHeight + heightStep * h); + const osg::Vec3 v(0., range, height); verts_->push_back(v); - const float value = data_->getValueByIndex(h, r); values_->push_back(value); } @@ -453,7 +426,7 @@ void Profile::init3D_() return; //Build a 3D voxel representation of the profile. The minimum height is specified by the height_ setting and the maximum height is the height_ + the display thickness - unsigned int minHeightIndex = data_->getHeightIndex(profileContext_->heightM_); + unsigned int minHeightIndex = data_->getHeightIndex(profileContext_->heightM); // Error check the height index if (minHeightIndex == CompositeProfileProvider::INVALID_HEIGHT_INDEX) { @@ -463,7 +436,7 @@ void Profile::init3D_() } minHeightIndex = osg::clampBetween(minHeightIndex, 0u, numHeights - 1); - unsigned int maxHeightIndex = simCore::sdkMin(minHeightIndex + profileContext_->displayThickness_, numHeights - 1); + unsigned int maxHeightIndex = simCore::sdkMin(minHeightIndex + profileContext_->displayThickness, numHeights - 1); //If we have no valid thickness assume they want to just display a single voxel if (minHeightIndex == maxHeightIndex) { @@ -485,9 +458,6 @@ void Profile::init3D_() return; } - simCore::Vec3 tpSphereXYZ; - simCore::geodeticToSpherical(profileContext_->refLLA_.lat(), profileContext_->refLLA_.lon(), profileContext_->refLLA_.alt(), tpSphereXYZ); - const unsigned int heightIndexCount = maxHeightIndex - minHeightIndex + 1; const unsigned int numVerts = 2 * heightIndexCount * numRanges; verts_->reserve(numVerts); @@ -504,21 +474,14 @@ void Profile::init3D_() for (unsigned int h = minHeightIndex; h <= maxHeightIndex; h++) { - const double height = minHeight + heightStep * h; + // use one height adjustment for both vertices + const double height = adjustHeight_(x0, y0, minHeight + heightStep * h); //Left vert - osg::Vec3 v0(x0, y0, height); + const osg::Vec3 v0(x0, y0, height); //Right vert - osg::Vec3 v1(x1, y1, height); - - if (profileContext_->sphericalEarth_) - { - adjustSpherical_(v0, tpSphereXYZ); - adjustSpherical_(v1, tpSphereXYZ); - } - + const osg::Vec3 v1(x1, y1, height); verts_->push_back(v0); verts_->push_back(v1); - const double value = data_->getValueByIndex(h, r); values_->push_back(value); values_->push_back(value); @@ -605,7 +568,7 @@ void Profile::init3DTexture_() assert(numHeights > 0); //Build a 3D voxel representation of the profile. The minimum height is specified by the height_ setting and the maximum height is the height_ + the display thickness - unsigned int minHeightIndex = data_->getHeightIndex(profileContext_->heightM_); + unsigned int minHeightIndex = data_->getHeightIndex(profileContext_->heightM); // Error check the height index if (minHeightIndex == CompositeProfileProvider::INVALID_HEIGHT_INDEX) { @@ -615,11 +578,9 @@ void Profile::init3DTexture_() } minHeightIndex = osg::clampBetween(minHeightIndex, 0u, numHeights - 1); - unsigned int maxHeightIndex = simCore::sdkMin(minHeightIndex + profileContext_->displayThickness_, numHeights - 1); + unsigned int maxHeightIndex = simCore::sdkMin(minHeightIndex + profileContext_->displayThickness, numHeights - 1); // TODO: determine how to support spherical earth like other draw modes - //simCore::Vec3 tpSphereXYZ; - //simCore::geodeticToSpherical(refCoord_.lat(), refCoord_.lon(), refCoord_.alt(), tpSphereXYZ); //If we have no valid thickness assume they want to just display a single voxel if (minHeightIndex == maxHeightIndex) @@ -819,7 +780,7 @@ void Profile::init3DTexture_() } // Only create the texture if it doesn't already exist, otherwise you can just reuse it - if (texture_ == NULL) + if (texture_ == nullptr) { texture_ = new osg::Texture2D(createImage_()); texture_->setResizeNonPowerOfTwoHint(false); @@ -849,7 +810,7 @@ void Profile::init3DPoints_() assert(numHeights > 0); //Build a 3D voxel representation of the profile. The minimum height is specified by the height_ setting and the maximum height is the height_ + the display thickness - unsigned int minHeightIndex = data_->getHeightIndex(profileContext_->heightM_); + unsigned int minHeightIndex = data_->getHeightIndex(profileContext_->heightM); // Error check the height index if (minHeightIndex == CompositeProfileProvider::INVALID_HEIGHT_INDEX) { @@ -859,7 +820,7 @@ void Profile::init3DPoints_() } minHeightIndex = osg::clampBetween(minHeightIndex, 0u, numHeights - 1); - unsigned int maxHeightIndex = simCore::sdkMin(minHeightIndex + profileContext_->displayThickness_, numHeights - 1); + unsigned int maxHeightIndex = simCore::sdkMin(minHeightIndex + profileContext_->displayThickness, numHeights - 1); //If we have no valid thickness assume they want to just display a single voxel if (minHeightIndex == maxHeightIndex) { @@ -881,9 +842,6 @@ void Profile::init3DPoints_() return; } - simCore::Vec3 tpSphereXYZ; - simCore::geodeticToSpherical(profileContext_->refLLA_.lat(), profileContext_->refLLA_.lon(), profileContext_->refLLA_.alt(), tpSphereXYZ); - const unsigned int numVerts = (maxHeightIndex - minHeightIndex + 1) * numRanges; values_->reserve(numVerts); @@ -902,12 +860,8 @@ void Profile::init3DPoints_() if (value <= AREPS_GROUND_VALUE) continue; - const double height = minHeight + heightStep * h; - osg::Vec3 v(0, range, height); - if (profileContext_->sphericalEarth_) - { - adjustSpherical_(v, tpSphereXYZ); - } + const double height = adjustHeight_(0, range, minHeight + heightStep * h); + const osg::Vec3 v(0, range, height); points->pushVertex(v); values_->push_back(value); } @@ -925,7 +879,7 @@ osg::Image* Profile::createImage_() { // dev error; can't init a profile without valid active provider assert(0); - return NULL; + return nullptr; } const unsigned int numRanges = data_->getNumRanges(); const unsigned int numHeights = data_->getNumHeights(); @@ -1147,7 +1101,7 @@ class Profile::RaeVoxelProcessor : public Profile::RahVoxelProcessor //---------------------------------------------------------------------------- -int Profile::buildVoxel_(VoxelProcessor& vProcessor, const simCore::Vec3& tpSphereXYZ, unsigned int rangeIndex, osg::Geometry* geometry) +int Profile::buildVoxel_(VoxelProcessor& vProcessor, unsigned int rangeIndex, osg::Geometry* geometry) { VoxelProcessor::VoxelRange voxelRange; VoxelProcessor::VoxelHeight nearVoxelHeight; @@ -1188,13 +1142,10 @@ int Profile::buildVoxel_(VoxelProcessor& vProcessor, const simCore::Vec3& tpSphe //v0, v1 values_->push_back(value01); values_->push_back(value01); - osg::Vec3 v0(voxelRange.valNear * cosTheta0_, voxelRange.valNear * sinTheta0_, nearVoxelHeight.valBottom); // Near right - osg::Vec3 v1(voxelRange.valNear * cosTheta1_, voxelRange.valNear * sinTheta1_, nearVoxelHeight.valBottom); // Near left - if (profileContext_->sphericalEarth_) - { - adjustSpherical_(v0, tpSphereXYZ); - adjustSpherical_(v1, tpSphereXYZ); - } + // use one height adjustment for both vertices + const double adjustedHeight = adjustHeight_(voxelRange.valNear * cosTheta0_, voxelRange.valNear * sinTheta0_, nearVoxelHeight.valBottom); + const osg::Vec3 v0(voxelRange.valNear * cosTheta0_, voxelRange.valNear * sinTheta0_, adjustedHeight); // Near right + const osg::Vec3 v1(voxelRange.valNear * cosTheta1_, voxelRange.valNear * sinTheta1_, adjustedHeight); // Near left verts_->push_back(v0); verts_->push_back(v1); } @@ -1205,13 +1156,10 @@ int Profile::buildVoxel_(VoxelProcessor& vProcessor, const simCore::Vec3& tpSphe //v2, v3 values_->push_back(value23); values_->push_back(value23); - osg::Vec3 v2(voxelRange.valFar * cosTheta1_, voxelRange.valFar * sinTheta1_, farVoxelHeight.valBottom); // Far left - osg::Vec3 v3(voxelRange.valFar * cosTheta0_, voxelRange.valFar * sinTheta0_, farVoxelHeight.valBottom); // Far right - if (profileContext_->sphericalEarth_) - { - adjustSpherical_(v2, tpSphereXYZ); - adjustSpherical_(v3, tpSphereXYZ); - } + // use one height adjustment for both vertices + double adjustedHeight = adjustHeight_(voxelRange.valFar * cosTheta1_, voxelRange.valFar * sinTheta1_, farVoxelHeight.valBottom); + const osg::Vec3 v2(voxelRange.valFar * cosTheta1_, voxelRange.valFar * sinTheta1_, adjustedHeight); // Far left + const osg::Vec3 v3(voxelRange.valFar * cosTheta0_, voxelRange.valFar * sinTheta0_, adjustedHeight); // Far right verts_->push_back(v2); verts_->push_back(v3); const unsigned int i2 = startIndex++; @@ -1223,13 +1171,10 @@ int Profile::buildVoxel_(VoxelProcessor& vProcessor, const simCore::Vec3& tpSphe //v4, v5 values_->push_back(value45); values_->push_back(value45); - osg::Vec3 v4(voxelRange.valNear * cosTheta0_, voxelRange.valNear * sinTheta0_, nearVoxelHeight.valTop); // Near right - osg::Vec3 v5(voxelRange.valNear * cosTheta1_, voxelRange.valNear * sinTheta1_, nearVoxelHeight.valTop); // Near left - if (profileContext_->sphericalEarth_) - { - adjustSpherical_(v4, tpSphereXYZ); - adjustSpherical_(v5, tpSphereXYZ); - } + // use one height adjustment for both vertices + const double adjustedHeight = adjustHeight_(voxelRange.valNear * cosTheta0_, voxelRange.valNear * sinTheta0_, nearVoxelHeight.valTop); + const osg::Vec3 v4(voxelRange.valNear * cosTheta0_, voxelRange.valNear * sinTheta0_, adjustedHeight); // Near right + const osg::Vec3 v5(voxelRange.valNear * cosTheta1_, voxelRange.valNear * sinTheta1_, adjustedHeight); // Near left verts_->push_back(v4); verts_->push_back(v5); } @@ -1240,13 +1185,10 @@ int Profile::buildVoxel_(VoxelProcessor& vProcessor, const simCore::Vec3& tpSphe //v6, v7 values_->push_back(value67); values_->push_back(value67); - osg::Vec3 v6(voxelRange.valFar * cosTheta1_, voxelRange.valFar * sinTheta1_, farVoxelHeight.valTop); // Far left - osg::Vec3 v7(voxelRange.valFar * cosTheta0_, voxelRange.valFar * sinTheta0_, farVoxelHeight.valTop); // Far right - if (profileContext_->sphericalEarth_) - { - adjustSpherical_(v6, tpSphereXYZ); - adjustSpherical_(v7, tpSphereXYZ); - } + // use one height adjustment for both vertices + adjustedHeight = adjustHeight_(voxelRange.valFar * cosTheta1_, voxelRange.valFar * sinTheta1_, farVoxelHeight.valTop); + const osg::Vec3 v6(voxelRange.valFar * cosTheta1_, voxelRange.valFar * sinTheta1_, adjustedHeight); // Far left + const osg::Vec3 v7(voxelRange.valFar * cosTheta0_, voxelRange.valFar * sinTheta0_, adjustedHeight); // Far right verts_->push_back(v6); verts_->push_back(v7); const unsigned int i6 = startIndex++; @@ -1299,13 +1241,10 @@ void Profile::initRAE_() assert(0); return; } - RahVoxelProcessor vProcessor(*(data_.get()), profileContext_->heightM_); + RahVoxelProcessor vProcessor(*(data_.get()), profileContext_->heightM); if (!vProcessor.isValid()) return; - simCore::Vec3 tpSphereXYZ; - simCore::geodeticToSpherical(profileContext_->refLLA_.lat(), profileContext_->refLLA_.lon(), profileContext_->refLLA_.alt(), tpSphereXYZ); - const unsigned int numRanges = data_->getNumRanges(); const size_t numVoxels = (numRanges - 1); const size_t vertsPerVoxel = 8; @@ -1318,7 +1257,7 @@ void Profile::initRAE_() for (unsigned int r = 0; r < (numRanges - 1); ++r) { // build voxel that spans from rangeIndex r to rangeIndex r+1 - const int rv = buildVoxel_(vProcessor, tpSphereXYZ, r, geometry); + const int rv = buildVoxel_(vProcessor, r, geometry); if (rv != 0) break; } diff --git a/SDK/simVis/RFProp/Profile.h b/SDK/simVis/RFProp/Profile.h index 87c4bcac9..e21fed1ff 100644 --- a/SDK/simVis/RFProp/Profile.h +++ b/SDK/simVis/RFProp/Profile.h @@ -27,14 +27,14 @@ #include #include "osg/MatrixTransform" #include "simCore/Common/Common.h" -#include "simCore/Calc/Vec3.h" -#include "simCore/Calc/Math.h" #include "simVis/RFProp/ColorProvider.h" #include "simVis/RFProp/ProfileDataProvider.h" +namespace simCore { class DatumConvert; } namespace simRF { class CompositeProfileProvider; +struct ProfileContext; /** Responsible for rendering a single profile of data. */ class SDKVIS_EXPORT Profile : public osg::MatrixTransform @@ -58,30 +58,6 @@ class SDKVIS_EXPORT Profile : public osg::MatrixTransform DRAWMODE_RAE, }; - /** Display context that all profiles share; owned by the ProfileManager */ - struct ProfileContext - { - ProfileContext() - : refLLA_(0., 0., 0.), - heightM_(0), - elevAngleR_(0.), - displayThickness_(1), - mode_(Profile::DRAWMODE_2D_HORIZONTAL), - type_(simRF::ProfileDataProvider::THRESHOLDTYPE_NONE), - agl_(false), - sphericalEarth_(true) // SIM-11515 - determine what data sources require this - {} - - simCore::Vec3 refLLA_; ///< Reference coordinate used for coordinate conversion used in the visualization, in radians and meters - double heightM_; ///< 2D Horizontal display height, in meters - double elevAngleR_; ///< elevation angle used in the current display, in radians - unsigned int displayThickness_; ///< display thickness for 3D displays, in # height steps - Profile::DrawMode mode_; ///< Type of display, e.g. 2D, 3D - ProfileDataProvider::ThresholdType type_; ///< threshold type selected for display, e.g., POD, SNR, CNR - bool agl_; ///< whether height values for the 2D Horizontal display are referenced to height above ground level (AGL) or to mean sea level (MSL). - bool sphericalEarth_; ///< whether the profile data are specified for spherical or WGS84 earth - }; - /** Adds a ProfileDataProvider to our CompositeProfileProvider */ void addProvider(ProfileDataProvider* provider); @@ -163,13 +139,13 @@ class SDKVIS_EXPORT Profile : public osg::MatrixTransform class RaeVoxelProcessor; /** Creates a voxel (volume pixel) at the given location */ - int buildVoxel_(VoxelProcessor& vProcessor, const simCore::Vec3& tpSphereXYZ, unsigned int rangeIndex, osg::Geometry* geometry); + int buildVoxel_(VoxelProcessor& vProcessor, unsigned int rangeIndex, osg::Geometry* geometry); /** Fixes the orientation of the profile */ void updateOrientation_(); - /** Adjusts point height if it was originally based on spherical XYZ */ - void adjustSpherical_(osg::Vec3& v, const simCore::Vec3& tpSphereXYZ); + /** Adjusts point height if it was originally based on spherical XYZ or MSL */ + double adjustHeight_(double x, double y, double z) const; /** Tesselate the 2D Vertical with triangle strip */ void tesselate2DVert_(unsigned int numRanges, unsigned int numHeights, unsigned int startIndex, osg::ref_ptr values, osg::Geometry* geometry) const; diff --git a/SDK/simVis/RFProp/ProfileContext.cpp b/SDK/simVis/RFProp/ProfileContext.cpp new file mode 100644 index 000000000..b598d10c9 --- /dev/null +++ b/SDK/simVis/RFProp/ProfileContext.cpp @@ -0,0 +1,78 @@ +/* -*- mode: c++ -*- */ +/**************************************************************************** + ***** ***** + ***** Classification: UNCLASSIFIED ***** + ***** Classified By: ***** + ***** Declassify On: ***** + ***** ***** + **************************************************************************** + * + * + * Developed by: Naval Research Laboratory, Tactical Electronic Warfare Div. + * EW Modeling & Simulation, Code 5773 + * 4555 Overlook Ave. + * Washington, D.C. 20375-5339 + * + * License for source code can be found at: + * https://github.com/USNavalResearchLaboratory/simdissdk/blob/master/LICENSE.txt + * + * The U.S. Government retains all rights to use, duplicate, distribute, + * disclose, or release this software. + * + */ +#include "simCore/Calc/Calculations.h" +#include "simCore/Calc/DatumConvert.h" +#include "simCore/Calc/Math.h" +#include "simCore/Time/TimeClass.h" +#include "simVis/RFProp/ProfileContext.h" + +namespace simRF { + +ProfileContext::ProfileContext(std::shared_ptr datumConvert) + : heightM(0.), + elevAngleR(0.), + displayThickness(1), + mode(Profile::DRAWMODE_2D_HORIZONTAL), + type(simRF::ProfileDataProvider::THRESHOLDTYPE_NONE), + agl(false), + sphericalEarth(true), + datumConvert_(datumConvert) +{ +} + +void ProfileContext::setRefLla(const simCore::Vec3& lla) +{ + refLla = lla; + coordConvert_.setReferenceOrigin(refLla); + simCore::geodeticToSpherical(refLla.lat(), refLla.lon(), refLla.alt(), tpSphereXYZ_); +} + +double ProfileContext::adjustHeight(const simCore::Vec3& xEast) const +{ + if (sphericalEarth) + { + // heights are offsets in meters to a spherical tangent plane at the reflla + simCore::Vec3 sphereXYZ; + simCore::tangentPlane2Sphere(refLla, xEast, sphereXYZ, &tpSphereXYZ_); + const double altAboveSphere = v3Length(sphereXYZ) - simCore::EARTH_RADIUS; + return xEast.z() + refLla.alt() - (altAboveSphere - xEast.z()); + } + + // heights in data are MSL or AGL and need to be converted to HAE height for the scenegraph + // AGL not implemented + if (datumConvert_.get()) + { + // determine lla at x,y offset from reflla + simCore::Coordinate out; + simCore::Coordinate in(simCore::COORD_SYS_XEAST, xEast); + coordConvert_.convert(in, out, simCore::COORD_SYS_LLA); + + // determine conversion from MSL to HAE, force use of EGM96 + const double mslToHaeM = datumConvert_->convertVerticalDatum(simCore::Vec3(out.lat(), out.lon(), 0.), simCore::TimeStamp(1996, 0.), + simCore::COORD_SYS_LLA, simCore::VERTDATUM_MSL, simCore::VERTDATUM_WGS84, 0.); + return xEast.z() + mslToHaeM; + } + return xEast.z(); +} + +} diff --git a/SDK/simVis/RFProp/ProfileContext.h b/SDK/simVis/RFProp/ProfileContext.h new file mode 100644 index 000000000..a0797d391 --- /dev/null +++ b/SDK/simVis/RFProp/ProfileContext.h @@ -0,0 +1,60 @@ +/* -*- mode: c++ -*- */ +/**************************************************************************** + ***** ***** + ***** Classification: UNCLASSIFIED ***** + ***** Classified By: ***** + ***** Declassify On: ***** + ***** ***** + **************************************************************************** + * + * + * Developed by: Naval Research Laboratory, Tactical Electronic Warfare Div. + * EW Modeling & Simulation, Code 5773 + * 4555 Overlook Ave. + * Washington, D.C. 20375-5339 + * + * License for source code can be found at: + * https://github.com/USNavalResearchLaboratory/simdissdk/blob/master/LICENSE.txt + * + * The U.S. Government retains all rights to use, duplicate, distribute, + * disclose, or release this software. + * + */ +#ifndef SIMVIS_RFPROP_PROFILE_CONTEXT_H +#define SIMVIS_RFPROP_PROFILE_CONTEXT_H + +#include +#include "osg/Vec3f" +#include "simCore/Calc/CoordinateConverter.h" +#include "simVis/RFProp/Profile.h" + +namespace simCore { class DatumConvert; } +namespace simRF +{ +/** Display context that all profiles share */ +struct ProfileContext +{ +public: + explicit ProfileContext(std::shared_ptr datumConvert); + + void setRefLla(const simCore::Vec3& refLla); + + /// returns wgs84 height of point at specified xEast offset from the refLla + double adjustHeight(const simCore::Vec3& xEast) const; + + simCore::Vec3 refLla; ///< Reference coordinate used for coordinate conversion used in the visualization, in radians and meters + double heightM; ///< display height, in meters + double elevAngleR; ///< elevation angle used in the current display, in radians + unsigned int displayThickness; ///< display thickness for 3D displays, in # height steps + Profile::DrawMode mode; ///< Type of display, e.g. 2D, 3D + ProfileDataProvider::ThresholdType type; ///< threshold type selected for display, e.g., POD, SNR, CNR + bool agl; ///< whether height values for the 2D Horizontal display are referenced to height above ground level (AGL) or to mean sea level (MSL). + bool sphericalEarth; ///< whether the profile data are specified for spherical or WGS84 earth + +private: + std::shared_ptr datumConvert_; ///< provides MSL data for height correction + simCore::CoordinateConverter coordConvert_; ///< converts datapoint enu values to LLA for datum + simCore::Vec3 tpSphereXYZ_; ///< refLLA converted to spherical earth +}; +} +#endif diff --git a/SDK/simVis/RFProp/ProfileManager.cpp b/SDK/simVis/RFProp/ProfileManager.cpp index a002489c7..0a5e7bb6e 100644 --- a/SDK/simVis/RFProp/ProfileManager.cpp +++ b/SDK/simVis/RFProp/ProfileManager.cpp @@ -30,17 +30,18 @@ #include "simVis/RFProp/BearingProfileMap.h" #include "simVis/RFProp/ColorProvider.h" #include "simVis/RFProp/CompositeProfileProvider.h" +#include "simVis/RFProp/ProfileContext.h" #include "simVis/RFProp/ProfileManager.h" namespace simRF { -ProfileManager::ProfileManager() +ProfileManager::ProfileManager(std::shared_ptr datumConvert) : simVis::LocatorNode(new simVis::Locator()), history_(15.0 * simCore::DEG2RAD), - bearing_(0), + bearing_(0.), alpha_(1.f), displayOn_(false), - profileContext_(std::make_shared()) + profileContext_(std::make_shared(datumConvert)) { // Create initial map; ownership moves to timeBearingProfiles_ currentProfileMap_ = new BearingProfileMap; @@ -100,7 +101,7 @@ void ProfileManager::initShaders_() { osgEarth::VirtualProgram* vp = osgEarth::VirtualProgram::getOrCreate(getOrCreateStateSet()); simVis::Shaders package; - if (profileContext_->mode_ == Profile::DRAWMODE_3D_TEXTURE) + if (profileContext_->mode == Profile::DRAWMODE_3D_TEXTURE) { package.load(vp, package.rfPropTextureBasedVertex()); package.load(vp, package.rfPropTextureBasedFragment()); @@ -154,7 +155,7 @@ void ProfileManager::setDisplay(bool onOff) for (const auto& iter : *currentProfileMap_) { // send THRESHOLDTYPE_NONE to turn profiles off - iter.second->setThresholdType(displayOn_ ? profileContext_->type_ : ProfileDataProvider::THRESHOLDTYPE_NONE); + iter.second->setThresholdType(displayOn_ ? profileContext_->type : ProfileDataProvider::THRESHOLDTYPE_NONE); } updateVisibility_(); @@ -196,28 +197,28 @@ void ProfileManager::setHistory(double history) bool ProfileManager::getAGL() const { - return profileContext_->agl_; + return profileContext_->agl; } void ProfileManager::setAGL(bool agl) { - if (profileContext_->agl_ != agl) + if (profileContext_->agl != agl) { - profileContext_->agl_ = agl; + profileContext_->agl = agl; dirty_(); } } Profile::DrawMode ProfileManager::getMode() const { - return profileContext_->mode_; + return profileContext_->mode; } void ProfileManager::setMode(Profile::DrawMode mode) { - if (profileContext_->mode_ != mode) + if (profileContext_->mode != mode) { - profileContext_->mode_ = mode; + profileContext_->mode = mode; initShaders_(); dirty_(); } @@ -225,31 +226,31 @@ void ProfileManager::setMode(Profile::DrawMode mode) ProfileDataProvider::ThresholdType ProfileManager::getThresholdType() const { - return profileContext_->type_; + return profileContext_->type; } void ProfileManager::setThresholdType(ProfileDataProvider::ThresholdType type) { - if (profileContext_->type_ != type) + if (profileContext_->type != type) { - profileContext_->type_ = type; + profileContext_->type = type; for (const auto& iter : *currentProfileMap_) { - iter.second->setThresholdType(profileContext_->type_); + iter.second->setThresholdType(profileContext_->type); } } } unsigned int ProfileManager::getDisplayThickness() const { - return profileContext_->displayThickness_; + return profileContext_->displayThickness; } void ProfileManager::setDisplayThickness(unsigned int displayThickness) { - if (profileContext_->displayThickness_ != displayThickness) + if (profileContext_->displayThickness != displayThickness) { - profileContext_->displayThickness_ = displayThickness; + profileContext_->displayThickness = displayThickness; dirty_(); } } @@ -270,69 +271,65 @@ void ProfileManager::setBearing(double bearing) double ProfileManager::getHeight() const { - return profileContext_->heightM_; + return profileContext_->heightM; } void ProfileManager::setHeight(double height) { - if (profileContext_->heightM_ != height) + if (profileContext_->heightM != height) { - profileContext_->heightM_ = height; + profileContext_->heightM = height; dirty_(); } } double ProfileManager::getRefLat() const { - return profileContext_->refLLA_.lat(); + return profileContext_->refLla.lat(); } double ProfileManager::getRefLon() const { - return profileContext_->refLLA_.lon(); + return profileContext_->refLla.lon(); } double ProfileManager::getRefAlt() const { - return profileContext_->refLLA_.alt(); + return profileContext_->refLla.alt(); } void ProfileManager::setRefCoord(double latRad, double lonRad, double alt) { - getLocator()->setCoordinate(simCore::Coordinate( - simCore::COORD_SYS_LLA, simCore::Vec3(latRad, lonRad, alt)), 0.); - - if (latRad != profileContext_->refLLA_.lat() || lonRad != profileContext_->refLLA_.lon() || alt != profileContext_->refLLA_.alt()) - { - profileContext_->refLLA_.set(lonRad, latRad, alt); - dirty_(); - } + const simCore::Vec3 refLla(latRad, lonRad, alt); + getLocator()->setCoordinate(simCore::Coordinate(simCore::COORD_SYS_LLA, refLla), 0.); + profileContext_->setRefLla(refLla); + dirty_(); } bool ProfileManager::getSphericalEarth() const { - return profileContext_->sphericalEarth_; + return profileContext_->sphericalEarth; } void ProfileManager::setSphericalEarth(bool sphericalEarth) { - if (profileContext_->sphericalEarth_ != sphericalEarth) + if (profileContext_->sphericalEarth != sphericalEarth) { - profileContext_->sphericalEarth_ = sphericalEarth; + profileContext_->sphericalEarth = sphericalEarth; dirty_(); } } double ProfileManager::getElevAngle() const { - return profileContext_->elevAngleR_; + return profileContext_->elevAngleR; } void ProfileManager::setElevAngle(double elevAngleRad) { - if (profileContext_->elevAngleR_ != elevAngleRad) + if (profileContext_->elevAngleR != elevAngleRad) { - profileContext_->elevAngleR_ = elevAngleRad; + profileContext_->elevAngleR = elevAngleRad; dirty_(); } } @@ -344,7 +341,7 @@ Profile* ProfileManager::getProfileByBearing(double bearingR) const const Profile* ProfileManager::getProfile(unsigned int index) const { - return ((index < getNumChildren()) ? dynamic_cast(getChild(index)) : NULL); + return ((index < getNumChildren()) ? dynamic_cast(getChild(index)) : nullptr); } void ProfileManager::addProfile(Profile* profile) diff --git a/SDK/simVis/RFProp/ProfileManager.h b/SDK/simVis/RFProp/ProfileManager.h index 2121e42f5..cac8ff8dc 100644 --- a/SDK/simVis/RFProp/ProfileManager.h +++ b/SDK/simVis/RFProp/ProfileManager.h @@ -23,13 +23,16 @@ #ifndef SIMVIS_RFPROP_PROFILE_MANAGER_H #define SIMVIS_RFPROP_PROFILE_MANAGER_H +#include #include "simVis/LocatorNode.h" #include "simVis/RFProp/Profile.h" +namespace simCore { class DatumConvert; } namespace simRF { class BearingProfileMap; class ColorProvider; +struct ProfileContext; /** * Manages a collection of Profiles @@ -39,8 +42,9 @@ class SDKVIS_EXPORT ProfileManager : public simVis::LocatorNode public: /** * Creates a new ProfileManager + * @param datumConvert converter for MSL heights */ - ProfileManager(); + explicit ProfileManager(std::shared_ptr datumConvert); void reset(); @@ -103,14 +107,14 @@ class SDKVIS_EXPORT ProfileManager : public simVis::LocatorNode /** * Gets the profile at the given bearing * @param bearingR bearing in radians - * @return profile at specified bearing, or NULL if none + * @return profile at specified bearing, or nullptr if none */ Profile* getProfileByBearing(double bearingR) const; /** * Gets the profile at the specified index, intended to support simple iteration through all profiles. * @param index of profile to return - * @return profile at specified index, or NULL if none + * @return profile at specified index, or nullptr if none */ const Profile* getProfile(unsigned int index) const; @@ -255,7 +259,7 @@ class SDKVIS_EXPORT ProfileManager : public simVis::LocatorNode double bearing_; ///< current bearing of RF prop display float alpha_; ///< Alpha value (1.0 opaque, 0.0 transparent) bool displayOn_; ///< whether visualization is active or not - std::shared_ptr profileContext_; ///< context shared by manager and each profile + std::shared_ptr profileContext_; ///< context shared by manager and each profile }; } diff --git a/SDK/simVis/RFProp/RFPropagationFacade.cpp b/SDK/simVis/RFProp/RFPropagationFacade.cpp index 85e670916..ee4f0184f 100644 --- a/SDK/simVis/RFProp/RFPropagationFacade.cpp +++ b/SDK/simVis/RFProp/RFPropagationFacade.cpp @@ -116,11 +116,11 @@ namespace simRF const int DEFAULT_TRANSPARENCY = 60; // percentage, 0-100. 100 is fully transparent, 0 is opaque const int DEFAULT_HISTORY = 30; // degrees -RFPropagationFacade::RFPropagationFacade(simData::ObjectId id, osg::Group* parent) +RFPropagationFacade::RFPropagationFacade(simData::ObjectId id, osg::Group* parent, std::shared_ptr datumConvert) : id_(id), antennaHeightMeters_(0.0), rfParamsSet_(false), - profileManager_(new simRF::ProfileManager()), + profileManager_(new simRF::ProfileManager(datumConvert)), parent_(parent) { // add profileManager_ to the parent node @@ -224,7 +224,7 @@ int RFPropagationFacade::setColorMap(simRF::ProfileDataProvider::ThresholdType t colorMaps_[type] = colorMap; break; } - if (colorProvider_ == NULL) + if (colorProvider_ == nullptr) return 0; // update the color provider if the specified type is currently active @@ -235,7 +235,7 @@ int RFPropagationFacade::setColorMap(simRF::ProfileDataProvider::ThresholdType t int RFPropagationFacade::setSlotData(simRF::Profile* profile) { - if (profile == NULL) + if (profile == nullptr) return 1; profileManager_->addProfile(profile); return 0; @@ -355,7 +355,7 @@ int RFPropagationFacade::setThresholdMode(simRF::ColorProvider::ColorMode mode) simRF::ColorProvider::ColorMode RFPropagationFacade::thresholdMode() const { - if (colorProvider_ == NULL) + if (colorProvider_ == nullptr) return simRF::ColorProvider::COLORMODE_BELOW; return colorProvider_->getMode(); } @@ -387,7 +387,7 @@ int RFPropagationFacade::setThresholdValue(int value) int RFPropagationFacade::threshold() const { - if (colorProvider_ == NULL) + if (colorProvider_ == nullptr) return 0; return static_cast(colorProvider_->getThreshold()); } @@ -719,7 +719,7 @@ const simRF::CompositeProfileProvider* RFPropagationFacade::getProfileProvider(d const simRF::Profile *profile = getSlotData(azimRad); if (profile) return dynamic_cast(profile->getDataProvider()); - return NULL; + return nullptr; } void RFPropagationFacade::setAntennaHeight(float antennaHeightM) @@ -736,28 +736,28 @@ float RFPropagationFacade::antennaHeight() const float RFPropagationFacade::minHeight() const { const Profile* profile = getProfile(0); - if (profile == NULL) + if (profile == nullptr) return 0.0f; const simRF::CompositeProfileProvider* cProvider = profile->getDataProvider(); - return (cProvider != NULL) ? cProvider->getMinHeight() : 0.0f; + return (cProvider != nullptr) ? cProvider->getMinHeight() : 0.0f; } float RFPropagationFacade::maxHeight() const { const Profile* profile = getProfile(0); - if (profile == NULL) + if (profile == nullptr) return 0.0f; const simRF::CompositeProfileProvider* cProvider = profile->getDataProvider(); - return (cProvider != NULL) ? cProvider->getMaxHeight() : 0.0f; + return (cProvider != nullptr) ? cProvider->getMaxHeight() : 0.0f; } unsigned int RFPropagationFacade::heightSteps() const { const Profile* profile = getProfile(0); - if (profile == NULL) + if (profile == nullptr) return 0; const simRF::CompositeProfileProvider* cProvider = profile->getDataProvider(); - return (cProvider != NULL) ? cProvider->getNumHeights() : 0; + return (cProvider != nullptr) ? cProvider->getNumHeights() : 0; } @@ -849,7 +849,7 @@ void RFPropagationFacade::initializeDefaultColors_() void RFPropagationFacade::setGradientByThresholdType_(simRF::ProfileDataProvider::ThresholdType type) { - if (colorProvider_ == NULL) + if (colorProvider_ == nullptr) return; // apply the appropriate color map, or the default if we don't have one specified for this type std::map::const_iterator foundColor = colorMaps_.find(type); diff --git a/SDK/simVis/RFProp/RFPropagationFacade.h b/SDK/simVis/RFProp/RFPropagationFacade.h index 760b57280..2ccea7be1 100644 --- a/SDK/simVis/RFProp/RFPropagationFacade.h +++ b/SDK/simVis/RFProp/RFPropagationFacade.h @@ -24,6 +24,7 @@ #define SIMVIS_RFPROP_RFPROPAGATIONFACADE_H #include +#include #include #include #include "osg/ref_ptr" @@ -34,7 +35,11 @@ #include "simVis/RFProp/ProfileManager.h" #include "simVis/RFProp/PODProfileDataProvider.h" -namespace simCore { class TimeStamp; } +namespace simCore +{ + class TimeStamp; + class DatumConvert; +} namespace simRF { @@ -47,9 +52,10 @@ class SDKVIS_EXPORT RFPropagationFacade /** * Construct an RF Propagation beam handler for the specified beam * @param beamId Beam to configure - * @param parent node to which the visual display's locator is attached; if NULL, no display will be created + * @param parent node to which the visual display's locator is attached; if nullptr, no display will be created + * @param datumConvert converter for MSL heights */ - RFPropagationFacade(simData::ObjectId beamId, osg::Group* parent); + RFPropagationFacade(simData::ObjectId beamId, osg::Group* parent, std::shared_ptr datumConvert); virtual ~RFPropagationFacade(); /** @@ -401,7 +407,7 @@ class SDKVIS_EXPORT RFPropagationFacade /** * Gets the composite provider for the specified azimuth the antenna height that will be used for the display * @param azimRad Azimuth angle referenced to True North in radians - * @return the composite provider , or NULL if no provider exists at the specified azimuth + * @return the composite provider, or nullptr if no provider exists at the specified azimuth */ const simRF::CompositeProfileProvider* getProfileProvider(double azimRad) const; @@ -467,7 +473,7 @@ class SDKVIS_EXPORT RFPropagationFacade /** * Gets the profiles at the specified index - * @return requested profile, or NULL if the index was not valid + * @return requested profile, or nullptr if the index was not valid */ const simRF::Profile* getProfile(unsigned int index) const; diff --git a/SDK/simVis/RFProp/RFPropagationManager.h b/SDK/simVis/RFProp/RFPropagationManager.h index f0e1e382f..edb876a38 100644 --- a/SDK/simVis/RFProp/RFPropagationManager.h +++ b/SDK/simVis/RFProp/RFPropagationManager.h @@ -42,14 +42,14 @@ class RFPropagationManager /** * Returns an existing RFPropagationFacade object for the specified beam entity * @param beamId ID of a beam to retrieve RF Propagation data - * @return RFPropagationData object pointer, NULL if specified beamId does not have a RFPropagationFacade Object + * @return RFPropagationData object pointer, nullptr if specified beamId does not have a RFPropagationFacade Object */ virtual RFPropagationFacade* getRFPropagation(simData::ObjectId beamId) const = 0; /** * Returns existing or newly created RFPropagationFacade object for the specified beam entity, new objects are owned by this manager * @param beamId ID of a beam to retrieve RF Propagation data - * @return RFPropagationData object pointer, NULL if specified beamId is not a beam entity ID + * @return RFPropagationData object pointer, nullptr if specified beamId is not a beam entity ID */ virtual RFPropagationFacade* getOrCreateRFPropagation(simData::ObjectId beamId) = 0; @@ -74,11 +74,11 @@ class NullRFPropagationManager : public RFPropagationManager } virtual simRF::RFPropagationFacade* getRFPropagation(simData::ObjectId id) const { - return NULL; + return nullptr; } virtual simRF::RFPropagationFacade* getOrCreateRFPropagation(simData::ObjectId id) { - return NULL; + return nullptr; } virtual int loadFiles(simData::ObjectId beamId, const std::vector& files) { diff --git a/SDK/simVis/RFProp/SNRDataProvider.cpp b/SDK/simVis/RFProp/SNRDataProvider.cpp index 40badbd76..d1a632e55 100644 --- a/SDK/simVis/RFProp/SNRDataProvider.cpp +++ b/SDK/simVis/RFProp/SNRDataProvider.cpp @@ -37,7 +37,7 @@ SNRDataProvider::SNRDataProvider(const TwoWayPowerDataProvider* twoWayPowerProvi SNRDataProvider::~SNRDataProvider() { - twoWayPowerProvider_ = NULL; + twoWayPowerProvider_ = nullptr; } double SNRDataProvider::getValueByIndex(unsigned int heightIndex, unsigned int rangeIndex) const diff --git a/SDK/simVis/RadialLOS.cpp b/SDK/simVis/RadialLOS.cpp index 88c1ddd67..431bc2b1b 100644 --- a/SDK/simVis/RadialLOS.cpp +++ b/SDK/simVis/RadialLOS.cpp @@ -85,17 +85,25 @@ RadialLOS::RadialLOS() } RadialLOS::RadialLOS(const RadialLOS& rhs) - : dirty_(rhs.dirty_), - radials_(rhs.radials_), - originMap_(rhs.originMap_), - range_max_(rhs.range_max_), - range_resolution_(rhs.range_resolution_), - azim_center_(rhs.azim_center_), - fov_(rhs.fov_), - azim_resolution_(rhs.azim_resolution_), - use_scene_graph_(rhs.use_scene_graph_) { - //nop + *this = rhs; +} + +RadialLOS& RadialLOS::operator=(const RadialLOS& rhs) +{ + dirty_ = rhs.dirty_; + radials_ = rhs.radials_; + originMap_ = rhs.originMap_; + range_max_ = rhs.range_max_; + range_resolution_ = rhs.range_resolution_; + azim_center_ = rhs.azim_center_; + fov_ = rhs.fov_; + azim_resolution_ = rhs.azim_resolution_; + use_scene_graph_ = rhs.use_scene_graph_; + // nocopy: srs_ + // nocopy: elevationWorkingSet_ + + return *this; } void RadialLOS::setMaxRange(const osgEarth::Distance& value) @@ -145,7 +153,7 @@ void RadialLOS::setAzimuthalResolution(const osgEarth::Angle& value) bool RadialLOS::compute(osgEarth::MapNode* mapNode, const simCore::Coordinate& originCoord) { - assert(mapNode != NULL); + assert(mapNode != nullptr); #ifdef LOS_TIME_PROFILING osg::Timer_t startTime = osg::Timer::instance()->tick(); @@ -158,16 +166,6 @@ bool RadialLOS::compute(osgEarth::MapNode* mapNode, const simCore::Coordinate& o if (!convertCoordToGeoPoint(originCoord, originMap_, mapNode->getMapSRS())) return false; - if (!use_scene_graph_) - { - // create an elevation sampler on demand: - if (envelope_.valid() == false) - { - envelope_ = mapNode->getMap()->getElevationPool()->createEnvelope( - mapNode->getMapSRS(), 23); - } - } - osg::Matrix local2world; originMap_.createLocalToWorld(local2world); @@ -254,7 +252,8 @@ bool RadialLOS::compute(osgEarth::MapNode* mapNode, const simCore::Coordinate& o } else { - hae = envelope_->getElevation(mapPoint.x(), mapPoint.y()); + osgEarth::ElevationSample sample = mapNode->getMap()->getElevationPool()->getSample(mapPoint, osgEarth::Distance(1.0, osgEarth::Units::METERS), &elevationWorkingSet_); + hae = sample.elevation().as(osgEarth::Units::METERS); hamsl = hae; ok = (hae != NO_DATA_VALUE); } @@ -268,7 +267,7 @@ bool RadialLOS::compute(osgEarth::MapNode* mapNode, const simCore::Coordinate& o convertGeoPointToCoord(mapPoint, destCoord, mapNode); double elev; - simCore::calculateAbsAzEl(originLlaCoord.position(), destCoord.position(), NULL, &elev, NULL, simCore::FLAT_EARTH, &cc); + simCore::calculateAbsAzEl(originLlaCoord.position(), destCoord.position(), nullptr, &elev, nullptr, simCore::FLAT_EARTH, &cc); bool visible = false; if (elev >= maxElev) @@ -368,7 +367,7 @@ bool RadialLOS::update(osgEarth::MapNode* mapNode, const osgEarth::GeoExtent& ex cc.setReferenceOrigin(originLlaCoord.lat(), originLlaCoord.lon(), originLlaCoord.alt()); double elev; - simCore::calculateAbsAzEl(originLlaCoord.position(), destCoord.position(), NULL, &elev, NULL, simCore::FLAT_EARTH, &cc); + simCore::calculateAbsAzEl(originLlaCoord.position(), destCoord.position(), nullptr, &elev, nullptr, simCore::FLAT_EARTH, &cc); sample.elev_rad_ = elev; } diff --git a/SDK/simVis/RadialLOS.h b/SDK/simVis/RadialLOS.h index 0e7db7b81..9b15deab0 100644 --- a/SDK/simVis/RadialLOS.h +++ b/SDK/simVis/RadialLOS.h @@ -92,6 +92,11 @@ class SDKVIS_EXPORT RadialLOS */ virtual ~RadialLOS() { } + /** + * Assignment + */ + RadialLOS& operator = (const RadialLOS& rhs); + /** * Sets the maximum range of the sample * @param[in ] value Maximum range @@ -173,10 +178,10 @@ class SDKVIS_EXPORT RadialLOS * Re-samples the terrain for all sample points that fall within the specified extent. * @param[in ] mapNode Map interface to use for sampling * @param[in ] extent Geospatial extent within which to update the samples - * @param patch Patch node, possibly NULL + * @param patch Patch node, possibly nullptr * @return True upon success */ - bool update(osgEarth::MapNode* mapNode, const osgEarth::GeoExtent& extent, osg::Node* patch = NULL); + bool update(osgEarth::MapNode* mapNode, const osgEarth::GeoExtent& extent, osg::Node* patch = nullptr); /** * Gets the number of samples in each radial @@ -237,7 +242,7 @@ class SDKVIS_EXPORT RadialLOS osgEarth::Angle fov_; osgEarth::Angle azim_resolution_; osg::ref_ptr srs_; - osg::ref_ptr envelope_; + osgEarth::ElevationPool::WorkingSet elevationWorkingSet_; bool use_scene_graph_; bool getBoundingRadials_(double azim_rad, const Radial*& out_r0, const Radial*& out_r1, double& out_mix) const; diff --git a/SDK/simVis/RadialLOSNode.cpp b/SDK/simVis/RadialLOSNode.cpp index bffd8e86c..8860e4453 100644 --- a/SDK/simVis/RadialLOSNode.cpp +++ b/SDK/simVis/RadialLOSNode.cpp @@ -263,9 +263,9 @@ void RadialLOSNode::refreshGeometry_() unsigned int numVerts = 1u + radials.size() * samplesPerRadial; - osg::Vec3Array* verts = NULL; - osg::Vec4Array* colors = NULL; - osg::DrawElementsUInt* tris = NULL; + osg::Vec3Array* verts = nullptr; + osg::Vec4Array* colors = nullptr; + osg::DrawElementsUInt* tris = nullptr; if (rebuildGeometry) { diff --git a/SDK/simVis/RangeTool.cpp b/SDK/simVis/RangeTool.cpp index ec16f6ab0..ec1f19863 100644 --- a/SDK/simVis/RangeTool.cpp +++ b/SDK/simVis/RangeTool.cpp @@ -100,7 +100,7 @@ void RangeTool::RefreshGroup::traverse(osg::NodeVisitor& nv) if (nv.getVisitorType() == nv.UPDATE_VISITOR && tool_.valid()) { // send a null scenario and invalid timestamp, these will be handled appropriately below - tool_->update(NULL, simCore::INFINITE_TIME_STAMP); + tool_->update(nullptr, simCore::INFINITE_TIME_STAMP); ADJUST_UPDATE_TRAV_COUNT(this, -1); } osg::Group::traverse(nv); @@ -137,8 +137,8 @@ void RangeTool::onUninstall(const ScenarioManager& scenario) // remove all range tool state related to scenario associations_.clear(); // scenario has already removed us from the scenegraph - root_ = NULL; - lastScenario_ = NULL; + root_ = nullptr; + lastScenario_ = nullptr; } void RangeTool::onUpdate(const ScenarioManager& scenario, const simCore::TimeStamp& timeStamp, const EntityVector& updates) @@ -313,7 +313,7 @@ RangeTool::Association::Association(simData::ObjectId id1, simData::ObjectId id2 : id1_(id1), id2_(id2), visible_(true), - xform_(NULL) + xform_(nullptr) { geode_ = new osg::Geode(); osg::StateSet* s = geode_->getOrCreateStateSet(); @@ -626,7 +626,7 @@ void RangeTool::Association::refresh_(EntityNode* obj0, EntityNode* obj1, const if (textOptions.showText_ == TextOptions::NONE) continue; - osgEarth::LabelNode* text = NULL; + osgEarth::LabelNode* text = nullptr; if (labelCount >= labels_->getNumChildren()) { osgEarth::Style style; @@ -729,9 +729,9 @@ void RangeTool::LineGraphic::createGeometry(osg::Vec3Array* verts, GLenum mode, void RangeTool::PieSliceGraphic::createGeometry(const osg::Vec3& originVec, osg::Vec3d startVec, osg::Vec3d endVec, double angle, osg::Geode* geode, RangeToolState& state) { - osg::Geometry* arcEndVecGeom = NULL; - osg::Geometry* startVecGeom = NULL; - osg::Vec3Array* verts = NULL; + osg::Geometry* arcEndVecGeom = nullptr; + osg::Geometry* startVecGeom = nullptr; + osg::Vec3Array* verts = nullptr; if (geode) { @@ -846,7 +846,7 @@ void RangeTool::PieSliceGraphic::createGeometry(const osg::Vec3& originVec, osg: osg::Vec3 RangeTool::PieSliceGraphic::labelPos(RangeToolState& state) { if (!labelPos_.isSet()) - render(NULL, state); + render(nullptr, state); return *labelPos_; } diff --git a/SDK/simVis/RangeToolState.cpp b/SDK/simVis/RangeToolState.cpp index 1186054ad..288592b07 100644 --- a/SDK/simVis/RangeToolState.cpp +++ b/SDK/simVis/RangeToolState.cpp @@ -30,8 +30,8 @@ RangeToolState::RangeToolState(EntityState* beginEntity, EntityState* endEntity) endEntity_(endEntity) { // Must pass in entities - assert(beginEntity_ != NULL); - assert(endEntity_ != NULL); + assert(beginEntity_ != nullptr); + assert(endEntity_ != nullptr); } RangeToolState::~RangeToolState() @@ -239,8 +239,8 @@ osg::Vec3d RangeToolState::coord(RangeToolState::Coord which) earthModel_, &coordConv_, &downRng, - NULL, - NULL); + nullptr, + nullptr); coord_[which] = osg::Vec3d(downRng*sin(fpa[0]), downRng*cos(fpa[0]), 0.0); } break; diff --git a/SDK/simVis/Registry.cpp b/SDK/simVis/Registry.cpp index f64716c63..60f4294c7 100644 --- a/SDK/simVis/Registry.cpp +++ b/SDK/simVis/Registry.cpp @@ -20,6 +20,7 @@ * disclose, or release this software. * */ +#include #include "OpenThreads/Mutex" #include "OpenThreads/ScopedLock" #include "osg/Version" @@ -166,7 +167,7 @@ class simVis::Registry::FindFileCallback : public osgDB::FindFileCallback simVis::Registry::Registry() : modelCache_(new ModelCache), fileSearch_(new simCore::NoSearchFileSearch()), - sequenceTimeUpdater_(new simVis::SequenceTimeUpdater(NULL)) + sequenceTimeUpdater_(new simVis::SequenceTimeUpdater(nullptr)) { // Configure the model cache modelCache_->setSequenceTimeUpdater(sequenceTimeUpdater_.get()); @@ -221,26 +222,28 @@ simVis::Registry::Registry() if (cantFindFont->getStateSet()) cantFindFont->getStateSet()->removeAttribute(osg::StateAttribute::PROGRAM); #endif + // Should not be possible that this entry exists; note, this doesn't leak in either case. + assert(fontCache_.find(CANT_FIND_FONT) == fontCache_.end()); fontCache_[CANT_FIND_FONT] = cantFindFont; // prime a default font which will be returned if the requested font cannot be found osgText::Font* defaultFont = getOrCreateFont(DEFAULT_FONT); osgEarth::Registry* osgEarthRegistry = osgEarth::Registry::instance(); - if (osgEarthRegistry->getDefaultFont() == NULL) + if (osgEarthRegistry->getDefaultFont() == nullptr) osgEarthRegistry->setDefaultFont(defaultFont); } simVis::Registry::~Registry() { delete modelCache_; - modelCache_ = NULL; + modelCache_ = nullptr; } static OpenThreads::Mutex s_instMutex; simVis::Registry* simVis::Registry::instance() { - static Registry* s_inst = NULL; + static Registry* s_inst = nullptr; if (!s_inst) { OpenThreads::ScopedLock lock(s_instMutex); @@ -317,7 +320,11 @@ void simVis::Registry::setShareArticulatedIconModels(bool value) std::string simVis::Registry::findModelFile(const std::string& name) const { +#ifdef HAVE_OSGEARTH_THREADING + osgEarth::Threading::ScopedRecursiveMutexLock lock(fileSearchMutex_); +#else osgEarth::Threading::ScopedMutexLock lock(fileSearchMutex_); +#endif if (!name.empty()) { @@ -387,14 +394,14 @@ void simVis::Registry::clearModelCache() osg::Node* simVis::Registry::getOrCreateIconModel(const std::string& location, bool* pIsImage) const { - // if doing a memory check, return NULL to load in a box instead of a complex icon + // if doing a memory check, return nullptr to load in a box instead of a complex icon if (memoryChecking_) - return NULL; + return nullptr; // Attempt to locate the filename std::string uri = findModelFile(location); if (uri.empty()) - return NULL; + return nullptr; return modelCache_->getOrCreateIconModel(uri, pIsImage); } @@ -447,7 +454,11 @@ osgText::Font* simVis::Registry::getOrCreateFont(const std::string& name) const std::string simVis::Registry::findFontFile(const std::string& name) const { +#ifdef HAVE_OSGEARTH_THREADING + osgEarth::Threading::ScopedRecursiveMutexLock lock(fileSearchMutex_); +#else osgEarth::Threading::ScopedMutexLock lock(fileSearchMutex_); +#endif if (!name.empty()) { @@ -516,7 +527,7 @@ osg::Referenced* simVis::Registry::getObject(const std::string& key) const if (i != weakObjectCache_.end()) return i->second.get(); else - return NULL; + return nullptr; } void simVis::Registry::setClock(simCore::Clock* clock) @@ -531,9 +542,13 @@ simCore::Clock* simVis::Registry::getClock() const void simVis::Registry::setFileSearch(simCore::FileSearchPtr fileSearch) { +#ifdef HAVE_OSGEARTH_THREADING + osgEarth::Threading::ScopedRecursiveMutexLock lock(fileSearchMutex_); +#else osgEarth::Threading::ScopedMutexLock lock(fileSearchMutex_); +#endif - if (fileSearch == NULL) + if (fileSearch == nullptr) fileSearch_.reset(new simCore::NoSearchFileSearch()); else fileSearch_ = fileSearch; @@ -541,8 +556,13 @@ void simVis::Registry::setFileSearch(simCore::FileSearchPtr fileSearch) std::string simVis::Registry::findFile_(const std::string& filename, simCore::FileSearch::SearchFileType fileType) const { +#ifdef HAVE_OSGEARTH_THREADING + osgEarth::Threading::ScopedRecursiveMutexLock lock(fileSearchMutex_); +#else osgEarth::Threading::ScopedMutexLock lock(fileSearchMutex_); - if (fileSearch_ == NULL) +#endif + + if (fileSearch_ == nullptr) return ""; return fileSearch_->findFile(filename, fileType); } diff --git a/SDK/simVis/Registry.h b/SDK/simVis/Registry.h index ff441a60d..b5c5aa3fd 100644 --- a/SDK/simVis/Registry.h +++ b/SDK/simVis/Registry.h @@ -29,9 +29,15 @@ #include "osg/observer_ptr" #include "osg/ref_ptr" #include "osgDB/FileUtils" -#include "osgEarth/ThreadingUtils" #include "simCore/Common/Common.h" #include "simCore/Common/FileSearch.h" +#include "simVis/osgEarthVersion.h" + +#ifdef HAVE_OSGEARTH_THREADING +#include "osgEarth/Threading" +#else +#include "osgEarth/ThreadingUtils" +#endif namespace osg { class FrameStamp; } namespace osgText { class Font; } @@ -118,14 +124,14 @@ class SDKVIS_EXPORT Registry /** * Gets or loads a node that represent the specified icon. * The result will be either a 3D model or a billboard icon depending on the - * Not multi-thread safe. * file type of the icon file found. + * Not multi-thread safe. * @param[in ] name Location of the file * @param[inout] pIsImage Pointer to a boolean that will be set to true if the loaded model refers - * to an image, or false if using a model. Only set for if the return value is non-NULL. - * @return A node, or NULL if no file was found. + * to an image, or false if using a model. Only set for if the return value is non-nullptr. + * @return A node, or nullptr if no file was found. */ - osg::Node* getOrCreateIconModel(const std::string& name, bool* pIsImage = NULL) const; + osg::Node* getOrCreateIconModel(const std::string& name, bool* pIsImage = nullptr) const; /** Retrieve a pointer to the model cache. */ ModelCache* modelCache() const; @@ -242,7 +248,11 @@ class SDKVIS_EXPORT Registry bool memoryChecking_; simCore::FileSearchPtr fileSearch_; +#ifdef HAVE_OSGEARTH_THREADING + mutable osgEarth::Threading::RecursiveMutex fileSearchMutex_; +#else mutable OpenThreads::ReentrantMutex fileSearchMutex_; +#endif /// We maintain a callback method that blocks HTTP results, and uses our file search class ReadFileCallback; diff --git a/SDK/simVis/RocketBurn.cpp b/SDK/simVis/RocketBurn.cpp index a6b50671e..d7d8d9696 100644 --- a/SDK/simVis/RocketBurn.cpp +++ b/SDK/simVis/RocketBurn.cpp @@ -57,14 +57,14 @@ RocketBurn::RocketBurn(PlatformNode &hostPlatform, osg::Texture2D& texture) simVis::DisableDepthOnAlpha::setAlphaThreshold(stateSet, 0.001f); // Add to the platform - if (hostPlatform.getModel() != NULL) + if (hostPlatform.getModel() != nullptr) hostPlatform.getModel()->addScaledChild(transform_.get()); } RocketBurn::~RocketBurn() { removeFromScene_(); - transform_ = NULL; + transform_ = nullptr; } // A RocketBurn visual is a series of poofs (textured quads). diff --git a/SDK/simVis/RocketBurnStorage.cpp b/SDK/simVis/RocketBurnStorage.cpp index c067c9e3c..e732b6cf2 100644 --- a/SDK/simVis/RocketBurnStorage.cpp +++ b/SDK/simVis/RocketBurnStorage.cpp @@ -117,7 +117,7 @@ class RocketBurnStorage::DataStoreListener : public simData::DataStore::DefaultL RocketBurnStorage::RocketBurnStorage(simData::DataStore &dataStore, simVis::ScenarioManager &scenarioManager) : scenarioManager_(scenarioManager), dataStore_(dataStore), - texture_(NULL) + texture_(nullptr) { } @@ -143,7 +143,7 @@ void RocketBurnStorage::addBurnData(simData::ObjectId platId, uint64_t burnId, d } // lazy initialization of texture and other resources that are only needed if a rocketBurn is instantiated - if (texture_ == NULL) + if (texture_ == nullptr) { const std::string imageFile = simVis::Registry::instance()->findModelFile(BURN_TEXTURE_FILE); osg::ref_ptr image; diff --git a/SDK/simVis/Scenario.cpp b/SDK/simVis/Scenario.cpp index 1310ab295..49652635b 100644 --- a/SDK/simVis/Scenario.cpp +++ b/SDK/simVis/Scenario.cpp @@ -144,7 +144,7 @@ osg::Node* ScenarioManager::EntityRecord::getNode() const bool ScenarioManager::EntityRecord::getLocation(osg::Vec3d& output) const { - // Check for NULL + // Check for nullptr if (!node_.valid() || !node_->getLocator()) return false; simCore::Vec3 outPos; @@ -204,7 +204,7 @@ osg::Group* ScenarioManager::SimpleEntityGraph::node() const int ScenarioManager::SimpleEntityGraph::addOrUpdate(EntityRecord* record) { // Assertion failure means ScenarioManager error - assert(record != NULL && record->getEntityNode() != NULL); + assert(record != nullptr && record->getEntityNode() != nullptr); // add the entity to the scenegraph by adding the entity to the Group, but only if: not already in the group and not a CR that is hosted (into the scenegraph) by its host platform. const auto node = record->getEntityNode(); @@ -274,8 +274,8 @@ class ScenarioManager::SurfaceClamping : public PlatformTspiFilter if (!prefs.surfaceclamping() || !coordSurfaceClamping_.isValid()) return PlatformTspiFilterManager::POINT_UNCHANGED; - osgEarth::ElevationEnvelope::Context& context = lut_[props.id()]; - coordSurfaceClamping_.clampCoordToMapSurface(llaCoord, context); + osgEarth::ElevationPool::WorkingSet& ws = lut_[props.id()]; + coordSurfaceClamping_.clampCoordToMapSurface(llaCoord, ws); return PlatformTspiFilterManager::POINT_CHANGED; } @@ -300,7 +300,7 @@ class ScenarioManager::SurfaceClamping : public PlatformTspiFilter private: CoordSurfaceClamping coordSurfaceClamping_; - std::map lut_; + std::map lut_; }; @@ -335,12 +335,12 @@ class ScenarioManager::AboveSurfaceClamping : public PlatformTspiFilter // getHeight() can give inaccurate results depending on how much map data is loaded into the scene graph, while ElevationEnvelope can be prohibitively slow if there are many clamped entities double elevation = 0; - if (useMaxElevPrec_ && envelope_.valid()) + if (useMaxElevPrec_) { - double terrainHeightHae = envelope_->getElevation(llaCoord.lon()*simCore::RAD2DEG, llaCoord.lat()*simCore::RAD2DEG); // height above ellipsoid, the rough elevation - // If getting elevation fails, clamp above 0 - if (terrainHeightHae != NO_DATA_VALUE) - elevation = terrainHeightHae; + osgEarth::GeoPoint point(mapNode_->getMapSRS(), llaCoord.lon()*simCore::RAD2DEG, llaCoord.lat()*simCore::RAD2DEG, 0, osgEarth::ALTMODE_ABSOLUTE); + osgEarth::ElevationSample sample = mapNode_->getMap()->getElevationPool()->getSample(point, osgEarth::Distance(1.0, osgEarth::Units::METERS), nullptr); + if (sample.hasData()) + elevation = sample.elevation().as(osgEarth::Units::METERS); } else { @@ -363,10 +363,6 @@ class ScenarioManager::AboveSurfaceClamping : public PlatformTspiFilter void setMapNode(const osgEarth::MapNode* map) { mapNode_ = map; - if (mapNode_.valid() && useMaxElevPrec_) - envelope_ = mapNode_->getMap()->getElevationPool()->createEnvelope(mapNode_->getMapSRS(), MAX_LOD); - else - envelope_ = NULL; } void setUseMaxElevPrec(bool useMaxElevPrec) @@ -375,19 +371,10 @@ class ScenarioManager::AboveSurfaceClamping : public PlatformTspiFilter return; useMaxElevPrec_ = useMaxElevPrec; - if (useMaxElevPrec_ && mapNode_.valid()) - { - // Envelope should not be valid if useMaxElevPrec was just turned on - assert(!envelope_.valid()); - envelope_ = mapNode_->getMap()->getElevationPool()->createEnvelope(mapNode_->getMapSRS(), MAX_LOD); - } - else - envelope_ = NULL; } private: osg::observer_ptr mapNode_; - osg::ref_ptr envelope_; bool useMaxElevPrec_; }; @@ -413,7 +400,7 @@ class ScenarioManager::ScenarioLosCreator : public LosCreator { if (map_.valid()) return new RadialLOSNode(map_.get()); - return NULL; + return nullptr; } private: @@ -424,9 +411,9 @@ class ScenarioManager::ScenarioLosCreator : public LosCreator ScenarioManager::ScenarioManager(ProjectorManager* projMan) : platformTspiFilterManager_(new PlatformTspiFilterManager()), - surfaceClamping_(NULL), - aboveSurfaceClamping_(NULL), - lobSurfaceClamping_(NULL), + surfaceClamping_(nullptr), + aboveSurfaceClamping_(nullptr), + lobSurfaceClamping_(nullptr), root_(new osg::Group), entityGraph_(new SimpleEntityGraph), projectorManager_(projMan), @@ -480,80 +467,27 @@ ScenarioManager::ScenarioManager(ProjectorManager* projMan) scenarioEciLocator_ = new Locator(); } -#ifdef USE_DEPRECATED_SIMDISSDK_API ScenarioManager::ScenarioManager(LocatorFactory* factory, ProjectorManager* projMan) - : platformTspiFilterManager_(new PlatformTspiFilterManager()), - surfaceClamping_(NULL), - aboveSurfaceClamping_(NULL), - lobSurfaceClamping_(NULL), - root_(new osg::Group), - entityGraph_(new SimpleEntityGraph), - projectorManager_(projMan), - labelContentManager_(new NullLabelContentManager()), - rfManager_(new simRF::NullRFPropagationManager()), - losCreator_(new ScenarioLosCreator()) + : ScenarioManager(projMan) { - root_->setName("root"); - root_->addChild(entityGraph_->node()); - addChild(root_.get()); - - // Install a callback that will convey the Horizon info - osg::EllipsoidModel em; - // 11km is rough depth of Mariana Trench; decrease radius to help horizon culling work underwater - em.setRadiusEquator(em.getRadiusEquator() - 11000.0); - em.setRadiusPolar(em.getRadiusPolar() - 11000.0); - SetHorizonCullCallback* setHorizon = new SetHorizonCullCallback(new osgEarth::Horizon(em)); - root_->addCullCallback(setHorizon); - - // Clamping requires a Group for MapNode changes - surfaceClamping_ = new SurfaceClamping(); - aboveSurfaceClamping_ = new AboveSurfaceClamping(); - lobSurfaceClamping_ = new CoordSurfaceClamping(); - - // set normal rescaling so that dynamically-scaled platforms have - // proper lighting. Note: once we move to using shaders we don't - // need this anymore - osg::StateSet* stateSet = getOrCreateStateSet(); -#ifdef OSG_GL_FIXED_FUNCTION_AVAILABLE - // GL_RESCALE_NORMAL is deprecated in GL CORE builds - stateSet->setMode(GL_RESCALE_NORMAL, 1); -#endif - // Lighting will be off for all objects under the Scenario, - // unless explicitly turned on further down the scene graph - simVis::setLighting(stateSet, osg::StateAttribute::OFF); - - setName("simVis::ScenarioManager"); - - platformTspiFilterManager_->addFilter(surfaceClamping_); - platformTspiFilterManager_->addFilter(aboveSurfaceClamping_); - - // Install shaders used by multiple entities at the scenario level - AlphaTest::installShaderProgram(stateSet); - BeamPulse::installShaderProgram(stateSet); - DisableDepthOnAlpha::installShaderProgram(stateSet); - LobGroupNode::installShaderProgram(stateSet); - OverrideColor::installShaderProgram(stateSet); - PolygonStipple::installShaderProgram(stateSet); - TrackHistoryNode::installShaderProgram(stateSet); } -#endif ScenarioManager::~ScenarioManager() { // Do not delete surfaceClamping_ or surfaceLimiting_ delete platformTspiFilterManager_; - platformTspiFilterManager_ = NULL; + platformTspiFilterManager_ = nullptr; delete lobSurfaceClamping_; - lobSurfaceClamping_ = NULL; + lobSurfaceClamping_ = nullptr; delete losCreator_; - losCreator_ = NULL; + losCreator_ = nullptr; // guarantee that ScenarioTools receive OnUninstall() calls removeAllTools_(); } void ScenarioManager::bind(simData::DataStore* dataStore) { - assert(dataStore != NULL); + assert(dataStore != nullptr); // sets up notifications so that changes to the datastore will // create objects in the scene graph: @@ -572,7 +506,7 @@ void ScenarioManager::unbind(simData::DataStore* dataStore, bool clearAll) void ScenarioManager::setLabelContentManager(LabelContentManager* manager) { - if (manager == NULL) + if (manager == nullptr) labelContentManager_ = new NullLabelContentManager(); else labelContentManager_ = manager; @@ -580,7 +514,7 @@ void ScenarioManager::setLabelContentManager(LabelContentManager* manager) void ScenarioManager::setRFPropagationManager(simRF::RFPropagationManagerPtr manager) { - if (manager == NULL) + if (manager == nullptr) rfManager_.reset(new simRF::NullRFPropagationManager()); else rfManager_ = manager; @@ -665,7 +599,7 @@ void ScenarioManager::removeEntity(simData::ObjectId id) { SAFETRYBEGIN; const EntityRepo::iterator i = entities_.find(id); - EntityRecord* record = (i != entities_.end()) ? i->second.get() : NULL; + EntityRecord* record = (i != entities_.end()) ? i->second.get() : nullptr; if (record) { EntityNode* entity = record->getEntityNode(); @@ -719,7 +653,7 @@ PlatformNode* ScenarioManager::addPlatform(const simData::PlatformProperties& pr dataStore, *platformTspiFilterManager_, root_.get(), - new Locator(scenarioEciLocator_), + new Locator(scenarioEciLocator_.get()), dataStore.referenceYear()); node->getModel()->addCallback(new BeamNoseFixer(this)); @@ -737,14 +671,14 @@ PlatformNode* ScenarioManager::addPlatform(const simData::PlatformProperties& pr return node; SAFETRYEND("adding platform"); - return NULL; + return nullptr; } BeamNode* ScenarioManager::addBeam(const simData::BeamProperties& props, simData::DataStore& dataStore) { SAFETRYBEGIN; // attempt to anchor the beam to its host platform: - PlatformNode* host = NULL; + PlatformNode* host = nullptr; if (props.has_hostid()) host = find(props.hostid()); @@ -771,18 +705,18 @@ BeamNode* ScenarioManager::addBeam(const simData::BeamProperties& props, simData return node; SAFETRYEND("adding beam"); - return NULL; + return nullptr; } GateNode* ScenarioManager::addGate(const simData::GateProperties& props, simData::DataStore& dataStore) { SAFETRYBEGIN; // attempt to anchor the gate to its host beam or platform: - EntityNode* host = NULL; + EntityNode* host = nullptr; if (props.has_hostid()) host = find(props.hostid()); - if ((props.type() == simData::GateProperties_GateType_TARGET) && (dynamic_cast(host) == NULL)) + if ((props.type() == simData::GateProperties_GateType_TARGET) && (dynamic_cast(host) == nullptr)) { // simVis gate will not update this gate - it will look just like an invisible zombie SIM_WARN << "ScenarioManager::addGate: a target gate requires a Beam host; gate will be ignored." << std::endl; @@ -806,14 +740,14 @@ GateNode* ScenarioManager::addGate(const simData::GateProperties& props, simData return node; SAFETRYEND("adding gate"); - return NULL; + return nullptr; } LaserNode* ScenarioManager::addLaser(const simData::LaserProperties& props, simData::DataStore& dataStore) { SAFETRYBEGIN; // attempt to anchor the laser to its host platform: - EntityNode* host = NULL; + EntityNode* host = nullptr; if (props.has_hostid()) host = find(props.hostid()); @@ -835,20 +769,20 @@ LaserNode* ScenarioManager::addLaser(const simData::LaserProperties& props, simD return node; SAFETRYEND("adding laser"); - return NULL; + return nullptr; } LobGroupNode* ScenarioManager::addLobGroup(const simData::LobGroupProperties& props, simData::DataStore& dataStore) { SAFETRYBEGIN; // attempt to anchor to the host platform - EntityNode* host = NULL; + EntityNode* host = nullptr; if (props.has_hostid()) host = find(props.hostid()); // no host, no LOB group. if (!host) - return NULL; + return nullptr; LobGroupNode* node = new LobGroupNode(props, host, lobSurfaceClamping_, dataStore); @@ -865,14 +799,14 @@ LobGroupNode* ScenarioManager::addLobGroup(const simData::LobGroupProperties& pr return node; SAFETRYEND("adding LOB group"); - return NULL; + return nullptr; } CustomRenderingNode* ScenarioManager::addCustomRendering(const simData::CustomRenderingProperties& props, simData::DataStore& dataStore) { SAFETRYBEGIN; // attempt to anchor to the host - EntityNode* host = NULL; + EntityNode* host = nullptr; if (props.has_hostid()) host = find(props.hostid()); @@ -883,7 +817,7 @@ CustomRenderingNode* ScenarioManager::addCustomRendering(const simData::CustomRe // host will attach the cr to the scenegraph; ScenarioManager::SimpleEntityGraph::addOrUpdate will understand not to attach to scenario's group host->addChild(node); } - entities_[node->getId()] = new EntityRecord(node, NULL, &dataStore); + entities_[node->getId()] = new EntityRecord(node, nullptr, &dataStore); hosterTable_.insert(std::make_pair((host ? host->getId() : 0), node->getId())); notifyToolsOfAdd_(node); @@ -892,13 +826,13 @@ CustomRenderingNode* ScenarioManager::addCustomRendering(const simData::CustomRe return node; SAFETRYEND("adding custom"); - return NULL; + return nullptr; } ProjectorNode* ScenarioManager::addProjector(const simData::ProjectorProperties& props, simData::DataStore& dataStore) { SAFETRYBEGIN; - EntityNode* host = NULL; + EntityNode* host = nullptr; if (props.has_hostid()) host = find(props.hostid()); @@ -922,7 +856,7 @@ ProjectorNode* ScenarioManager::addProjector(const simData::ProjectorProperties& return node; SAFETRYEND("adding projector"); - return NULL; + return nullptr; } bool ScenarioManager::setPlatformPrefs(simData::ObjectId id, const simData::PlatformPrefs& prefs) @@ -1043,25 +977,25 @@ EntityNode* ScenarioManager::find(const simData::ObjectId& id) const { SAFETRYBEGIN; EntityRepo::const_iterator i = entities_.find(id); - return i != entities_.end() ? static_cast(i->second->getNode()) : NULL; + return i != entities_.end() ? static_cast(i->second->getNode()) : nullptr; SAFETRYEND(std::string(osgEarth::Stringify() << "finding entity ID " << id)); - return NULL; + return nullptr; } const EntityNode* ScenarioManager::getHostPlatform(const EntityNode* entity) const { - if (entity == NULL) - return NULL; + if (entity == nullptr) + return nullptr; simData::ObjectId hostId; while (entity->getHostId(hostId)) { entity = find(hostId); - if (entity == NULL) + if (entity == nullptr) { // An orphan entity without a host platform assert(false); - return NULL; + return nullptr; } } @@ -1105,7 +1039,7 @@ EntityNode* ScenarioManager::find(osg::View* _view, float x, float y, int typeMa if (!view) { SIM_WARN << "ScenarioManager::findEntity: ILLEGAL: view is not a simVis::View" << std::endl; - return NULL; + return nullptr; } osg::Camera* cam = _view->getCamera(); @@ -1195,7 +1129,7 @@ EntityNode* ScenarioManager::find(osg::View* _view, float x, float y, int typeMa } } - return NULL; + return nullptr; } void ScenarioManager::addTool(ScenarioTool* tool) @@ -1353,7 +1287,7 @@ void ScenarioManager::getAllEntities(EntityVector& output) const osg::Group* ScenarioManager::getOrCreateAttachPoint(const std::string& name) { - osg::Group* result = NULL; + osg::Group* result = nullptr; std::map >::const_iterator i = customAttachPoints_.find(name); if (i != customAttachPoints_.end() && i->second.valid()) { diff --git a/SDK/simVis/Scenario.h b/SDK/simVis/Scenario.h index 89c8c316b..fdd945d93 100644 --- a/SDK/simVis/Scenario.h +++ b/SDK/simVis/Scenario.h @@ -58,7 +58,6 @@ class ProjectorNode; class ScenarioTool; //---------------------------------------------------------------------------- -#ifdef USE_DEPRECATED_SIMDISSDK_API /// Interface for an object that can create a new Locator class LocatorFactory { @@ -66,12 +65,12 @@ class LocatorFactory virtual ~LocatorFactory() {} /// create a new locator - virtual Locator* createLocator() const = 0; + virtual SDK_DEPRECATE(Locator* createLocator() const, "LocatorFactory is deprecated.") = 0; /// create a new platform locator - virtual Locator* createEciLocator() const = 0; + virtual SDK_DEPRECATE(Locator* createEciLocator() const, "LocatorFactory is deprecated.") = 0; }; -#endif + //---------------------------------------------------------------------------- /** @@ -248,7 +247,7 @@ class SDKVIS_EXPORT ScenarioManager : public osgEarth::LODScaleGroup /** * Find an entity by its unique ID. * @param id Unique entity ID - * @return Entity node, or NULL if not found + * @return Entity node, or nullptr if not found */ EntityNode* find(const simData::ObjectId &id) const; @@ -256,14 +255,14 @@ class SDKVIS_EXPORT ScenarioManager : public osgEarth::LODScaleGroup * Returns the host platform for the given entity * If entity is a platform it will return itself * @param entity Need its host platform - * @return the host platform for the given entity, or NULL if not found (orphan) + * @return the host platform for the given entity, or nullptr if not found (orphan) */ const EntityNode* getHostPlatform(const EntityNode* entity) const; /** * Find a node and casts it to the requested type (convenience function) * @param id Unique entity ID - * @return Entity node, cast to the requested type, or NULL if not found. + * @return Entity node, cast to the requested type, or nullptr if not found. */ template T* find(const simData::ObjectId &id) const @@ -277,7 +276,7 @@ class SDKVIS_EXPORT ScenarioManager : public osgEarth::LODScaleGroup * @param x X mouse coordinate * @param y Y mouse coordinate * @param typeMask Traversal mask of node type to find, or ~0 to find anything - * @return Entity node, or NULL if nothing was hit + * @return Entity node, or nullptr if nothing was hit */ EntityNode* find(osg::View *view, float x, float y, int typeMask = ~0) const; @@ -297,9 +296,9 @@ class SDKVIS_EXPORT ScenarioManager : public osgEarth::LODScaleGroup /** * Remove entities from the scenario. * @param[in ] dataStore Remove entities that originated from this data store. - * Pass in NULL to remove all entities regardless of origin. + * Pass in nullptr to remove all entities regardless of origin. */ - void clearEntities(simData::DataStore* dataStore = NULL); + void clearEntities(simData::DataStore* dataStore = nullptr); /** * Remove the entity referenced by 'id' from the entity list and from @@ -370,13 +369,11 @@ class SDKVIS_EXPORT ScenarioManager : public osgEarth::LODScaleGroup /** Creates a new ScenarioManager with the given projector manager */ explicit ScenarioManager(ProjectorManager* projMan); -#ifdef USE_DEPRECATED_SIMDISSDK_API /** * Creates a new ScenarioManager with the given locator factory and projector manager * @deprecated */ SDK_DEPRECATE(ScenarioManager(LocatorFactory* factory, ProjectorManager* projMan), "Method will be removed in a future SDK release"); -#endif /** * Check for scenario entity updates and applies them to the corresponding diff --git a/SDK/simVis/ScenarioDataStoreAdapter.cpp b/SDK/simVis/ScenarioDataStoreAdapter.cpp index c703e4b9c..4dd981c04 100644 --- a/SDK/simVis/ScenarioDataStoreAdapter.cpp +++ b/SDK/simVis/ScenarioDataStoreAdapter.cpp @@ -93,7 +93,7 @@ class MyListener : public simData::DataStore::Listener } /// current time has been changed - virtual void onTimeChange(simData::DataStore *source) + virtual void onChange(simData::DataStore *source) { if (scenarioManager_.valid()) scenarioManager_->update(source); @@ -377,7 +377,7 @@ ScenarioDataStoreAdapter::ScenarioDataStoreAdapter(simData::DataStore* dataStore void ScenarioDataStoreAdapter::bind(simData::DataStore* dataStore, ScenarioManager* scenario) { - if (dataStore == NULL) + if (dataStore == nullptr) { unbind(dataStore); } @@ -421,7 +421,7 @@ void ScenarioDataStoreAdapter::bind(simData::DataStore* dataStore, ScenarioManag void ScenarioDataStoreAdapter::unbind(simData::DataStore* dataStore) { - if (dataStore != NULL) + if (dataStore != nullptr) { // remove data store listeners std::map::iterator li = listeners_.find(dataStore); diff --git a/SDK/simVis/SceneManager.cpp b/SDK/simVis/SceneManager.cpp index 8bb1f5512..8e12ef6bd 100644 --- a/SDK/simVis/SceneManager.cpp +++ b/SDK/simVis/SceneManager.cpp @@ -106,7 +106,7 @@ void SceneManager::detectTerrainEngineDriverProblems_() // Try to detect the osgearth_engine_rex driver; if not present, we will likely fail to render anything useful osgDB::Registry* registry = osgDB::Registry::instance(); const std::string engineDriverExtension = "osgearth_engine_rex"; - if (registry->getReaderWriterForExtension(engineDriverExtension) != NULL) + if (registry->getReaderWriterForExtension(engineDriverExtension) != nullptr) { hasEngineDriverProblem_ = false; return; @@ -258,10 +258,10 @@ void SceneManager::setSkyNode(osgEarth::SkyNode* skyNode) skyNodeParent->removeChild(skyNode_.get()); } } - skyNode_ = NULL; + skyNode_ = nullptr; // install a new one. - if (skyNode != NULL) + if (skyNode != nullptr) { // insert the sky between this node and its children. skyNode_ = skyNode; @@ -271,14 +271,14 @@ void SceneManager::setSkyNode(osgEarth::SkyNode* skyNode) bool SceneManager::isSilverLining_(const osgEarth::SkyNode* skyNode) const { - if (skyNode == NULL) + if (skyNode == nullptr) return false; try { // Attempt to use RTTI to determine if sky node is from SilverLining. While not // ideal, there is no other way to automatically determine. const char* typeName = typeid(*skyNode).name(); - if (typeName == NULL) + if (typeName == nullptr) return false; // Search for the name SilverLining in the type ID @@ -342,7 +342,7 @@ void SceneManager::setMapNode(osgEarth::MapNode* mapNode) void SceneManager::setMap(osgEarth::Map* map) { // Swaps out the layers of underlying mapNode_ with layers in map. - if (map == NULL) + if (map == nullptr) return; if (mapNode_.valid()) @@ -488,7 +488,7 @@ osg::Node* SceneManager::getManipulatorAttachPoint() const osg::Group* SceneManager::getOrCreateAttachPoint(const std::string& name) const { // Assertion failure means this method was called before init_() - assert(scenarioManager_ != NULL); + assert(scenarioManager_ != nullptr); return scenarioManager_->getOrCreateAttachPoint(name); } diff --git a/SDK/simVis/SceneManager.h b/SDK/simVis/SceneManager.h index 40cd662d4..1613df463 100644 --- a/SDK/simVis/SceneManager.h +++ b/SDK/simVis/SceneManager.h @@ -82,7 +82,7 @@ namespace simVis * The map displayed in this scene. * @return the Map */ - osgEarth::Map* getMap() { return mapNode_.valid() ? mapNode_->getMap() : NULL; } + osgEarth::Map* getMap() { return mapNode_.valid() ? mapNode_->getMap() : nullptr; } /** * Sets the Map. This method actually will copy the layers from the provided diff --git a/SDK/simVis/SimdisMeasurement.cpp b/SDK/simVis/SimdisMeasurement.cpp index 48b4d479d..a41a9b493 100644 --- a/SDK/simVis/SimdisMeasurement.cpp +++ b/SDK/simVis/SimdisMeasurement.cpp @@ -55,69 +55,69 @@ RfMeasurement::RfMeasurement(const std::string& name, const std::string& abbr, c void RfMeasurement::getRfParameters_(RangeToolState& state, double *azAbs, double *elAbs, double *hgtMeters, double* xmtGaindB, double* rcvGaindB, double* rcs, bool useDb, double* freqMHz, double* powerWatts) const { - if (azAbs != NULL || elAbs != NULL) + if (azAbs != nullptr || elAbs != nullptr) { double azAbsLocal; double elAbsLocal; - calculateTrueAngles_(state, &azAbsLocal, &elAbsLocal, NULL); - if (azAbs != NULL) + calculateTrueAngles_(state, &azAbsLocal, &elAbsLocal, nullptr); + if (azAbs != nullptr) *azAbs = azAbsLocal; - if (elAbs != NULL) + if (elAbs != nullptr) *elAbs = elAbsLocal; } auto simdisBeginState = dynamic_cast(state.beginEntity_); auto simdisEndState = dynamic_cast(state.endEntity_); - if (hgtMeters != NULL) + if (hgtMeters != nullptr) { *hgtMeters = 0.0; - if (simdisBeginState != NULL) + if (simdisBeginState != nullptr) { const simRF::RFPropagationFacade* rf = simdisBeginState->rfPropagation_; - if (rf != NULL) + if (rf != nullptr) *hgtMeters = rf->antennaHeight(); } } // Do NOT set RF parameter values from RFPropagationFacade, in order to match the behavior of SIMDIS 9 - if (xmtGaindB != NULL || rcvGaindB != NULL) + if (xmtGaindB != nullptr || rcvGaindB != nullptr) { double xmtGaindBLocal = simCore::DEFAULT_ANTENNA_GAIN; double rcvGaindBLocal = simCore::DEFAULT_ANTENNA_GAIN; - if (simdisBeginState != NULL) + if (simdisBeginState != nullptr) { const simVis::BeamNode* beam = dynamic_cast(simdisBeginState->node_.get()); if (beam) { double azRelLocal; double elRelLocal; - RelOriMeasurement::getAngles(&azRelLocal, &elRelLocal, NULL, state); + RelOriMeasurement::getAngles(&azRelLocal, &elRelLocal, nullptr, state); xmtGaindBLocal = beam->gain(azRelLocal, elRelLocal); rcvGaindBLocal = xmtGaindBLocal; } } - if (xmtGaindB != NULL) + if (xmtGaindB != nullptr) *xmtGaindB = xmtGaindBLocal; - if (rcvGaindB != NULL) + if (rcvGaindB != nullptr) *rcvGaindB = rcvGaindBLocal; } - if (rcs != NULL) + if (rcs != nullptr) { double rcsLocal = useDb ? simCore::SMALL_DB_VAL : simCore::SMALL_RCS_SM; // To match SIMDIS 9, the end entity must be a platform. if (state.endEntity_->type_ == simData::PLATFORM) { - if (simdisEndState != NULL) + if (simdisEndState != nullptr) { simCore::RadarCrossSectionPtr rcsPtr = simdisEndState->platformHostNode_->getRcs(); - if (rcsPtr != NULL) + if (rcsPtr != nullptr) { // need the angles from the target to the beam source to get the correct rcs values double azTarget; @@ -143,7 +143,7 @@ void RfMeasurement::getRfParameters_(RangeToolState& state, double *azAbs, doubl assert(0); // node class should match the type, which was shown to be PLATFORM above } - simCore::calculateRelAzEl(state.endEntity_->lla_, state.endEntity_->ypr_, state.beginEntity_->lla_, &azTarget, &elTarget, NULL, state.earthModel_, &state.coordConv_); + simCore::calculateRelAzEl(state.endEntity_->lla_, state.endEntity_->ypr_, state.beginEntity_->lla_, &azTarget, &elTarget, nullptr, state.earthModel_, &state.coordConv_); if (useDb) rcsLocal = rcsPtr->RCSdB(frequency, azTarget, elTarget, type); else @@ -154,7 +154,7 @@ void RfMeasurement::getRfParameters_(RangeToolState& state, double *azAbs, doubl *rcs = rcsLocal; } - if ((freqMHz != NULL) || (powerWatts != NULL)) + if ((freqMHz != nullptr) || (powerWatts != nullptr)) { double freqMHzBLocal = 0.0; double powerWattsLocal = 0.0; @@ -166,10 +166,10 @@ void RfMeasurement::getRfParameters_(RangeToolState& state, double *azAbs, doubl powerWattsLocal = prefs.power(); } - if (freqMHz != NULL) + if (freqMHz != nullptr) *freqMHz = freqMHzBLocal; - if (powerWatts != NULL) + if (powerWatts != nullptr) *powerWatts = powerWattsLocal; } } @@ -191,7 +191,7 @@ double RFGainMeasurement::value(RangeToolState& state) const { double azRelLocal; double elRelLocal; - getAngles(&azRelLocal, &elRelLocal, NULL, state); + getAngles(&azRelLocal, &elRelLocal, nullptr, state); return beam->gain(azRelLocal, elRelLocal); } } @@ -220,7 +220,7 @@ double RFPowerMeasurement::value(RangeToolState& state) const double freqMHz; double xmtPowerWatts; - getRfParameters_(state, &az, NULL, &hgtMeters, &xmtGaindB, &rcvGaindB, &rcsSqm, false, &freqMHz, &xmtPowerWatts); + getRfParameters_(state, &az, nullptr, &hgtMeters, &xmtGaindB, &rcvGaindB, &rcsSqm, false, &freqMHz, &xmtPowerWatts); double slantRngMeters = simCore::calculateSlant(state.beginEntity_->lla_, state.endEntity_->lla_, state.earthModel_, &state.coordConv_); double gndRngMeters = simCore::calculateGroundDist(state.beginEntity_->lla_, state.endEntity_->lla_, state.earthModel_, &state.coordConv_); if (rcsSqm == simCore::SMALL_RCS_SM) @@ -235,7 +235,7 @@ double RFPowerMeasurement::value(RangeToolState& state) const if (simdisState) { simRF::RFPropagationFacade* rf = simdisState->rfPropagation_; - if (rf != NULL) + if (rf != nullptr) power = rf->getReceivedPower(az, slantRngMeters, hgtMeters, xmtGaindB, rcvGaindB, rcsSqm, gndRngMeters); } @@ -268,7 +268,7 @@ double RFOneWayPowerMeasurement::value(RangeToolState& state) const double freqMHz; double xmtPowerWatts; - getRfParameters_(state, &az, NULL, &hgtMeters, &xmtGaindB, &rcvGaindB, NULL, false, &freqMHz, &xmtPowerWatts); + getRfParameters_(state, &az, nullptr, &hgtMeters, &xmtGaindB, &rcvGaindB, nullptr, false, &freqMHz, &xmtPowerWatts); double slantRngMeters = simCore::calculateSlant(state.beginEntity_->lla_, state.endEntity_->lla_, state.earthModel_, &state.coordConv_); double gndRngMeters = simCore::calculateGroundDist(state.beginEntity_->lla_, state.endEntity_->lla_, state.earthModel_, &state.coordConv_); @@ -278,7 +278,7 @@ double RFOneWayPowerMeasurement::value(RangeToolState& state) const if (simdisState) { simRF::RFPropagationFacade* rf = simdisState->rfPropagation_; - if (rf != NULL) + if (rf != nullptr) power = rf->getOneWayPower(az, slantRngMeters, hgtMeters, xmtGaindB, gndRngMeters, rcvGaindB); } @@ -329,7 +329,7 @@ double HorizonMeasurement::calcAboveHorizon_(RangeToolState& state, simCore::Hor return 0; SimdisEntityState* simdisState = dynamic_cast(state.beginEntity_); - if (simdisState == NULL) + if (simdisState == nullptr) return 0; // Check if obstructed by terrain @@ -337,10 +337,12 @@ double HorizonMeasurement::calcAboveHorizon_(RangeToolState& state, simCore::Hor { // If any elevation from beginEntity_ to the terrain at an intermediate point is higher than this, endEntity_ is obstructed by terrain double targetElev; - simCore::calculateAbsAzEl(state.beginEntity_->lla_, state.endEntity_->lla_, NULL, &targetElev, NULL, state.earthModel_, &state.coordConv_); + simCore::calculateAbsAzEl(state.beginEntity_->lla_, state.endEntity_->lla_, nullptr, &targetElev, nullptr, state.earthModel_, &state.coordConv_); + // find the elevation pool and establish a local working set + // since we'll be doing multiple spatially-similar queries osg::ref_ptr pool = state.mapNode_->getMap()->getElevationPool(); - osg::ref_ptr envelope = pool->createEnvelope(state.mapNode_->getMapSRS(), 23); + osgEarth::ElevationPool::WorkingSet workingSet; // Use the los range resolution of the begin entity as the rangeDelta for getting intermediate points double rangeDelta = simdisState->platformHostNode_->getPrefs().losrangeresolution(); @@ -355,14 +357,14 @@ double HorizonMeasurement::calcAboveHorizon_(RangeToolState& state, simCore::Hor currGeoPoint.x() = iter->lon() * simCore::RAD2DEG; currGeoPoint.y() = iter->lat() * simCore::RAD2DEG; - float elevation = envelope->getElevation(currGeoPoint.x(), currGeoPoint.y()); - if (elevation != NO_DATA_VALUE) + osgEarth::ElevationSample sample = pool->getSample(currGeoPoint, osgEarth::Distance(1.0, osgEarth::Units::METERS), &workingSet); + if (sample.hasData()) { - currGeoPoint.z() = elevation; - simCore::Vec3 currLLA(currGeoPoint.y() * simCore::DEG2RAD, currGeoPoint.x() * simCore::DEG2RAD, elevation); + currGeoPoint.z() = sample.elevation().as(osgEarth::Units::METERS); + simCore::Vec3 currLLA(currGeoPoint.y() * simCore::DEG2RAD, currGeoPoint.x() * simCore::DEG2RAD, currGeoPoint.z()); double relativeElev; - simCore::calculateAbsAzEl(state.beginEntity_->lla_, currLLA, NULL, &relativeElev, NULL, state.earthModel_, &state.coordConv_); + simCore::calculateAbsAzEl(state.beginEntity_->lla_, currLLA, nullptr, &relativeElev, nullptr, state.earthModel_, &state.coordConv_); if (relativeElev > targetElev) return 0; } @@ -404,15 +406,15 @@ PodMeasurement::PodMeasurement() double PodMeasurement::value(RangeToolState& state) const { auto simdisState = dynamic_cast(state.beginEntity_); - if (simdisState == NULL) + if (simdisState == nullptr) return 0.0; simRF::RFPropagationFacade* rf = simdisState->rfPropagation_; - if (rf == NULL) + if (rf == nullptr) return 0.0; double az; - getRfParameters_(state, &az, NULL, NULL, NULL, NULL, NULL, false, NULL, NULL); + getRfParameters_(state, &az, nullptr, nullptr, nullptr, nullptr, nullptr, false, nullptr, nullptr); double gndRngMeters = simCore::calculateGroundDist(state.beginEntity_->lla_, state.endEntity_->lla_, state.earthModel_, &state.coordConv_); return rf->getPOD(az, gndRngMeters, state.endEntity_->lla_.alt()); @@ -421,11 +423,11 @@ double PodMeasurement::value(RangeToolState& state) const bool PodMeasurement::willAccept(const RangeToolState& state) const { auto simdisState = dynamic_cast(state.beginEntity_); - if (simdisState == NULL) + if (simdisState == nullptr) return false; return isBeamToEntity_(state.beginEntity_->type_, state.endEntity_->type_) && - (simdisState->rfPropagation_ != NULL); + (simdisState->rfPropagation_ != nullptr); } //---------------------------------------------------------------------------- @@ -437,15 +439,15 @@ LossMeasurement::LossMeasurement() double LossMeasurement::value(RangeToolState& state) const { auto simdisState = dynamic_cast(state.beginEntity_); - if (simdisState == NULL) + if (simdisState == nullptr) return static_cast(simCore::SMALL_DB_VAL); simRF::RFPropagationFacade* rf = simdisState->rfPropagation_; - if (rf == NULL) + if (rf == nullptr) return static_cast(simCore::SMALL_DB_VAL); double az; - getRfParameters_(state, &az, NULL, NULL, NULL, NULL, NULL, false, NULL, NULL); + getRfParameters_(state, &az, nullptr, nullptr, nullptr, nullptr, nullptr, false, nullptr, nullptr); double gndRngMeters = simCore::calculateGroundDist(state.beginEntity_->lla_, state.endEntity_->lla_, state.earthModel_, &state.coordConv_); return rf->getLoss(az, gndRngMeters, state.endEntity_->lla_.alt()); @@ -454,11 +456,11 @@ double LossMeasurement::value(RangeToolState& state) const bool LossMeasurement::willAccept(const RangeToolState& state) const { auto simdisState = dynamic_cast(state.beginEntity_); - if (simdisState == NULL) + if (simdisState == nullptr) return false; return isBeamToEntity_(state.beginEntity_->type_, state.endEntity_->type_) && - (simdisState->rfPropagation_ != NULL); + (simdisState->rfPropagation_ != nullptr); } //---------------------------------------------------------------------------- @@ -470,15 +472,15 @@ PpfMeasurement::PpfMeasurement() double PpfMeasurement::value(RangeToolState& state) const { auto simdisState = dynamic_cast(state.beginEntity_); - if (simdisState == NULL) + if (simdisState == nullptr) return static_cast(simCore::SMALL_DB_VAL); simRF::RFPropagationFacade* rf = simdisState->rfPropagation_; - if (rf == NULL) + if (rf == nullptr) return static_cast(simCore::SMALL_DB_VAL); double az; - getRfParameters_(state, &az, NULL, NULL, NULL, NULL, NULL, false, NULL, NULL); + getRfParameters_(state, &az, nullptr, nullptr, nullptr, nullptr, nullptr, false, nullptr, nullptr); double gndRngMeters = simCore::calculateGroundDist(state.beginEntity_->lla_, state.endEntity_->lla_, state.earthModel_, &state.coordConv_); return rf->getPPF(az, gndRngMeters, state.endEntity_->lla_.alt()); @@ -487,11 +489,11 @@ double PpfMeasurement::value(RangeToolState& state) const bool PpfMeasurement::willAccept(const RangeToolState& state) const { auto simdisState = dynamic_cast(state.beginEntity_); - if (simdisState == NULL) + if (simdisState == nullptr) return false; return isBeamToEntity_(state.beginEntity_->type_, state.endEntity_->type_) && - (simdisState->rfPropagation_ != NULL); + (simdisState->rfPropagation_ != nullptr); } //---------------------------------------------------------------------------- @@ -503,11 +505,11 @@ SnrMeasurement::SnrMeasurement() double SnrMeasurement::value(RangeToolState& state) const { auto simdisState = dynamic_cast(state.beginEntity_); - if (simdisState == NULL) + if (simdisState == nullptr) return static_cast(simCore::SMALL_DB_VAL); simRF::RFPropagationFacade* rf = simdisState->rfPropagation_; - if (rf == NULL) + if (rf == nullptr) return static_cast(simCore::SMALL_DB_VAL); double az; @@ -515,7 +517,7 @@ double SnrMeasurement::value(RangeToolState& state) const double rcvGaindB; double rcsSqm; - getRfParameters_(state, &az, NULL, NULL, &xmtGaindB, &rcvGaindB, &rcsSqm, false, NULL, NULL); + getRfParameters_(state, &az, nullptr, nullptr, &xmtGaindB, &rcvGaindB, &rcsSqm, false, nullptr, nullptr); double slantRngMeters = simCore::calculateSlant(state.beginEntity_->lla_, state.endEntity_->lla_, state.earthModel_, &state.coordConv_); double gndRngMeters = simCore::calculateGroundDist(state.beginEntity_->lla_, state.endEntity_->lla_, state.earthModel_, &state.coordConv_); double altitude = state.endEntity_->lla_.alt(); @@ -530,11 +532,11 @@ double SnrMeasurement::value(RangeToolState& state) const bool SnrMeasurement::willAccept(const RangeToolState& state) const { auto simdisState = dynamic_cast(state.beginEntity_); - if (simdisState == NULL) + if (simdisState == nullptr) return false; return isBeamToEntity_(state.beginEntity_->type_, state.endEntity_->type_) && - (simdisState->rfPropagation_ != NULL); + (simdisState->rfPropagation_ != nullptr); } //---------------------------------------------------------------------------- @@ -546,15 +548,15 @@ CnrMeasurement::CnrMeasurement() double CnrMeasurement::value(RangeToolState& state) const { auto simdisState = dynamic_cast(state.beginEntity_); - if (simdisState == NULL) + if (simdisState == nullptr) return static_cast(simCore::SMALL_DB_VAL); simRF::RFPropagationFacade* rf = simdisState->rfPropagation_; - if (rf == NULL) + if (rf == nullptr) return static_cast(simCore::SMALL_DB_VAL); double az; - getRfParameters_(state, &az, NULL, NULL, NULL, NULL, NULL, false, NULL, NULL); + getRfParameters_(state, &az, nullptr, nullptr, nullptr, nullptr, nullptr, false, nullptr, nullptr); //unlike other RF - related calculations, CNR doesn't have a height component double gndRngMeters = simCore::calculateGroundDist(state.beginEntity_->lla_, state.endEntity_->lla_, state.earthModel_, &state.coordConv_); @@ -564,11 +566,11 @@ double CnrMeasurement::value(RangeToolState& state) const bool CnrMeasurement::willAccept(const RangeToolState& state) const { auto simdisState = dynamic_cast(state.beginEntity_); - if (simdisState == NULL) + if (simdisState == nullptr) return false; return isBeamToEntity_(state.beginEntity_->type_, state.endEntity_->type_) && - (simdisState->rfPropagation_ != NULL); + (simdisState->rfPropagation_ != nullptr); } //---------------------------------------------------------------------------- @@ -581,7 +583,7 @@ double RcsMeasurement::value(RangeToolState& state) const { //RCS is a measure of the electrical or reflective area of a target, it is usually expressed in square meters or dBsm. double rcsDb; - getRfParameters_(state, NULL, NULL, NULL, NULL, NULL, &rcsDb, true, NULL, NULL); + getRfParameters_(state, nullptr, nullptr, nullptr, nullptr, nullptr, &rcsDb, true, nullptr, nullptr); return rcsDb; } @@ -589,12 +591,12 @@ double RcsMeasurement::value(RangeToolState& state) const bool RcsMeasurement::willAccept(const RangeToolState& state) const { auto simdisState = dynamic_cast(state.endEntity_); - if (simdisState == NULL) + if (simdisState == nullptr) return false; return (simdisState->type_ == simData::PLATFORM) && (simdisState->node_->getId() == simdisState->platformHostNode_->getId()) && - (simdisState->platformHostNode_->getRcs() != NULL); + (simdisState->platformHostNode_->getRcs() != nullptr); } diff --git a/SDK/simVis/SimdisRangeToolState.cpp b/SDK/simVis/SimdisRangeToolState.cpp index dea9eacc2..bf9bfd2e2 100644 --- a/SDK/simVis/SimdisRangeToolState.cpp +++ b/SDK/simVis/SimdisRangeToolState.cpp @@ -47,13 +47,13 @@ osg::Vec3d SimdisRangeToolState::coord(Coord which) if (beginEntity_->type_ == simData::BEAM) { auto simdisState = dynamic_cast(beginEntity_); - if (simdisState == NULL) + if (simdisState == nullptr) return osg::Vec3d(); const simVis::BeamNode* beam = dynamic_cast(simdisState->node_.get()); // Node not defined correctly; type() and pointer should match) - assert(beam != NULL); - if (beam != NULL) + assert(beam != nullptr); + if (beam != nullptr) { simCore::Vec3 from; beam->getClosestPoint(endEntity_->lla_, from); @@ -67,13 +67,13 @@ osg::Vec3d SimdisRangeToolState::coord(Coord which) assert(endEntity_->type_ == simData::BEAM); auto simdisState = dynamic_cast(endEntity_); - if (simdisState == NULL) + if (simdisState == nullptr) return osg::Vec3d(); const simVis::BeamNode* beam = dynamic_cast(simdisState->node_.get()); // Node not defined correctly; type() and pointer should match) - assert(beam != NULL); - if (beam != NULL) + assert(beam != nullptr); + if (beam != nullptr) { simCore::Vec3 to; beam->getClosestPoint(beginEntity_->lla_, to); @@ -87,11 +87,11 @@ osg::Vec3d SimdisRangeToolState::coord(Coord which) int SimdisRangeToolState::populateEntityState(const simVis::ScenarioManager& scenario, const simVis::EntityNode* node, EntityState* state) { - if ((node == NULL) || (state == NULL)) + if ((node == nullptr) || (state == nullptr)) return 1; auto hostNode = dynamic_cast(scenario.getHostPlatform(node)); - if (hostNode == NULL) + if (hostNode == nullptr) return 1; state->id_ = node->getId(); @@ -103,7 +103,7 @@ int SimdisRangeToolState::populateEntityState(const simVis::ScenarioManager& sce state->hostId_ = hostNode->getId(); auto simdisState = dynamic_cast(state); - if (simdisState != NULL) + if (simdisState != nullptr) { simdisState->node_ = node; simdisState->platformHostNode_ = hostNode; @@ -120,11 +120,11 @@ int SimdisRangeToolState::populateEntityState(const simVis::ScenarioManager& sce { // Platforms need velocity which is not available from getPositionOrientation, so add it in const simVis::PlatformNode* platform = dynamic_cast(node); - if (platform == NULL) + if (platform == nullptr) return 1; const simData::PlatformUpdate* update = platform->update(); - if (update == NULL) + if (update == nullptr) return 1; simCore::Coordinate ecef(simCore::COORD_SYS_ECEF, @@ -137,7 +137,7 @@ int SimdisRangeToolState::populateEntityState(const simVis::ScenarioManager& sce state->vel_ = needVelocity.velocity(); } - if ((simdisState != NULL) && (simdisState->type_ == simData::BEAM)) + if ((simdisState != nullptr) && (simdisState->type_ == simData::BEAM)) { simRF::RFPropagationManagerPtr manager = scenario.rfPropagationManager(); simdisState->rfPropagation_ = manager->getRFPropagation(node->getId()); diff --git a/SDK/simVis/SimdisRangeToolState.h b/SDK/simVis/SimdisRangeToolState.h index 0390942d0..67374c33d 100644 --- a/SDK/simVis/SimdisRangeToolState.h +++ b/SDK/simVis/SimdisRangeToolState.h @@ -43,9 +43,9 @@ struct SDKVIS_EXPORT SimdisEntityState : public EntityState simRF::RFPropagationFacade* rfPropagation_; ///< If the entity is a beam this MAY BE set SimdisEntityState() - : node_(NULL), - platformHostNode_(NULL), - rfPropagation_(NULL) + : node_(nullptr), + platformHostNode_(nullptr), + rfPropagation_(nullptr) { } virtual ~SimdisEntityState() diff --git a/SDK/simVis/SphericalVolume.cpp b/SDK/simVis/SphericalVolume.cpp index da25e02bf..abb18b6e3 100644 --- a/SDK/simVis/SphericalVolume.cpp +++ b/SDK/simVis/SphericalVolume.cpp @@ -144,7 +144,7 @@ namespace nearFaceOffset_(nearFaceOffset), drawWalls_(drawWalls) { - // svPyramid must provide a non-NULL vertex array + // svPyramid must provide a non-nullptr vertex array assert(vertexArray); setName("simVis::SphericalVolume::svPyramidOutline"); xform.addChild(this); @@ -405,13 +405,13 @@ namespace generateWalls_(solidGeometry_.get()); // release our ref_ptr, we don't need it anymore - solidGeometry_ = NULL; + solidGeometry_ = nullptr; } const bool drawOutlines = (simVis::SVData::DRAW_MODE_OUTLINE & data.drawMode_) == simVis::SVData::DRAW_MODE_OUTLINE; if (drawOutlines) { - // must provide a non-NULL vertexArray to svPyramidOutline + // must provide a non-nullptr vertexArray to svPyramidOutline assert(vertexArray_); svPyramidOutline* outline = new svPyramidOutline(xform, vertexArray_.get(), numPointsX_, numPointsZ_, farFaceOffset_, nearFaceOffset_, drawWalls_); outline->setColor(color_); @@ -453,7 +453,7 @@ namespace // Calculate the number of vertices for performance hotspot fix in push_back() // vertices will be added in this order: gate origin, far face, near face (if drawn), cone bottom, then cone right (if drawn), cone top (if drawn), cone left (if drawn) - const unsigned int loop = hasNear_ ? 2 : 1; + const unsigned int loop = hasNear_ ? 2u : 1u; reserveSizeFace_ = 1 + (loop * numPointsX_ * numPointsZ_); reserveSizeCone_ = 0; drawFaces_ = (data.drawMode_ != simVis::SVData::DRAW_MODE_OUTLINE); @@ -1101,7 +1101,7 @@ void SVFactory::processWireframe_(osg::MatrixTransform* xform, int drawMode) if (SVData::DRAW_MODE_WIRE & drawMode) { osg::Geometry* solidGeom = SVFactory::solidGeometry(xform); - if (solidGeom == NULL || solidGeom->empty()) + if (solidGeom == nullptr || solidGeom->empty()) { assert(0); return; @@ -1160,7 +1160,7 @@ void SVFactory::updateStippling(osg::MatrixTransform* xform, bool stippling) { // only the solid geometry can be stippled osg::Geometry* geom = SVFactory::solidGeometry(xform); - if (geom == NULL || geom->empty()) + if (geom == nullptr || geom->empty()) { // Assertion failure means internal consistency error, or caller has inconsistent input assert(0); @@ -1173,7 +1173,7 @@ void SVFactory::updateLighting(osg::MatrixTransform* xform, bool lighting) { // lighting is only applied to the solid geometry osg::Geometry* geom = SVFactory::solidGeometry(xform); - if (geom == NULL || geom->empty()) + if (geom == nullptr || geom->empty()) { // Assertion failure means internal consistency error, or caller has inconsistent input assert(0); @@ -1189,7 +1189,7 @@ void SVFactory::updateBlending(osg::MatrixTransform* xform, bool blending) { // blending is only applied to the solid geometry osg::Geometry* geom = SVFactory::solidGeometry(xform); - if (geom == NULL || geom->empty()) + if (geom == nullptr || geom->empty()) { // Assertion failure means internal consistency error, or caller has inconsistent input assert(0); @@ -1203,7 +1203,7 @@ void SVFactory::updateBlending(osg::MatrixTransform* xform, bool blending) void SVFactory::updateColor(osg::MatrixTransform* xform, const osg::Vec4f& color) { osg::Geometry* geom = SVFactory::solidGeometry(xform); - if (geom == NULL || geom->empty()) + if (geom == nullptr || geom->empty()) { // Assertion failure means internal consistency error, or caller has inconsistent input assert(0); @@ -1227,7 +1227,7 @@ void SVFactory::updateColor(osg::MatrixTransform* xform, const osg::Vec4f& color // if we have an 2nd (optional) geode, it is opaque; update its color, but remove transparency osg::Geode* opaqueGeode = SVFactory::opaqueGeode(xform); - if (opaqueGeode == NULL) + if (opaqueGeode == nullptr) return; // the opaque geode may be an svPyramidOutline; svPyramidOutline sets the opacity itself @@ -1242,7 +1242,7 @@ void SVFactory::updateColor(osg::MatrixTransform* xform, const osg::Vec4f& color if (opaqueGeode->getNumDrawables() == 1) { geom = opaqueGeode->getDrawable(0)->asGeometry(); - if (geom == NULL) + if (geom == nullptr) { // Assertion failure means internal consistency error, or caller has inconsistent input assert(0); @@ -1278,7 +1278,7 @@ void SVFactory::updateColor(osg::MatrixTransform* xform, const osg::Vec4f& color void SVFactory::updateNearRange(osg::MatrixTransform* xform, double nearRange) { osg::Geometry* geom = SVFactory::solidGeometry(xform); - if (geom == NULL || geom->empty()) + if (geom == nullptr || geom->empty()) { // Assertion failure means internal consistency error, or caller has inconsistent input assert(0); @@ -1290,7 +1290,7 @@ void SVFactory::updateNearRange(osg::MatrixTransform* xform, double nearRange) SVMetaContainer* meta = static_cast(geom->getUserData()); // Assertion failure means internal consistency error, or caller has inconsistent input assert(meta); - if (verts == NULL || meta == NULL) + if (verts == nullptr || meta == nullptr) return; const std::vector& m = meta->vertMeta_; @@ -1309,7 +1309,7 @@ void SVFactory::updateNearRange(osg::MatrixTransform* xform, double nearRange) void SVFactory::updateFarRange(osg::MatrixTransform* xform, double farRange) { osg::Geometry* geom = SVFactory::solidGeometry(xform); - if (geom == NULL || geom->empty()) + if (geom == nullptr || geom->empty()) { // Assertion failure means internal consistency error, or caller has inconsistent input assert(0); @@ -1321,7 +1321,7 @@ void SVFactory::updateFarRange(osg::MatrixTransform* xform, double farRange) SVMetaContainer* meta = static_cast(geom->getUserData()); // Assertion failure means internal consistency error, or caller has inconsistent input assert(meta); - if (verts == NULL || meta == NULL) + if (verts == nullptr || meta == nullptr) return; const std::vector& m = meta->vertMeta_; @@ -1340,7 +1340,7 @@ void SVFactory::updateFarRange(osg::MatrixTransform* xform, double farRange) void SVFactory::updateHorizAngle(osg::MatrixTransform* xform, double oldAngle, double newAngle) { osg::Geometry* geom = SVFactory::solidGeometry(xform); - if (geom == NULL || geom->empty()) + if (geom == nullptr || geom->empty()) { // Assertion failure means internal consistency error, or caller has inconsistent input assert(0); @@ -1349,7 +1349,7 @@ void SVFactory::updateHorizAngle(osg::MatrixTransform* xform, double oldAngle, d osg::Vec3Array* verts = static_cast(geom->getVertexArray()); SVMetaContainer* meta = static_cast(geom->getUserData()); osg::Vec3Array* normals = static_cast(geom->getNormalArray()); - if (verts == NULL || meta == NULL || normals == NULL) + if (verts == nullptr || meta == nullptr || normals == nullptr) { // Assertion failure means internal consistency error, or caller has inconsistent input assert(0); @@ -1492,7 +1492,7 @@ void SVFactory::updateHorizAngle(osg::MatrixTransform* xform, double oldAngle, d void SVFactory::updateVertAngle(osg::MatrixTransform* xform, double oldAngle, double newAngle) { osg::Geometry* geom = SVFactory::solidGeometry(xform); - if (geom == NULL || geom->empty()) + if (geom == nullptr || geom->empty()) { // Assertion failure means internal consistency error, or caller has inconsistent input assert(0); @@ -1501,7 +1501,7 @@ void SVFactory::updateVertAngle(osg::MatrixTransform* xform, double oldAngle, do osg::Vec3Array* verts = static_cast(geom->getVertexArray()); SVMetaContainer* meta = static_cast(geom->getUserData()); osg::Vec3Array* normals = static_cast(geom->getNormalArray()); - if (verts == NULL || meta == NULL || normals == NULL) + if (verts == nullptr || meta == nullptr || normals == nullptr) { // Assertion failure means internal consistency error, or caller has inconsistent input assert(0); @@ -1642,26 +1642,26 @@ void SVFactory::updateVertAngle(osg::MatrixTransform* xform, double oldAngle, do osg::Geometry* SVFactory::solidGeometry(osg::MatrixTransform* xform) { - if (xform == NULL || xform->getNumChildren() == 0) - return NULL; + if (xform == nullptr || xform->getNumChildren() == 0) + return nullptr; osg::Geode* geode = xform->getChild(0)->asGeode(); - if (geode == NULL || geode->getNumDrawables() == 0) - return NULL; + if (geode == nullptr || geode->getNumDrawables() == 0) + return nullptr; return geode->getDrawable(0)->asGeometry(); } // if the sv has a 2nd geode that adds outline or wireframe, it will be the MatrixTransform 2nd child osg::Geode* SVFactory::opaqueGeode(osg::MatrixTransform* xform) { - if (xform == NULL || xform->getNumChildren() < 2) - return NULL; + if (xform == nullptr || xform->getNumChildren() < 2) + return nullptr; return xform->getChild(1)->asGeode(); } // dirty bounds for all geometries in the xform void SVFactory::dirtyBound_(osg::MatrixTransform* xform) { - if (xform == NULL || xform->getNumChildren() == 0) + if (xform == nullptr || xform->getNumChildren() == 0) return; // handle the geometries in the primary geode diff --git a/SDK/simVis/SphericalVolume.h b/SDK/simVis/SphericalVolume.h index 9bad113de..d040332d9 100644 --- a/SDK/simVis/SphericalVolume.h +++ b/SDK/simVis/SphericalVolume.h @@ -135,9 +135,9 @@ class SVFactory /// tweak the verts to update the vertical angle static void updateVertAngle(osg::MatrixTransform* xform, double oldAngle, double newAngle); - /// Retrieves the 2nd opaque geode (e.g., outline or wireframe), or NULL if there is none + /// Retrieves the 2nd opaque geode (e.g., outline or wireframe), or nullptr if there is none static osg::Geode* opaqueGeode(osg::MatrixTransform* xform); - /// Retrieves the primary 'solid' geometry, or NULL if there is no such geometry + /// Retrieves the primary 'solid' geometry, or nullptr if there is no such geometry static osg::Geometry* solidGeometry(osg::MatrixTransform* xform); private: diff --git a/SDK/simVis/TargetDelegation.cpp b/SDK/simVis/TargetDelegation.cpp index 959b89e22..8c8a51ade 100644 --- a/SDK/simVis/TargetDelegation.cpp +++ b/SDK/simVis/TargetDelegation.cpp @@ -63,11 +63,11 @@ void TargetDelegation::addOrUpdate(const PlatformNode* platform) // determine whether we're already tracking this platform: const TargetNodeMap::iterator t = targetNodes_.find(platform); const bool isTracked = t != targetNodes_.end(); - osg::MatrixTransform* mt = isTracked? t->second.get() : NULL; + osg::MatrixTransform* mt = isTracked? t->second.get() : nullptr; // get the ECEF position of the target const simData::PlatformUpdate* update = platform->update(); - if (update == NULL) + if (update == nullptr) { // this probably means the platform should have been removed assert(0); diff --git a/SDK/simVis/Text.h b/SDK/simVis/Text.h index 08f2c0a65..e88efc3f8 100644 --- a/SDK/simVis/Text.h +++ b/SDK/simVis/Text.h @@ -44,7 +44,7 @@ namespace simVis virtual osg::Object* cloneType() const { return new Text(); } virtual osg::Object* clone(const osg::CopyOp& copyop) const { return new Text(*this,copyop); } - virtual bool isSameKindAs(const osg::Object* obj) const { return dynamic_cast(obj)!=NULL; } + virtual bool isSameKindAs(const osg::Object* obj) const { return dynamic_cast(obj)!=nullptr; } virtual const char* className() const { return "Text"; } virtual const char* libraryName() const { return "simVis"; } diff --git a/SDK/simVis/TimeTicks.cpp b/SDK/simVis/TimeTicks.cpp index 56250e5ed..5f8a5a531 100644 --- a/SDK/simVis/TimeTicks.cpp +++ b/SDK/simVis/TimeTicks.cpp @@ -79,11 +79,11 @@ TimeTicks::TimeTicks(const simData::DataStore& ds, Locator* parentLocator, Platf lastLabelTime_(-1.0), labelInterval_(0.0), timeDirection_(simCore::FORWARD), - chunkGroup_(NULL), - labelGroup_(NULL), + chunkGroup_(nullptr), + labelGroup_(nullptr), platformTspiFilterManager_(platformTspiFilterManager), entityId_(entityId), - currentPointChunk_(NULL), + currentPointChunk_(nullptr), parentLocator_(parentLocator) { updateSliceBase_ = ds_.platformUpdateSlice(entityId); @@ -104,11 +104,11 @@ TimeTicks::TimeTicks(const simData::DataStore& ds, Locator* parentLocator, Platf TimeTicks::~TimeTicks() { - chunkGroup_ = NULL; - labelGroup_ = NULL; - currentPointChunk_ = NULL; - parentLocator_ = NULL; - localLocator_ = NULL; + chunkGroup_ = nullptr; + labelGroup_ = nullptr; + currentPointChunk_ = nullptr; + parentLocator_ = nullptr; + localLocator_ = nullptr; } void TimeTicks::reset() @@ -124,7 +124,7 @@ void TimeTicks::reset() labelGroup_ = new osg::Group(); addChild(labelGroup_); addChild(chunkGroup_); - currentPointChunk_ = NULL; + currentPointChunk_ = nullptr; lastLargeTickTime_ = -1.0; lastLabelTime_ = -1.0; singlePoint_ = false; @@ -143,7 +143,7 @@ TimeTicksChunk* TimeTicks::getCurrentChunk_() return chunk; } } - return NULL; + return nullptr; } TimeTicksChunk* TimeTicks::getLastChunk_() @@ -154,7 +154,7 @@ TimeTicksChunk* TimeTicks::getLastChunk_() TimeTicksChunk* chunk = static_cast(chunkGroup_->getChild(num - 1)); return chunk; } - return NULL; + return nullptr; } TimeTicksChunk* TimeTicks::getFirstChunk_() @@ -165,7 +165,7 @@ TimeTicksChunk* TimeTicks::getFirstChunk_() TimeTicksChunk* chunk = static_cast(chunkGroup_->getChild(0)); return chunk; } - return NULL; + return nullptr; } double TimeTicks::toDrawTime_(double updateTime) const @@ -176,7 +176,7 @@ double TimeTicks::toDrawTime_(double updateTime) const void TimeTicks::addUpdate_(double tickTime) { const simData::PlatformUpdateSlice* updateSlice = static_cast(updateSliceBase_); - if (updateSlice == NULL) + if (updateSlice == nullptr) { // a valid/active platform must have an updateSlice - if assert fails, ensure that time ticks is not being updated for a non valid platform assert(0); @@ -237,7 +237,7 @@ void TimeTicks::addUpdate_(double tickTime) if (addLabel || newChunk) { // these are the only two cases that require a new locator - newLocator = new Locator(parentLocator_); + newLocator = new Locator(parentLocator_.get()); newLocator->setCoordinate(ecefTickCoord, tickTime); if (parentLocator_->isEci()) newLocator->setEciRotationTime(-tickTime, tickTime, false); @@ -291,7 +291,7 @@ void TimeTicks::addUpdate_(double tickTime) } // locator node syncs its matrix to locator immediately - LocatorNode* locNode = new LocatorNode(newLocator); + LocatorNode* locNode = new LocatorNode(newLocator.get()); osgText::Text* text = new osgText::Text(); text->setPosition(osg::Vec3(0.f, 0.f, 0.f)); text->setText(labelText); @@ -519,7 +519,7 @@ void TimeTicks::update() return; const simData::PlatformUpdateSlice* updateSlice = static_cast(updateSliceBase_); - if (updateSlice == NULL) + if (updateSlice == nullptr) { // a valid/active platform must have an updateSlice - if assert fails, ensure that time ticks is not being updated for a non valid platform assert(0); @@ -527,7 +527,7 @@ void TimeTicks::update() } // if the current is not valid, and scenario is prior to first update time, nothing to do - if (updateSlice->current() == NULL && ds_.updateTime() < updateSlice->firstTime()) + if (updateSlice->current() == nullptr && ds_.updateTime() < updateSlice->firstTime()) { // platform is not valid, this should only occur during platform creation return; diff --git a/SDK/simVis/TimeTicks.h b/SDK/simVis/TimeTicks.h index ad797bbe0..30a6a42d9 100644 --- a/SDK/simVis/TimeTicks.h +++ b/SDK/simVis/TimeTicks.h @@ -104,19 +104,19 @@ class SDKVIS_EXPORT TimeTicks : public osg::Group /** * Return a chunk to which you can add a new point - * @return chunk that can accept a new point, or NULL if a new one needs to be created + * @return chunk that can accept a new point, or nullptr if a new one needs to be created */ TimeTicksChunk* getCurrentChunk_(); /** * Return the last chunk in the group, - * @return last chunk, or NULL if group is empty + * @return last chunk, or nullptr if group is empty */ TimeTicksChunk* getLastChunk_(); /** * Return the first chunk in the group - * @return first chunk, or NULL if group is empty + * @return first chunk, or nullptr if group is empty */ TimeTicksChunk* getFirstChunk_(); diff --git a/SDK/simVis/TimeTicksChunk.cpp b/SDK/simVis/TimeTicksChunk.cpp index 27ccb9654..cedc38666 100644 --- a/SDK/simVis/TimeTicksChunk.cpp +++ b/SDK/simVis/TimeTicksChunk.cpp @@ -45,11 +45,11 @@ TimeTicksChunk::TimeTicksChunk(unsigned int maxSize, Type type, double lineLengt TimeTicksChunk::~TimeTicksChunk() { - lineGroup_ = NULL; - line_ = NULL; - point_ = NULL; - largePoint_ = NULL; - line_ = NULL; + lineGroup_ = nullptr; + line_ = nullptr; + point_ = nullptr; + largePoint_ = nullptr; + line_ = nullptr; } bool TimeTicksChunk::addPoint(const Locator& tickLocator, double time, const osg::Vec4& color, bool large) diff --git a/SDK/simVis/TrackChunkNode.cpp b/SDK/simVis/TrackChunkNode.cpp index e19a74282..8f9cb4c6c 100644 --- a/SDK/simVis/TrackChunkNode.cpp +++ b/SDK/simVis/TrackChunkNode.cpp @@ -122,11 +122,11 @@ TrackChunkNode::TrackChunkNode(unsigned int maxSize, simData::TrackPrefs_Mode mo TrackChunkNode::~TrackChunkNode() { - lineGroup_ = NULL; - centerLine_ = NULL; - centerPoints_ = NULL; - ribbon_ = NULL; - drop_ = NULL; + lineGroup_ = nullptr; + centerLine_ = nullptr; + centerPoints_ = nullptr; + ribbon_ = nullptr; + drop_ = nullptr; } /// add a new point to the chunk. diff --git a/SDK/simVis/TrackHistory.cpp b/SDK/simVis/TrackHistory.cpp index 56dcab585..843773089 100644 --- a/SDK/simVis/TrackHistory.cpp +++ b/SDK/simVis/TrackHistory.cpp @@ -60,13 +60,13 @@ class TrackHistoryNode::ColorTableObserver : public simData::DataTableManager::M void onAddTable(simData::DataTable* table) { - if ((table != NULL) && (table->ownerId() == parent_.entityId_) && (table->tableName() == simData::INTERNAL_TRACK_HISTORY_TABLE)) + if ((table != nullptr) && (table->ownerId() == parent_.entityId_) && (table->tableName() == simData::INTERNAL_TRACK_HISTORY_TABLE)) parent_.initializeTableId_(); } void onPreRemoveTable(simData::DataTable* table) { - if (table != NULL && table->tableId() == parent_.tableId_) + if (table != nullptr && table->tableId() == parent_.tableId_) { parent_.tableId_ = 0; table->removeObserver(parent_.colorChangeObserver_); @@ -112,12 +112,12 @@ TrackHistoryNode::TrackHistoryNode(const simData::DataStore& ds, Locator* parent lastCurrentTime_(-1.0), timeDirection_(simCore::FORWARD), timeDirectionSign_(1.0), - chunkGroup_(NULL), - altModeXform_(NULL), + chunkGroup_(nullptr), + altModeXform_(nullptr), platformTspiFilterManager_(platformTspiFilterManager), entityId_(entityId), tableId_(0), - currentPointChunk_(NULL), + currentPointChunk_(nullptr), parentLocator_(parentLocator) { updateSliceBase_ = ds_.platformUpdateSlice(entityId); @@ -125,7 +125,7 @@ TrackHistoryNode::TrackHistoryNode(const simData::DataStore& ds, Locator* parent activeColor_ = defaultColor_; - localLocator_ = new simVis::Locator(parentLocator_); + localLocator_ = new simVis::Locator(parentLocator_.get()); setNodeMask(simVis::DISPLAY_MASK_TRACK_HISTORY); @@ -133,6 +133,7 @@ TrackHistoryNode::TrackHistoryNode(const simData::DataStore& ds, Locator* parent // configure the local state set simVis::setLighting(getOrCreateStateSet(), 0); + getOrCreateStateSet()->setRenderBinDetails(BIN_TRACK_HISTORY, BIN_GLOBAL_SIMSDK); // flatten in overhead mode. simVis::OverheadMode::enableGeometryFlattening(true, this); @@ -150,13 +151,13 @@ TrackHistoryNode::~TrackHistoryNode() if (tableId_ > 0) { simData::DataTable* table = ds_.dataTableManager().getTable(tableId_); - if (table != NULL) + if (table != nullptr) table->removeObserver(colorChangeObserver_); } - chunkGroup_ = NULL; - currentPointChunk_ = NULL; - parentLocator_ = NULL; - localLocator_ = NULL; + chunkGroup_ = nullptr; + currentPointChunk_ = nullptr; + parentLocator_ = nullptr; + localLocator_ = nullptr; } // handle an explicit reset @@ -167,16 +168,16 @@ void TrackHistoryNode::reset() hasLastDrawTime_ = false; lastCurrentTime_ = -1.0; totalPoints_ = 0; - altModeXform_ = NULL; + altModeXform_ = nullptr; chunkGroup_ = new osg::Group(); this->addChild(chunkGroup_); - currentPointChunk_ = NULL; + currentPointChunk_ = nullptr; } void TrackHistoryNode::checkColorHistoryChange_(const simData::DataTable& table, const simData::TableRow& row) { simData::TableColumn* col = table.column(simData::INTERNAL_TRACK_HISTORY_COLOR_COLUMN); - if (col == NULL) + if (col == nullptr) { assert(0); // if the table exists, the column should exist return; @@ -188,7 +189,7 @@ void TrackHistoryNode::checkColorHistoryChange_(const simData::DataTable& table, const simData::PlatformUpdateSlice* updateSlice = static_cast(updateSliceBase_); // there might be no current data after a flush, if a color command is added before any new update data - if (updateSlice == NULL || updateSlice->current() == NULL) + if (updateSlice == nullptr || updateSlice->current() == nullptr) return; // if this row is not in the span of our slice, don't bother to reset @@ -203,7 +204,7 @@ void TrackHistoryNode::checkColorHistoryChange_(const simData::DataTable& table, } /** -* Return a chunk to which you can add a new point, or NULL if one needs to be created for that addition. +* Return a chunk to which you can add a new point, or nullptr if one needs to be created for that addition. */ TrackChunkNode* TrackHistoryNode::getCurrentChunk_() { @@ -218,7 +219,7 @@ TrackChunkNode* TrackHistoryNode::getCurrentChunk_() return chunk; } } - return NULL; + return nullptr; } osg::Vec4f TrackHistoryNode::historyColorAtTime_(double time) @@ -237,13 +238,13 @@ osg::Vec4f TrackHistoryNode::historyColorAtTime_(double time) // use the tableId_ if we have it simData::DataTable* table = ds_.dataTableManager().getTable(tableId_); // no color history table, simply return the default color - if (table == NULL) + if (table == nullptr) { assert(0); // table id is no longer valid, somehow the table got removed return defaultColor_; } simData::TableColumn* column = table->column(simData::INTERNAL_TRACK_HISTORY_COLOR_COLUMN); - if (column == NULL) + if (column == nullptr) { assert(0); // found the table, but missing the expected data column return defaultColor_; @@ -268,7 +269,7 @@ void TrackHistoryNode::initializeTableId_() if (tableId_ != 0) return; simData::DataTable* table = ds_.dataTableManager().findTable(entityId_, simData::INTERNAL_TRACK_HISTORY_TABLE); - if (table == NULL) + if (table == nullptr) return; tableId_ = table->tableId(); assert(tableId_ > 0); // a table was created with an invalid table id @@ -295,18 +296,18 @@ void TrackHistoryNode::addUpdate_(const simData::PlatformUpdate& u, const simDat if (!chunk) { // new chunk needs a new locator - osg::ref_ptr newChunkLocator = new Locator(parentLocator_); + osg::ref_ptr newChunkLocator = new Locator(parentLocator_.get()); chunk = new TrackChunkNode(chunkSize_, lastPlatformPrefs_.trackprefs().trackdrawmode()); // set the new chunk's locator - this will establish the position of the chunk - chunk->setLocator(newChunkLocator); + chunk->setLocator(newChunkLocator.get()); // if there is a preceding chunk, duplicate its last point so there is no // discontinuity from previous chunk to this new chunk - this matters for line, ribbon and bridge drawing modes // note that this extra point needs to be removed during data limiting - if (chunkGroup_->getNumChildren() > 0 && prevUpdate != NULL) + if (chunkGroup_->getNumChildren() > 0 && prevUpdate != nullptr) { - if (fillLocator_(*prevUpdate, newChunkLocator)) + if (fillLocator_(*prevUpdate, newChunkLocator.get())) { const double last_t = prevUpdate->time(); chunk->addPoint(*(newChunkLocator.get()), last_t, historyColorAtTime_(last_t), hostBounds_); @@ -397,7 +398,7 @@ void TrackHistoryNode::updateVisibility_(const simData::TrackPrefs& prefs) void TrackHistoryNode::updateAltMode_(bool altmode, const simData::PlatformUpdateSlice& updateSlice) { // create the altmode group if necessary: - if (altmode && altModeXform_ == NULL) + if (altmode && altModeXform_ == nullptr) { dropVertsDrawable_ = new osgEarth::LineDrawable(GL_LINES); dropVertsDrawable_->setColor(simVis::Color::White); @@ -634,7 +635,7 @@ void TrackHistoryNode::update() return; const simData::PlatformUpdateSlice* updateSlice = static_cast(updateSliceBase_); - if (updateSlice == NULL) + if (updateSlice == nullptr) { // a valid/active platform must have an updateSlice - if assert fails, ensure that track history is not being updated for a non valid platform assert(0); @@ -642,7 +643,7 @@ void TrackHistoryNode::update() } // if the current is not valid, and scenario is prior to first update time, nothing to do - if (updateSlice->current() == NULL && ds_.updateTime() < updateSlice->firstTime()) + if (updateSlice->current() == nullptr && ds_.updateTime() < updateSlice->firstTime()) { // platform is not valid, this should only occur during platform creation return; @@ -726,7 +727,7 @@ void TrackHistoryNode::updateTrackData_(double currentTime, double firstTime) void TrackHistoryNode::backfillTrackHistory_(double endTime, double beginTime) { const simData::PlatformUpdateSlice* updateSlice = static_cast(updateSliceBase_); - if (updateSlice == NULL) + if (updateSlice == nullptr) { // a valid/active platform must have an updateSlice - if assert fails, ensure that track history is not being updated for a non valid platform assert(0); @@ -768,7 +769,7 @@ void TrackHistoryNode::backfillTrackHistory_(double endTime, double beginTime) void TrackHistoryNode::updateCurrentPoint_(const simData::PlatformUpdateSlice& updateSlice) { // remove previous, will recreate if needed - if (currentPointChunk_ != NULL) + if (currentPointChunk_ != nullptr) currentPointChunk_->reset(); // only line, ribbon, and bridge draw modes require this processing, @@ -780,13 +781,13 @@ void TrackHistoryNode::updateCurrentPoint_(const simData::PlatformUpdateSlice& u // create the special chunk for rendering the interpolated point, has two points to connect to rest of history osg::ref_ptr currentChunkLocator; - if (currentPointChunk_ == NULL) + if (currentPointChunk_ == nullptr) { currentPointChunk_ = new TrackChunkNode(2, lastPlatformPrefs_.trackprefs().trackdrawmode()); - if (currentPointChunk_ == NULL) + if (currentPointChunk_ == nullptr) return; addChild(currentPointChunk_); - currentChunkLocator = new Locator(parentLocator_); + currentChunkLocator = new Locator(parentLocator_.get()); currentPointChunk_->setLocator(currentChunkLocator.get()); } else @@ -794,7 +795,7 @@ void TrackHistoryNode::updateCurrentPoint_(const simData::PlatformUpdateSlice& u // find the most current update, either whatever is current, or the last available update const simData::PlatformUpdate* current = updateSlice.current(); - if (current == NULL) + if (current == nullptr) { simData::PlatformUpdateSlice::Iterator iter = updateSlice.lower_bound(updateSlice.lastTime()); current = iter.next(); diff --git a/SDK/simVis/TrackHistory.h b/SDK/simVis/TrackHistory.h index 188acec4d..fc587f96c 100644 --- a/SDK/simVis/TrackHistory.h +++ b/SDK/simVis/TrackHistory.h @@ -128,7 +128,7 @@ class SDKVIS_EXPORT TrackHistoryNode : public osg::Group /** * Return a chunk to which you can add a new point - * @return chunk that can accept a new point, or NULL if a new one needs to be created + * @return chunk that can accept a new point, or nullptr if a new one needs to be created */ TrackChunkNode* getCurrentChunk_(); diff --git a/SDK/simVis/Utils.cpp b/SDK/simVis/Utils.cpp index 92f4cd4c8..2bfd5846f 100644 --- a/SDK/simVis/Utils.cpp +++ b/SDK/simVis/Utils.cpp @@ -172,7 +172,7 @@ namespace haveInit_(false) { setName(simVis::BIN_TWO_PASS_ALPHA); - setStateSet(NULL); + setStateSet(nullptr); // Note! We do not protect the depth settings here, because this then allows us to // disable the depth buffer at a higher level (e.g. when enabling Overhead mode). @@ -283,12 +283,6 @@ namespace namespace simVis { -bool useRexEngine() -{ - // The MP engine is no longer supported. Always use rex. - return true; -} - bool getLighting(osg::StateSet* stateset, osg::StateAttribute::OverrideValue& out_value) { if (!stateset) @@ -827,7 +821,7 @@ osg::Matrix computeLocalToWorld(const osg::Node* node) simCore::Vec3 computeNodeGeodeticPosition(const osg::Node* node) { - if (node == NULL) + if (node == nullptr) return simCore::Vec3(); const osg::Vec3d& ecefPos = computeLocalToWorld(node).getTrans(); simCore::Vec3 llaPos; @@ -1162,9 +1156,9 @@ void FixDeprecatedDrawModes::apply(osg::Geometry& geom) const unsigned int numPrimSets = geom.getNumPrimitiveSets(); for (unsigned int k = 0; k < numPrimSets; ++k) { - // Only care about non-NULL primitive sets + // Only care about non-nullptr primitive sets const osg::PrimitiveSet* primSet = geom.getPrimitiveSet(k); - if (primSet == NULL) + if (primSet == nullptr) continue; // Search for modes that are deprecated in GL3 @@ -1287,7 +1281,7 @@ bool PixelScaleHudTransform::computeWorldToLocalMatrix(osg::Matrix& matrix, osg: osg::Matrixd PixelScaleHudTransform::computeMatrix_(osg::NodeVisitor* nv) const { - osg::CullStack* cs = nv ? nv->asCullStack() : NULL; + osg::CullStack* cs = nv ? nv->asCullStack() : nullptr; if (cs) invertedMvpw_ = osg::Matrix::inverse(*cs->getMVPW()); return invertedMvpw_; diff --git a/SDK/simVis/Utils.h b/SDK/simVis/Utils.h index 035e55702..83006cbf6 100644 --- a/SDK/simVis/Utils.h +++ b/SDK/simVis/Utils.h @@ -50,10 +50,10 @@ // MACROS to test for changes in protobuf properties. #define PB_HAS_FIELD(a, field) ( \ - ((a)!=NULL) && ((a)->has_##field()) ) + ((a)!=nullptr) && ((a)->has_##field()) ) #define PB_DOESNT_HAVE_FIELD(a, field) ( \ - ((a)==NULL) || (!(a)->has_##field()) ) + ((a)==nullptr) || (!(a)->has_##field()) ) #define PB_FIELD_APPEARED(a, b, field) ( \ PB_DOESNT_HAVE_FIELD((a), field) && \ @@ -105,13 +105,6 @@ namespace simVis { class PlatformModelNode; -#ifdef USE_DEPRECATED_SIMDISSDK_API - /** - * Whether to use the REX terrain engine. - */ - SDK_DEPRECATE(SDKVIS_EXPORT bool useRexEngine(), "Method will be removed in a future SDK release."); -#endif - /** * Enable or disable lighting on a state set. We must set both the * FFP mode and the uniform to support shader-based and non-shader-based @@ -165,7 +158,7 @@ namespace simVis /** * Utility template method to find the first Update Callback of the given type. * @param node Node to search the update callback chain of - * @return First update callback that is of type T, or NULL if none is found. + * @return First update callback that is of type T, or nullptr if none is found. */ template T* findUpdateCallbackOfType(osg::Node* node) @@ -178,7 +171,7 @@ namespace simVis return asType; callback = callback->getNestedCallback(); } - return NULL; + return nullptr; } /// convert a simCore::Coordinate to a GeoPoint, if possible diff --git a/SDK/simVis/VaporTrail.cpp b/SDK/simVis/VaporTrail.cpp index 236ef3ae6..f4f690f38 100644 --- a/SDK/simVis/VaporTrail.cpp +++ b/SDK/simVis/VaporTrail.cpp @@ -97,11 +97,11 @@ VaporTrail::~VaporTrail() recyclePuffs_.clear(); if (expireModeGroup_.valid()) expireModeGroup_->removeChild(vaporTrailGroup_); - vaporTrailGroup_ = NULL; - hostPlatform_ = NULL; + vaporTrailGroup_ = nullptr; + hostPlatform_ = nullptr; textures_.clear(); - locator_ = NULL; + locator_ = nullptr; } void VaporTrail::update(double time) @@ -296,7 +296,7 @@ int VaporTrail::addFirstPuff_() // interpolation may be required simData::PlatformUpdate interpolatedPlatformUpdate; simData::Interpolator* li = dataStore_.interpolator(); - if (platformUpdate->time() != time && li != NULL && platformIter.hasNext()) + if (platformUpdate->time() != time && li != nullptr && platformIter.hasNext()) { // defn of upper_bound previous() assert(platformUpdate->time() < time); diff --git a/SDK/simVis/VaporTrailStorage.cpp b/SDK/simVis/VaporTrailStorage.cpp index 8710dfdf2..5072cfbc3 100644 --- a/SDK/simVis/VaporTrailStorage.cpp +++ b/SDK/simVis/VaporTrailStorage.cpp @@ -64,7 +64,7 @@ VaporTrailStorage::~VaporTrailStorage() // remove the vaporTrails from the scene graph for (std::map >::iterator it = vaporTrailsByKey_.begin(); it != vaporTrailsByKey_.end(); ++it) { - it->second = NULL; + it->second = nullptr; } vaporTrailsByKey_.clear(); idsByPlatform_.clear(); @@ -112,7 +112,7 @@ int VaporTrailStorage::addVaporTrail(simData::ObjectId platId, unsigned int id, return 1; } - if (dataStoreListener_ == NULL) + if (dataStoreListener_ == nullptr) { dataStoreListener_.reset(new DataStoreListener(*this)); dataStore_.addListener(dataStoreListener_); diff --git a/SDK/simVis/View.cpp b/SDK/simVis/View.cpp index 0844c6c03..c8079703b 100644 --- a/SDK/simVis/View.cpp +++ b/SDK/simVis/View.cpp @@ -40,6 +40,7 @@ #include "simVis/Entity.h" #include "simVis/Gate.h" #include "simVis/Locator.h" +#include "simVis/LocatorNode.h" #include "simVis/NavigationModes.h" #include "simVis/OverheadMode.h" #include "simVis/CustomRendering.h" @@ -47,6 +48,7 @@ #include "simVis/Popup.h" #include "simVis/Registry.h" #include "simVis/SceneManager.h" +#include "simVis/Scenario.h" #include "simVis/Utils.h" #include "simVis/View.h" @@ -225,18 +227,18 @@ void InsetChange::operator()(simVis::View* inset, const EventType& e) FocusManager::FocusManager(simVis::View* host) : host_(host), - viewman_(NULL), - focused_(NULL), + viewman_(nullptr), + focused_(nullptr), borderIdle_(simVis::Color::White, 2), borderFocus_(simVis::Color::Yellow, 3) { - if (host != NULL) + if (host != nullptr) host->setBorderProperties(borderIdle_); } FocusManager::~FocusManager() { - setViewManager(NULL); + setViewManager(nullptr); } void FocusManager::setViewManager(simVis::ViewManager* viewman) @@ -247,7 +249,7 @@ void FocusManager::setViewManager(simVis::ViewManager* viewman) if (viewman_.valid()) { viewman_->removeCallback(viewManagerCB_.get()); - viewManagerCB_ = NULL; + viewManagerCB_ = nullptr; for (std::map< simVis::View*, osg::ref_ptr >::const_iterator it = insets_.begin(); it != insets_.end(); ++it) it->first->removeCallback(it->second.get()); @@ -313,7 +315,7 @@ void FocusManager::focus(simVis::View* view) { if (!view) { - // There should be no callback unless there is a non-NULL value + // There should be no callback unless there is a non-nullptr value assert(0); return; } @@ -376,7 +378,7 @@ void FocusManager::setUnfocusedBorderProperties(const simVis::View::BorderProper void FocusManager::applyBorderProperties(simVis::View* view) const { - if (view != NULL) + if (view != nullptr) { if (view == focused_.get()) view->setBorderProperties(borderFocus_); @@ -431,8 +433,8 @@ void FocusManager::clearFocus() for (unsigned int i = 0; i < insets.size(); ++i) insets[i]->setBorderProperties(borderIdle_); } - focused_ = NULL; - fireCallbacks_(NULL, Callback::VIEW_FOCUSED); + focused_ = nullptr; + fireCallbacks_(nullptr, Callback::VIEW_FOCUSED); } void FocusManager::reFocus() @@ -458,7 +460,7 @@ void FocusManager::removeCallback(FocusManager::Callback* callback) void FocusManager::fireCallbacks_(simVis::View* view, const FocusManager::Callback::EventType& e) { - if (view == NULL) + if (view == nullptr) view = host_.get(); for (Callbacks::const_iterator i = callbacks_.begin(); i != callbacks_.end(); ++i) (*i)->operator()(view, e); @@ -515,13 +517,13 @@ class View::ViewTetherCallback : public osgEarth::Util::EarthManipulator::Tether /// Process the change-of-tether event void operator()(osg::Node* node) { - // if node is NULL, tether is broken - if (node == NULL && view_.valid()) + // if node is nullptr, tether is broken + if (node == nullptr && view_.valid()) { if (view_->isWatchEnabled()) - view_->enableWatchMode(NULL, NULL); + view_->enableWatchMode(nullptr, nullptr); if (view_->isCockpitEnabled()) - view_->enableCockpitMode(NULL); + view_->enableCockpitMode(nullptr); // Note that the mouse azim/elev locks associated with Watch or Cockpit mode are // not unlocked here. They are conditionally unlocked in either the enableWatchMode() @@ -553,7 +555,7 @@ View::View() viewType_(VIEW_TOPLEVEL), useOverheadClamping_(true), overheadNearFarCallback_(new SetNearFarCallback), - updateCameraNodeVisitor_(NULL) + updateCameraNodeVisitor_(nullptr) { // start out displaying all things. setDisplayMask(simVis::DISPLAY_MASK_ALL); @@ -773,7 +775,7 @@ bool View::setUpViewAsInset_(simVis::View* host) osg::Camera* bordercamera = this->getOrCreateHUD(); simVis::FocusManager* focusManager = host->getFocusManager(); borderNode_ = new BorderNode(); - if (focusManager != NULL) + if (focusManager != nullptr) focusManager->applyBorderProperties(this); bordercamera->addChild(borderNode_.get()); @@ -841,7 +843,7 @@ bool View::isValidNewInsetName(const std::string& newName, const simVis::View* v // No duplicates simVis::View* potentialDuplicate = getInsetByName(newName); - if (potentialDuplicate != NULL) + if (potentialDuplicate != nullptr) return potentialDuplicate == view; // If both point to the same view then do duplicate return true; @@ -919,7 +921,7 @@ int View::getIndexOfInset(simVis::View* view) const simVis::View* View::getInset(unsigned int index) const { - return index < getNumInsets() ? insets_[index].get() : NULL; + return index < getNumInsets() ? insets_[index].get() : nullptr; } simVis::View* View::getInsetByName(const std::string& name) const @@ -929,7 +931,7 @@ simVis::View* View::getInsetByName(const std::string& name) const if (i->get()->getName() == name) return i->get(); } - return NULL; + return nullptr; } bool View::setExtents(const Extents& e) @@ -1230,7 +1232,7 @@ void View::tetherCamera(osg::Node *node, const simVis::Viewpoint& vp, double dur newVp.setNode(realTether); // Set the focal point if needed (i.e. if there is no tether node) - if (realTether == NULL && vp.nodeIsSet()) + if (realTether == nullptr && vp.nodeIsSet()) { osg::ref_ptr oldTether = vp.getNode(); simCore::Vec3 lla = simVis::computeNodeGeodeticPosition(oldTether.get()); @@ -1246,7 +1248,7 @@ void View::tetherCamera(osg::Node *node, const simVis::Viewpoint& vp, double dur osg::Node* View::getCameraTether() const { - osg::Node* result = NULL; + osg::Node* result = nullptr; const simVis::EarthManipulator* manip = dynamic_cast(getCameraManipulator()); if (manip) { @@ -1440,6 +1442,8 @@ void View::setNavigationMode(const NavMode& mode) manip->applySettings(new CenterViewNavigationMode(overheadEnabled_, watchEnabled_)); else if (mode == NAVMODE_GIS) manip->applySettings(new GisNavigationMode(this, overheadEnabled_, watchEnabled_)); + else if (mode == NAVMODE_BUILDER) + manip->applySettings(new BuilderNavigationMode(overheadEnabled_, watchEnabled_)); // Restore the retained settings manip->getSettings()->setArcViewpointTransitions(arcTransitions); @@ -1469,7 +1473,8 @@ void View::enableOverheadMode(bool enableOverhead) if (updateCameraNodeVisitor_.valid() == false) { updateCameraNodeVisitor_ = new osg::NodeVisitor(); - manip->setUpdateCameraNodeVisitor(updateCameraNodeVisitor_.get()); + if (manip) + manip->setUpdateCameraNodeVisitor(updateCameraNodeVisitor_.get()); } osg::StateSet* cameraState = getCamera()->getOrCreateStateSet(); @@ -1478,7 +1483,7 @@ void View::enableOverheadMode(bool enableOverhead) // Disable watch mode if needed if (isWatchEnabled()) { - enableWatchMode(NULL, NULL); + enableWatchMode(nullptr, nullptr); } // always have north up in overhead mode simVis::Viewpoint vp = getViewpoint(); @@ -1637,7 +1642,7 @@ void View::enableWatchMode(osg::Node* watched, osg::Node* watcher) osg::ref_ptr tetherNode; tetherNode = manip->getViewpoint().getNode(); simVis::Viewpoint untether; - untether.setNode(NULL); + untether.setNode(nullptr); // Set a focal point to force a clear-out of the node; this will get updated to a better place in updateWatchView_() simCore::Vec3 lla = simVis::computeNodeGeodeticPosition(tetherNode.get()); untether.focalPoint()->set(osgEarth::SpatialReference::create("wgs84"), @@ -1665,7 +1670,7 @@ void View::enableWatchMode(osg::Node* watched, osg::Node* watcher) // Assert various post-conditions of enabling watch mode. Failing any of // these assertions will jump us out of watch mode immediately on next frame. assert(isWatchEnabled()); - assert(manip != NULL); + assert(manip != nullptr); assert(watcherNode_.valid()); assert(watchedNode_.valid()); assert(!manip->isTethering()); @@ -1673,7 +1678,7 @@ void View::enableWatchMode(osg::Node* watched, osg::Node* watcher) } } } - else if (watcherNode_ == NULL && !watchEnabled_) + else if (watcherNode_ == nullptr && !watchEnabled_) return; // Reset the eye azim/elev/range to what it was before we started monkeying with it. In @@ -1685,8 +1690,8 @@ void View::enableWatchMode(osg::Node* watched, osg::Node* watcher) resetVp.setNode(getModelNodeForTether(watcherNode_.get())); // Clear out watch values so that our observer doesn't pick up anything - watcherNode_ = NULL; - watchedNode_ = NULL; + watcherNode_ = nullptr; + watchedNode_ = nullptr; watchEnabled_ = false; // Swap the view back to what we had before, tethered to the watcher. @@ -1713,14 +1718,14 @@ simVis::EntityNode* View::getWatcherNode() const { if (isWatchEnabled()) return watcherNode_.get(); - return NULL; + return nullptr; } simVis::EntityNode* View::getWatchedNode() const { if (isWatchEnabled()) return watchedNode_.get(); - return NULL; + return nullptr; } void View::updateWatchView_() @@ -1733,7 +1738,7 @@ void View::updateWatchView_() // Jump out of watch mode if we're tethering, or if one of the watch nodes is invalid if (!manip || !watcherNode_.valid() || !watchedNode_.valid() || manip->isTethering()) { - enableWatchMode(NULL, NULL); + enableWatchMode(nullptr, nullptr); return; } @@ -1741,7 +1746,7 @@ void View::updateWatchView_() simVis::EntityNode* watchedEntityNode = getWatchedNode(); if (!watchedEntityNode) { - enableWatchMode(NULL, NULL); + enableWatchMode(nullptr, nullptr); return; } @@ -1808,7 +1813,7 @@ void View::updateWatchView_() // Now that we know where the eye is, calculate the orientation to the watched node double azR; double elR; - simCore::calculateAbsAzEl(realEyeLla, watchedLla, &azR, &elR, NULL, simCore::WGS_84, NULL); + simCore::calculateAbsAzEl(realEyeLla, watchedLla, &azR, &elR, nullptr, simCore::WGS_84, nullptr); updatedViewpoint.heading()->set(azR, osgEarth::Units::RADIANS); updatedViewpoint.pitch()->set(elR, osgEarth::Units::RADIANS); @@ -1932,7 +1937,7 @@ void simVis::View::fixProjectionForNewViewport_(double nx, double ny, double nw, { // Avoid divide-by-0 osg::Camera* camera = getCamera(); - if (camera == NULL) + if (camera == nullptr) return; // nw and nh should not be 0. If they are, someone upstream is giving incorrect values. // Fix those cases regardless here. @@ -1992,23 +1997,32 @@ void View::fixCockpitFlag_(osg::Node* node, osgEarth::Util::EarthManipulator* ma osg::Node* View::getModelNodeForTether(osg::Node* node) const { EntityNode* entityNode = dynamic_cast(node); - if (entityNode) - { - // Entity nodes typically have proxies (children) that we center on. - osg::Node* proxyNode = entityNode->findAttachment(); - // Fall back to Gate centroids - if (!proxyNode) - proxyNode = entityNode->findAttachment(); - - if ((!proxyNode) && (entityNode->type() == simData::CUSTOM_RENDERING)) - { - auto customNode = static_cast(entityNode); - proxyNode = customNode->locatorNode(); - } - - if (proxyNode) - node = proxyNode; - } + if (!entityNode) + return nullptr; + + switch (entityNode->type()) + { + case simData::PLATFORM: + return entityNode->findAttachment(); + case simData::GATE: + return entityNode->findAttachment(); + case simData::CUSTOM_RENDERING: + return static_cast(entityNode)->locatorNode(); + case simData::BEAM: + case simData::LASER: + case simData::PROJECTOR: + return entityNode->findAttachment(); + case simData::LOB_GROUP: + return entityNode->findAttachment(); + + // Passed in an invalid node + case simData::NONE: + case simData::ALL: + return node; + } + + // A new entity type was added and the code above was not updated + assert(false); return node; } @@ -2024,10 +2038,10 @@ simVis::EntityNode* View::getEntityNode(osg::Node* node) const { simVis::EntityNode* entityNode = dynamic_cast(node->getParent(0)); // If assert triggers, there's some weird unexpected hierarchy; investigate and resolve weirdness - assert(entityNode != NULL); + assert(entityNode != nullptr); return entityNode; } - return NULL; + return nullptr; } simVis::EarthManipulator* View::getEarthManipulator() diff --git a/SDK/simVis/View.h b/SDK/simVis/View.h index 2dbb46051..b1b07b427 100644 --- a/SDK/simVis/View.h +++ b/SDK/simVis/View.h @@ -47,7 +47,8 @@ enum NavMode NAVMODE_GLOBESPIN, NAVMODE_ZOOM, NAVMODE_CENTERVIEW, - NAVMODE_GIS + NAVMODE_GIS, + NAVMODE_BUILDER }; /// A camera viewpoint configuration @@ -148,7 +149,7 @@ class SDKVIS_EXPORT View : public osgViewer::View /** Views can either be top-level, insets, or HUDs */ enum ViewType { - VIEW_TOPLEVEL = 0, ///< getHostView() will be NULL; standalone view (potentially with children) + VIEW_TOPLEVEL = 0, ///< getHostView() will be nullptr; standalone view (potentially with children) VIEW_INSET, ///< getHostView() will be parent view VIEW_SUPERHUD ///< getHostView() will be underlay view }; @@ -162,7 +163,7 @@ class SDKVIS_EXPORT View : public osgViewer::View * Returns the views "host view" if there is one. * See setUpViewAsInset() for a description of the host view. * - * @return A managed view, or NULL if this view is independent. + * @return A managed view, or nullptr if this view is independent. */ simVis::View* getHostView() const; @@ -229,12 +230,12 @@ class SDKVIS_EXPORT View : public osgViewer::View int getIndexOfInset(simVis::View* view) const; /** - * Gets an inset by index, returning NULL on invalid index + * Gets an inset by index, returning nullptr on invalid index */ simVis::View* getInset(unsigned int index) const; /** - * Gets an inset by name, returning NULL if no inset has the name. + * Gets an inset by name, returning nullptr if no inset has the name. */ simVis::View* getInsetByName(const std::string& name) const; @@ -271,7 +272,7 @@ class SDKVIS_EXPORT View : public osgViewer::View * Tether the camera location to a scenario entity. Transitions to the viewpoint with * a duration of 0 seconds. Accounts for entity node graph to tether to correct node * in the platform graph. - * @param node EntityNode or PlatformModelNode to which to tether the camera, or NULL to clear + * @param node EntityNode or PlatformModelNode to which to tether the camera, or nullptr to clear * the tether. The node will be processed through getModelNodeForTether_(), so the node in * getViewpoint() may be different than the one requested. * @see tetherCamera(osg::Node*, const simVis::Viewpoint&, double) @@ -283,7 +284,7 @@ class SDKVIS_EXPORT View : public osgViewer::View * Tether the camera location to a scenario entity and apply focal offsets. Will transition * to new camera view during duration specified. Accounts for entity node graph to tether * to correct node in the platform graph. - * @param node EntityNode or PlatformModelNode to which to tether the camera, or NULL to clear + * @param node EntityNode or PlatformModelNode to which to tether the camera, or nullptr to clear * the tether. The node will be processed through getModelNodeForTether_(), so the node in * getViewpoint() may be different than the one requested. * @param vp Parameters for the viewpoint. Tether node in Viewpoint will be replaced with @@ -294,7 +295,7 @@ class SDKVIS_EXPORT View : public osgViewer::View /** * Get the node to which the camera is tethered. - * @return a node, or NULL if the camera is not tethered. + * @return a node, or nullptr if the camera is not tethered. * @see simVis::Viewpoint::getNode() * @see getViewpoint() */ @@ -378,7 +379,7 @@ class SDKVIS_EXPORT View : public osgViewer::View /** * Enable/disable cockpit mode (camera positioned in cockpit and using az/el/roll of tether platform) - * @param tether Node to which to tether in cockpit mode, or NULL to disable + * @param tether Node to which to tether in cockpit mode, or nullptr to disable */ void enableCockpitMode(osg::Node* tether); @@ -390,8 +391,8 @@ class SDKVIS_EXPORT View : public osgViewer::View /** * Enable/disable watch mode (camera positioned at watcher position, and pointed at watched position) - * @param watched Node that will be watched, or NULL to disable - * @param watcher Node that is watching, or NULL to disable + * @param watched Node that will be watched, or nullptr to disable + * @param watcher Node that is watching, or nullptr to disable */ void enableWatchMode(osg::Node* watched, osg::Node* watcher); @@ -403,13 +404,13 @@ class SDKVIS_EXPORT View : public osgViewer::View /** * Get the EntityNode that watch mode is using as the watcher - * @return a EntityNode, or NULL if the view is not in watch mode + * @return a EntityNode, or nullptr if the view is not in watch mode */ simVis::EntityNode* getWatcherNode() const; /** * Get the EntityNode that watch mode is using as the watched (i.e. target for the camera) - * @return a EntityNode, or NULL if the view is not in watch mode + * @return a EntityNode, or nullptr if the view is not in watch mode */ simVis::EntityNode* getWatchedNode() const; @@ -613,22 +614,19 @@ class SDKVIS_EXPORT View : public osgViewer::View ViewType type() const; /** - * Gets the entity node's model node if the specified node is an EntityNode. Essentially - * returns either the simVis::EntityNode, or for platforms will find the PlatformModelNode - * under the provided EntityNode. Tethering requires a PlatformModelNode for platforms, - * or the EntityNode for other entity types. + * Gets a node suitable for tethering. The type of node varies based on the entity type. * @param node Either an EntityNode or PlatformModelNode representing the entity to tether. - * @return the entity node of the tether node, or the original node if not a Platform Model node + * @return A node suitable for tethering */ osg::Node* getModelNodeForTether(osg::Node* node) const; /** * Up-casts an osg::Node to a simVis::EntityNode. The incoming osg::Node may already be a * simVis::EntityNode, or it might be a simVis::PlatformModelNode. The return is always - * either a valid simVis::EntityNode pointer, or NULL. + * either a valid simVis::EntityNode pointer, or nullptr. * @param node Either a simVis::EntityNode, or a simVis::PlatformModelNode, representing the * entity in question. - * @return Pointer to the EntityNode, or NULL if not able to pull out that pointer from the input. + * @return Pointer to the EntityNode, or nullptr if not able to pull out that pointer from the input. */ simVis::EntityNode* getEntityNode(osg::Node* node) const; diff --git a/SDK/simVis/ViewManager.cpp b/SDK/simVis/ViewManager.cpp index 3a2545b0e..f41694e74 100644 --- a/SDK/simVis/ViewManager.cpp +++ b/SDK/simVis/ViewManager.cpp @@ -66,7 +66,7 @@ namespace viewMan_(viewMan), width_(0), height_(0), - resizeView_(NULL) + resizeView_(nullptr) { } bool handle(const osgGA::GUIEventAdapter& ea, osgGA::GUIActionAdapter& aa, osg::Object* object, osg::NodeVisitor*) @@ -85,7 +85,7 @@ namespace { viewMan_->handleResize(width_, height_); aa.requestRedraw(); - resizeView_ = NULL; + resizeView_ = nullptr; } return false; } @@ -182,7 +182,7 @@ void AddEventHandlerToViews::removeFromViews(const simVis::ViewManager& viewMana void AddEventHandlerToViews::operator()(simVis::View* inset, const EventType& e) { - if (guiEventHandler_ != NULL) + if (guiEventHandler_ != nullptr) { switch (e) { @@ -268,7 +268,7 @@ unsigned int ViewManager::getNumViews() const simVis::View* ViewManager::getView(unsigned int index) const { - return index < getNumViews() ? dynamic_cast(viewer_->getView(index)) : NULL; + return index < getNumViews() ? dynamic_cast(viewer_->getView(index)) : nullptr; } @@ -281,7 +281,7 @@ simVis::View* ViewManager::getViewByName(const std::string& name) const if ((*i)->getName() == name) return dynamic_cast(*i); } - return NULL; + return nullptr; } diff --git a/SDK/simVis/ViewManagerLogDbAdapter.cpp b/SDK/simVis/ViewManagerLogDbAdapter.cpp index d7f300928..d998c7fcb 100644 --- a/SDK/simVis/ViewManagerLogDbAdapter.cpp +++ b/SDK/simVis/ViewManagerLogDbAdapter.cpp @@ -132,7 +132,7 @@ ViewManagerLogDbAdapter::~ViewManagerLogDbAdapter() void ViewManagerLogDbAdapter::install(simVis::ViewManager* viewManager) { // Already installed? - if (viewManager == NULL || std::find(viewManagers_.begin(), viewManagers_.end(), viewManager) != viewManagers_.end()) + if (viewManager == nullptr || std::find(viewManagers_.begin(), viewManagers_.end(), viewManager) != viewManagers_.end()) return; // Retrieve the views and install on each @@ -153,7 +153,7 @@ void ViewManagerLogDbAdapter::uninstall(simVis::ViewManager* viewManager) { // Already installed? ViewManagerList::iterator vmlIter = std::find(viewManagers_.begin(), viewManagers_.end(), viewManager); - if (viewManager == NULL || vmlIter == viewManagers_.end()) + if (viewManager == nullptr || vmlIter == viewManagers_.end()) return; // Remove it from lists first to avoid callbacks diff --git a/SDK/simVis/Viewer.cpp b/SDK/simVis/Viewer.cpp index 9ecb911ad..0d6d5b275 100644 --- a/SDK/simVis/Viewer.cpp +++ b/SDK/simVis/Viewer.cpp @@ -104,9 +104,9 @@ void Viewer::setMapNode(osgEarth::MapNode* mapNode) getViews(views); for (std::vector::const_iterator i = views.begin(); i != views.end(); ++i) { - // Each view in the views list should be valid and non-NULL + // Each view in the views list should be valid and non-nullptr assert(*i); - if (*i == NULL) + if (*i == nullptr) continue; // Not every view necessarily has a camera manipulator (e.g. SuperHud doesn't) @@ -115,7 +115,7 @@ void Viewer::setMapNode(osgEarth::MapNode* mapNode) { // Changing the manipulator attach point will reset the view; save and restore the view. simVis::Viewpoint vp = (*i)->getViewpoint(); - manip->setNode(NULL); + manip->setNode(nullptr); manip->setNode(scene_->getManipulatorAttachPoint()); (*i)->setViewpoint(vp, 0); } @@ -130,7 +130,7 @@ void Viewer::setMap(osgEarth::Map* map) int Viewer::run() { - bool hasManip = getMainView()->getCameraManipulator() != NULL; + bool hasManip = getMainView()->getCameraManipulator() != nullptr; osg::Matrix savedViewMatrix; // do some final set up before running the frame loop. @@ -151,7 +151,7 @@ int Viewer::run() if (!hasManip) { - getMainView()->setCameraManipulator(NULL); + getMainView()->setCameraManipulator(nullptr); getMainView()->getCamera()->setViewMatrix(savedViewMatrix); } @@ -164,12 +164,12 @@ int Viewer::run() View* Viewer::getMainView() { - return getNumViews() > 0 ? getView(0) : NULL; + return getNumViews() > 0 ? getView(0) : nullptr; } const View* Viewer::getMainView() const { - return getNumViews() > 0 ? getView(0) : NULL; + return getNumViews() > 0 ? getView(0) : nullptr; } void Viewer::addEventHandler(osgGA::GUIEventHandler* handler) diff --git a/SDK/simVis/osgEarthVersion.h.in b/SDK/simVis/osgEarthVersion.h.in index 8cea2ef59..d07f146ae 100644 --- a/SDK/simVis/osgEarthVersion.h.in +++ b/SDK/simVis/osgEarthVersion.h.in @@ -31,6 +31,9 @@ #cmakedefine HAVE_TRITON_NODEKIT #cmakedefine HAVE_SILVERLINING_NODEKIT +// osgEarth post-3.0 1f5f57c1d9c renamed headers and classes +#cmakedefine HAVE_OSGEARTH_THREADING + /** Detected osgearth-simdis-sdk version */ #define SDK_OSGEARTH_VERSION_MAJOR @SDK_OSGEARTH_VERSION_MAJOR@ diff --git a/Testing/SimCore/CalculateInput.txt b/Testing/SimCore/CalculateInput.txt index a7c1aeb23..7219e1ee5 100644 --- a/Testing/SimCore/CalculateInput.txt +++ b/Testing/SimCore/CalculateInput.txt @@ -31,6 +31,22 @@ DRCRDownValueWGS84 0.0 0.0 0.0 -1.433629385640828 2.159265359 -.21 -1.433629385640828 2.159265359 -.21 1.183185307179587 -2.3 -23 -2291529.0724728065542876720428467 516938.7131038807565346360206604 -12267014.516633462160825729370117 +GeodesicDRCRWGS84 0.0 0.0 0.0 +-1.510 -170830.0 0871.0 -1.510 -170830.0 0871.0 891.08 -18.0 9.0 +1177585.938329717 -2946030.752630158 + +GeodesicDRCRWGS84 0.0 0.0 0.0 +32.1 123 51.1 32.1 123 51.1 -21.15 0.1 121.3 +-9905790.910484871 2763186.414549443 + +GeodesicDRCRWGS84 0.0 0.0 0.0 +283.1 -322.1 -11.1023 283.1 -322.1 -11.1023 235.11 3085.0 3.0 +3188243.08897836 -8518375.099915884 + +GeodesicDRCRWGS84 0.0 0.0 0.0 +-14.0 -312 -.21 -14.0 -312 -.21 -5.1 -2.3 -23 +-17653537.86503112 525618.2308189553 + GroundDistWGS84 0.0 0.0 0.0 -1.510 -2.7578684014 871.0 -1.132313619501204 0.84955592154 9.0 3156499.362367233 @@ -252,6 +268,55 @@ AbsAzElWGS84 0.0 0.0 0.0 1.4860903700976058061655749042984 -1.3815886502152368020546191473841 1.5548831384813641687259178070235 +GeodesicDRCRFlatEarth 2.3 -70.0 0.0 +-1.510 -170830.0 0871.0 -1.510 -170830.0 0871.0 891.08 -18.0 9.0 +1177585.938329717 -2946030.752630158 + +GeodesicDRCRFlatEarth 2.3 -70.0 0.0 +32.1 123 51.1 32.1 123 51.1 -21.15 0.1 121.3 +-9905790.910484871 2763186.414549443 + +GeodesicDRCRFlatEarth 2.3 -70.0 0.0 +283.1 -322.1 -11.1023 283.1 -322.1 -11.1023 235.11 3085.0 3.0 +3188243.088977836 -8518375.099915884 + +GeodesicDRCRFlatEarth 2.3 -70.0 0.0 +-14.0 -312 -.21 -14.0 -312 -.21 -5.1 -2.3 -23 +-17653537.86503112 525618.2308189553 + +VelocityDeltaFlatEarth 2.3 -70.0 0.0 +-1.510 -170830.0 0871.0 -1.510 -170830.0 0871.0 130.4 -68.123453 216547.64 891.08 -18.0 9.0 11.510 2170830.0 05171.1 4564.456 485.246 7931.465 +208664.025509893 + +VelocityDeltaFlatEarth 2.3 -70.0 0.0 +32.1 123 51.1 32.1 123 51.1 654 6321 5654 -21.15 0.1 121.3 -554. -57. -6543.5 .54844 465.54 -7835.45 +14720.009241008189 + +VelocityDeltaFlatEarth 2.3 -70.0 0.0 +283.1 -322.1 -11.1023 283.1 -322.1 -11.1023 4653.1 -67253.546 -654.79 235.11 3085.0 3.0 45623.2465 5448973.546 6547.24 -784.45 -22189 -4543.79 +45557.706013237941 + +VelocityDeltaFlatEarth 2.3 -70.0 0.0 +-14.0 -312 -.21 -14.0 -312 -.21 -6723 4573 4567 -5.1 -2.3 -23 -65.79 5467.87 654.79 58735149.574 546.54 -54.45 +58741872.893790454 + +AltitudeFlatEarth 1.5707863 -70.0 0.0 +-1.510 -170830.0 0871.0 891.08 -18.0 9.0 +-862 + +AltitudeFlatEarth 1.5707863 -70.0 0.0 +32.1 123 51.1 -21.15 0.1 121.3 +70.199999999999988631316227838397 + +AltitudeFlatEarth 1.5707863 -70.0 0.0 +283.1 -322.1 -11.1023 235.11 3085.0 3.0 +14.102299999999999613464751746505 + +AltitudeFlatEarth 1.5707863 -70.0 0.0 +-14.0 -312 -.21 -5.1 -2.3 -23 +-22.78999999999999914734871708788 + + SlantTangentPlaneWGS84 2.3 -70.0 0.0 -1.510 -2.7578684014 871.0 -1.132313619501204 0.84955592154 9.0 3124784.7428872650489211082458496 @@ -284,6 +349,22 @@ DRCRDownValueTangentPlaneWGS84 2.3 -70.0 0.0 -1.433629385640828 2.159265359 -.21 -1.433629385640828 2.159265359 -.21 1.183185307179587 -2.3 -23 -2291529.0724728065542876720428467 516938.7131038807565346360206604 -12267014.516633462160825729370117 +GeodesicDRCRTangentPlaneWGS84 2.3 -70.0 0.0 +-1.510 -170830.0 0871.0 -1.510 -170830.0 0871.0 891.08 -18.0 9.0 +1177585.938329717 -2946030.752630158 + +GeodesicDRCRTangentPlaneWGS84 2.3 -70.0 0.0 +32.1 123 51.1 32.1 123 51.1 -21.15 0.1 121.3 +-9905790.910484871 2763186.414549443 + +GeodesicDRCRTangentPlaneWGS84 2.3 -70.0 0.0 +283.1 -322.1 -11.1023 283.1 -322.1 -11.1023 235.11 3085.0 3.0 +3188243.088977836 -8518375.099915884 + +GeodesicDRCRTangentPlaneWGS84 2.3 -70.0 0.0 +-14.0 -312 -.21 -14.0 -312 -.21 -5.1 -2.3 -23 +-17653537.86503112 525618.2308189553 + GroundDistTangentPlaneWGS84 2.3 -70.0 0.0 -1.510 -2.7578684014 871.0 -1.132313619501204 0.84955592154 9.0 3029989.259687593 @@ -385,6 +466,69 @@ AbsAzElTangentPlaneWGS84 2.3 -70.0 0.0 -1.433629385640828 2.159265359 -.21 1.183185307179587 -2.3 -23 1.4860903700976058061655749042984 -1.3815886502152368020546191473841 1.5548831384813641687259178070235 +SlantPerfectSphere 0 0 0.0 +-1.510 -170830.0 0871.0 891.08 -18.0 9.0 +3116029.859846306 + +SlantPerfectSphere 0 0 0.0 +32.1 123 51.1 -21.15 0.1 121.3 +8978993.879687592 + +SlantPerfectSphere 0 0 0.0 +283.1 -322.1 -11.1023 235.11 3085.0 3.0 +8041235.07183367 + +SlantPerfectSphere 0 0 0.0 +-14.0 -312 -.21 -5.1 -2.3 -23 +12531229.18617708 + +DRCRDownValuePerfectSphere 0 0 0.0 +-1.510 -170830.0 0871.0 -1.510 -170830.0 0871.0 891.08 -18.0 9.0 +1046022.44987513 -2834598.899237857 -761924.0134360846 + +DRCRDownValuePerfectSphere 0 0 0.0 +32.1 123 51.1 32.1 123 51.1 -21.15 0.1 121.3 +-5782494.653504141 2691014.500662178 -6320089.210674891 + +DRCRDownValuePerfectSphere 0 0 0.0 +283.1 -322.1 -11.1023 283.1 -322.1 -11.1023 235.11 3085.0 3.0 +711167.1428956094 -6201698.795634295 -5068987.554096151 + +DRCRDownValuePerfectSphere 0 0 0.0 +-14.0 -312 -.21 -14.0 -312 -.21 -5.1 -2.3 -23 +-2283414.97378242 526539.5519026145 -12310177.78402427 + +GeodesicDRCRPerfectSphere 0 0 0.0 +-1.510 -170830.0 0871.0 -1.510 -170830.0 0871.0 891.08 -18.0 9.0 +1177585.938329717 -2946030.752630158 + +GeodesicDRCRPerfectSphere 0 0 0.0 +32.1 123 51.1 32.1 123 51.1 -21.15 0.1 121.3 +-9905790.910484871 2763186.414549443 + +GeodesicDRCRPerfectSphere 0 0 0.0 +283.1 -322.1 -11.1023 283.1 -322.1 -11.1023 235.11 3085.0 3.0 +3188243.088977836 -8518375.099915884 + +GeodesicDRCRPerfectSphere 0 0 0.0 +-14.0 -312 -.21 -14.0 -312 -.21 -5.1 -2.3 -23 +-17653537.86503112 525618.2308189553 + +AbsAzElPerfectSphere 0 0 0.0 +-1.510 -170830.0 0871.0 891.08 -18.0 9.0 +3.5559062478181417965572563844034 -0.24702240743845496617758783486352 2.6629174718464709847864924086025 + +AbsAzElPerfectSphere 0 0 0.0 +32.1 123 51.1 -21.15 0.1 121.3 +3.3901021407458746814711503247963 -0.78083809310872753783883126743603 2.3302189120188425697222101007355 + +AbsAzElPerfectSphere 0 0 0.0 +283.1 -322.1 -11.1023 235.11 3085.0 3.0 +5.1832243983599628478486920357682 -0.68203521994539018091785465003341 1.2109292773043041080427428823896 + +AbsAzElPerfectSphere 0 0 0.0 +-14.0 -312 -.21 -5.1 -2.3 -23 +1.4813317287594847115883567312267 -1.3826891841013340123112129731453 1.5540879991562974726804213787545 PositionInGateWGS84 0.0 0.0 0.0 0.0 1.5707963268 200 0.0000488692 1.5708137801 200 0 0 0.174532925 0.174532925 300 400 diff --git a/Testing/SimCore/CalculateLibTest.cpp b/Testing/SimCore/CalculateLibTest.cpp index 9c80e3927..adc7f9e84 100644 --- a/Testing/SimCore/CalculateLibTest.cpp +++ b/Testing/SimCore/CalculateLibTest.cpp @@ -171,7 +171,7 @@ int testCalculateGeodesicDRCR(double *from, double *to, simCore::EarthModelCalcu simCore::calculateGeodesicDRCR(simCore::Vec3(from), from[3], simCore::Vec3(to), &downRng, &crossRng); - if (almostEqual(downRng, result[0]) && + if (almostEqual(downRng, result[0], 1.3) && almostEqual(crossRng, result[1])) { std::cerr << "successful" << std::endl; diff --git a/Testing/SimCore/CalculationTest.cpp b/Testing/SimCore/CalculationTest.cpp index c48d2435c..683f722f0 100644 --- a/Testing/SimCore/CalculationTest.cpp +++ b/Testing/SimCore/CalculationTest.cpp @@ -293,19 +293,19 @@ int testGeodeticRangePair(double fromLat, double fromLon, double toLat, double t // Sanity check the downrange value by comparing it to the distance to the corner // The values will not be exact since the surface is curved, but they will be close - double distance = simCore::sodanoInverse(fromLla[0], fromLla[1], 0.0, toLla[0], fromLla[1], NULL, NULL); + double distance = simCore::sodanoInverse(fromLla[0], fromLla[1], 0.0, toLla[0], fromLla[1], nullptr, nullptr); rv += SDK_ASSERT(simCore::areEqual(fabs(downRng1), distance, 1.0)); // Sanity check the cross range value by comparing it to the distance to the corner // The values will not be exact since the surface is curved, but they will be close - distance = simCore::sodanoInverse(fromLla[0], fromLla[1], 0.0, fromLla[0], toLla[1], NULL, NULL); + distance = simCore::sodanoInverse(fromLla[0], fromLla[1], 0.0, fromLla[0], toLla[1], nullptr, nullptr); rv += SDK_ASSERT(simCore::areEqual(fabs(crossRng1), distance, 1.0)); // Point directly at the target double azfwd = 0; double downRngAtTarget; double crossRngAtTarget; - distance = simCore::sodanoInverse(fromLla[0], fromLla[1], 0.0, toLla[0], toLla[1], &azfwd, NULL); + distance = simCore::sodanoInverse(fromLla[0], fromLla[1], 0.0, toLla[0], toLla[1], &azfwd, nullptr); simCore::calculateGeodesicDRCR(fromLla, azfwd, toLla, &downRngAtTarget, &crossRngAtTarget); rv += SDK_ASSERT(simCore::areEqual(distance, downRngAtTarget, 0.01)); rv += SDK_ASSERT(simCore::areEqual(0.0, crossRngAtTarget, 0.01)); @@ -345,7 +345,7 @@ int testGeodeticRanges() rv += testGeodeticRangePair(M_PI+delta, M_PI+delta, M_PI-delta, M_PI-delta); - // Test that NULL arguments are supported + // Test that nullptr arguments are supported simCore::Vec3 fromLla(-delta, -delta, 0.0); simCore::Vec3 toLla(delta, delta, 0.0); double downRng1 = 0.0; @@ -354,8 +354,8 @@ int testGeodeticRanges() double downRng2 = 0.0; double crossRng2 = 0.0; - simCore::calculateGeodesicDRCR(fromLla, 0.0, toLla, &downRng2, NULL); - simCore::calculateGeodesicDRCR(fromLla, 0.0, toLla, NULL, &crossRng2); + simCore::calculateGeodesicDRCR(fromLla, 0.0, toLla, &downRng2, nullptr); + simCore::calculateGeodesicDRCR(fromLla, 0.0, toLla, nullptr, &crossRng2); rv += SDK_ASSERT(simCore::areEqual(downRng1, downRng2)); rv += SDK_ASSERT(simCore::areEqual(crossRng1, crossRng2)); @@ -997,7 +997,7 @@ int testRotateEulerAngle() trueAzElCalculated = simCore::rotateEulerAngle(hostYPR, bodyAzEl); rv += SDK_ASSERT(simCore::areAnglesEqual(trueAzElCalculated.x(), RAD15)); rv += SDK_ASSERT(simCore::areAnglesEqual(trueAzElCalculated.y(), 0)); - simCore::calculateRelAngToTrueAzEl(trueAzElCalculated.x(), trueAzElCalculated.y(), hostYPR, &bodyAz, &bodyEl, NULL); + simCore::calculateRelAngToTrueAzEl(trueAzElCalculated.x(), trueAzElCalculated.y(), hostYPR, &bodyAz, &bodyEl, nullptr); bodyAzElCalculated.set(bodyAz, bodyEl, 0.0); rv += SDK_ASSERT(simCore::v3AreAnglesEqual(bodyAzElCalculated, bodyAzEl)); @@ -1005,7 +1005,7 @@ int testRotateEulerAngle() trueAzElCalculated = simCore::rotateEulerAngle(hostYPR, bodyAzEl); rv += SDK_ASSERT(simCore::areAnglesEqual(trueAzElCalculated.x(), RAD30)); rv += SDK_ASSERT(simCore::areAnglesEqual(trueAzElCalculated.y(), 0)); - simCore::calculateRelAngToTrueAzEl(trueAzElCalculated.x(), trueAzElCalculated.y(), hostYPR, &bodyAz, &bodyEl, NULL); + simCore::calculateRelAngToTrueAzEl(trueAzElCalculated.x(), trueAzElCalculated.y(), hostYPR, &bodyAz, &bodyEl, nullptr); bodyAzElCalculated.set(bodyAz, bodyEl, 0.0); rv += SDK_ASSERT(simCore::v3AreAnglesEqual(bodyAzElCalculated, bodyAzEl)); @@ -1013,7 +1013,7 @@ int testRotateEulerAngle() trueAzElCalculated = simCore::rotateEulerAngle(hostYPR, bodyAzEl); rv += SDK_ASSERT(simCore::areAnglesEqual(trueAzElCalculated.x(), -RAD15)); rv += SDK_ASSERT(simCore::areAnglesEqual(trueAzElCalculated.y(), 0)); - simCore::calculateRelAngToTrueAzEl(trueAzElCalculated.x(), trueAzElCalculated.y(), hostYPR, &bodyAz, &bodyEl, NULL); + simCore::calculateRelAngToTrueAzEl(trueAzElCalculated.x(), trueAzElCalculated.y(), hostYPR, &bodyAz, &bodyEl, nullptr); bodyAzElCalculated.set(bodyAz, bodyEl, 0.0); rv += SDK_ASSERT(simCore::v3AreAnglesEqual(bodyAzElCalculated, bodyAzEl)); @@ -1021,7 +1021,7 @@ int testRotateEulerAngle() trueAzElCalculated = simCore::rotateEulerAngle(hostYPR, bodyAzEl); rv += SDK_ASSERT(simCore::areAnglesEqual(trueAzElCalculated.x(), -RAD30)); rv += SDK_ASSERT(simCore::areAnglesEqual(trueAzElCalculated.y(), 0)); - simCore::calculateRelAngToTrueAzEl(trueAzElCalculated.x(), trueAzElCalculated.y(), hostYPR, &bodyAz, &bodyEl, NULL); + simCore::calculateRelAngToTrueAzEl(trueAzElCalculated.x(), trueAzElCalculated.y(), hostYPR, &bodyAz, &bodyEl, nullptr); bodyAzElCalculated.set(bodyAz, bodyEl, 0.0); rv += SDK_ASSERT(simCore::v3AreAnglesEqual(bodyAzElCalculated, bodyAzEl)); } @@ -1033,7 +1033,7 @@ int testRotateEulerAngle() trueAzElCalculated = simCore::rotateEulerAngle(hostYPR, bodyAzEl); rv += SDK_ASSERT(simCore::areAnglesEqual(trueAzElCalculated.x(), RAD180 + RAD15)); rv += SDK_ASSERT(simCore::areAnglesEqual(trueAzElCalculated.y(), 0)); - simCore::calculateRelAngToTrueAzEl(trueAzElCalculated.x(), trueAzElCalculated.y(), hostYPR, &bodyAz, &bodyEl, NULL); + simCore::calculateRelAngToTrueAzEl(trueAzElCalculated.x(), trueAzElCalculated.y(), hostYPR, &bodyAz, &bodyEl, nullptr); bodyAzElCalculated.set(bodyAz, bodyEl, 0.0); rv += SDK_ASSERT(simCore::v3AreAnglesEqual(bodyAzElCalculated, bodyAzEl)); @@ -1041,7 +1041,7 @@ int testRotateEulerAngle() trueAzElCalculated = simCore::rotateEulerAngle(hostYPR, bodyAzEl); rv += SDK_ASSERT(simCore::areAnglesEqual(trueAzElCalculated.x(), RAD180 + RAD30)); rv += SDK_ASSERT(simCore::areAnglesEqual(trueAzElCalculated.y(), 0)); - simCore::calculateRelAngToTrueAzEl(trueAzElCalculated.x(), trueAzElCalculated.y(), hostYPR, &bodyAz, &bodyEl, NULL); + simCore::calculateRelAngToTrueAzEl(trueAzElCalculated.x(), trueAzElCalculated.y(), hostYPR, &bodyAz, &bodyEl, nullptr); bodyAzElCalculated.set(bodyAz, bodyEl, 0.0); rv += SDK_ASSERT(simCore::v3AreAnglesEqual(bodyAzElCalculated, bodyAzEl)); @@ -1049,7 +1049,7 @@ int testRotateEulerAngle() trueAzElCalculated = simCore::rotateEulerAngle(hostYPR, bodyAzEl); rv += SDK_ASSERT(simCore::areAnglesEqual(trueAzElCalculated.x(), RAD180 - RAD15)); rv += SDK_ASSERT(simCore::areAnglesEqual(trueAzElCalculated.y(), 0)); - simCore::calculateRelAngToTrueAzEl(trueAzElCalculated.x(), trueAzElCalculated.y(), hostYPR, &bodyAz, &bodyEl, NULL); + simCore::calculateRelAngToTrueAzEl(trueAzElCalculated.x(), trueAzElCalculated.y(), hostYPR, &bodyAz, &bodyEl, nullptr); bodyAzElCalculated.set(bodyAz, bodyEl, 0.0); rv += SDK_ASSERT(simCore::v3AreAnglesEqual(bodyAzElCalculated, bodyAzEl)); @@ -1057,7 +1057,7 @@ int testRotateEulerAngle() trueAzElCalculated = simCore::rotateEulerAngle(hostYPR, bodyAzEl); rv += SDK_ASSERT(simCore::areAnglesEqual(trueAzElCalculated.x(), RAD180 - RAD30)); rv += SDK_ASSERT(simCore::areAnglesEqual(trueAzElCalculated.y(), 0)); - simCore::calculateRelAngToTrueAzEl(trueAzElCalculated.x(), trueAzElCalculated.y(), hostYPR, &bodyAz, &bodyEl, NULL); + simCore::calculateRelAngToTrueAzEl(trueAzElCalculated.x(), trueAzElCalculated.y(), hostYPR, &bodyAz, &bodyEl, nullptr); bodyAzElCalculated.set(bodyAz, bodyEl, 0.0); rv += SDK_ASSERT(simCore::v3AreAnglesEqual(bodyAzElCalculated, bodyAzEl)); } @@ -1069,7 +1069,7 @@ int testRotateEulerAngle() trueAzElCalculated = simCore::rotateEulerAngle(hostYPR, bodyAzEl); rv += SDK_ASSERT(simCore::areAnglesEqual(trueAzElCalculated.x(), RAD15)); rv += SDK_ASSERT(simCore::areAnglesEqual(trueAzElCalculated.y(), RAD15)); - simCore::calculateRelAngToTrueAzEl(trueAzElCalculated.x(), trueAzElCalculated.y(), hostYPR, &bodyAz, &bodyEl, NULL); + simCore::calculateRelAngToTrueAzEl(trueAzElCalculated.x(), trueAzElCalculated.y(), hostYPR, &bodyAz, &bodyEl, nullptr); bodyAzElCalculated.set(bodyAz, bodyEl, 0.0); rv += SDK_ASSERT(simCore::v3AreAnglesEqual(bodyAzElCalculated, bodyAzEl)); @@ -1077,7 +1077,7 @@ int testRotateEulerAngle() trueAzElCalculated = simCore::rotateEulerAngle(hostYPR, bodyAzEl); rv += SDK_ASSERT(simCore::areAnglesEqual(trueAzElCalculated.x(), RAD15)); rv += SDK_ASSERT(simCore::areAnglesEqual(trueAzElCalculated.y(), RAD30)); - simCore::calculateRelAngToTrueAzEl(trueAzElCalculated.x(), trueAzElCalculated.y(), hostYPR, &bodyAz, &bodyEl, NULL); + simCore::calculateRelAngToTrueAzEl(trueAzElCalculated.x(), trueAzElCalculated.y(), hostYPR, &bodyAz, &bodyEl, nullptr); bodyAzElCalculated.set(bodyAz, bodyEl, 0.0); rv += SDK_ASSERT(simCore::v3AreAnglesEqual(bodyAzElCalculated, bodyAzEl)); @@ -1085,7 +1085,7 @@ int testRotateEulerAngle() trueAzElCalculated = simCore::rotateEulerAngle(hostYPR, bodyAzEl); rv += SDK_ASSERT(simCore::areAnglesEqual(trueAzElCalculated.x(), RAD15)); rv += SDK_ASSERT(simCore::areAnglesEqual(trueAzElCalculated.y(), -RAD15)); - simCore::calculateRelAngToTrueAzEl(trueAzElCalculated.x(), trueAzElCalculated.y(), hostYPR, &bodyAz, &bodyEl, NULL); + simCore::calculateRelAngToTrueAzEl(trueAzElCalculated.x(), trueAzElCalculated.y(), hostYPR, &bodyAz, &bodyEl, nullptr); bodyAzElCalculated.set(bodyAz, bodyEl, 0.0); rv += SDK_ASSERT(simCore::v3AreAnglesEqual(bodyAzElCalculated, bodyAzEl)); @@ -1093,7 +1093,7 @@ int testRotateEulerAngle() trueAzElCalculated = simCore::rotateEulerAngle(hostYPR, bodyAzEl); rv += SDK_ASSERT(simCore::areAnglesEqual(trueAzElCalculated.x(), RAD15)); rv += SDK_ASSERT(simCore::areAnglesEqual(trueAzElCalculated.y(), -RAD30)); - simCore::calculateRelAngToTrueAzEl(trueAzElCalculated.x(), trueAzElCalculated.y(), hostYPR, &bodyAz, &bodyEl, NULL); + simCore::calculateRelAngToTrueAzEl(trueAzElCalculated.x(), trueAzElCalculated.y(), hostYPR, &bodyAz, &bodyEl, nullptr); bodyAzElCalculated.set(bodyAz, bodyEl, 0.0); rv += SDK_ASSERT(simCore::v3AreAnglesEqual(bodyAzElCalculated, bodyAzEl)); } @@ -1106,7 +1106,7 @@ int testRotateEulerAngle() rv += SDK_ASSERT(simCore::areAnglesEqual(trueAzElCalculated.x(), -0.055 * simCore::DEG2RAD, 1e-2)); rv += SDK_ASSERT(simCore::areAnglesEqual(trueAzElCalculated.y(), 4.82922 * simCore::DEG2RAD, 1e-2)); rv += SDK_ASSERT(simCore::areAnglesEqual(trueAzElCalculated.z(), -91.2972 * simCore::DEG2RAD, 1e-2)); - simCore::calculateRelAngToTrueAzEl(trueAzElCalculated.x(), trueAzElCalculated.y(), hostYPR, &bodyAz, &bodyEl, NULL); + simCore::calculateRelAngToTrueAzEl(trueAzElCalculated.x(), trueAzElCalculated.y(), hostYPR, &bodyAz, &bodyEl, nullptr); bodyAzElCalculated.set(bodyAz, bodyEl, 0.0); rv += SDK_ASSERT(simCore::v3AreAnglesEqual(bodyAzElCalculated, bodyAzEl)); } @@ -1749,7 +1749,7 @@ int testBoresightAlphaBeta() const double elevExpected = row[10] * simCore::DEG2RAD; const double cmpExpected = row[11] * simCore::DEG2RAD; - simCore::calculateRelAzEl(fromLla.position(), fromOri, toLla.position(), &azim, &elev, &cmp, simCore::WGS_84, NULL); // Coord Converter optional for WGS_84 models + simCore::calculateRelAzEl(fromLla.position(), fromOri, toLla.position(), &azim, &elev, &cmp, simCore::WGS_84, nullptr); // Coord Converter optional for WGS_84 models rv += SDK_ASSERT(simCore::areAnglesEqual(azim, azimExpected, tolerance)); rv += SDK_ASSERT(simCore::areAnglesEqual(elev, elevExpected, tolerance)); @@ -1759,6 +1759,69 @@ int testBoresightAlphaBeta() return rv; } +int testTangentPlane2Sphere() +{ + int rv = 0; + + // with trivial tangent plane offset(ht only), at any lla point, spherical and wgs84 are trivially comparable + for (double lat : { 1., 10., 60.}) + { + for (double lon : {3., 5., 13., 27., 53., 90.}) + { + for (double alt : {30., 500., 1300., 2700., 5300., 9000.}) + { + simCore::Vec3 refLla(lat, lon, alt); + simCore::Vec3 tpSphereXYZ; + simCore::geodeticToSpherical(refLla.lat(), refLla.lon(), refLla.alt(), tpSphereXYZ); + + for (double z : { 10., 100., 1000., 10000., 100000.}) + { + simCore::Vec3 sphereXYZ; + simCore::Vec3 tpVec(0., 0., z); + simCore::tangentPlane2Sphere(refLla, tpVec, sphereXYZ, &tpSphereXYZ); + const double altAboveSphere = v3Length(sphereXYZ) - simCore::EARTH_RADIUS; + rv += SDK_ASSERT(simCore::areEqual(z + refLla.alt(), altAboveSphere)); + } + } + } + } + + simCore::Vec3 refLla(0., 0., 0.); + simCore::Vec3 tpSphereXYZ; + simCore::geodeticToSpherical(refLla.lat(), refLla.lon(), refLla.alt(), tpSphereXYZ); + // with x,y offsets, things get interesting + for (double z : { 0., 10., 100., 1000., 10000., 100000.}) + { + simCore::Vec3 sphereXYZ; + simCore::Vec3 tpVec(10000., 0., z); + simCore::tangentPlane2Sphere(refLla, tpVec, sphereXYZ, &tpSphereXYZ); + const double altAboveSphere = v3Length(sphereXYZ) - simCore::EARTH_RADIUS; + + // this approximates the ht offset between the spherical earth and the ellipsoidal earth at a point dropped to the earth from the point on the tangent plane. + const double sphereToEllipsoidOffset = altAboveSphere - (refLla.alt() + z); + // the spherical earth is always bigger than wgs84 ellipsoid, except that they are the same size at the equator + rv += SDK_ASSERT(sphereToEllipsoidOffset >= 0); + } + + // verify that spherical height is constant with respect to x/y distance from an arbitrary reflla + refLla = simCore::Vec3(10., 20., 50.); + simCore::geodeticToSpherical(refLla.lat(), refLla.lon(), refLla.alt(), tpSphereXYZ); + for (double i : { 10., 100., 1000., 10000., 100000.}) + { + simCore::Vec3 sphereXYZ; + + simCore::Vec3 t1(i, 100., 100.); + simCore::tangentPlane2Sphere(refLla, t1, sphereXYZ, &tpSphereXYZ); + const double alt1 = v3Length(sphereXYZ); + + simCore::Vec3 t2(100., i, 100.); + simCore::tangentPlane2Sphere(refLla, t2, sphereXYZ, &tpSphereXYZ); + const double alt2 = v3Length(sphereXYZ); + rv += SDK_ASSERT(simCore::areEqual(alt1, alt2)); + } + return rv; +} + } int CalculationTest(int argc, char* argv[]) @@ -1788,6 +1851,6 @@ int CalculationTest(int argc, char* argv[]) rv += testTaos_intercept(); rv += testAoaSideslipTotalAoa(); rv += testBoresightAlphaBeta(); - + rv += testTangentPlane2Sphere(); return rv; } diff --git a/Testing/SimCore/CoordConvertLibTest.cpp b/Testing/SimCore/CoordConvertLibTest.cpp index 304fef082..f622a8af1 100644 --- a/Testing/SimCore/CoordConvertLibTest.cpp +++ b/Testing/SimCore/CoordConvertLibTest.cpp @@ -168,7 +168,7 @@ static int checkValues(int uniqueID, const char* whichTest, // static void createTestCases(vTestCases* testCases) { - if (testCases == NULL) + if (testCases == nullptr) return; TestCase* tempTestCase; @@ -1057,7 +1057,7 @@ int CoordConvertLibTest(int _argc_, char *_argv_[]) ++testCaseIterator) { TestCase* temp = *testCaseIterator; - if (temp != NULL) + if (temp != nullptr) { simCore::Coordinate inTSPI(temp->InputCoordinateSystem_, temp->InputPosition_, temp->InputEul_, temp->InputVelocity_, temp->InputAcc_); diff --git a/Testing/SimCore/EMTest.cpp b/Testing/SimCore/EMTest.cpp index 251a23a81..b32c94d60 100644 --- a/Testing/SimCore/EMTest.cpp +++ b/Testing/SimCore/EMTest.cpp @@ -72,7 +72,7 @@ int rcsTest(int argc, char* argv[]) } simCore::RadarCrossSection* rcsData_ = simCore::RcsFileParser::loadRCSFile(filepath); - rv += SDK_ASSERT(rcsData_!=NULL); + rv += SDK_ASSERT(rcsData_!=nullptr); simCore::PolarityType polarity; float freqHz; @@ -503,11 +503,11 @@ int antennaPatternTest(int argc, char* argv[]) antennaGainParameters.freq_ = 3e+9f; - simCore::AntennaPattern* pattern = NULL; + simCore::AntennaPattern* pattern = nullptr; const std::string bilinear = filepath + "bilinear.apbf"; { pattern = simCore::loadPatternFile(bilinear, 3.0e+003); - rv += SDK_ASSERT(NULL != pattern); + rv += SDK_ASSERT(nullptr != pattern); if (pattern) { float min, max; @@ -519,37 +519,37 @@ int antennaPatternTest(int argc, char* argv[]) rv += SDK_ASSERT(simCore::areEqual(gain, -31.4724312f)); delete pattern; } - pattern = NULL; + pattern = nullptr; } { pattern = simCore::loadPatternFile(bilinear, 2.51e+003); - rv += SDK_ASSERT(NULL != pattern); + rv += SDK_ASSERT(nullptr != pattern); if (pattern) delete pattern; - pattern = NULL; + pattern = nullptr; } { pattern = simCore::loadPatternFile(bilinear, 3.49e+003); - rv += SDK_ASSERT(NULL != pattern); + rv += SDK_ASSERT(nullptr != pattern); if (pattern) delete pattern; - pattern = NULL; + pattern = nullptr; } // successful test will output ERROR message to console { pattern = simCore::loadPatternFile(bilinear, 2.5e+003); - rv += SDK_ASSERT(NULL == pattern); + rv += SDK_ASSERT(nullptr == pattern); } // successful test will output ERROR message to console { pattern = simCore::loadPatternFile(bilinear, 3.5e+003); - rv += SDK_ASSERT(NULL == pattern); + rv += SDK_ASSERT(nullptr == pattern); } const std::string monopulse = filepath + "monopulse.apmf"; { pattern = simCore::loadPatternFile(monopulse, 3.0e+003); - rv += SDK_ASSERT(NULL != pattern); + rv += SDK_ASSERT(nullptr != pattern); { float min, max; pattern->minMaxGain(&min, &max, antennaGainParameters); @@ -560,37 +560,37 @@ int antennaPatternTest(int argc, char* argv[]) rv += SDK_ASSERT(simCore::areEqual(gain, -31.4642982f)); delete pattern; } - pattern = NULL; + pattern = nullptr; } { pattern = simCore::loadPatternFile(monopulse, 2.51e+003); - rv += SDK_ASSERT(NULL != pattern); + rv += SDK_ASSERT(nullptr != pattern); if (pattern) delete pattern; - pattern = NULL; + pattern = nullptr; } { pattern = simCore::loadPatternFile(monopulse, 3.49e+003); - rv += SDK_ASSERT(NULL != pattern); + rv += SDK_ASSERT(nullptr != pattern); if (pattern) delete pattern; - pattern = NULL; + pattern = nullptr; } // successful test will output ERROR message to console { pattern = simCore::loadPatternFile(monopulse, 2.5e+003); - rv += SDK_ASSERT(NULL == pattern); + rv += SDK_ASSERT(nullptr == pattern); } // successful test will output ERROR message to console { pattern = simCore::loadPatternFile(monopulse, 3.5e+003); - rv += SDK_ASSERT(NULL == pattern); + rv += SDK_ASSERT(nullptr == pattern); } { pattern = simCore::loadPatternFile(filepath + "umts.aprf", -0.0); - rv += SDK_ASSERT(NULL != pattern); + rv += SDK_ASSERT(nullptr != pattern); if (pattern) { // these tests verify that same result continues to be returned; not testing validity of calc, not based on gold data. @@ -602,12 +602,12 @@ int antennaPatternTest(int argc, char* argv[]) rv += SDK_ASSERT(simCore::areEqual(gain, -2.80341649f)); delete pattern; } - pattern = NULL; + pattern = nullptr; } { pattern = simCore::loadPatternFile(filepath + "24032g.nsm", -0.0); - rv += SDK_ASSERT(NULL != pattern); + rv += SDK_ASSERT(nullptr != pattern); if (pattern) { // these tests verify that same result continues to be returned; not testing validity of calc, not based on gold data. @@ -619,12 +619,12 @@ int antennaPatternTest(int argc, char* argv[]) rv += SDK_ASSERT(simCore::areEqual(gain, -300.f)); delete pattern; } - pattern = NULL; + pattern = nullptr; } { pattern = simCore::loadPatternFile(filepath + "dipoleXFDTD.uan", -0.0); - rv += SDK_ASSERT(NULL != pattern); + rv += SDK_ASSERT(nullptr != pattern); if (pattern) { // these tests verify that same result continues to be returned; not testing validity of calc, not based on gold data. @@ -636,12 +636,12 @@ int antennaPatternTest(int argc, char* argv[]) rv += SDK_ASSERT(simCore::areEqual(gain, 0.920442045f)); delete pattern; } - pattern = NULL; + pattern = nullptr; } { pattern = simCore::loadPatternFile(filepath + "ant_sidelobes.aptf", -0.0); - rv += SDK_ASSERT(NULL != pattern); + rv += SDK_ASSERT(nullptr != pattern); if (pattern) { // these tests verify that same result continues to be returned; not testing validity of calc, not based on gold data. @@ -653,12 +653,12 @@ int antennaPatternTest(int argc, char* argv[]) rv += SDK_ASSERT(simCore::areEqual(gain, -55.7457581f)); delete pattern; } - pattern = NULL; + pattern = nullptr; } { pattern = simCore::loadPatternFile(filepath + "cardioid_az.txt", -0.0); - rv += SDK_ASSERT(NULL != pattern); + rv += SDK_ASSERT(nullptr != pattern); if (pattern) { // these tests verify that same result continues to be returned; not testing validity of calc, not based on gold data. @@ -670,7 +670,7 @@ int antennaPatternTest(int argc, char* argv[]) rv += SDK_ASSERT(simCore::areEqual(gain, 2.88438296f)); delete pattern; } - pattern = NULL; + pattern = nullptr; } diff --git a/Testing/SimCore/MgrsTest.cpp b/Testing/SimCore/MgrsTest.cpp index c4ce4cb4b..6217dfc8c 100644 --- a/Testing/SimCore/MgrsTest.cpp +++ b/Testing/SimCore/MgrsTest.cpp @@ -137,7 +137,7 @@ int mgrsToLla() // White box test on the pointer rv += SDK_ASSERT(simCore::Mgrs::convertMgrsToGeodetic("31NBA2", lat, lon, &err) != 0); - rv += SDK_ASSERT(simCore::Mgrs::convertMgrsToGeodetic("31NBA2", lat, lon, NULL) != 0); + rv += SDK_ASSERT(simCore::Mgrs::convertMgrsToGeodetic("31NBA2", lat, lon, nullptr) != 0); return rv; } diff --git a/Testing/SimCore/StringFormatTest.cpp b/Testing/SimCore/StringFormatTest.cpp index 06259d48e..674b5227b 100644 --- a/Testing/SimCore/StringFormatTest.cpp +++ b/Testing/SimCore/StringFormatTest.cpp @@ -245,12 +245,7 @@ int testBuildString() rv += SDK_ASSERT("0123456789.1" == simCore::buildString("", 123456789.123456789, 12, 1, "", true)); // rounding -#ifdef WIN32 - rv += SDK_ASSERT("1" == simCore::buildString("", 0.5, 1, 0)); -#else - rv += SDK_ASSERT("0" == simCore::buildString("", 0.5, 1, 0)); - rv += SDK_ASSERT("1" == simCore::buildString("", 0.5 + std::numeric_limits::epsilon(), 1, 0)); -#endif + rv += SDK_ASSERT("2" == simCore::buildString("", 1.5, 1, 0)); rv += SDK_ASSERT("0" == simCore::buildString("", 0.5 - std::numeric_limits::epsilon(), 1, 0)); rv += SDK_ASSERT("1.0" == simCore::buildString("", 0.99, 1, 1)); diff --git a/Testing/SimCore/StringUtilsTest.cpp b/Testing/SimCore/StringUtilsTest.cpp index 5266cdc91..14d11fab2 100644 --- a/Testing/SimCore/StringUtilsTest.cpp +++ b/Testing/SimCore/StringUtilsTest.cpp @@ -423,7 +423,7 @@ int testTextReplacer() // Test a bunch of failures on addReplaceable rv += SDK_ASSERT(replacer.addReplaceable(new CustomReplaceable("", "foo")) != 0); - rv += SDK_ASSERT(replacer.addReplaceable(NULL) != 0); + rv += SDK_ASSERT(replacer.addReplaceable(nullptr) != 0); rv += SDK_ASSERT(replacer.addReplaceable(new CustomReplaceable("%VAR", "foo")) != 0); rv += SDK_ASSERT(replacer.addReplaceable(new CustomReplaceable("%VAR%", "foo")) == 0); rv += SDK_ASSERT(replacer.addReplaceable(new CustomReplaceable("VAR%", "foo")) != 0); @@ -440,16 +440,16 @@ int testTextReplacer() rv += SDK_ASSERT(replacer.deleteReplaceable("VAR") != 0); // Test the deleteReplaceable() with pointers - rv += SDK_ASSERT(replacer.deleteReplaceable(NULL) != 0); + rv += SDK_ASSERT(replacer.deleteReplaceable(nullptr) != 0); auto* fooVariable = new CustomReplaceable("VAR", "foo"); rv += SDK_ASSERT(replacer.addReplaceable(fooVariable) == 0); - rv += SDK_ASSERT(replacer.deleteReplaceable(NULL) != 0); + rv += SDK_ASSERT(replacer.deleteReplaceable(nullptr) != 0); rv += SDK_ASSERT(replacer.deleteReplaceable(fooVariable) == 0); // Should not stay in the list after last command rv += SDK_ASSERT(replacer.deleteReplaceable("VAR") != 0); // The memory in fooVariable is considered deleted and is now invalid - fooVariable = NULL; + fooVariable = nullptr; rv += SDK_ASSERT(replacer.format("test %VAR% 123") == "test %VAR% 123"); rv += SDK_ASSERT(replacer.addReplaceable(new CustomReplaceable("VAR", "baz")) == 0); rv += SDK_ASSERT(replacer.format("test %VAR% 123") == "test baz 123"); diff --git a/Testing/SimCore/TokenizerTest.cpp b/Testing/SimCore/TokenizerTest.cpp index 507d2d105..309dd7ae2 100644 --- a/Testing/SimCore/TokenizerTest.cpp +++ b/Testing/SimCore/TokenizerTest.cpp @@ -483,7 +483,7 @@ namespace // SIMDIS_DIR to c:/people/..., or similar; string-safe std::string env(const std::string& envVar) { - if (getenv(envVar.c_str()) != NULL) + if (getenv(envVar.c_str()) != nullptr) return getenv(envVar.c_str()); return "$(" + envVar + ")"; } diff --git a/Testing/SimCore/UnitsFormatter.cpp b/Testing/SimCore/UnitsFormatter.cpp index e07c5b599..185fa10bc 100644 --- a/Testing/SimCore/UnitsFormatter.cpp +++ b/Testing/SimCore/UnitsFormatter.cpp @@ -408,8 +408,8 @@ int testDoubles(const simCore::TextFormatter* fmt, simCore::UnitContextAdapter* int rv = 0; rv += SDK_ASSERT(fmt->formatDouble(0.0) == "0"); rv += SDK_ASSERT(fmt->formatDouble(-0.4) == "0"); - rv += SDK_ASSERT(fmt->formatDouble(-0.50000001) == "-1"); - rv += SDK_ASSERT(fmt->formatDouble(0.50000001) == "1"); + rv += SDK_ASSERT(fmt->formatDouble(-1.50000001) == "-2"); + rv += SDK_ASSERT(fmt->formatDouble(1.50000001) == "2"); rv += SDK_ASSERT(fmt->formatDouble(1234567890123.05) == "1234567890123"); units->setGenericPrecision(2); rv += SDK_ASSERT(fmt->formatDouble(0.001) == "0.00"); diff --git a/Testing/SimCore/ValidNumberTest.cpp b/Testing/SimCore/ValidNumberTest.cpp index ce584c250..dee995189 100644 --- a/Testing/SimCore/ValidNumberTest.cpp +++ b/Testing/SimCore/ValidNumberTest.cpp @@ -34,7 +34,7 @@ namespace /** Returns true when testString conversion to type T worked as expectedValid dictates. */ template -bool validateValueNoCompare(const std::string& testString, bool expectedValid, T* convertedValue=NULL, bool allowPlusSign=true) +bool validateValueNoCompare(const std::string& testString, bool expectedValid, T* convertedValue=nullptr, bool allowPlusSign=true) { bool rv = true; // Return value defaults to good @@ -54,7 +54,7 @@ bool validateValueNoCompare(const std::string& testString, bool expectedValid, T std::cerr << "isValidNumber<" << typeid(T).name() << "> failed with input: " << testString << std::endl; rv = false; } - if (convertedValue != NULL) + if (convertedValue != nullptr) *convertedValue = val; return rv; } diff --git a/Testing/SimData/CategoryDataTest.cpp b/Testing/SimData/CategoryDataTest.cpp index 0a89c8d12..77773b67d 100644 --- a/Testing/SimData/CategoryDataTest.cpp +++ b/Testing/SimData/CategoryDataTest.cpp @@ -411,21 +411,21 @@ int testDeleteEntity(simData::DataStore& ds) simUtil::DataStoreTestHelper helper(&ds); uint64_t plat100 = helper.addPlatform(); helper.addCategoryData(plat100, "Plat100", "100", -1.0); - rv += SDK_ASSERT(ds.categoryDataSlice(plat100) != NULL); - rv += SDK_ASSERT(ds.categoryDataSlice(plat100+1) == NULL); // random sanity check + rv += SDK_ASSERT(ds.categoryDataSlice(plat100) != nullptr); + rv += SDK_ASSERT(ds.categoryDataSlice(plat100+1) == nullptr); // random sanity check // Validate that removing the entity removes its category data slice too ds.removeEntity(plat100); - rv += SDK_ASSERT(ds.categoryDataSlice(plat100) == NULL); + rv += SDK_ASSERT(ds.categoryDataSlice(plat100) == nullptr); // Same test, recursive on a LOB uint64_t plat101 = helper.addPlatform(); uint64_t lob102 = helper.addLOB(plat101); helper.addCategoryData(lob102, "LOB102", "102", -1.0); - rv += SDK_ASSERT(ds.categoryDataSlice(lob102) != NULL); // random sanity check + rv += SDK_ASSERT(ds.categoryDataSlice(lob102) != nullptr); // random sanity check // Remove it and double check ds.removeEntity(plat101); - rv += SDK_ASSERT(ds.categoryDataSlice(plat101) == NULL); - rv += SDK_ASSERT(ds.categoryDataSlice(lob102) == NULL); + rv += SDK_ASSERT(ds.categoryDataSlice(plat101) == nullptr); + rv += SDK_ASSERT(ds.categoryDataSlice(lob102) == nullptr); return rv; } @@ -767,7 +767,7 @@ int testIsDuplicateValue() ds.setDataLimiting(false); // Needs to be false to avoid triggering duplicate values const simData::MemoryCategoryDataSlice* cd = dynamic_cast(ds.categoryDataSlice(id)); - rv += SDK_ASSERT(cd != NULL); + rv += SDK_ASSERT(cd != nullptr); rv += SDK_ASSERT(cd->numItems() == 0); // No items, no duplicates rv += SDK_ASSERT(!cd->isDuplicateValue(10, "key", "value")); @@ -1389,16 +1389,16 @@ int testRegExpSimplify() rv += SDK_ASSERT(checks.size() == 1); // Test getRegExp()/getRegExpPattern() - rv += SDK_ASSERT(filter.getRegExp(KEY2) != NULL); + rv += SDK_ASSERT(filter.getRegExp(KEY2) != nullptr); rv += SDK_ASSERT(filter.getRegExp(KEY2)->pattern() == "e3"); rv += SDK_ASSERT(filter.getRegExpPattern(KEY2) == "e3"); - rv += SDK_ASSERT(filter.getRegExp(KEY3) == NULL); + rv += SDK_ASSERT(filter.getRegExp(KEY3) == nullptr); rv += SDK_ASSERT(filter.getRegExpPattern(KEY3).empty()); // Test a different pattern rv += SDK_ASSERT(filter.deserialize("key3(1)^^e2$", reFactory)); - rv += SDK_ASSERT(filter.getRegExp(KEY2) == NULL); + rv += SDK_ASSERT(filter.getRegExp(KEY2) == nullptr); rv += SDK_ASSERT(filter.getRegExpPattern(KEY2).empty()); - rv += SDK_ASSERT(filter.getRegExp(KEY3) != NULL); + rv += SDK_ASSERT(filter.getRegExp(KEY3) != nullptr); rv += SDK_ASSERT(filter.getRegExp(KEY3)->pattern() == "^e2$"); rv += SDK_ASSERT(filter.getRegExpPattern(KEY3) == "^e2$"); diff --git a/Testing/SimData/DataStorePerformanceTest/DataStorePerformanceTest.cpp b/Testing/SimData/DataStorePerformanceTest/DataStorePerformanceTest.cpp index 31fdca5d3..a23af0079 100644 --- a/Testing/SimData/DataStorePerformanceTest/DataStorePerformanceTest.cpp +++ b/Testing/SimData/DataStorePerformanceTest/DataStorePerformanceTest.cpp @@ -90,8 +90,8 @@ class CountListener : public simData::DataStore::DefaultListener counters_->pref++; } - /// current time has been changed - virtual void onTimeChange(simData::DataStore *source) + /// data store has changed + virtual void onChange(simData::DataStore *source) { counters_->time++; } @@ -258,7 +258,7 @@ class Entity if (!row.empty()) table->addRow(row); - // Add a small epsilon to introduce NULLs + // Add a small epsilon to introduce nullptrs realTime += TIME_EPSILON; } } @@ -268,7 +268,7 @@ class Entity }; AddRowPerTable addRowPerTable(time, rowModulus); const simData::TableList* tables = helper_.dataStore()->dataTableManager().tablesForOwner(id); - if (tables != NULL) + if (tables != nullptr) tables->accept(addRowPerTable); } @@ -349,11 +349,11 @@ class Entity simData::DataTableManager& mgr = helper_.dataStore()->dataTableManager(); for (size_t table = 0; table < numTables; ++table) { - simData::DataTable* newTable = NULL; + simData::DataTable* newTable = nullptr; mgr.addDataTable(id, "Table " + asString_(table), &newTable); for (size_t col = 0; col < numColPerTable; ++col) { - newTable->addColumn("Column " + asString_(col), tableVariableType_, 0, NULL); + newTable->addColumn("Column " + asString_(col), tableVariableType_, 0, nullptr); } } } diff --git a/Testing/SimData/MemoryDataTableTest.cpp b/Testing/SimData/MemoryDataTableTest.cpp index b2acb58cd..e781471a6 100644 --- a/Testing/SimData/MemoryDataTableTest.cpp +++ b/Testing/SimData/MemoryDataTableTest.cpp @@ -227,9 +227,9 @@ int managerTest(DataTableManager& mgr) { int rv = 0; // Initial check - rv += SDK_ASSERT(mgr.getTable(1) == NULL); + rv += SDK_ASSERT(mgr.getTable(1) == nullptr); rv += SDK_ASSERT(mgr.tableCount() == 0); - rv += SDK_ASSERT(mgr.tablesForOwner(10) == NULL); + rv += SDK_ASSERT(mgr.tablesForOwner(10) == nullptr); // add observer to test ManagerObserver // NOTE, since this has been wrapped in shared ptr we don't have to delete explicitly @@ -237,26 +237,26 @@ int managerTest(DataTableManager& mgr) mgr.addObserver(simData::DataTableManager::ManagerObserverPtr(testObserver)); // Add a single table - simData::DataTable* table10Foo = NULL; + simData::DataTable* table10Foo = nullptr; rv += SDK_ASSERT(mgr.addDataTable(10, "Foo", &table10Foo).isSuccess()); - rv += SDK_ASSERT(table10Foo != NULL); + rv += SDK_ASSERT(table10Foo != nullptr); rv += SDK_ASSERT(mgr.findTable(10, "Foo") == table10Foo); - rv += SDK_ASSERT(mgr.findTable(11, "Foo") == NULL); + rv += SDK_ASSERT(mgr.findTable(11, "Foo") == nullptr); rv += SDK_ASSERT(mgr.tableCount() == 1); - rv += SDK_ASSERT(mgr.tablesForOwner(10) != NULL); + rv += SDK_ASSERT(mgr.tablesForOwner(10) != nullptr); rv += SDK_ASSERT(mgr.tablesForOwner(10)->tableCount() == 1); // Add 2 more tables testObserver->setExpectedTableName("Bar"); - simData::DataTable* table10Bar = NULL; + simData::DataTable* table10Bar = nullptr; rv += SDK_ASSERT(mgr.addDataTable(10, "Bar", &table10Bar).isSuccess()); - simData::DataTable* table10Baz = NULL; + simData::DataTable* table10Baz = nullptr; testObserver->setExpectedTableName("Baz"); rv += SDK_ASSERT(mgr.addDataTable(10, "Baz", &table10Baz).isSuccess()); - rv += SDK_ASSERT(table10Bar != NULL); - rv += SDK_ASSERT(table10Baz != NULL); + rv += SDK_ASSERT(table10Bar != nullptr); + rv += SDK_ASSERT(table10Baz != nullptr); rv += SDK_ASSERT(mgr.tableCount() == 3); - rv += SDK_ASSERT(mgr.tablesForOwner(10) != NULL); + rv += SDK_ASSERT(mgr.tablesForOwner(10) != nullptr); rv += SDK_ASSERT(mgr.tablesForOwner(10)->tableCount() == 3); // They should all be different tables ... rv += SDK_ASSERT(table10Foo != table10Bar); @@ -268,41 +268,41 @@ int managerTest(DataTableManager& mgr) rv += SDK_ASSERT(table10Foo->tableId() != table10Baz->tableId()); // Add a duplicate table name; should return error, but also return valid pointer - simData::DataTable* table10FooDupe = NULL; + simData::DataTable* table10FooDupe = nullptr; rv += SDK_ASSERT(mgr.addDataTable(10, "Foo", &table10FooDupe).isError()); - simData::DataTable* table10BarDupe = NULL; + simData::DataTable* table10BarDupe = nullptr; rv += SDK_ASSERT(mgr.addDataTable(10, "Bar", &table10BarDupe).isError()); - simData::DataTable* table10BazDupe = NULL; + simData::DataTable* table10BazDupe = nullptr; rv += SDK_ASSERT(mgr.addDataTable(10, "Baz", &table10BazDupe).isError()); rv += SDK_ASSERT(table10FooDupe == table10Foo); rv += SDK_ASSERT(table10BarDupe == table10Bar); rv += SDK_ASSERT(table10BazDupe == table10Baz); rv += SDK_ASSERT(mgr.tableCount() == 3); - rv += SDK_ASSERT(mgr.tablesForOwner(10) != NULL); + rv += SDK_ASSERT(mgr.tablesForOwner(10) != nullptr); rv += SDK_ASSERT(mgr.tablesForOwner(10)->tableCount() == 3); // Add empty string testObserver->setExpectedTableName(""); - simData::DataTable* emptyStringDT = NULL; + simData::DataTable* emptyStringDT = nullptr; rv += SDK_ASSERT(mgr.addDataTable(10, "", &emptyStringDT).isError()); - rv += SDK_ASSERT(emptyStringDT == NULL); + rv += SDK_ASSERT(emptyStringDT == nullptr); rv += SDK_ASSERT(mgr.tableCount() == 3); - rv += SDK_ASSERT(mgr.tablesForOwner(10) != NULL); + rv += SDK_ASSERT(mgr.tablesForOwner(10) != nullptr); rv += SDK_ASSERT(mgr.tablesForOwner(10)->tableCount() == 3); // Add 2 tables to another ID testObserver->setExpectedTableName("Foo"); - simData::DataTable* table11Foo = NULL; + simData::DataTable* table11Foo = nullptr; rv += SDK_ASSERT(mgr.addDataTable(11, "Foo", &table11Foo).isSuccess()); testObserver->setExpectedTableName("Bar"); - simData::DataTable* table11Bar = NULL; + simData::DataTable* table11Bar = nullptr; rv += SDK_ASSERT(mgr.addDataTable(11, "Bar", &table11Bar).isSuccess()); - rv += SDK_ASSERT(table11Foo != NULL); - rv += SDK_ASSERT(table11Bar != NULL); + rv += SDK_ASSERT(table11Foo != nullptr); + rv += SDK_ASSERT(table11Bar != nullptr); rv += SDK_ASSERT(mgr.tableCount() == 5); - rv += SDK_ASSERT(mgr.tablesForOwner(10) != NULL); + rv += SDK_ASSERT(mgr.tablesForOwner(10) != nullptr); rv += SDK_ASSERT(mgr.tablesForOwner(10)->tableCount() == 3); - rv += SDK_ASSERT(mgr.tablesForOwner(11) != NULL); + rv += SDK_ASSERT(mgr.tablesForOwner(11) != nullptr); rv += SDK_ASSERT(mgr.tablesForOwner(11)->tableCount() == 2); // Test getTable() @@ -317,7 +317,7 @@ int managerTest(DataTableManager& mgr) rv += SDK_ASSERT(mgr.findTable(10, "Baz") == table10Baz); rv += SDK_ASSERT(mgr.findTable(11, "Foo") == table11Foo); rv += SDK_ASSERT(mgr.findTable(11, "Bar") == table11Bar); - rv += SDK_ASSERT(mgr.findTable(11, "Baz") == NULL); + rv += SDK_ASSERT(mgr.findTable(11, "Baz") == nullptr); // Now's a good time to test owner IDs rv += SDK_ASSERT(table10Foo->ownerId() == 10); rv += SDK_ASSERT(table10Bar->ownerId() == 10); @@ -329,15 +329,15 @@ int managerTest(DataTableManager& mgr) const TableList* table10List = mgr.tablesForOwner(10); const TableList* table11List = mgr.tablesForOwner(11); const TableList* table12List = mgr.tablesForOwner(12); - rv += SDK_ASSERT(table10List != NULL); - rv += SDK_ASSERT(table11List != NULL); - rv += SDK_ASSERT(table12List == NULL); + rv += SDK_ASSERT(table10List != nullptr); + rv += SDK_ASSERT(table11List != nullptr); + rv += SDK_ASSERT(table12List == nullptr); rv += SDK_ASSERT(table10List->findTable("Foo") == table10Foo); rv += SDK_ASSERT(table10List->findTable("Bar") == table10Bar); rv += SDK_ASSERT(table10List->findTable("Baz") == table10Baz); rv += SDK_ASSERT(table11List->findTable("Foo") == table11Foo); rv += SDK_ASSERT(table11List->findTable("Bar") == table11Bar); - rv += SDK_ASSERT(table11List->findTable("Baz") == NULL); + rv += SDK_ASSERT(table11List->findTable("Baz") == nullptr); rv += SDK_ASSERT(table10List->ownerId() == 10); rv += SDK_ASSERT(table11List->ownerId() == 11); rv += SDK_ASSERT(table10List->tableCount() == 3); @@ -350,14 +350,14 @@ int managerTest(DataTableManager& mgr) testObserver->setExpectedTableName("Bar"); // set observer to prepare for Bar delete rv += SDK_ASSERT(mgr.deleteTable(table10BarId).isSuccess()); rv += SDK_ASSERT(mgr.tableCount() == 4); - rv += SDK_ASSERT(mgr.tablesForOwner(10) != NULL); - rv += SDK_ASSERT(mgr.tablesForOwner(11) != NULL); + rv += SDK_ASSERT(mgr.tablesForOwner(10) != nullptr); + rv += SDK_ASSERT(mgr.tablesForOwner(11) != nullptr); rv += SDK_ASSERT(table10List->tableCount() == 2); rv += SDK_ASSERT(table11List->tableCount() == 2); rv += SDK_ASSERT(table10Foo->tableId() == table10FooId); rv += SDK_ASSERT(table10Baz->tableId() == table10BazId); rv += SDK_ASSERT(mgr.getTable(table10FooId) == table10Foo); - rv += SDK_ASSERT(mgr.getTable(table10BarId) == NULL); + rv += SDK_ASSERT(mgr.getTable(table10BarId) == nullptr); rv += SDK_ASSERT(mgr.getTable(table10BazId) == table10Baz); // set owner id for deleteTablesByOwner test @@ -366,13 +366,13 @@ int managerTest(DataTableManager& mgr) // Test deleteByOwner mgr.deleteTablesByOwner(11); rv += SDK_ASSERT(mgr.tableCount() == 2); - rv += SDK_ASSERT(mgr.tablesForOwner(10) != NULL); - rv += SDK_ASSERT(mgr.tablesForOwner(11) == NULL); + rv += SDK_ASSERT(mgr.tablesForOwner(10) != nullptr); + rv += SDK_ASSERT(mgr.tablesForOwner(11) == nullptr); rv += SDK_ASSERT(table10List->tableCount() == 2); rv += SDK_ASSERT(table10Foo->tableId() == table10FooId); rv += SDK_ASSERT(table10Baz->tableId() == table10BazId); rv += SDK_ASSERT(mgr.getTable(table10FooId) == table10Foo); - rv += SDK_ASSERT(mgr.getTable(table10BarId) == NULL); + rv += SDK_ASSERT(mgr.getTable(table10BarId) == nullptr); rv += SDK_ASSERT(mgr.getTable(table10BazId) == table10Baz); // Test a double delete @@ -591,9 +591,9 @@ int timeContainerTest(MemoryTable::TimeContainer& times) int tableTest(simData::DataTable& table) { int rv = 0; - simData::TableColumn* column1 = NULL; - simData::TableColumn* column2 = NULL; - simData::TableColumn* column3 = NULL; + simData::TableColumn* column1 = nullptr; + simData::TableColumn* column2 = nullptr; + simData::TableColumn* column3 = nullptr; // create test observer. NOTE: since this is wrapped in a shared ptr, don't need to delete explicitly TestTableObserver* testObserver = new TestTableObserver(table); @@ -602,10 +602,10 @@ int tableTest(simData::DataTable& table) // Empty column name is an error rv += SDK_ASSERT(table.columnCount() == 0); rv += SDK_ASSERT(table.addColumn("", VT_INT32, 0, &column1).isError()); - rv += SDK_ASSERT(column1 == NULL); + rv += SDK_ASSERT(column1 == nullptr); testObserver->setExpectedColumnName("1"); rv += SDK_ASSERT(table.addColumn("1", VT_INT32, 0, &column1).isSuccess()); - rv += SDK_ASSERT(column1 != NULL); + rv += SDK_ASSERT(column1 != nullptr); // Duplicate name is an error rv += SDK_ASSERT(table.addColumn("1", VT_INT32, 0, &column2).isError()); rv += SDK_ASSERT(column2 == column1); // Should point to column 1, even though there's an error @@ -613,7 +613,7 @@ int tableTest(simData::DataTable& table) rv += SDK_ASSERT(table.addColumn("2", VT_INT32, 0, &column2).isSuccess()); // Sanity checks rv += SDK_ASSERT(column2 != column1); - rv += SDK_ASSERT(column2 != NULL); + rv += SDK_ASSERT(column2 != nullptr); rv += SDK_ASSERT(column1->columnId() != column2->columnId()); rv += SDK_ASSERT(column1->name() == "1"); rv += SDK_ASSERT(column2->name() == "2"); @@ -621,17 +621,17 @@ int tableTest(simData::DataTable& table) rv += SDK_ASSERT(table.column("1") == column1); rv += SDK_ASSERT(table.column("2") == column2); - rv += SDK_ASSERT(table.column("3") == NULL); + rv += SDK_ASSERT(table.column("3") == nullptr); rv += SDK_ASSERT(table.column(column1->columnId()) == column1); rv += SDK_ASSERT(table.column(column2->columnId()) == column2); - rv += SDK_ASSERT(table.column(500) == NULL); // Should be unique + rv += SDK_ASSERT(table.column(500) == nullptr); // Should be unique // Add another column testObserver->setExpectedColumnName("3"); rv += SDK_ASSERT(table.addColumn("3", VT_INT32, 0, &column3).isSuccess()); rv += SDK_ASSERT(column3 != column1); rv += SDK_ASSERT(column3 != column2); - rv += SDK_ASSERT(column3 != NULL); + rv += SDK_ASSERT(column3 != nullptr); // Store the column IDs to check that they don't change over the next few tests simData::TableColumnId col1Id = column1->columnId(); simData::TableColumnId col2Id = column2->columnId(); @@ -643,8 +643,8 @@ int tableTest(simData::DataTable& table) testObserver->setExpectedColumnName("2"); rv += SDK_ASSERT(table.removeColumn("2").isSuccess()); // Verify that the column is in fact removed - rv += SDK_ASSERT(table.column(col2Id) == NULL); - rv += SDK_ASSERT(table.column("2") == NULL); + rv += SDK_ASSERT(table.column(col2Id) == nullptr); + rv += SDK_ASSERT(table.column("2") == nullptr); // Removing a column should not affect the other columns rv += SDK_ASSERT(col1Id == column1->columnId()); @@ -659,7 +659,7 @@ int tableTest(simData::DataTable& table) rv += SDK_ASSERT(table.addColumn("2", VT_INT32, 0, &column2).isSuccess()); rv += SDK_ASSERT(column2 != column1); rv += SDK_ASSERT(column2 != column3); - rv += SDK_ASSERT(column2 != NULL); + rv += SDK_ASSERT(column2 != nullptr); // Should not reuse the ID of removed column rv += SDK_ASSERT(col2Id != column2->columnId()); col2Id = column2->columnId(); @@ -722,54 +722,54 @@ int tableTest(simData::DataTable& table) // Check interpolate on given values double value = 0; - rv += SDK_ASSERT(column1->interpolate(value, 10.0, NULL).isSuccess()); + rv += SDK_ASSERT(column1->interpolate(value, 10.0, nullptr).isSuccess()); rv += SDK_ASSERT(simCore::areEqual(value, 1001.0)); - rv += SDK_ASSERT(column1->interpolate(value, 20.0, NULL).isSuccess()); + rv += SDK_ASSERT(column1->interpolate(value, 20.0, nullptr).isSuccess()); rv += SDK_ASSERT(simCore::areEqual(value, 2001.0)); - rv += SDK_ASSERT(column1->interpolate(value, 30.0, NULL).isSuccess()); + rv += SDK_ASSERT(column1->interpolate(value, 30.0, nullptr).isSuccess()); rv += SDK_ASSERT(simCore::areEqual(value, 3001.0)); // Actually interpolate - rv += SDK_ASSERT(column1->interpolate(value, 25.0, NULL).isSuccess()); + rv += SDK_ASSERT(column1->interpolate(value, 25.0, nullptr).isSuccess()); rv += SDK_ASSERT(simCore::areEqual(value, 2501.0)); // Check that extrapolation fails before time, and succeeds with current value after time - rv += SDK_ASSERT(column1->interpolate(value, 5.0, NULL).isError()); - rv += SDK_ASSERT(column1->interpolate(value, 35.0, NULL).isSuccess()); + rv += SDK_ASSERT(column1->interpolate(value, 5.0, nullptr).isError()); + rv += SDK_ASSERT(column1->interpolate(value, 35.0, nullptr).isSuccess()); rv += SDK_ASSERT(simCore::areEqual(value, 3001.0)); // Now with column 2 - rv += SDK_ASSERT(column2->interpolate(value, 10.0, NULL).isSuccess()); + rv += SDK_ASSERT(column2->interpolate(value, 10.0, nullptr).isSuccess()); rv += SDK_ASSERT(simCore::areEqual(value, 1002.0)); - rv += SDK_ASSERT(column2->interpolate(value, 20.0, NULL).isSuccess()); + rv += SDK_ASSERT(column2->interpolate(value, 20.0, nullptr).isSuccess()); rv += SDK_ASSERT(simCore::areEqual(value, 2002.0)); - rv += SDK_ASSERT(column2->interpolate(value, 30.0, NULL).isSuccess()); + rv += SDK_ASSERT(column2->interpolate(value, 30.0, nullptr).isSuccess()); rv += SDK_ASSERT(simCore::areEqual(value, 3002.0)); // Actually interpolate - rv += SDK_ASSERT(column2->interpolate(value, 25.0, NULL).isSuccess()); + rv += SDK_ASSERT(column2->interpolate(value, 25.0, nullptr).isSuccess()); rv += SDK_ASSERT(simCore::areEqual(value, 2502.0)); // Check that extrapolation fails before time, and succeeds with current value after time - rv += SDK_ASSERT(column2->interpolate(value, 5.0, NULL).isError()); - rv += SDK_ASSERT(column2->interpolate(value, 35.0, NULL).isSuccess()); + rv += SDK_ASSERT(column2->interpolate(value, 5.0, nullptr).isError()); + rv += SDK_ASSERT(column2->interpolate(value, 35.0, nullptr).isSuccess()); rv += SDK_ASSERT(simCore::areEqual(value, 3002.0)); // Now with column 3 - rv += SDK_ASSERT(column3->interpolate(value, 10.0, NULL).isSuccess()); + rv += SDK_ASSERT(column3->interpolate(value, 10.0, nullptr).isSuccess()); rv += SDK_ASSERT(simCore::areEqual(value, 1003.0)); - rv += SDK_ASSERT(column3->interpolate(value, 20.0, NULL).isSuccess()); + rv += SDK_ASSERT(column3->interpolate(value, 20.0, nullptr).isSuccess()); rv += SDK_ASSERT(simCore::areEqual(value, 2003.0)); - rv += SDK_ASSERT(column3->interpolate(value, 30.0, NULL).isSuccess()); + rv += SDK_ASSERT(column3->interpolate(value, 30.0, nullptr).isSuccess()); rv += SDK_ASSERT(simCore::areEqual(value, 3003.0)); // Actually interpolate - rv += SDK_ASSERT(column3->interpolate(value, 25.0, NULL).isSuccess()); + rv += SDK_ASSERT(column3->interpolate(value, 25.0, nullptr).isSuccess()); rv += SDK_ASSERT(simCore::areEqual(value, 2503.0)); // Check that extrapolation fails before time, and succeeds with current value after time - rv += SDK_ASSERT(column3->interpolate(value, 5.0, NULL).isError()); - rv += SDK_ASSERT(column3->interpolate(value, 35.0, NULL).isSuccess()); + rv += SDK_ASSERT(column3->interpolate(value, 5.0, nullptr).isError()); + rv += SDK_ASSERT(column3->interpolate(value, 35.0, nullptr).isSuccess()); rv += SDK_ASSERT(simCore::areEqual(value, 3003.0)); // Add 3 new columns - simData::TableColumn* column4 = NULL; - simData::TableColumn* column5 = NULL; - simData::TableColumn* column6 = NULL; + simData::TableColumn* column4 = nullptr; + simData::TableColumn* column5 = nullptr; + simData::TableColumn* column6 = nullptr; testObserver->setExpectedColumnName("4"); rv += SDK_ASSERT(table.addColumn("4", VT_UINT32, 0, &column4).isSuccess()); testObserver->setExpectedColumnName("5"); @@ -799,17 +799,17 @@ int tableTest(simData::DataTable& table) rv += SDK_ASSERT(table.addRow(row).isSuccess()); // Spot check interpolation on all columns at time 25 - rv += SDK_ASSERT(column1->interpolate(value, 25.0, NULL).isSuccess()); + rv += SDK_ASSERT(column1->interpolate(value, 25.0, nullptr).isSuccess()); rv += SDK_ASSERT(simCore::areEqual(value, 2501.0)); - rv += SDK_ASSERT(column2->interpolate(value, 25.0, NULL).isSuccess()); + rv += SDK_ASSERT(column2->interpolate(value, 25.0, nullptr).isSuccess()); rv += SDK_ASSERT(simCore::areEqual(value, 2502.0)); - rv += SDK_ASSERT(column3->interpolate(value, 25.0, NULL).isSuccess()); + rv += SDK_ASSERT(column3->interpolate(value, 25.0, nullptr).isSuccess()); rv += SDK_ASSERT(simCore::areEqual(value, 2503.0)); - rv += SDK_ASSERT(column4->interpolate(value, 25.0, NULL).isSuccess()); + rv += SDK_ASSERT(column4->interpolate(value, 25.0, nullptr).isSuccess()); rv += SDK_ASSERT(simCore::areEqual(value, 2504.0)); - rv += SDK_ASSERT(column5->interpolate(value, 25.0, NULL).isSuccess()); + rv += SDK_ASSERT(column5->interpolate(value, 25.0, nullptr).isSuccess()); rv += SDK_ASSERT(simCore::areEqual(value, 2505.0)); - rv += SDK_ASSERT(column6->interpolate(value, 25.0, NULL).isSuccess()); + rv += SDK_ASSERT(column6->interpolate(value, 25.0, nullptr).isSuccess()); rv += SDK_ASSERT(simCore::areEqual(value, 2506.0)); // Store column IDs to check for changes in later steps @@ -821,8 +821,8 @@ int tableTest(simData::DataTable& table) testObserver->setExpectedColumnName("3"); rv += SDK_ASSERT(table.removeColumn("3").isSuccess()); // Verify that the column is in fact removed - rv += SDK_ASSERT(table.column(col3Id) == NULL); - rv += SDK_ASSERT(table.column("3") == NULL); + rv += SDK_ASSERT(table.column(col3Id) == nullptr); + rv += SDK_ASSERT(table.column("3") == nullptr); // Check that other columns are not affected, especially columns 1 and 2 which are in the same subtable at this point rv += SDK_ASSERT(col1Id == column1->columnId()); @@ -855,9 +855,9 @@ int tableTest(simData::DataTable& table) testObserver->setExpectedRowTime(85.0); rv += SDK_ASSERT(table.addRow(row).isSuccess()); // Now check those values... - rv += SDK_ASSERT(column1->interpolate(value, 80.0, NULL).isSuccess()); + rv += SDK_ASSERT(column1->interpolate(value, 80.0, nullptr).isSuccess()); rv += SDK_ASSERT(simCore::areEqual(value, 123.0)); - rv += SDK_ASSERT(column4->interpolate(value, 85.0, NULL).isSuccess()); + rv += SDK_ASSERT(column4->interpolate(value, 85.0, nullptr).isSuccess()); rv += SDK_ASSERT(simCore::areEqual(value, 321.0)); // did our observer get any errors? @@ -902,7 +902,7 @@ int flushTest(simData::DataTable& table) numDataValues.clear(); // This could fail if the container does not implement delayed flush - rv += SDK_ASSERT(delayedFlush.get() != NULL); + rv += SDK_ASSERT(delayedFlush.get() != nullptr); // Clear out the memory and make sure it's still all 0 delayedFlush.reset(); @@ -910,7 +910,7 @@ int flushTest(simData::DataTable& table) rv += SDK_ASSERT(numDataValues.numColumns() == table.columnCount()); rv += SDK_ASSERT(numDataValues.size() == 0); numDataValues.clear(); - rv += SDK_ASSERT(delayedFlush.get() == NULL); + rv += SDK_ASSERT(delayedFlush.get() == nullptr); return rv; } @@ -927,12 +927,12 @@ int dataLimitSecondsTest() prefs->mutable_commonprefs()->set_datalimittime(5.0); // limiting to 5 seconds t.commit(); - simData::DataTable* table = NULL; + simData::DataTable* table = nullptr; rv += SDK_ASSERT(ds->dataTableManager().addDataTable(plat1, "Data Limit Test Table", &table).isSuccess()); // add some columns - simData::TableColumn* column1 = NULL; - simData::TableColumn* column2 = NULL; + simData::TableColumn* column1 = nullptr; + simData::TableColumn* column2 = nullptr; rv += SDK_ASSERT(table->addColumn("1", VT_INT32, 0, &column1).isSuccess()); rv += SDK_ASSERT(table->addColumn("2", VT_INT64, 0, &column2).isSuccess()); @@ -1058,7 +1058,7 @@ int dataLimitingTest() // algorithm that is employed in the double buffer time container. t.commit(); - simData::DataTable* table = NULL; + simData::DataTable* table = nullptr; rv += SDK_ASSERT(ds->dataTableManager().addDataTable(plat1, "Data Limit Test Table", &table).isSuccess()); // create test observer. NOTE: since this is wrapped in a shared ptr, don't need to delete explicitly (but we do want to test removeObserver() @@ -1067,8 +1067,8 @@ int dataLimitingTest() table->addObserver(testObserverPtr); // add some columns - simData::TableColumn* column1 = NULL; - simData::TableColumn* column2 = NULL; + simData::TableColumn* column1 = nullptr; + simData::TableColumn* column2 = nullptr; testObserver->setExpectedColumnName("1"); rv += SDK_ASSERT(table->addColumn("1", VT_INT32, 0, &column1).isSuccess()); testObserver->setExpectedColumnName("2"); @@ -1209,8 +1209,8 @@ int dataLimitingTest() // Stale: 2, 5, 6; Fresh: 5.5, 5.75 // add some more columns so we can cause a split - simData::TableColumn* column3 = NULL; - simData::TableColumn* column4 = NULL; + simData::TableColumn* column3 = nullptr; + simData::TableColumn* column4 = nullptr; testObserver->setExpectedColumnName("3"); rv += SDK_ASSERT(table->addColumn("3", VT_INT8, 0, &column3).isSuccess()); testObserver->setExpectedColumnName("4"); @@ -1251,11 +1251,11 @@ int getTimeRangeTest() prefs->mutable_commonprefs()->set_datalimitpoints(6); // start out limiting to 6 points t.commit(); - simData::DataTable* table = NULL; + simData::DataTable* table = nullptr; rv += SDK_ASSERT(ds->dataTableManager().addDataTable(plat1, "Data Limit Test Table", &table).isSuccess()); // Add a column - simData::TableColumn* column1 = NULL; + simData::TableColumn* column1 = nullptr; rv += SDK_ASSERT(table->addColumn("1", VT_INT32, 0, &column1).isSuccess()); // add some rows @@ -1300,7 +1300,7 @@ int getTimeRangeTest() // Test again, with data being added in reverse. Creates situation where the // DoubleBufferTimeContainer's FRESH bin has earlier times than the STALE bin - simData::TableColumn* column2 = NULL; + simData::TableColumn* column2 = nullptr; rv += SDK_ASSERT(table->addColumn("2", VT_INT32, 0, &column2).isSuccess()); newRow.clear(); @@ -1359,9 +1359,9 @@ int subTableIterationTest(simData::MemoryTable::TimeContainer* newTimeContainer) rv += SDK_ASSERT(!invalidIter.hasPrevious()); // Add 5 rows of data for 3 columns; start column numbering at 4 (random) - rv += SDK_ASSERT(subTable.addColumn("C4", 4, simData::VT_INT32, 0, NULL).isSuccess()); - rv += SDK_ASSERT(subTable.addColumn("C5", 5, simData::VT_STRING, 0, NULL).isSuccess()); - rv += SDK_ASSERT(subTable.addColumn("C6", 6, simData::VT_FLOAT, 0, NULL).isSuccess()); + rv += SDK_ASSERT(subTable.addColumn("C4", 4, simData::VT_INT32, 0, nullptr).isSuccess()); + rv += SDK_ASSERT(subTable.addColumn("C5", 5, simData::VT_STRING, 0, nullptr).isSuccess()); + rv += SDK_ASSERT(subTable.addColumn("C6", 6, simData::VT_FLOAT, 0, nullptr).isSuccess()); // Create a helper class to ensure we don't split class NoSplit : public SubTable::SplitObserver { @@ -1754,9 +1754,9 @@ int testColumnIteration(simData::DataTable& table) // Create a data table with some null values rv += SDK_ASSERT(table.columnCount() == 0); - simData::TableColumn* c1 = NULL; - simData::TableColumn* c2 = NULL; - simData::TableColumn* c3 = NULL; + simData::TableColumn* c1 = nullptr; + simData::TableColumn* c2 = nullptr; + simData::TableColumn* c3 = nullptr; rv += SDK_ASSERT(table.addColumn("C1", simData::VT_UINT32, 0, &c1).isSuccess()); rv += SDK_ASSERT(table.addColumn("C2", simData::VT_INT32, 0, &c2).isSuccess()); rv += SDK_ASSERT(table.addColumn("C3", simData::VT_UINT64, 0, &c3).isSuccess()); @@ -1973,10 +1973,10 @@ int tableTest() { simData::MemoryDataStore ds; simData::DataTableManager& mgr = ds.dataTableManager(); - simData::DataTable* table = NULL; + simData::DataTable* table = nullptr; int rv = 0; rv += SDK_ASSERT(mgr.addDataTable(1, "Test Table", &table).isSuccess()); - rv += SDK_ASSERT(table != NULL); + rv += SDK_ASSERT(table != nullptr); rv += SDK_ASSERT(tableTest(*table) == 0); rv += SDK_ASSERT(flushTest(*table) == 0); return rv; @@ -1996,49 +1996,49 @@ int removeEntityTest() mgr.addObserver(simData::DataTableManager::ManagerObserverPtr(testObserver)); testObserver->setExpectedTableName("Plat1Table1"); - rv += SDK_ASSERT(mgr.addDataTable(plat1, "Plat1Table1", NULL).isSuccess()); + rv += SDK_ASSERT(mgr.addDataTable(plat1, "Plat1Table1", nullptr).isSuccess()); testObserver->setExpectedTableName("Plat1Table2"); - rv += SDK_ASSERT(mgr.addDataTable(plat1, "Plat1Table2", NULL).isSuccess()); + rv += SDK_ASSERT(mgr.addDataTable(plat1, "Plat1Table2", nullptr).isSuccess()); testObserver->setExpectedTableName("Plat2Table1"); - rv += SDK_ASSERT(mgr.addDataTable(plat2, "Plat2Table1", NULL).isSuccess()); + rv += SDK_ASSERT(mgr.addDataTable(plat2, "Plat2Table1", nullptr).isSuccess()); testObserver->setExpectedTableName("Plat2Table2"); - rv += SDK_ASSERT(mgr.addDataTable(plat2, "Plat2Table2", NULL).isSuccess()); + rv += SDK_ASSERT(mgr.addDataTable(plat2, "Plat2Table2", nullptr).isSuccess()); rv += SDK_ASSERT(mgr.tableCount() == 4); - rv += SDK_ASSERT(mgr.findTable(plat1, "Plat1Table1") != NULL); - rv += SDK_ASSERT(mgr.findTable(plat1, "Plat1Table2") != NULL); - rv += SDK_ASSERT(mgr.findTable(plat2, "Plat1Table1") == NULL); // random sanity check + rv += SDK_ASSERT(mgr.findTable(plat1, "Plat1Table1") != nullptr); + rv += SDK_ASSERT(mgr.findTable(plat1, "Plat1Table2") != nullptr); + rv += SDK_ASSERT(mgr.findTable(plat2, "Plat1Table1") == nullptr); // random sanity check // Removing the entity should automatically remove its tables testObserver->setExpectedOwnerId(plat1); testHelper.dataStore()->removeEntity(plat1); rv += SDK_ASSERT(mgr.tableCount() == 2); - rv += SDK_ASSERT(mgr.findTable(plat1, "Plat1Table1") == NULL); - rv += SDK_ASSERT(mgr.findTable(plat1, "Plat1Table2") == NULL); - rv += SDK_ASSERT(mgr.findTable(plat2, "Plat1Table1") == NULL); + rv += SDK_ASSERT(mgr.findTable(plat1, "Plat1Table1") == nullptr); + rv += SDK_ASSERT(mgr.findTable(plat1, "Plat1Table2") == nullptr); + rv += SDK_ASSERT(mgr.findTable(plat2, "Plat1Table1") == nullptr); // Re-add the platform to make sure there's no funny business plat1 = testHelper.addPlatform(); rv += SDK_ASSERT(mgr.tableCount() == 2); - rv += SDK_ASSERT(mgr.findTable(plat1, "Plat1Table1") == NULL); - rv += SDK_ASSERT(mgr.findTable(plat1, "Plat1Table2") == NULL); - rv += SDK_ASSERT(mgr.findTable(plat2, "Plat1Table1") == NULL); + rv += SDK_ASSERT(mgr.findTable(plat1, "Plat1Table1") == nullptr); + rv += SDK_ASSERT(mgr.findTable(plat1, "Plat1Table2") == nullptr); + rv += SDK_ASSERT(mgr.findTable(plat2, "Plat1Table1") == nullptr); testObserver->setExpectedTableName("Plat1Table3"); - rv += SDK_ASSERT(mgr.addDataTable(plat1, "Plat1Table3", NULL).isSuccess()); + rv += SDK_ASSERT(mgr.addDataTable(plat1, "Plat1Table3", nullptr).isSuccess()); rv += SDK_ASSERT(mgr.tableCount() == 3); - rv += SDK_ASSERT(mgr.findTable(plat1, "Plat1Table1") == NULL); - rv += SDK_ASSERT(mgr.findTable(plat1, "Plat1Table3") != NULL); + rv += SDK_ASSERT(mgr.findTable(plat1, "Plat1Table1") == nullptr); + rv += SDK_ASSERT(mgr.findTable(plat1, "Plat1Table3") != nullptr); // Try it with a non-platform entity uint64_t beam4 = testHelper.addBeam(plat1); uint64_t gate5 = testHelper.addGate(beam4); testObserver->setExpectedTableName("Gate5Table1"); - rv += SDK_ASSERT(mgr.addDataTable(gate5, "Gate5Table1", NULL).isSuccess()); + rv += SDK_ASSERT(mgr.addDataTable(gate5, "Gate5Table1", nullptr).isSuccess()); rv += SDK_ASSERT(mgr.tableCount() == 4); - rv += SDK_ASSERT(mgr.findTable(gate5, "Gate5Table1") != NULL); + rv += SDK_ASSERT(mgr.findTable(gate5, "Gate5Table1") != nullptr); testObserver->setExpectedOwnerId(gate5); testHelper.dataStore()->removeEntity(beam4); // should recursively kill gate5 rv += SDK_ASSERT(mgr.tableCount() == 3); - rv += SDK_ASSERT(mgr.findTable(gate5, "Gate5Table1") == NULL); + rv += SDK_ASSERT(mgr.findTable(gate5, "Gate5Table1") == nullptr); rv += testObserver->numErrors(); testObserver->setActive(false); @@ -2049,8 +2049,8 @@ int removeEntityTest() int testColumnIteration() { int rv = 0; - simData::MemoryTable::TableManager mgr(NULL); - simData::DataTable* memoryTable = NULL; + simData::MemoryTable::TableManager mgr(nullptr); + simData::DataTable* memoryTable = nullptr; rv += SDK_ASSERT(mgr.addDataTable(0, "Table", &memoryTable).isSuccess()); rv += SDK_ASSERT(testColumnIteration(*memoryTable) == 0); return rv; @@ -2105,7 +2105,7 @@ int doubleBufferTimeContainerTest() // Do a swap, and redo the searches std::vector noObservers; - tc.swapFreshStaleData(NULL, noObservers); + tc.swapFreshStaleData(nullptr, noObservers); rv += SDK_ASSERT(tc.begin().hasNext()); rv += SDK_ASSERT(tc.begin().next().index() == 0); rv += SDK_ASSERT(tc.lower_bound(5).next().index() == 0); @@ -2197,7 +2197,7 @@ int doubleBufferTimeContainerTest() // Swap, we should only have two times (15 and 25), because others were swapped+cleared rv += SDK_ASSERT(tc.size() == 6); - tc.swapFreshStaleData(NULL, noObservers); + tc.swapFreshStaleData(nullptr, noObservers); rv += SDK_ASSERT(tc.size() == 2); iter = tc.begin(); value = iter.next(); @@ -2217,7 +2217,7 @@ int testPartialFlush() { simData::MemoryDataStore ds; simData::DataTableManager& mgr = ds.dataTableManager(); - simData::DataTable* table = NULL; + simData::DataTable* table = nullptr; int rv = 0; rv += SDK_ASSERT(mgr.addDataTable(1, "Test Table", &table).isSuccess()); // Create two columns and add data to both diff --git a/Testing/SimData/TestCommands.cpp b/Testing/SimData/TestCommands.cpp index 2800d20bd..93a145073 100644 --- a/Testing/SimData/TestCommands.cpp +++ b/Testing/SimData/TestCommands.cpp @@ -123,7 +123,7 @@ int validateGateColor(simData::DataStore* ds, simData::ObjectId id, double time, ds->update(time); simData::DataStore::Transaction t; const simData::GatePrefs *prefs = ds->gatePrefs(id, &t); - if (prefs == NULL) + if (prefs == nullptr) return 1; if (prefs->commonprefs().color() != color) @@ -136,7 +136,7 @@ int addGateColor(simData::DataStore* ds, simData::ObjectId id, double time, uint { simData::DataStore::Transaction t; simData::GateCommand *command = ds->addGateCommand(id, &t); - if (command == NULL) + if (command == nullptr) return 1; command->set_time(time); @@ -152,7 +152,7 @@ int addGateOverrideColor(simData::DataStore* ds, simData::ObjectId id, double ti { simData::DataStore::Transaction t; simData::GateCommand *command = ds->addGateCommand(id, &t); - if (command == NULL) + if (command == nullptr) return 1; command->set_time(time); @@ -249,7 +249,7 @@ int validateBeamColor(simData::DataStore* ds, simData::ObjectId id, double time, ds->update(time); simData::DataStore::Transaction t; const simData::BeamPrefs *prefs = ds->beamPrefs(id, &t); - if (prefs == NULL) + if (prefs == nullptr) return 1; if (prefs->commonprefs().color() != color) @@ -262,7 +262,7 @@ int addBeamColor(simData::DataStore* ds, simData::ObjectId id, double time, uint { simData::DataStore::Transaction t; simData::BeamCommand *command = ds->addBeamCommand(id, &t); - if (command == NULL) + if (command == nullptr) return 1; command->set_time(time); @@ -278,7 +278,7 @@ int addBeamOverrideColor(simData::DataStore* ds, simData::ObjectId id, double ti { simData::DataStore::Transaction t; simData::BeamCommand *command = ds->addBeamCommand(id, &t); - if (command == NULL) + if (command == nullptr) return 1; command->set_time(time); @@ -365,7 +365,7 @@ int validatePlatformColor(simData::DataStore* ds, simData::ObjectId id, double t ds->update(time); simData::DataStore::Transaction t; const simData::PlatformPrefs *prefs = ds->platformPrefs(id, &t); - if (prefs == NULL) + if (prefs == nullptr) return 1; if (prefs->commonprefs().color() != color) @@ -378,7 +378,7 @@ int addPlatformColor(simData::DataStore* ds, simData::ObjectId id, double time, { simData::DataStore::Transaction t; simData::PlatformCommand *command = ds->addPlatformCommand(id, &t); - if (command == NULL) + if (command == nullptr) return 1; command->set_time(time); @@ -394,7 +394,7 @@ int addPlatformOverrideColor(simData::DataStore* ds, simData::ObjectId id, doubl { simData::DataStore::Transaction t; simData::PlatformCommand *command = ds->addPlatformCommand(id, &t); - if (command == NULL) + if (command == nullptr) return 1; command->set_time(time); diff --git a/Testing/SimData/TestGenericData.cpp b/Testing/SimData/TestGenericData.cpp index ba792e0b6..105f2f766 100644 --- a/Testing/SimData/TestGenericData.cpp +++ b/Testing/SimData/TestGenericData.cpp @@ -97,10 +97,10 @@ int testDataLimiting() int testCurrentValues(simData::DataStore& ds, const std::string& tag, const std::string& value) { const simData::GenericDataSlice* gd = ds.genericDataSlice(0); - if (gd == NULL) + if (gd == nullptr) return 1; const simData::GenericData* current = gd->current(); - if (current == NULL) + if (current == nullptr) return 1; bool foundTag = false; @@ -124,10 +124,10 @@ int testCurrentValues(simData::DataStore& ds, const std::string& tag, const std: int testShouldBeEmpty(simData::DataStore& ds) { const simData::GenericDataSlice* gd = ds.genericDataSlice(0); - if (gd == NULL) + if (gd == nullptr) return 1; const simData::GenericData* current = gd->current(); - if (current == NULL) + if (current == nullptr) return 1; return current->entry_size(); @@ -414,7 +414,7 @@ void test_5743() std::vector entries; virtual void operator()(const simData::GenericData *update) { - if (update == NULL) + if (update == nullptr) return; for (int k = 0; k < update->entry_size(); ++k) entries.push_back(update->entry(k)); diff --git a/Testing/SimData/TestInterpolation.cpp b/Testing/SimData/TestInterpolation.cpp index df252faba..dfc654d84 100644 --- a/Testing/SimData/TestInterpolation.cpp +++ b/Testing/SimData/TestInterpolation.cpp @@ -92,7 +92,7 @@ void testInterpolation_enable() assertTrue(ds.isInterpolationEnabled()); // unset interpolator - ds.setInterpolator(NULL); + ds.setInterpolator(nullptr); assertTrue(!ds.isInterpolationEnabled()); // disabling should succeed @@ -139,7 +139,7 @@ void testInterpolation_nearest() // nothing should exist before first datapoint ds->update(0.9); - assertEquals(pslice->current(), (const simData::PlatformUpdate*)NULL); + assertEquals(pslice->current(), (const simData::PlatformUpdate*)nullptr); assertTrue(!pslice->hasChanged()); assertEquals(pslice->isInterpolated(), false); // test that re-updating datastore at same time does not signal a changed dataslice update (non-interpolated case) @@ -153,19 +153,19 @@ void testInterpolation_nearest() // after end datapoint, we get nothing : "file mode" behavior ds->update(2.1); assertTrue(!pslice->hasChanged()); // if invalid before, and invalid after, no change. - assertEquals(pslice->current(), (const simData::PlatformUpdate*)NULL); + assertEquals(pslice->current(), (const simData::PlatformUpdate*)nullptr); assertEquals(pslice->isInterpolated(), false); // currently, an expired platform signals hasChanged at every update // at borders, should match the datapoints exactly ds->update(1.0); - assertTrue(pslice->current() != NULL); + assertTrue(pslice->current() != nullptr); assertEquals(pslice->isInterpolated(), false); assertEquals(pslice->current()->time(), 1.0); // at borders, should match the datapoints exactly ds->update(2.0); - assertTrue(pslice->current() != NULL); + assertTrue(pslice->current() != nullptr); assertTrue(pslice->hasChanged()); assertEquals(pslice->isInterpolated(), false); assertEquals(pslice->current()->time(), 2.0); @@ -179,7 +179,7 @@ void testInterpolation_nearest() // should match the nearest time when "interpolating" ds->update(1.4); - assertTrue(pslice->current() != NULL); + assertTrue(pslice->current() != nullptr); assertTrue(pslice->hasChanged()); assertEquals(pslice->isInterpolated(), true); assertEquals(pslice->current()->time(), 1.4); @@ -193,7 +193,7 @@ void testInterpolation_nearest() } ds->update(1.6); - assertTrue(pslice->current() != NULL); + assertTrue(pslice->current() != nullptr); assertEquals(pslice->isInterpolated(), true); assertEquals(pslice->current()->time(), 1.6); assertEquals(pslice->current()->x(), simCore::WGS_A + satelliteHeight + 20.0); @@ -238,30 +238,30 @@ void testInterpolation_linear() // nothing should exist before first datapoint or after end ds->update(0.9); - assertEquals(pslice->current(), (const simData::PlatformUpdate*)NULL); + assertEquals(pslice->current(), (const simData::PlatformUpdate*)nullptr); assertEquals(pslice->isInterpolated(), false); // after end datapoint, we get nothing : "file mode" behavior ds->update(2.1); - assertEquals(pslice->current(), (const simData::PlatformUpdate*)NULL); + assertEquals(pslice->current(), (const simData::PlatformUpdate*)nullptr); assertEquals(pslice->isInterpolated(), false); // at borders, should match the datapoints exactly ds->update(1.0); - assertTrue(pslice->current() != NULL); + assertTrue(pslice->current() != nullptr); assertEquals(pslice->isInterpolated(), false); assertEquals(pslice->current()->time(), 1.0); // at borders, should match the datapoints exactly ds->update(2.0); - assertTrue(pslice->current() != NULL); + assertTrue(pslice->current() != nullptr); assertEquals(pslice->isInterpolated(), false); assertEquals(pslice->current()->time(), 2.0); // should interpolate ds->update(1.5); assertTrue(pslice->hasChanged()); - assertTrue(pslice->current() != NULL); + assertTrue(pslice->current() != nullptr); assertEquals(pslice->isInterpolated(), true); assertEquals(pslice->current()->time(), 1.5); // test that re-updating datastore at same time does not signal a changed dataslice update (interpolated case) @@ -304,7 +304,7 @@ void testInterpolation_linearAngle() // add valid datapoints simData::DataStore::Transaction t; simData::LaserUpdate *u = ds->addLaserUpdate(laserId, &t); - assertTrue(u != NULL); + assertTrue(u != nullptr); u->set_time(1.0); u->mutable_orientation()->set_yaw(0.0); u->mutable_orientation()->set_pitch(0.0); @@ -316,7 +316,7 @@ void testInterpolation_linearAngle() // add valid datapoints simData::DataStore::Transaction t; simData::LaserUpdate *u = ds->addLaserUpdate(laserId, &t); - assertTrue(u != NULL); + assertTrue(u != nullptr); u->set_time(2.0); u->mutable_orientation()->set_yaw(0.5); u->mutable_orientation()->set_pitch(0.5); @@ -328,7 +328,7 @@ void testInterpolation_linearAngle() // add valid datapoints simData::DataStore::Transaction t; simData::LaserUpdate *u = ds->addLaserUpdate(laserId, &t); - assertTrue(u != NULL); + assertTrue(u != nullptr); u->set_time(3.0); u->mutable_orientation()->set_yaw(M_TWOPI - 0.5); u->mutable_orientation()->set_pitch(1.0); @@ -337,12 +337,12 @@ void testInterpolation_linearAngle() } const simData::LaserUpdateSlice *lslice = ds->laserUpdateSlice(laserId); - assertTrue(lslice != NULL); + assertTrue(lslice != nullptr); // nothing should exist before first datapoint ds->update(0.9); assertTrue(!lslice->hasChanged()); - assertEquals(lslice->current(), (const simData::LaserUpdate*)NULL); + assertEquals(lslice->current(), (const simData::LaserUpdate*)nullptr); assertEquals(lslice->isInterpolated(), false); // test that re-updating datastore at same time does not signal a changed dataslice update (interpolated case) { @@ -360,7 +360,7 @@ void testInterpolation_linearAngle() // at borders, should match the datapoints exactly ds->update(1.0); assertTrue(lslice->hasChanged()); - assertTrue(lslice->current() != NULL); + assertTrue(lslice->current() != nullptr); assertEquals(lslice->isInterpolated(), false); assertEquals(lslice->current()->time(), 1.0); // test that re-updating datastore at same time does not signal a changed dataslice update (interpolated case) @@ -373,14 +373,14 @@ void testInterpolation_linearAngle() // at borders, should match the datapoints exactly ds->update(3.0); - assertTrue(lslice->current() != NULL); + assertTrue(lslice->current() != nullptr); assertEquals(lslice->isInterpolated(), false); assertEquals(lslice->current()->time(), 3.0); // should interpolate ds->update(1.5); assertTrue(lslice->hasChanged()); - assertTrue(lslice->current() != NULL); + assertTrue(lslice->current() != nullptr); assertEquals(lslice->isInterpolated(), true); assertEquals(lslice->current()->time(), 1.5); assertTrue(simCore::areEqual(lslice->current()->orientation().yaw(), 0.25)); @@ -396,7 +396,7 @@ void testInterpolation_linearAngle() // should interpolate ds->update(2.5); - assertTrue(lslice->current() != NULL); + assertTrue(lslice->current() != nullptr); assertEquals(lslice->isInterpolated(), true); assertEquals(lslice->current()->time(), 2.5); assertTrue(simCore::areEqual(lslice->current()->orientation().yaw(), 0.0)); @@ -410,7 +410,7 @@ void testInterpolation_linearAngle() ds->update(2.6); // returns most recent (non-interpolated) datapoint - assertTrue(lslice->current() != NULL); + assertTrue(lslice->current() != nullptr); assertEquals(lslice->current()->time(), 2.0); assertEquals(lslice->isInterpolated(), false); } diff --git a/Testing/SimData/TestListener.cpp b/Testing/SimData/TestListener.cpp index 1aab69004..e591f0d71 100644 --- a/Testing/SimData/TestListener.cpp +++ b/Testing/SimData/TestListener.cpp @@ -95,7 +95,7 @@ class CounterListener : public simData::DataStore::DefaultListener ++pref_; } - virtual void onTimeChange(simData::DataStore *source) + virtual void onChange(simData::DataStore *source) { ++time_; } @@ -152,56 +152,56 @@ class AddDuringCallback : public simData::DataStore::DefaultListener virtual void onAddEntity(simData::DataStore *source, simData::ObjectId newId, simData::ObjectType ot) { - if ((listener_ != NULL) && (type_ == AddEntity)) + if ((listener_ != nullptr) && (type_ == AddEntity)) source->addListener(listener_); listener_.reset(); } virtual void onRemoveEntity(simData::DataStore *source, simData::ObjectId removedId, simData::ObjectType ot) { - if ((listener_ != NULL) && (type_ == RemoveEntity)) + if ((listener_ != nullptr) && (type_ == RemoveEntity)) source->addListener(listener_); listener_.reset(); } virtual void onPrefsChange(simData::DataStore *source, simData::ObjectId id) { - if ((listener_ != NULL) && (type_ == PrefsChange)) + if ((listener_ != nullptr) && (type_ == PrefsChange)) source->addListener(listener_); listener_.reset(); } - virtual void onTimeChange(simData::DataStore *source) + virtual void onChange(simData::DataStore *source) { - if ((listener_ != NULL) && (type_ == TimeChange)) + if ((listener_ != nullptr) && (type_ == TimeChange)) source->addListener(listener_); listener_.reset(); } virtual void onCategoryDataChange(simData::DataStore *source, simData::ObjectId changedId, simData::ObjectType ot) { - if ((listener_ != NULL) && (type_ == CategoryDataChange)) + if ((listener_ != nullptr) && (type_ == CategoryDataChange)) source->addListener(listener_); listener_.reset(); } virtual void onNameChange(simData::DataStore *source, simData::ObjectId changeId) { - if ((listener_ != NULL) && (type_ == NameChange)) + if ((listener_ != nullptr) && (type_ == NameChange)) source->addListener(listener_); listener_.reset(); } virtual void onFlush(simData::DataStore *source, simData::ObjectId flushedId) { - if ((listener_ != NULL) && (type_ == Flush)) + if ((listener_ != nullptr) && (type_ == Flush)) source->addListener(listener_); listener_.reset(); } virtual void onScenarioDelete(simData::DataStore* source) { - if ((listener_ != NULL) && (type_ == ScenarioDelete)) + if ((listener_ != nullptr) && (type_ == ScenarioDelete)) source->addListener(listener_); listener_.reset(); } @@ -223,7 +223,7 @@ class RemoveDuringCallback : public simData::DataStore::DefaultListener virtual void onAddEntity(simData::DataStore *source, simData::ObjectId newId, simData::ObjectType ot) { - if ((listener_ != NULL) && (type_ == AddEntity)) + if ((listener_ != nullptr) && (type_ == AddEntity)) { source->removeListener(listener_); listener_.reset(); @@ -232,7 +232,7 @@ class RemoveDuringCallback : public simData::DataStore::DefaultListener virtual void onRemoveEntity(simData::DataStore *source, simData::ObjectId removedId, simData::ObjectType ot) { - if ((listener_ != NULL) && (type_ == RemoveEntity)) + if ((listener_ != nullptr) && (type_ == RemoveEntity)) { source->removeListener(listener_); listener_.reset(); @@ -241,16 +241,16 @@ class RemoveDuringCallback : public simData::DataStore::DefaultListener virtual void onPrefsChange(simData::DataStore *source, simData::ObjectId id) { - if ((listener_ != NULL) && (type_ == PrefsChange)) + if ((listener_ != nullptr) && (type_ == PrefsChange)) { source->removeListener(listener_); listener_.reset(); } } - virtual void onTimeChange(simData::DataStore *source) + virtual void onChange(simData::DataStore *source) { - if ((listener_ != NULL) && (type_ == TimeChange)) + if ((listener_ != nullptr) && (type_ == TimeChange)) { source->removeListener(listener_); listener_.reset(); @@ -259,7 +259,7 @@ class RemoveDuringCallback : public simData::DataStore::DefaultListener virtual void onCategoryDataChange(simData::DataStore *source, simData::ObjectId changedId, simData::ObjectType ot) { - if ((listener_ != NULL) && (type_ == CategoryDataChange)) + if ((listener_ != nullptr) && (type_ == CategoryDataChange)) { source->removeListener(listener_); listener_.reset(); @@ -268,7 +268,7 @@ class RemoveDuringCallback : public simData::DataStore::DefaultListener virtual void onNameChange(simData::DataStore *source, simData::ObjectId changeId) { - if ((listener_ != NULL) && (type_ == NameChange)) + if ((listener_ != nullptr) && (type_ == NameChange)) { source->removeListener(listener_); listener_.reset(); @@ -277,7 +277,7 @@ class RemoveDuringCallback : public simData::DataStore::DefaultListener virtual void onFlush(simData::DataStore *source, simData::ObjectId flushedId) { - if ((listener_ != NULL) && (type_ == Flush)) + if ((listener_ != nullptr) && (type_ == Flush)) { source->removeListener(listener_); listener_.reset(); @@ -286,7 +286,7 @@ class RemoveDuringCallback : public simData::DataStore::DefaultListener virtual void onScenarioDelete(simData::DataStore* source) { - if ((listener_ != NULL) && (type_ == ScenarioDelete)) + if ((listener_ != nullptr) && (type_ == ScenarioDelete)) { source->removeListener(listener_); listener_.reset(); @@ -309,9 +309,9 @@ class RemoveMultipleDuringCallback : public simData::DataStore::DefaultListener { } - virtual void onTimeChange(simData::DataStore *source) + virtual void onChange(simData::DataStore *source) { - if ((listener1_ != NULL) && (type_ == TimeChange)) + if ((listener1_ != nullptr) && (type_ == TimeChange)) { source->removeListener(listener1_); source->removeListener(listener2_); @@ -841,4 +841,4 @@ int TestListener(int argc, char* argv[]) rv += testMultipleRemoval(); return rv; -} \ No newline at end of file +} diff --git a/Testing/SimData/TestMemRetrieval.cpp b/Testing/SimData/TestMemRetrieval.cpp index 4fe9c253d..ff7e7eb5c 100644 --- a/Testing/SimData/TestMemRetrieval.cpp +++ b/Testing/SimData/TestMemRetrieval.cpp @@ -85,8 +85,8 @@ void addPlatformGenericData(simData::DataStore* dataStore, uint64_t id, size_t i { simData::DataStore::Transaction transaction; simData::GenericData* genData = dataStore->addGenericData(id, &transaction); - SDK_ASSERT(genData != NULL); - if (genData == NULL) + SDK_ASSERT(genData != nullptr); + if (genData == nullptr) return; genData->set_time(static_cast(index)); @@ -105,8 +105,8 @@ void addPlatformCategoryData(simData::DataStore* dataStore, uint64_t id, size_t { simData::DataStore::Transaction transaction; simData::CategoryData* catData = dataStore->addCategoryData(id, &transaction); - SDK_ASSERT(catData != NULL); - if (catData == NULL) + SDK_ASSERT(catData != nullptr); + if (catData == nullptr) return; catData->set_time(static_cast(index)); @@ -179,8 +179,8 @@ class TestVisit : public simData::PlatformUpdateSlice::Visitor int sanityCheck(simData::DataStore* dataStore) { int rv = 0; - rv += SDK_ASSERT(dataStore != NULL); - if (dataStore == NULL) return rv; + rv += SDK_ASSERT(dataStore != nullptr); + if (dataStore == nullptr) return rv; simData::DataStore::IdList ids; dataStore->idList(&ids); @@ -191,8 +191,8 @@ int sanityCheck(simData::DataStore* dataStore) { rv += SDK_ASSERT(*idIter > 0 && *idIter <= NUM_PLATS); const simData::PlatformPrefs* prefs = dataStore->platformPrefs(*idIter, &transaction); - rv += SDK_ASSERT(prefs != NULL); - if (prefs == NULL) continue; + rv += SDK_ASSERT(prefs != nullptr); + if (prefs == nullptr) continue; // Check two prefs that were set rv += SDK_ASSERT(prefs->commonprefs().has_name()); rv += SDK_ASSERT(prefs->has_icon()); @@ -204,20 +204,20 @@ int sanityCheck(simData::DataStore* dataStore) double timeValue = NUM_POINTS / 2; dataStore->update(timeValue); const simData::PlatformUpdateSlice* slice = dataStore->platformUpdateSlice(1); - rv += SDK_ASSERT(slice != NULL); - if (slice == NULL) return rv; + rv += SDK_ASSERT(slice != nullptr); + if (slice == nullptr) return rv; // Get the current data (for timeValue) const simData::PlatformUpdate* update = slice->current(); - rv += SDK_ASSERT(update != NULL); - if (update == NULL) return rv; + rv += SDK_ASSERT(update != nullptr); + if (update == nullptr) return rv; rv += SDK_ASSERT(update->time() == timeValue); // Verify the time bounds; note that this might change depending on data store implementation simData::PlatformUpdateSlice::Bounds bounds = slice->interpolationBounds(); // TODO: Are bounds only set when update() is interpolated? - // rv += SDK_ASSERT(bounds.first != NULL); - // rv += SDK_ASSERT(bounds.second != NULL); - if (bounds.first != NULL && bounds.second != NULL) + // rv += SDK_ASSERT(bounds.first != nullptr); + // rv += SDK_ASSERT(bounds.second != nullptr); + if (bounds.first != nullptr && bounds.second != nullptr) { rv += SDK_ASSERT(bounds.first->time() == 0); rv += SDK_ASSERT(bounds.second->time() == NUM_POINTS - 1); @@ -264,7 +264,7 @@ int updateIterateTest(simData::DataStore* dataStore) const simData::PlatformUpdateSlice* slice = dataStore->platformUpdateSlice(1); simData::PlatformUpdateSlice::Iterator iter(slice); // Validate first entry with peek - rv += SDK_ASSERT(iter.peekNext() != NULL); + rv += SDK_ASSERT(iter.peekNext() != nullptr); rv += SDK_ASSERT(iter.peekNext()->time() == 0.0); // Validate copy constructor simData::PlatformUpdateSlice::Iterator copy(iter); @@ -278,7 +278,7 @@ int updateIterateTest(simData::DataStore* dataStore) copy.toBack(); rv += SDK_ASSERT(copy.hasPrevious()); rv += SDK_ASSERT(!copy.hasNext()); - rv += SDK_ASSERT(copy.peekPrevious() != NULL); + rv += SDK_ASSERT(copy.peekPrevious() != nullptr); rv += SDK_ASSERT(copy.peekPrevious()->time() == NUM_POINTS - 1); copy.toFront(); // Validate copy constructor @@ -290,7 +290,7 @@ int updateIterateTest(simData::DataStore* dataStore) const simData::PlatformUpdate* update = iter.next(); rv += SDK_ASSERT(peek == update); rv += SDK_ASSERT(peek == iter.peekPrevious()); - rv += SDK_ASSERT(update != NULL); + rv += SDK_ASSERT(update != nullptr); // Confirm time rv += SDK_ASSERT(update->time() == numSeen); numSeen++; @@ -326,8 +326,8 @@ int commandIterateTest(simData::DataStore* dataStore) int rv = 0; const simData::PlatformCommandSlice* slice = dataStore->platformCommandSlice(1); - rv += SDK_ASSERT(slice != NULL); - if (slice == NULL) + rv += SDK_ASSERT(slice != nullptr); + if (slice == nullptr) return rv; // check size @@ -418,8 +418,8 @@ int genericIterateTest(simData::DataStore* dataStore) int rv = 0; const simData::GenericDataSlice* slice = dataStore->genericDataSlice(1); - rv += SDK_ASSERT(slice != NULL); - if (slice == NULL) + rv += SDK_ASSERT(slice != nullptr); + if (slice == nullptr) return rv; // check size @@ -466,8 +466,8 @@ int categoryIterateTest(simData::DataStore* dataStore) int rv = 0; const simData::CategoryDataSlice* slice = dataStore->categoryDataSlice(1); - rv += SDK_ASSERT(slice != NULL); - if (slice == NULL) + rv += SDK_ASSERT(slice != nullptr); + if (slice == nullptr) return rv; // check size @@ -566,8 +566,8 @@ int duplicateTimesCheck(simData::DataStore* dataStore) // Update the data store and get the update-slice for platform 1 dataStore->update(1.0); // update to time 1.0 const simData::PlatformUpdateSlice* slice = dataStore->platformUpdateSlice(1); - rv += SDK_ASSERT(slice != NULL); - if (slice == NULL) return rv; + rv += SDK_ASSERT(slice != nullptr); + if (slice == nullptr) return rv; // Validate that the platform #1 has no duplicates and has data TestVisit testVisit; slice->visit(&testVisit); @@ -604,8 +604,8 @@ int superformIteration(simData::DataStore* dataStore) { rv += SDK_ASSERT(dataStore->objectType(*i) == simData::PLATFORM); const simData::PlatformUpdateSlice* slice = dataStore->platformUpdateSlice(*i); - rv += SDK_ASSERT(slice != NULL); - if (slice == NULL) + rv += SDK_ASSERT(slice != nullptr); + if (slice == nullptr) continue; // Iterate through the slice simData::PlatformUpdateSlice::Iterator iter(slice); @@ -646,11 +646,11 @@ int historicalDataCheck(simData::DataStore* dataStore) dataStore->update(50); // update to time int rv = 0; const simData::PlatformUpdateSlice* slice = dataStore->platformUpdateSlice(1); - rv += SDK_ASSERT(slice != NULL); - if (slice == NULL) return rv; + rv += SDK_ASSERT(slice != nullptr); + if (slice == nullptr) return rv; const simData::PlatformUpdate* update = slice->current(); - rv += SDK_ASSERT(update != NULL); - if (update == NULL) return rv; + rv += SDK_ASSERT(update != nullptr); + if (update == nullptr) return rv; // TODO @@ -668,11 +668,11 @@ int interpTester(simData::DataStore* dataStore, uint64_t id, double timeVal) timeVal = floor(timeVal); const simData::PlatformUpdateSlice* slice = dataStore->platformUpdateSlice(id); - rv += SDK_ASSERT(slice != NULL); - if (slice == NULL) return rv; + rv += SDK_ASSERT(slice != nullptr); + if (slice == nullptr) return rv; const simData::PlatformUpdate* update = slice->current(); - rv += SDK_ASSERT(update != NULL); - if (update == NULL) return rv; + rv += SDK_ASSERT(update != nullptr); + if (update == nullptr) return rv; // Test data now rv += SDK_ASSERT(update->time() == timeVal); rv += SDK_ASSERT(update->x() == timeVal); @@ -697,7 +697,7 @@ int interpolateTest(simData::DataStore* dataStore) rv += SDK_ASSERT(true == dataStore->canInterpolate()); rv += SDK_ASSERT(false == dataStore->isInterpolationEnabled()); // Remove the interpolator, then try to enable - dataStore->setInterpolator(NULL); + dataStore->setInterpolator(nullptr); rv += SDK_ASSERT(true == dataStore->canInterpolate()); rv += SDK_ASSERT(false == dataStore->enableInterpolation(true)); rv += SDK_ASSERT(false == dataStore->isInterpolationEnabled()); @@ -724,7 +724,7 @@ int interpolateTest(simData::DataStore* dataStore) rv += SDK_ASSERT(interpTester(dataStore, 1, 50) == 0); rv += SDK_ASSERT(interpTester(dataStore, 1, 50.5) == 0); - dataStore->setInterpolator(NULL); + dataStore->setInterpolator(nullptr); return rv; } @@ -762,7 +762,7 @@ int timeNextPreviousCheck(simData::DataStore* dataStore) return rv; // Get a slice const simData::PlatformUpdateSlice* slice = dataStore->platformUpdateSlice(*idList.begin()); - rv += SDK_ASSERT(slice != NULL); + rv += SDK_ASSERT(slice != nullptr); if (!slice) return rv; // Test some arbitrary times diff --git a/Testing/SimData/TestMemoryDataStore.cpp b/Testing/SimData/TestMemoryDataStore.cpp index dcc3e190f..1be43a142 100644 --- a/Testing/SimData/TestMemoryDataStore.cpp +++ b/Testing/SimData/TestMemoryDataStore.cpp @@ -203,7 +203,7 @@ class NewLobListener : public simData::DataStore::DefaultListener int rv = 0; simData::DataStore::Transaction transaction; const simData::LobGroupProperties* props = source->lobGroupProperties(id, &transaction); - rv += SDK_ASSERT(props != NULL); + rv += SDK_ASSERT(props != nullptr); transaction.complete(&props); if (rv != 0) throw MemDataStoreAssertException(); @@ -697,7 +697,7 @@ void testGenericData_insert() std::vector entries; virtual void operator()(const simData::GenericData *update) { - if (update == NULL) + if (update == nullptr) return; for (int k = 0; k < update->entry_size(); ++k) entries.push_back(update->entry(k)); @@ -728,8 +728,8 @@ void testGenericData_insert() gdslice->visit(&sc2); mdsAssertEquals(sc2.entries.size(), static_cast(0)); - // Doing a visitor with NULL should not crash - gdslice->visit(NULL); + // Doing a visitor with a nullptr should not crash + gdslice->visit(nullptr); } int testGenericData_update() @@ -948,7 +948,7 @@ int testGenericDataNoExpiration_update() // No new keys, but overwrite changes ds->update(10000000000.0); g2 = gdslice->current(); - mdsAssertNotEquals(g2, (const simData::GenericData *)NULL); + mdsAssertNotEquals(g2, (const simData::GenericData *)nullptr); rv += SDK_ASSERT(g2->entry().size() == 5); rv += SDK_ASSERT(findOnce(g1, "key1", "value1")); rv += SDK_ASSERT(findOnce(g1, "key2", "value2")); @@ -1435,20 +1435,20 @@ int testUpdateToNonCurrentTime() testHelper->addPlatformUpdate(2, platId); auto slice = ds->platformUpdateSlice(platId); - rv += SDK_ASSERT(slice->current() == NULL); + rv += SDK_ASSERT(slice->current() == nullptr); // Time before first point ds->update(0.0); - rv += SDK_ASSERT(slice->current() == NULL); + rv += SDK_ASSERT(slice->current() == nullptr); ds->update(2.0); - rv += SDK_ASSERT(slice->current() != NULL); - if (slice->current() != NULL) + rv += SDK_ASSERT(slice->current() != nullptr); + if (slice->current() != nullptr) rv += SDK_ASSERT(slice->current()->time() == 2.0); // Go back in time ds->update(1.0); - rv += SDK_ASSERT(slice->current() != NULL); - if (slice->current() != NULL) + rv += SDK_ASSERT(slice->current() != nullptr); + if (slice->current() != nullptr) rv += SDK_ASSERT(slice->current()->time() == 1.0); // add future point @@ -1456,26 +1456,26 @@ int testUpdateToNonCurrentTime() // Continue back in time ds->update(1.5); - rv += SDK_ASSERT(slice->current() != NULL); - if (slice->current() != NULL) + rv += SDK_ASSERT(slice->current() != nullptr); + if (slice->current() != nullptr) rv += SDK_ASSERT(slice->current()->time() == 1.5); // Jump to before first point ds->update(0.0); - rv += SDK_ASSERT(slice->current() == NULL); + rv += SDK_ASSERT(slice->current() == nullptr); ds->update(1.5); - rv += SDK_ASSERT(slice->current() != NULL); - if (slice->current() != NULL) + rv += SDK_ASSERT(slice->current() != nullptr); + if (slice->current() != nullptr) rv += SDK_ASSERT(slice->current()->time() == 1.5); ds->update(1.7); - rv += SDK_ASSERT(slice->current() != NULL); - if (slice->current() != NULL) + rv += SDK_ASSERT(slice->current() != nullptr); + if (slice->current() != nullptr) rv += SDK_ASSERT(slice->current()->time() == 1.7); // Finally pick up the last added point ds->update(3.0); - rv += SDK_ASSERT(slice->current() != NULL); - if (slice->current() != NULL) + rv += SDK_ASSERT(slice->current() != nullptr); + if (slice->current() != nullptr) rv += SDK_ASSERT(slice->current()->time() == 3.0); // Test Commands diff --git a/Testing/SimData/TestMemorySlice.cpp b/Testing/SimData/TestMemorySlice.cpp index fb621519c..372cc1d17 100644 --- a/Testing/SimData/TestMemorySlice.cpp +++ b/Testing/SimData/TestMemorySlice.cpp @@ -160,33 +160,33 @@ int testStaticPlatformUpdates() // Verify that only the first update results in slice hasChanged ds->update(1.0); rv += SDK_ASSERT(slice->hasChanged()); - rv += SDK_ASSERT(slice->current() != NULL); + rv += SDK_ASSERT(slice->current() != nullptr); rv += SDK_ASSERT(slice->current()->time() == -1.0); ds->update(1.1); rv += SDK_ASSERT(!slice->hasChanged()); - rv += SDK_ASSERT(slice->current() != NULL); + rv += SDK_ASSERT(slice->current() != nullptr); rv += SDK_ASSERT(slice->current()->time() == -1.0); ds->update(2.0); rv += SDK_ASSERT(!slice->hasChanged()); - rv += SDK_ASSERT(slice->current() != NULL); + rv += SDK_ASSERT(slice->current() != nullptr); rv += SDK_ASSERT(slice->current()->time() == -1.0); ds->update(10.0); rv += SDK_ASSERT(!slice->hasChanged()); - rv += SDK_ASSERT(slice->current() != NULL); + rv += SDK_ASSERT(slice->current() != nullptr); rv += SDK_ASSERT(slice->current()->time() == -1.0); ds->update(1.0); rv += SDK_ASSERT(!slice->hasChanged()); - rv += SDK_ASSERT(slice->current() != NULL); + rv += SDK_ASSERT(slice->current() != nullptr); rv += SDK_ASSERT(slice->current()->time() == -1.0); ds->flush(staticID); ds->update(1.0); rv += SDK_ASSERT(!slice->hasChanged()); - rv += SDK_ASSERT(slice->current() != NULL); + rv += SDK_ASSERT(slice->current() != nullptr); rv += SDK_ASSERT(slice->current()->time() == -1.0); return rv; diff --git a/Testing/SimData/TestMessageVisitor.cpp b/Testing/SimData/TestMessageVisitor.cpp index 21013ac67..82494f9a8 100644 --- a/Testing/SimData/TestMessageVisitor.cpp +++ b/Testing/SimData/TestMessageVisitor.cpp @@ -40,26 +40,26 @@ int testGetField() { std::pair out; rv += SDK_ASSERT(0 == simData::protobuf::getField(platPrefs, out, "brightness")); - rv += SDK_ASSERT(out.first != NULL && out.second != NULL); + rv += SDK_ASSERT(out.first != nullptr && out.second != nullptr); } // valid field { std::pair out; rv += SDK_ASSERT(0 == simData::protobuf::getField(platPrefs, out, "icon")); - rv += SDK_ASSERT(out.first != NULL && out.second != NULL); + rv += SDK_ASSERT(out.first != nullptr && out.second != nullptr); } // valid submessage { std::pair out; rv += SDK_ASSERT(0 == simData::protobuf::getField(platPrefs, out, "commonPrefs")); - rv += SDK_ASSERT(out.first != NULL); - rv += SDK_ASSERT(out.second == NULL); + rv += SDK_ASSERT(out.first != nullptr); + rv += SDK_ASSERT(out.second == nullptr); } // valid field in submessage { std::pair out; rv += SDK_ASSERT(0 == simData::protobuf::getField(platPrefs, out, "commonPrefs.dataDraw")); - rv += SDK_ASSERT(out.first != NULL && out.second != NULL); + rv += SDK_ASSERT(out.first != nullptr && out.second != nullptr); } @@ -82,14 +82,14 @@ int testGetField() { std::pair out; rv += SDK_ASSERT(0 == simData::protobuf::getField(platPrefs, out, "trackPrefs")); - rv += SDK_ASSERT(out.first != NULL); - rv += SDK_ASSERT(out.second == NULL); + rv += SDK_ASSERT(out.first != nullptr); + rv += SDK_ASSERT(out.second == nullptr); } // valid field in submessage { std::pair out; rv += SDK_ASSERT(0 == simData::protobuf::getField(platPrefs, out, "trackPrefs.trackDrawMode")); - rv += SDK_ASSERT(out.first != NULL && out.second != NULL); + rv += SDK_ASSERT(out.first != nullptr && out.second != nullptr); } diff --git a/Testing/SimData/TestNewUpdatesListener.cpp b/Testing/SimData/TestNewUpdatesListener.cpp index bc3704526..b366bce38 100644 --- a/Testing/SimData/TestNewUpdatesListener.cpp +++ b/Testing/SimData/TestNewUpdatesListener.cpp @@ -251,13 +251,13 @@ int testDataTableCollection() simData::DataTableManager& dtm = ds->dataTableManager(); simData::DataTable* table0; rv += SDK_ASSERT(dtm.addDataTable(0, "Table 0", &table0).isSuccess()); - rv += SDK_ASSERT(table0 != NULL); + rv += SDK_ASSERT(table0 != nullptr); simData::DataTable* table1; rv += SDK_ASSERT(dtm.addDataTable(plat1, "Table 1", &table1).isSuccess()); - rv += SDK_ASSERT(table1 != NULL); + rv += SDK_ASSERT(table1 != nullptr); simData::DataTable* table2; rv += SDK_ASSERT(dtm.addDataTable(plat2, "Table 2", &table2).isSuccess()); - rv += SDK_ASSERT(table2 != NULL); + rv += SDK_ASSERT(table2 != nullptr); // Create the table columns; plat1 gets 2 columns, rest get 1 column simData::TableColumn* col0_1; @@ -412,7 +412,7 @@ int testDataStoreProxy() const auto& ds2UpdatesListener = ds2->newUpdatesListener(); rv += SDK_ASSERT(&ds2->newUpdatesListener() == &ds2UpdatesListener); proxy.reset(ds2); - ds1 = NULL; // reset() will delete it + ds1 = nullptr; // reset() will delete it // Listener should have changed rv += SDK_ASSERT(&ds2->newUpdatesListener() == &ds1UpdatesListener); rv += SDK_ASSERT(&ds2->newUpdatesListener() != &ds2UpdatesListener); @@ -435,7 +435,7 @@ int testDataStoreProxy() const auto& ds3UpdatesListener = ds3->newUpdatesListener(); rv += SDK_ASSERT(&ds3->newUpdatesListener() == &ds3UpdatesListener); proxy.reset(ds3); - ds2 = NULL; // reset() will delete it + ds2 = nullptr; // reset() will delete it // Listener should have changed rv += SDK_ASSERT(&ds3->newUpdatesListener() == timeCollector.get()); rv += SDK_ASSERT(&ds3->newUpdatesListener() != &ds3UpdatesListener); diff --git a/Testing/SimData/TestSliceBounds.cpp b/Testing/SimData/TestSliceBounds.cpp index 5a84d73bb..8af77a363 100644 --- a/Testing/SimData/TestSliceBounds.cpp +++ b/Testing/SimData/TestSliceBounds.cpp @@ -35,7 +35,7 @@ int testUpperBound(const simData::PlatformUpdateSlice& slice) rv += SDK_ASSERT(!i.hasPrevious()); rv += SDK_ASSERT(i.hasNext()); const simData::PlatformUpdate* update = i.next(); - rv += SDK_ASSERT(update != NULL); + rv += SDK_ASSERT(update != nullptr); rv += SDK_ASSERT(simCore::areEqual(update->time(), 1.0)); // 1.0: upper bound should be 10 @@ -43,7 +43,7 @@ int testUpperBound(const simData::PlatformUpdateSlice& slice) rv += SDK_ASSERT(i.hasPrevious()); rv += SDK_ASSERT(i.hasNext()); update = i.next(); - rv += SDK_ASSERT(update != NULL); + rv += SDK_ASSERT(update != nullptr); rv += SDK_ASSERT(simCore::areEqual(update->time(), 10.0)); // 2.0: upper bound should be 10 @@ -51,7 +51,7 @@ int testUpperBound(const simData::PlatformUpdateSlice& slice) rv += SDK_ASSERT(i.hasPrevious()); rv += SDK_ASSERT(i.hasNext()); update = i.next(); - rv += SDK_ASSERT(update != NULL); + rv += SDK_ASSERT(update != nullptr); rv += SDK_ASSERT(simCore::areEqual(update->time(), 10.0)); // 10.0: upper bound should be 20 @@ -59,7 +59,7 @@ int testUpperBound(const simData::PlatformUpdateSlice& slice) rv += SDK_ASSERT(i.hasPrevious()); rv += SDK_ASSERT(i.hasNext()); update = i.next(); - rv += SDK_ASSERT(update != NULL); + rv += SDK_ASSERT(update != nullptr); rv += SDK_ASSERT(simCore::areEqual(update->time(), 20.0)); // 19.0: upper bound should be 20 @@ -67,7 +67,7 @@ int testUpperBound(const simData::PlatformUpdateSlice& slice) rv += SDK_ASSERT(i.hasPrevious()); rv += SDK_ASSERT(i.hasNext()); update = i.next(); - rv += SDK_ASSERT(update != NULL); + rv += SDK_ASSERT(update != nullptr); rv += SDK_ASSERT(simCore::areEqual(update->time(), 20.0)); // 20.0: upper bound should be [end] @@ -75,14 +75,14 @@ int testUpperBound(const simData::PlatformUpdateSlice& slice) rv += SDK_ASSERT(i.hasPrevious()); rv += SDK_ASSERT(!i.hasNext()); update = i.next(); - rv += SDK_ASSERT(update == NULL); + rv += SDK_ASSERT(update == nullptr); // 21.0: upper bound should be [end] i = slice.upper_bound(21.0); rv += SDK_ASSERT(i.hasPrevious()); rv += SDK_ASSERT(!i.hasNext()); update = i.next(); - rv += SDK_ASSERT(update == NULL); + rv += SDK_ASSERT(update == nullptr); return rv; } @@ -95,7 +95,7 @@ int testLowerBound(const simData::PlatformUpdateSlice& slice) rv += SDK_ASSERT(!i.hasPrevious()); rv += SDK_ASSERT(i.hasNext()); const simData::PlatformUpdate* update = i.next(); - rv += SDK_ASSERT(update != NULL); + rv += SDK_ASSERT(update != nullptr); rv += SDK_ASSERT(simCore::areEqual(update->time(), 1.0)); // 1.0: lower bound should be 1 @@ -103,7 +103,7 @@ int testLowerBound(const simData::PlatformUpdateSlice& slice) rv += SDK_ASSERT(!i.hasPrevious()); rv += SDK_ASSERT(i.hasNext()); update = i.next(); - rv += SDK_ASSERT(update != NULL); + rv += SDK_ASSERT(update != nullptr); rv += SDK_ASSERT(simCore::areEqual(update->time(), 1.0)); // 2.0: lower bound should be 10 @@ -111,7 +111,7 @@ int testLowerBound(const simData::PlatformUpdateSlice& slice) rv += SDK_ASSERT(i.hasPrevious()); rv += SDK_ASSERT(i.hasNext()); update = i.next(); - rv += SDK_ASSERT(update != NULL); + rv += SDK_ASSERT(update != nullptr); rv += SDK_ASSERT(simCore::areEqual(update->time(), 10.0)); // 10.0: lower bound should be 10 @@ -119,7 +119,7 @@ int testLowerBound(const simData::PlatformUpdateSlice& slice) rv += SDK_ASSERT(i.hasPrevious()); rv += SDK_ASSERT(i.hasNext()); update = i.next(); - rv += SDK_ASSERT(update != NULL); + rv += SDK_ASSERT(update != nullptr); rv += SDK_ASSERT(simCore::areEqual(update->time(), 10.0)); // 19.0: lower bound should be 20 @@ -127,7 +127,7 @@ int testLowerBound(const simData::PlatformUpdateSlice& slice) rv += SDK_ASSERT(i.hasPrevious()); rv += SDK_ASSERT(i.hasNext()); update = i.next(); - rv += SDK_ASSERT(update != NULL); + rv += SDK_ASSERT(update != nullptr); rv += SDK_ASSERT(simCore::areEqual(update->time(), 20.0)); // 20.0: lower bound should be 20 @@ -135,7 +135,7 @@ int testLowerBound(const simData::PlatformUpdateSlice& slice) rv += SDK_ASSERT(i.hasPrevious()); rv += SDK_ASSERT(i.hasNext()); update = i.next(); - rv += SDK_ASSERT(update != NULL); + rv += SDK_ASSERT(update != nullptr); rv += SDK_ASSERT(simCore::areEqual(update->time(), 20.0)); // 21.0: lower bound should be [end] @@ -143,7 +143,7 @@ int testLowerBound(const simData::PlatformUpdateSlice& slice) rv += SDK_ASSERT(i.hasPrevious()); rv += SDK_ASSERT(!i.hasNext()); update = i.next(); - rv += SDK_ASSERT(update == NULL); + rv += SDK_ASSERT(update == nullptr); return rv; } @@ -157,7 +157,7 @@ int testSingleItem(const simData::PlatformUpdateSlice& slice) rv += SDK_ASSERT(!i.hasPrevious()); rv += SDK_ASSERT(i.hasNext()); const simData::PlatformUpdate* update = i.next(); - rv += SDK_ASSERT(update != NULL); + rv += SDK_ASSERT(update != nullptr); rv += SDK_ASSERT(simCore::areEqual(update->time(), 10.0)); // 9.0: upper bound should be 10.0 @@ -165,7 +165,7 @@ int testSingleItem(const simData::PlatformUpdateSlice& slice) rv += SDK_ASSERT(!i.hasPrevious()); rv += SDK_ASSERT(i.hasNext()); update = i.next(); - rv += SDK_ASSERT(update != NULL); + rv += SDK_ASSERT(update != nullptr); rv += SDK_ASSERT(simCore::areEqual(update->time(), 10.0)); // 10.0: lower bound should be 10.0 @@ -173,7 +173,7 @@ int testSingleItem(const simData::PlatformUpdateSlice& slice) rv += SDK_ASSERT(!i.hasPrevious()); rv += SDK_ASSERT(i.hasNext()); update = i.next(); - rv += SDK_ASSERT(update != NULL); + rv += SDK_ASSERT(update != nullptr); rv += SDK_ASSERT(simCore::areEqual(update->time(), 10.0)); // 10.0: upper bound should be [end] @@ -181,21 +181,21 @@ int testSingleItem(const simData::PlatformUpdateSlice& slice) rv += SDK_ASSERT(i.hasPrevious()); rv += SDK_ASSERT(!i.hasNext()); update = i.next(); - rv += SDK_ASSERT(update == NULL); + rv += SDK_ASSERT(update == nullptr); // 11.0: lower bound should be [end] i = slice.lower_bound(11.0); rv += SDK_ASSERT(i.hasPrevious()); rv += SDK_ASSERT(!i.hasNext()); update = i.next(); - rv += SDK_ASSERT(update == NULL); + rv += SDK_ASSERT(update == nullptr); // 11.0: upper bound should be [end] i = slice.upper_bound(11.0); rv += SDK_ASSERT(i.hasPrevious()); rv += SDK_ASSERT(!i.hasNext()); update = i.next(); - rv += SDK_ASSERT(update == NULL); + rv += SDK_ASSERT(update == nullptr); return rv; } @@ -254,8 +254,8 @@ int TestSliceBounds(int argc, char* argv[]) helper.addPlatformUpdate(10.0, id); helper.addPlatformUpdate(20.0, id); const simData::PlatformUpdateSlice* slice = helper.dataStore()->platformUpdateSlice(id); - rv += SDK_ASSERT(slice != NULL); - if (slice == NULL) + rv += SDK_ASSERT(slice != nullptr); + if (slice == nullptr) return rv; // Test properties of the slice to make sure it's valid rv += SDK_ASSERT(slice->firstTime() == 1.0); @@ -269,8 +269,8 @@ int TestSliceBounds(int argc, char* argv[]) id = helper.addPlatform(); helper.addPlatformUpdate(10.0, id); slice = helper.dataStore()->platformUpdateSlice(id); - rv += SDK_ASSERT(slice != NULL); - if (slice == NULL) + rv += SDK_ASSERT(slice != nullptr); + if (slice == nullptr) return rv; // Test properties of the slice to make sure it's valid rv += SDK_ASSERT(slice->firstTime() == 10.0); diff --git a/Testing/SimNotify/TestNotify.cpp b/Testing/SimNotify/TestNotify.cpp index f6116576d..ae45fb232 100644 --- a/Testing/SimNotify/TestNotify.cpp +++ b/Testing/SimNotify/TestNotify.cpp @@ -396,8 +396,8 @@ void testStandardNotifyHandler() memset(stdoutBuf, '\0', sizeof(stdoutBuf)); // Reset stdout and stderr - setbuf(stdout, NULL); - setbuf(stderr, NULL); + setbuf(stdout, nullptr); + setbuf(stderr, nullptr); // Reset notify handlers to default simNotify::setNotifyLevel(simNotify::defaultNotifyLevel()); @@ -437,7 +437,7 @@ void testStdoutNotifyHandler() } // Reset stdout and stderr - setbuf(stdout, NULL); + setbuf(stdout, nullptr); // Reset notify handlers to default simNotify::setNotifyHandlers(simNotify::defaultNotifyHandler()); @@ -469,7 +469,7 @@ void testStderrNotifyHandler() } // Reset stdout and stderr - setbuf(stderr, NULL); + setbuf(stderr, nullptr); // Reset notify handlers to default simNotify::setNotifyHandlers(simNotify::defaultNotifyHandler()); diff --git a/Testing/SimQt/ActionRegistryTest.cpp b/Testing/SimQt/ActionRegistryTest.cpp index 374927fda..499650977 100644 --- a/Testing/SimQt/ActionRegistryTest.cpp +++ b/Testing/SimQt/ActionRegistryTest.cpp @@ -42,12 +42,12 @@ struct NewRegistry QAction* pluginManager; QAction* help; NewRegistry() - : reg(new ActionRegistry(NULL)), - superform(new QAction("superform", NULL)), - rangeTool(new QAction("rangeTool...", NULL)), - views(new QAction("views...", NULL)), - pluginManager(new QAction("pluginManager...", NULL)), - help(new QAction("help...", NULL)) + : reg(new ActionRegistry(nullptr)), + superform(new QAction("superform", nullptr)), + rangeTool(new QAction("rangeTool...", nullptr)), + views(new QAction("views...", nullptr)), + pluginManager(new QAction("pluginManager...", nullptr)), + help(new QAction("help...", nullptr)) { superform->setShortcuts(QList() << QKeySequence("Alt+S") << QKeySequence("Ctrl+S")); reg->registerAction("Tools", "SuperForm", superform); @@ -79,24 +79,24 @@ int testFind() rv += SDK_ASSERT(!reg.reg->actions().empty()); Action* action = reg.reg->findAction("Views"); - rv += SDK_ASSERT(action != NULL); - if (action != NULL) + rv += SDK_ASSERT(action != nullptr); + if (action != nullptr) { rv += SDK_ASSERT(action->description() == "Views"); rv += SDK_ASSERT(action->hotkeys().empty()); } action = reg.reg->findAction("View"); - rv += SDK_ASSERT(action == NULL); + rv += SDK_ASSERT(action == nullptr); // Re-register should not work; throw an exception for testing? //Action* badAction = reg.reg->registerAction("Unknown", "Views", reg.superform); - //rv += SDK_ASSERT(badAction != NULL); + //rv += SDK_ASSERT(badAction != nullptr); //rv += SDK_ASSERT(badAction->action() != reg.superform); //rv += SDK_ASSERT(badAction->group() != "Unknown"); // Re-register of same action with different name should also fail; throw an exception? //Action* badAction2 = reg.reg->registerAction("Another", "Another", reg.superform); - //if (badAction2 != NULL) + //if (badAction2 != nullptr) //{ // rv += SDK_ASSERT(badAction2->action() == reg.superform); // rv += SDK_ASSERT(badAction2->description() != "Another"); @@ -104,12 +104,12 @@ int testFind() //} action = reg.reg->findAction(QKeySequence("Alt+S")); - rv += SDK_ASSERT(action != NULL); - if (action != NULL) + rv += SDK_ASSERT(action != nullptr); + if (action != nullptr) rv += SDK_ASSERT(action->description() == "SuperForm"); action = reg.reg->findAction(QKeySequence("Ctrl+S")); - rv += SDK_ASSERT(action != NULL); - if (action != NULL) + rv += SDK_ASSERT(action != nullptr); + if (action != nullptr) { rv += SDK_ASSERT(action->description() == "SuperForm"); rv += SDK_ASSERT(action->hotkeys().size() == 2); @@ -118,14 +118,14 @@ int testFind() // Remove hotkey from SuperForm and re-search reg.reg->removeHotKey(action, 0); // should remove Alt+S action = reg.reg->findAction(QKeySequence("Alt+S")); - rv += SDK_ASSERT(action == NULL); + rv += SDK_ASSERT(action == nullptr); action = reg.reg->findAction(QKeySequence("Ctrl+S")); - rv += SDK_ASSERT(action != NULL); - if (action != NULL) + rv += SDK_ASSERT(action != nullptr); + if (action != nullptr) rv += SDK_ASSERT(action->hotkeys().size() == 1); // Search for nonexistent hotkey - rv += SDK_ASSERT(reg.reg->findAction(QKeySequence("Q")) == NULL); + rv += SDK_ASSERT(reg.reg->findAction(QKeySequence("Q")) == nullptr); return rv; } @@ -134,20 +134,20 @@ int testSetHotKey() { int rv = 0; NewRegistry reg; - rv += SDK_ASSERT(reg.reg->findAction(QKeySequence("V")) == NULL); - rv += SDK_ASSERT(reg.reg->findAction("Views") != NULL); + rv += SDK_ASSERT(reg.reg->findAction(QKeySequence("V")) == nullptr); + rv += SDK_ASSERT(reg.reg->findAction("Views") != nullptr); rv += SDK_ASSERT(reg.reg->setHotKey(reg.reg->findAction("Views"), QKeySequence("V")) == 0); - rv += SDK_ASSERT(reg.reg->findAction(QKeySequence("V")) != NULL); - rv += SDK_ASSERT(reg.reg->setHotKey(NULL, QKeySequence("V")) != 0); + rv += SDK_ASSERT(reg.reg->findAction(QKeySequence("V")) != nullptr); + rv += SDK_ASSERT(reg.reg->setHotKey(nullptr, QKeySequence("V")) != 0); Action* views = reg.reg->findAction(QKeySequence("V")); - rv += SDK_ASSERT(views != NULL); + rv += SDK_ASSERT(views != nullptr); if (views) rv += SDK_ASSERT(views->description() == "Views"); // Test an override reg.reg->setHotKey(views, QKeySequence("Alt+S")); views = reg.reg->findAction(QKeySequence("Alt+S")); - rv += SDK_ASSERT(views != NULL); + rv += SDK_ASSERT(views != nullptr); if (views) { rv += SDK_ASSERT(views->description() == "Views"); @@ -159,7 +159,7 @@ int testSetHotKey() bool hasKey(const NewRegistry& reg, const QString& desc, const QString& hotkey) { Action* act = reg.reg->findAction(QKeySequence(hotkey)); - return act != NULL && act->description() == desc; + return act != nullptr && act->description() == desc; } int testAddHotKey() @@ -181,24 +181,24 @@ int testAddHotKey() // Now look at the action-doesn't-exist cases... // case 1: action has no shortcuts during add - QAction test1("test1", NULL); + QAction test1("test1", nullptr); reg.reg->addHotKey("test1", QKeySequence("D")); - rv += SDK_ASSERT(reg.reg->findAction(QKeySequence("D")) == NULL); + rv += SDK_ASSERT(reg.reg->findAction(QKeySequence("D")) == nullptr); reg.reg->registerAction("test1", "test1", &test1); rv += SDK_ASSERT(hasKey(reg, "test1", "D")); // case 2: action has shortcuts during add - QAction test2("test2", NULL); + QAction test2("test2", nullptr); reg.reg->addHotKey("test2", QKeySequence("E")); test2.setShortcut(QKeySequence("F")); - rv += SDK_ASSERT(reg.reg->findAction(QKeySequence("E")) == NULL); - rv += SDK_ASSERT(reg.reg->findAction(QKeySequence("F")) == NULL); + rv += SDK_ASSERT(reg.reg->findAction(QKeySequence("E")) == nullptr); + rv += SDK_ASSERT(reg.reg->findAction(QKeySequence("F")) == nullptr); reg.reg->registerAction("test2", "test2", &test2); rv += SDK_ASSERT(hasKey(reg, "test2", "E")); rv += SDK_ASSERT(!hasKey(reg, "test2", "F")); // case 3: action has conflicting shortcuts during add - QAction test3("test3", NULL); + QAction test3("test3", nullptr); reg.reg->addHotKey("test3", QKeySequence("G")); test3.setShortcut(QKeySequence("E")); // Belongs to test2 rv += SDK_ASSERT(hasKey(reg, "test2", "E")); @@ -208,7 +208,7 @@ int testAddHotKey() rv += SDK_ASSERT(t3act->hotkeys().size() == 1); // only G // case 4: addAction's hotkey ends up being in use already - QAction test4("test4", NULL); + QAction test4("test4", nullptr); reg.reg->addHotKey("test4", QKeySequence("G")); rv += SDK_ASSERT(!hasKey(reg, "test3", "G")); auto t4act = reg.reg->registerAction("test4", "test4", &test4); @@ -253,7 +253,7 @@ int testExecute() NewRegistry reg; QPushButton testButton; testButton.setCheckable(true); - QAction action("exec", NULL); + QAction action("exec", nullptr); QObject::connect(&action, SIGNAL(triggered()), &testButton, SLOT(toggle())); rv += SDK_ASSERT(!testButton.isChecked()); action.trigger(); @@ -276,18 +276,18 @@ int testMemento() int rv = 0; NewRegistry reg; ActionRegistry::SettingsMemento* defaultSettings = reg.reg->createMemento(); - rv += SDK_ASSERT(defaultSettings != NULL); + rv += SDK_ASSERT(defaultSettings != nullptr); rv += SDK_ASSERT(reg.superform->shortcuts().size() == 2); rv += SDK_ASSERT(reg.reg->findAction(QKeySequence("Alt+S"))->action() == reg.superform); - rv += SDK_ASSERT(reg.reg->findAction(QKeySequence("Q")) == NULL); - rv += SDK_ASSERT(reg.reg->findAction(QKeySequence("R")) == NULL); + rv += SDK_ASSERT(reg.reg->findAction(QKeySequence("Q")) == nullptr); + rv += SDK_ASSERT(reg.reg->findAction(QKeySequence("R")) == nullptr); // Make some changes rv += SDK_ASSERT(0 == reg.reg->addHotKey("Views", QKeySequence("Q"))); rv += SDK_ASSERT(0 == reg.reg->addHotKey("Plugin Manager", QKeySequence("Alt+S"))); rv += SDK_ASSERT(reg.superform->shortcuts().size() == 1); rv += SDK_ASSERT(reg.reg->findAction(QKeySequence("Alt+S"))->action() == reg.pluginManager); rv += SDK_ASSERT(reg.reg->findAction(QKeySequence("Q"))->action() == reg.views); - rv += SDK_ASSERT(reg.reg->findAction(QKeySequence("R")) == NULL); + rv += SDK_ASSERT(reg.reg->findAction(QKeySequence("R")) == nullptr); // Save a new memento ActionRegistry::SettingsMemento* newSettings = reg.reg->createMemento(); // Restore last one @@ -295,29 +295,29 @@ int testMemento() // Test the original conditions again rv += SDK_ASSERT(reg.superform->shortcuts().size() == 2); rv += SDK_ASSERT(reg.reg->findAction(QKeySequence("Alt+S"))->action() == reg.superform); - rv += SDK_ASSERT(reg.reg->findAction(QKeySequence("Q")) == NULL); - rv += SDK_ASSERT(reg.reg->findAction(QKeySequence("R")) == NULL); + rv += SDK_ASSERT(reg.reg->findAction(QKeySequence("Q")) == nullptr); + rv += SDK_ASSERT(reg.reg->findAction(QKeySequence("R")) == nullptr); // Test restoring the new one newSettings->restore(*reg.reg); rv += SDK_ASSERT(reg.superform->shortcuts().size() == 1); rv += SDK_ASSERT(reg.reg->findAction(QKeySequence("Alt+S"))->action() == reg.pluginManager); rv += SDK_ASSERT(reg.reg->findAction(QKeySequence("Q"))->action() == reg.views); - rv += SDK_ASSERT(reg.reg->findAction(QKeySequence("R")) == NULL); + rv += SDK_ASSERT(reg.reg->findAction(QKeySequence("R")) == nullptr); // Go back to default; restore an action that doesn't exist (i.e. delete views) defaultSettings->restore(*reg.reg); rv += SDK_ASSERT(0 == reg.reg->removeAction("Views")); // Restore the configuration that had a views hotkey, make sure no crash newSettings->restore(*reg.reg); rv += SDK_ASSERT(reg.reg->findAction(QKeySequence("Alt+S"))->action() == reg.pluginManager); - rv += SDK_ASSERT(reg.reg->findAction(QKeySequence("Q")) == NULL); - rv += SDK_ASSERT(reg.reg->findAction(QKeySequence("R")) == NULL); + rv += SDK_ASSERT(reg.reg->findAction(QKeySequence("Q")) == nullptr); + rv += SDK_ASSERT(reg.reg->findAction(QKeySequence("R")) == nullptr); delete newSettings; // Restore the original settings, after deleting the new ones defaultSettings->restore(*reg.reg); rv += SDK_ASSERT(reg.superform->shortcuts().size() == 2); rv += SDK_ASSERT(reg.reg->findAction(QKeySequence("Alt+S"))->action() == reg.superform); - rv += SDK_ASSERT(reg.reg->findAction(QKeySequence("Q")) == NULL); - rv += SDK_ASSERT(reg.reg->findAction(QKeySequence("R")) == NULL); + rv += SDK_ASSERT(reg.reg->findAction(QKeySequence("Q")) == nullptr); + rv += SDK_ASSERT(reg.reg->findAction(QKeySequence("R")) == nullptr); // Looks good, return delete defaultSettings; @@ -328,12 +328,12 @@ int testAlias() { int rv = 0; - ActionRegistry* ar = new ActionRegistry(NULL); + ActionRegistry* ar = new ActionRegistry(nullptr); // Make an action - QAction* action1 = new QAction("acttion1", NULL); + QAction* action1 = new QAction("acttion1", nullptr); simQt::Action* firstAction = ar->registerAction("Test", "First", action1); - rv += SDK_ASSERT(firstAction != NULL); + rv += SDK_ASSERT(firstAction != nullptr); // Add an alias; which should work rv += SDK_ASSERT(ar->registerAlias("First", "FirstAlias1") == 0); @@ -359,7 +359,7 @@ int testAlias() rv += SDK_ASSERT(ar->findAction("FirstAlias2") == firstAction); // Find a bogus name that should fail - rv += SDK_ASSERT(ar->findAction("ShouldNotWork") == NULL); + rv += SDK_ASSERT(ar->findAction("ShouldNotWork") == nullptr); delete ar; delete action1; @@ -372,7 +372,7 @@ int testHotKeyAssignment() int rv = 0; NewRegistry reg; - QAction exec1("exec1", NULL); + QAction exec1("exec1", nullptr); const QKeySequence ks1("1"); exec1.setShortcut(ks1); @@ -383,14 +383,14 @@ int testHotKeyAssignment() // Add action; it should recognize shortcut and be correct simQt::Action* qAction = reg.reg->registerAction("Temp", "exec1", &exec1); - rv += SDK_ASSERT(qAction != NULL); + rv += SDK_ASSERT(qAction != nullptr); rv += SDK_ASSERT(reg.reg->getKeySequenceAssignment(ks1, actionName) == simQt::ActionRegistry::ASSIGNED_TO_ACTION); rv += SDK_ASSERT(actionName == "exec1"); // Swap hot key const QKeySequence ks2("2"); rv += SDK_ASSERT(reg.reg->setHotKey(qAction, ks2) == 0); - rv += SDK_ASSERT(qAction != NULL); + rv += SDK_ASSERT(qAction != nullptr); rv += SDK_ASSERT(reg.reg->getKeySequenceAssignment(ks1, actionName) == simQt::ActionRegistry::UNASSIGNED); rv += SDK_ASSERT(actionName.isEmpty()); rv += SDK_ASSERT(reg.reg->getKeySequenceAssignment(ks2, actionName) == simQt::ActionRegistry::ASSIGNED_TO_ACTION); @@ -398,7 +398,7 @@ int testHotKeyAssignment() // Remove hot key rv += SDK_ASSERT(reg.reg->removeAction("exec1") == 0); - qAction = NULL; + qAction = nullptr; rv += SDK_ASSERT(reg.reg->getKeySequenceAssignment(ks1, actionName) == simQt::ActionRegistry::UNASSIGNED); rv += SDK_ASSERT(actionName.isEmpty()); // ks2 should have transitioned to unknown @@ -414,9 +414,9 @@ int testHotKeyAssignment() rv += SDK_ASSERT(actionName == "exec3"); // Reassign it to something that does exist - QAction exec2("exec2", NULL); + QAction exec2("exec2", nullptr); qAction = reg.reg->registerAction("Temp", "exec2", &exec2); - rv += SDK_ASSERT(qAction != NULL); + rv += SDK_ASSERT(qAction != nullptr); rv += SDK_ASSERT(reg.reg->getKeySequenceAssignment(ks3, actionName) == simQt::ActionRegistry::ASSIGNED_TO_UNKNOWN); rv += SDK_ASSERT(actionName == "exec3"); rv += SDK_ASSERT(reg.reg->addHotKey("exec2", ks3) == 0); @@ -425,7 +425,7 @@ int testHotKeyAssignment() // Remove that action; it should be assigned to unknown, but to exec2 now and not exec3 rv += SDK_ASSERT(reg.reg->removeAction("exec2") == 0); - qAction = NULL; + qAction = nullptr; rv += SDK_ASSERT(reg.reg->getKeySequenceAssignment(ks3, actionName) == simQt::ActionRegistry::ASSIGNED_TO_UNKNOWN); rv += SDK_ASSERT(actionName == "exec2"); // Fix it back to exec3 @@ -434,9 +434,9 @@ int testHotKeyAssignment() rv += SDK_ASSERT(actionName == "exec3"); // Add exec3 and it should still be on exec3 - QAction exec3("exec3", NULL); + QAction exec3("exec3", nullptr); qAction = reg.reg->registerAction("Temp", "exec3", &exec3); - rv += SDK_ASSERT(qAction != NULL); + rv += SDK_ASSERT(qAction != nullptr); rv += SDK_ASSERT(reg.reg->getKeySequenceAssignment(ks3, actionName) == simQt::ActionRegistry::ASSIGNED_TO_ACTION); rv += SDK_ASSERT(actionName == "exec3"); @@ -453,10 +453,10 @@ int testHotKeyAssignment() rv += SDK_ASSERT(reg.reg->addHotKey("exec4", ks4) == 0); rv += SDK_ASSERT(reg.reg->getKeySequenceAssignment(ks4, actionName) == simQt::ActionRegistry::ASSIGNED_TO_UNKNOWN); rv += SDK_ASSERT(actionName == "exec4"); - QAction exec5("exec5", NULL); + QAction exec5("exec5", nullptr); exec5.setShortcut(ks4); qAction = reg.reg->registerAction("Temp", "exec5", &exec5); - rv += SDK_ASSERT(qAction != NULL); + rv += SDK_ASSERT(qAction != nullptr); rv += SDK_ASSERT(reg.reg->getKeySequenceAssignment(ks4, actionName) == simQt::ActionRegistry::ASSIGNED_TO_ACTION); rv += SDK_ASSERT(actionName == "exec5"); rv += SDK_ASSERT(reg.reg->setHotKey(qAction, ks1) == 0); diff --git a/Testing/SimQt/GradientTest.cpp b/Testing/SimQt/GradientTest.cpp index 15cc25de7..6e69fde64 100644 --- a/Testing/SimQt/GradientTest.cpp +++ b/Testing/SimQt/GradientTest.cpp @@ -70,48 +70,28 @@ int testGradient() rv += SDK_ASSERT(grad.colors().size() == 5); rv += SDK_ASSERT(grad.colorAt(0.125f) != Qt::darkYellow); - // Test 0 control points, and outside-0 points + // Test a "cleared" gradient grad.clearColors(); - rv += SDK_ASSERT(grad.colors().size() == 0); - rv += SDK_ASSERT(grad.colorAt(0.f) == Qt::black); - rv += SDK_ASSERT(grad.colorAt(1.f) == Qt::black); - const QColor midGray = qRgba(128, 128, 128, 255); - rv += SDK_ASSERT(grad.setColor(0.5f, midGray) == 0); - rv += SDK_ASSERT(grad.colors().size() == 1); - rv += SDK_ASSERT(grad.colorAt(0.f) == midGray); - rv += SDK_ASSERT(grad.colorAt(0.4f) == midGray); - rv += SDK_ASSERT(grad.colorAt(0.5f) == midGray); - rv += SDK_ASSERT(grad.colorAt(0.6f) == midGray); - rv += SDK_ASSERT(grad.colorAt(1.f) == midGray); - - // Add one at 0.75 - const QColor darkGray = qRgba(192, 192, 192, 255); - rv += SDK_ASSERT(grad.setColor(0.75f, darkGray) == 0); - rv += SDK_ASSERT(grad.colorAt(0.f) == midGray); - rv += SDK_ASSERT(grad.colorAt(0.4f) == midGray); - rv += SDK_ASSERT(grad.colorAt(0.5f) == midGray); - rv += SDK_ASSERT(grad.colorAt(0.75f) == darkGray); - rv += SDK_ASSERT(grad.colorAt(0.85f) == darkGray); - rv += SDK_ASSERT(grad.colorAt(1.f) == darkGray); + rv += SDK_ASSERT(grad.colors().size() == 2); + rv += SDK_ASSERT(grad.colorAt(0.f) == Qt::white); + rv += SDK_ASSERT(grad.colorAt(1.f) == Qt::white); // Test setColors with points outside 0/1 std::map colorMap; colorMap[-1.f] = Qt::white; + colorMap[0.2f] = Qt::red; + colorMap[0.8f] = Qt::green; colorMap[2.f] = Qt::white; rv += SDK_ASSERT(grad.colors().size() == 2); grad.setColors(colorMap); - rv += SDK_ASSERT(grad.colors().size() == 0); - rv += SDK_ASSERT(grad.colorAt(0.f) == Qt::black); - rv += SDK_ASSERT(grad.colorAt(0.5f) == Qt::black); - rv += SDK_ASSERT(grad.colorAt(1.f) == Qt::black); - - // Test constructor with outside-0/1 points - colorMap[0.5f] = Qt::green; - simQt::ColorGradient grad2(colorMap); - rv += SDK_ASSERT(grad2.colors().size() == 1); - rv += SDK_ASSERT(grad2.colorAt(0.f) == Qt::green); - rv += SDK_ASSERT(grad2.colorAt(0.5f) == Qt::green); - rv += SDK_ASSERT(grad2.colorAt(1.f) == Qt::green); + rv += SDK_ASSERT(grad.colors().size() == 2); + rv += SDK_ASSERT(grad.colorAt(0.f) == Qt::red); + QColor mid = grad.colorAt(0.5f); + rv += SDK_ASSERT(mid.red() == 127); + rv += SDK_ASSERT(mid.green() == 127); + rv += SDK_ASSERT(mid.blue() == 0); + rv += SDK_ASSERT(mid.alpha() == 255); + rv += SDK_ASSERT(grad.colorAt(1.f) == Qt::green); return rv; } diff --git a/Testing/SimQt/SettingsTest.cpp b/Testing/SimQt/SettingsTest.cpp index e70d9ad1b..a82c0be30 100644 --- a/Testing/SimQt/SettingsTest.cpp +++ b/Testing/SimQt/SettingsTest.cpp @@ -246,7 +246,7 @@ int testSettingsWithoutMetaData() settings.clear(); // Set a single value without meta data (as if from a .ini file or registry) settings.setValue("Setting1", "1"); - simQt::SettingsModel model(NULL, settings); + simQt::SettingsModel model(nullptr, settings); int rv = 0; rv += SDK_ASSERT(model.allNames().size() == 1); @@ -394,7 +394,7 @@ int testMemento(simQt::Settings& settings) // Save a memento std::unique_ptr before(settings.createMemento()); - rv += SDK_ASSERT(before != NULL); + rv += SDK_ASSERT(before != nullptr); // Change values in unexpected ways settings.setValue("DefaultInt", 4.5); @@ -408,7 +408,7 @@ int testMemento(simQt::Settings& settings) rv += SDK_ASSERT(settings.value("AnotherInt").toInt() == 7); std::unique_ptr after(settings.createMemento()); - rv += SDK_ASSERT(after != NULL); + rv += SDK_ASSERT(after != nullptr); // Test values after restoring the old memento rv += SDK_ASSERT(before->restore(settings) == 0); @@ -478,7 +478,7 @@ int SettingsTest(int argc, char* argv[]) rv += testPersistentMetaData(); QSettings qSettings; - simQt::SettingsPtr settings(new simQt::SettingsModel(NULL, qSettings)); + simQt::SettingsPtr settings(new simQt::SettingsModel(nullptr, qSettings)); rv += testSingleLevel(settings); simQt::SettingsGroupPtr group(new simQt::SettingsGroup(settings.get(), "")); diff --git a/Testing/SimVis/GogTest.cpp b/Testing/SimVis/GogTest.cpp index 25d9ab9ef..8e3eff1fc 100644 --- a/Testing/SimVis/GogTest.cpp +++ b/Testing/SimVis/GogTest.cpp @@ -24,8 +24,12 @@ #include #include #include "simNotify/Notify.h" +#include "simCore/Calc/Math.h" +#include "simCore/Calc/Units.h" #include "simCore/Common/SDKAssert.h" #include "simCore/Common/Version.h" +#include "simCore/String/Format.h" +#include "simCore/String/Tokenizer.h" #include "simVis/GOG/GogNodeInterface.h" #include "simVis/GOG/ParsedShape.h" #include "simVis/GOG/Parser.h" @@ -416,6 +420,114 @@ int testParseMetaData() return rv; } + +bool findTokenValue(std::stringstream& ss, const std::string& token, const std::string& value) +{ + std::vector tokens; + std::string line; + while (simCore::getStrippedLine(ss, line)) + { + simCore::quoteTokenizer(tokens, line); + line = simCore::lowerCase(line); + // 3d is a special case that represents a GOG keyword made up of multiple tokens + if (tokens[0] == "3d") + { + if (tokens.size() < 3) + return false; + if ((tokens[0] + " " + tokens[1]) == token) + return tokens[2] == value; + } + else if (tokens[0] == token) + { + if (tokens.size() < 1) + return false; + return tokens[1] == value; + } + } + return false; +} + +int testAltitudeUnits() +{ + int rv = 0; + + simVis::GOG::Parser parser; + // loaded GOG shape nodes + simVis::GOG::Parser::OverlayNodeVector gogs; + // follow data for attached GOGs + std::vector followData; + + std::stringstream input; + + // Test loading line with altitude units specified + std::string lineGog = FILE_VERSION + + "start\n line\n lla 22.1 - 159.7 2\n lla 22.1 - 159.3 2\n 3d offsetalt 2\n altitudeUnits km\n end\n"; + input << lineGog; + bool parsedGog = parser.loadGOGs(input, simVis::GOG::GOGNODE_GEOGRAPHIC, gogs, followData); + rv += SDK_ASSERT(parsedGog); // verify parsing worked + rv += SDK_ASSERT(gogs.size() == 1); + if (!gogs.empty()) + { + double altOffset = 0.; + rv += SDK_ASSERT(gogs.front()->getAltOffset(altOffset) == 0); + rv += SDK_ASSERT(altOffset == 2000); // value is in meters, verify it still matches 2 km + + std::stringstream serializedLine; + gogs.front()->serializeToStream(serializedLine); + // line should always serialize out altitude units as meters, despite input + rv += SDK_ASSERT(findTokenValue(serializedLine, "altitudeunits", "meters")); + } + clearItems(gogs, followData, input); + + // Test loading circle with altitude units specified + std::string circleGog = FILE_VERSION + + "start\n circle\n centerlla 22.1 - 159.7 2\n radius 200\n 3d offsetalt 2\n altitudeUnits km\n end\n"; + input << circleGog; + parsedGog = parser.loadGOGs(input, simVis::GOG::GOGNODE_GEOGRAPHIC, gogs, followData); + rv += SDK_ASSERT(parsedGog); // verify parsing worked + rv += SDK_ASSERT(gogs.size() == 1); + if (!gogs.empty()) + { + double altOffset = 0.; + rv += SDK_ASSERT(gogs.front()->getAltOffset(altOffset) == 0); + rv += SDK_ASSERT(altOffset == 2000); // value is in meters, verify it still matches 2 km + + std::stringstream serializedCircle; + gogs.front()->serializeToStream(serializedCircle); + // circle should serialize out to the same units it went in as + rv += SDK_ASSERT(findTokenValue(serializedCircle, "altitudeunits", "km")); + } + clearItems(gogs, followData, input); + + // Test loading LatLonAltBox with no altitude units specified, altitude units default to ft + std::string llabGog = FILE_VERSION + + "start\n LatLonAltBox 21.945 22.0 -159.454 -159.41 1. 4.\n 3d offsetalt 2000\n end\n"; + input << llabGog; + parsedGog = parser.loadGOGs(input, simVis::GOG::GOGNODE_GEOGRAPHIC, gogs, followData); + rv += SDK_ASSERT(parsedGog); // verify parsing worked + rv += SDK_ASSERT(gogs.size() == 1); + if (!gogs.empty()) + { + double altOffset = 0.; + rv += SDK_ASSERT(gogs.front()->getAltOffset(altOffset) == 0); + simCore::Units altMeters(simCore::Units::METERS); + simCore::Units altFeet(simCore::Units::FEET); + // alt offset is in meters, verify it is equivalent to 2000 ft + rv += SDK_ASSERT(simCore::areEqual(altOffset, altFeet.convertTo(altMeters, 2000))); + + // now update altitude offset to 3000 ft + gogs.front()->setAltOffset(altFeet.convertTo(altMeters, 3000)); + + std::stringstream serializedLlab; + gogs.front()->serializeToStream(serializedLlab); + // verify that altitude offset serializes out as 3000 ft + rv += SDK_ASSERT(findTokenValue(serializedLlab, "3d offsetalt", "3000")); + } + clearItems(gogs, followData, input); + + return rv; +} + } int GogTest(int argc, char* argv[]) @@ -428,6 +540,7 @@ int GogTest(int argc, char* argv[]) // Run tests rv += testLoadRelativeAndAbsolute(); rv += testParseMetaData(); + rv += testAltitudeUnits(); // Shut down protobuf lib for valgrind testing google::protobuf::ShutdownProtobufLibrary(); diff --git a/Testing/SimVis/LocatorTest.cpp b/Testing/SimVis/LocatorTest.cpp index 61f3ca953..d3981ce17 100644 --- a/Testing/SimVis/LocatorTest.cpp +++ b/Testing/SimVis/LocatorTest.cpp @@ -88,7 +88,7 @@ int testOnePositionOrientation(simVis::Locator* loc, const simCore::Vec3& pos, c int testOrientation(simVis::Locator* loc, const simCore::Vec3& pos, simCore::CoordinateSystem coordsys) { - using namespace simCore; + using simCore::DEG2RAD; int rv = 0; // Test extremes @@ -103,13 +103,13 @@ int testOrientation(simVis::Locator* loc, const simCore::Vec3& pos, simCore::Coo // Test local offsets // We can have orientations and offsets in the same axes, but anything else will fail as we're only adding them together instead of // using rotation matrices. - rv += testOnePositionOrientation(loc, pos, Vec3(), simCore::Vec3(0.0 * DEG2RAD, 0.0 * DEG2RAD, 0.0 * DEG2RAD), 145000, coordsys); - rv += testOnePositionOrientation(loc, pos, Vec3(30.0 * DEG2RAD, 0.0, 0.0), simCore::Vec3(180.0 * DEG2RAD, 0.0 * DEG2RAD, 0.0 * DEG2RAD), 145000, coordsys); - rv += testOnePositionOrientation(loc, pos, Vec3(60.0 * DEG2RAD, 0.0, 0.0), simCore::Vec3(-180.0 * DEG2RAD, 0.0 * DEG2RAD, 0.0 * DEG2RAD), 145000, coordsys); - rv += testOnePositionOrientation(loc, pos, Vec3(0.0, -30.0 * DEG2RAD, 0.0), simCore::Vec3(0.0 * DEG2RAD, 90.0 * DEG2RAD, 0.0 * DEG2RAD), 145000, coordsys); - rv += testOnePositionOrientation(loc, pos, Vec3(0.0, 60.0 * DEG2RAD, 0.0), simCore::Vec3(0.0 * DEG2RAD, -90.0 * DEG2RAD, 0.0 * DEG2RAD), 145000, coordsys); - rv += testOnePositionOrientation(loc, pos, Vec3(0.0, 0.0, 30.0 * DEG2RAD), simCore::Vec3(0.0 * DEG2RAD, 0.0 * DEG2RAD, 180.0 * DEG2RAD), 145000, coordsys); - rv += testOnePositionOrientation(loc, pos, Vec3(0.0, 0.0, 60.0 * DEG2RAD), simCore::Vec3(0.0 * DEG2RAD, 0.0 * DEG2RAD, -180.0 * DEG2RAD), 145000, coordsys); + rv += testOnePositionOrientation(loc, pos, simCore::Vec3(), simCore::Vec3(0.0 * DEG2RAD, 0.0 * DEG2RAD, 0.0 * DEG2RAD), 145000, coordsys); + rv += testOnePositionOrientation(loc, pos, simCore::Vec3(30.0 * DEG2RAD, 0.0, 0.0), simCore::Vec3(180.0 * DEG2RAD, 0.0 * DEG2RAD, 0.0 * DEG2RAD), 145000, coordsys); + rv += testOnePositionOrientation(loc, pos, simCore::Vec3(60.0 * DEG2RAD, 0.0, 0.0), simCore::Vec3(-180.0 * DEG2RAD, 0.0 * DEG2RAD, 0.0 * DEG2RAD), 145000, coordsys); + rv += testOnePositionOrientation(loc, pos, simCore::Vec3(0.0, -30.0 * DEG2RAD, 0.0), simCore::Vec3(0.0 * DEG2RAD, 90.0 * DEG2RAD, 0.0 * DEG2RAD), 145000, coordsys); + rv += testOnePositionOrientation(loc, pos, simCore::Vec3(0.0, 60.0 * DEG2RAD, 0.0), simCore::Vec3(0.0 * DEG2RAD, -90.0 * DEG2RAD, 0.0 * DEG2RAD), 145000, coordsys); + rv += testOnePositionOrientation(loc, pos, simCore::Vec3(0.0, 0.0, 30.0 * DEG2RAD), simCore::Vec3(0.0 * DEG2RAD, 0.0 * DEG2RAD, 180.0 * DEG2RAD), 145000, coordsys); + rv += testOnePositionOrientation(loc, pos, simCore::Vec3(0.0, 0.0, 60.0 * DEG2RAD), simCore::Vec3(0.0 * DEG2RAD, 0.0 * DEG2RAD, -180.0 * DEG2RAD), 145000, coordsys); // Test random orientation rv += testOnePositionOrientation(loc, pos, simCore::Vec3(15.0 * DEG2RAD, 30.0 * DEG2RAD, 45.0 * DEG2RAD), simCore::Vec3(), 145000, coordsys); @@ -128,7 +128,7 @@ int testOrientation(simVis::Locator* loc, const simCore::Vec3& pos, simCore::Coo int testGetLocatorPositionOrientation(simVis::Locator* loc) { - using namespace simCore; + using simCore::DEG2RAD; int rv = 0; // Test extremes @@ -192,6 +192,44 @@ int testStaticEci(double eciReferenceTime) return rv; } +// Create two locators, first with base coordinate, +// and second that adds position and orientation offsets. +// Test that convenience methods getLocatorPositionOrientation +// and getLocatorPosition return same values for position +int testPositionVsPositionOrientation() +{ + using simCore::DEG2RAD; + int rv = 0; + + osg::ref_ptr locator1 = new simVis::Locator(); + osg::ref_ptr locator2 = new simVis::Locator(locator1); + + // Create locator with position and orientation + simCore::Coordinate coord( + simCore::COORD_SYS_LLA, + simCore::Vec3(22.0 * DEG2RAD, 123.0 * DEG2RAD, 200), + simCore::Vec3(22.0 * DEG2RAD, 30.0 * DEG2RAD, 0)); + + locator1->setCoordinate(coord, 0., 0.); + + // add position and orientation offsets to 2nd locator + locator2->setLocalOffsets(simCore::Vec3(10., 20., 30.), simCore::Vec3(15.0 * DEG2RAD, 30.0 * DEG2RAD, 45.0 * DEG2RAD)); + + // Retrieve the output position in LLA + simCore::Vec3 outPosition; + simCore::Vec3 outOrientation; + simCore::Vec3 outPosition2; + locator2->getLocatorPositionOrientation(&outPosition, &outOrientation, simCore::COORD_SYS_LLA); + locator2->getLocatorPosition(&outPosition2, simCore::COORD_SYS_LLA); + + // Check that position obtained from getLocatorPositionOrientation matches getLocatorPosition + rv += SDK_ASSERT(simCore::areAnglesEqual(outPosition.lat(), outPosition2.lat())); + rv += SDK_ASSERT(simCore::areAnglesEqual(outPosition.lon(), outPosition2.lon())); + rv += SDK_ASSERT(simCore::areEqual(outPosition.alt(), outPosition2.alt())); + + return rv; +} + } int LocatorTest(int argc, char* argv[]) @@ -234,5 +272,6 @@ int LocatorTest(int argc, char* argv[]) rv += testStaticEci(-10.); } + rv += testPositionVsPositionOrientation(); return rv; } diff --git a/share/ExternalSdkProject/CoreExample/CoreExample.cpp b/share/ExternalSdkProject/CoreExample/CoreExample.cpp index cf543c90f..a6262549c 100644 --- a/share/ExternalSdkProject/CoreExample/CoreExample.cpp +++ b/share/ExternalSdkProject/CoreExample/CoreExample.cpp @@ -31,12 +31,12 @@ static const simCore::Vec3 BALTIMORE_LLA(39.29038 * simCore::DEG2RAD, -76.61219 int main(int argc, char* argv[]) { // Note that the WGS_84 earth model does not require a CoordConvert - // instance to calculate ground distance, so we pass in NULL - const double distanceKm = simCore::calculateGroundDist(DC_LLA, BALTIMORE_LLA, simCore::WGS_84, NULL) / 1000.0; + // instance to calculate ground distance, so we pass in nullptr + const double distanceKm = simCore::calculateGroundDist(DC_LLA, BALTIMORE_LLA, simCore::WGS_84, nullptr) / 1000.0; // Calculate the azimuth (true) as well between the two posits double azimuth = 0.0; - simCore::calculateAbsAzEl(DC_LLA, BALTIMORE_LLA, &azimuth, NULL, NULL, simCore::WGS_84, NULL); + simCore::calculateAbsAzEl(DC_LLA, BALTIMORE_LLA, &azimuth, nullptr, nullptr, simCore::WGS_84, nullptr); azimuth *= simCore::RAD2DEG; // Report the value on console diff --git a/swig/CMakeLists.txt b/swig/CMakeLists.txt index 11fed87a7..a7d17a245 100644 --- a/swig/CMakeLists.txt +++ b/swig/CMakeLists.txt @@ -4,6 +4,7 @@ endif() # Avoid making SWIG targets with older CMake, to avoid extra complications if("${CMAKE_VERSION}" VERSION_LESS 3.13) + message(STATUS "Skipping SIMDIS SDK SWIG module, CMake 3.13 or newer required.") return() endif() diff --git a/swig/Testing/CMakeLists.txt b/swig/Testing/CMakeLists.txt index 07b994597..97f2ea386 100644 --- a/swig/Testing/CMakeLists.txt +++ b/swig/Testing/CMakeLists.txt @@ -6,16 +6,9 @@ endif() # FindPython3.cmake was added in 3.12 and is better than PythonInterp cmake_minimum_required(VERSION 3.12) -# Pull the version from CMakeImport/ImportPython3.cmake -set(DESIRED_PYTHON_VERSION ${Python3_VERSION}) - if(WIN32) - # Need to match the version exactly on Windows for some reason or crash - find_package(Python3 ${DESIRED_PYTHON_VERSION} EXACT COMPONENTS Interpreter QUIET) - # Python3's find_package() EXACT does not work as advertised in all cases. - if(NOT DESIRED_PYTHON_VERSION VERSION_EQUAL Python3_VERSION) - return() - endif() + # Windows has been picky about which versions can be mixed + find_package(Python3 3.8 COMPONENTS Interpreter QUIET) else() # Linux is more forgiving find_package(Python3 3.6 COMPONENTS Interpreter QUIET)